From matthew at theiselins.net Sat Jan 2 07:35:07 2010 From: matthew at theiselins.net (Matthew Iselin) Date: Sat, 2 Jan 2010 16:35:07 +1000 Subject: [cdi-devel] Proposed Dynamic Driver Loading System Message-ID: Hi, I have been able to get access to a WiFi hotspot, so this mail comes a little earlier than I thought it would. :) This proposal covers the addition of a feature to CDI which enables drivers to be loaded dynamically and on-demand rather than statically at a single point in time. Now that drivers no longer do their own probe of devices, but rather provide a set of initialisation functions to the OS which are called at a convenient time by the OS, it is possible to implement an (optional) scheme through which drivers can be loaded on-demand. The benefits of this include reducing the memory footprint for the OS (especially in the case of monolithic OS's) and greater flexibility. The idea is that the OS stores a map of device identifiers (at this stage the proposal considers the use of PCI vendor and device codes) which detail the name of a driver which is to be loaded if the given device is detected. This list may be OS-specific, or there may be a generic list provided as part of CDI. Either way, the OS is open to interpret the driver name as it sees fit: for example, appending ".o" in the case of Pedigree. This map might look something like this: /** OS-specific map of PCI identifiers -> driver names */ struct cdi_os_pci_driver_map = { 0x8086, 0x1230, "piix", // Vendor, Device, Driver name ... }; I would like for this map to be implemented as part of CDI, in order to ensure that the list is kept up-to-date with drivers as they are written for CDI. Keeping the list in CDI also decreases the amount of work required to port CDI to a new OS and take advantage of these kind of features. In this early draft of the concept, there is no support for non-PCI devices. Things such as USB with each device having a class code (eg, mass storage, or human interface device) may need their own list. This would be logical as the method for loading drivers dynamically upon a hotplug or similar event could be quite different to that of detecting static PCI devices at boot-time. Hot plug PCI devices are considered to be out of the scope of this proposal. At a time defined by the OS implementing CDI, the list of PCI devices will be iterated, and each device will be checked against the known PCI->driver list. Should a driver be found in this list, the driver will be loaded (if not already) and used to initialise the detected device. Now, this brings up a small tangent: it is my belief that driver loading could be added to the CDI interface, as something like: /* Returns -1 if the driver could not be loaded, zero otherwise */ int cdi_load_driver(const char *); However, this may be difficult to justify. After all, how many actual drivers really need to load another driver? The alternative is to have the OS perform driver loading itself, which effectively moves most of this subsystem to the OS side (making this hardly related to CDI at all :) ) So the routine at boot-time might be something like this, for a monolithic kernel: 1. Probe the PCI bus and develop a list of devices that are present 2. Use this list to find drivers to load based on the PCI->driver map 3. Load each driver, calling the necessary initialisation function for each relevant device. 4. (optional) Install hooks for hotplugging Point 4 may need explanation. The kernel will need to provide some form of callback to be called when a new device becomes available (eg, a USB device is plugged in). Whilst non-PCI devices are out of the scope of this initial proposal, it cannot hurt to look into the crystal ball and add support for future expansion. This proposal covers the concept of adding a dynamic driver loading system to CDI in order to reduce memory footprint, improve loading times of OS's utilising CDI, and to also establish initial steps towards supporting proper hotplugging of more complex devices. The proposal can be interpreted as being completely unrelated to CDI; this is only true if features such as `cdi_load_driver' are removed and the PCI->device map is not kept within CDI. As an aside, this might also be a good time to mention that it might be nice to start a wiki or something somewhere to document CDI, how to port CDI to a new OS, and some of the optional features like the one proposed here. Cheers, Matt From matthew at theiselins.net Sat Jan 2 07:46:38 2010 From: matthew at theiselins.net (Matthew Iselin) Date: Sat, 2 Jan 2010 16:46:38 +1000 Subject: [cdi-devel] Proposed Dynamic Driver Loading System Message-ID: Hi, I have been able to get access to a WiFi hotspot, so this mail comes a little earlier than I thought it would. :) This proposal covers the addition of a feature to CDI which enables drivers to be loaded dynamically and on-demand rather than statically at a single point in time. Now that drivers no longer do their own probe of devices, but rather provide a set of initialisation functions to the OS which are called at a convenient time by the OS, it is possible to implement an (optional) scheme through which drivers can be loaded on-demand. The benefits of this include reducing the memory footprint for the OS (especially in the case of monolithic OS's) and greater flexibility. The idea is that the OS stores a map of device identifiers (at this stage the proposal considers the use of PCI vendor and device codes) which detail the name of a driver which is to be loaded if the given device is detected. This list may be OS-specific, or there may be a generic list provided as part of CDI. Either way, the OS is open to interpret the driver name as it sees fit: for example, appending ".o" in the case of Pedigree. This map might look something like this: /** OS-specific map of PCI identifiers -> driver names */ struct cdi_os_pci_driver_map = { 0x8086, 0x1230, "piix", // Vendor, Device, Driver name ... }; I would like for this map to be implemented as part of CDI, in order to ensure that the list is kept up-to-date with drivers as they are written for CDI. Keeping the list in CDI also decreases the amount of work required to port CDI to a new OS and take advantage of these kind of features. In this early draft of the concept, there is no support for non-PCI devices. Things such as USB with each device having a class code (eg, mass storage, or human interface device) may need their own list. This would be logical as the method for loading drivers dynamically upon a hotplug or similar event could be quite different to that of detecting static PCI devices at boot-time. Hot plug PCI devices are considered to be out of the scope of this proposal. At a time defined by the OS implementing CDI, the list of PCI devices will be iterated, and each device will be checked against the known PCI->driver list. Should a driver be found in this list, the driver will be loaded (if not already) and used to initialise the detected device. Now, this brings up a small tangent: it is my belief that driver loading could be added to the CDI interface, as something like: /* Returns -1 if the driver could not be loaded, zero otherwise */ int cdi_load_driver(const char *); However, this may be difficult to justify. After all, how many actual drivers really need to load another driver? The alternative is to have the OS perform driver loading itself, which effectively moves most of this subsystem to the OS side (making this hardly related to CDI at all :) ) So the routine at boot-time might be something like this, for a monolithic kernel: 1. Probe the PCI bus and develop a list of devices that are present 2. Use this list to find drivers to load based on the PCI->driver map 3. Load each driver, calling the necessary initialisation function for each relevant device. 4. (optional) Install hooks for hotplugging Point 4 may need explanation. The kernel will need to provide some form of callback to be called when a new device becomes available (eg, a USB device is plugged in). Whilst non-PCI devices are out of the scope of this initial proposal, it cannot hurt to look into the crystal ball and add support for future expansion. This proposal covers the concept of adding a dynamic driver loading system to CDI in order to reduce memory footprint, improve loading times of OS's utilising CDI, and to also establish initial steps towards supporting proper hotplugging of more complex devices. The proposal can be interpreted as being completely unrelated to CDI; this is only true if features such as `cdi_load_driver' are removed and the PCI->device map is not kept within CDI. As an aside, this might also be a good time to mention that it might be nice to start a wiki or something somewhere to document CDI, how to port CDI to a new OS, and some of the optional features like the one proposed here. Cheers, Matt From matthew at theiselins.net Sat Jan 2 07:58:39 2010 From: matthew at theiselins.net (Matthew Iselin) Date: Sat, 2 Jan 2010 16:58:39 +1000 Subject: [cdi-devel] Proposed Dynamic Driver Loading System Message-ID: Hi, I have been able to get access to a WiFi hotspot, so this mail comes a little earlier than I thought it would. :) This proposal covers the addition of a feature to CDI which enables drivers to be loaded dynamically and on-demand rather than statically at a single point in time. Now that drivers no longer do their own probe of devices, but rather provide a set of initialisation functions to the OS which are called at a convenient time by the OS, it is possible to implement an (optional) scheme through which drivers can be loaded on-demand. The benefits of this include reducing the memory footprint for the OS (especially in the case of monolithic OS's) and greater flexibility. The idea is that the OS stores a map of device identifiers (at this stage the proposal considers the use of PCI vendor and device codes) which detail the name of a driver which is to be loaded if the given device is detected. This list may be OS-specific, or there may be a generic list provided as part of CDI. Either way, the OS is open to interpret the driver name as it sees fit: for example, appending ".o" in the case of Pedigree. This map might look something like this: /** OS-specific map of PCI identifiers -> driver names */ struct cdi_os_pci_driver_map = { 0x8086, 0x1230, "piix", // Vendor, Device, Driver name ... }; I would like for this map to be implemented as part of CDI, in order to ensure that the list is kept up-to-date with drivers as they are written for CDI. Keeping the list in CDI also decreases the amount of work required to port CDI to a new OS and take advantage of these kind of features. In this early draft of the concept, there is no support for non-PCI devices. Things such as USB with each device having a class code (eg, mass storage, or human interface device) may need their own list. This would be logical as the method for loading drivers dynamically upon a hotplug or similar event could be quite different to that of detecting static PCI devices at boot-time. Hot plug PCI devices are considered to be out of the scope of this proposal. At a time defined by the OS implementing CDI, the list of PCI devices will be iterated, and each device will be checked against the known PCI->driver list. Should a driver be found in this list, the driver will be loaded (if not already) and used to initialise the detected device. Now, this brings up a small tangent: it is my belief that driver loading could be added to the CDI interface, as something like: /* Returns -1 if the driver could not be loaded, zero otherwise */ int cdi_load_driver(const char *); However, this may be difficult to justify. After all, how many actual drivers really need to load another driver? The alternative is to have the OS perform driver loading itself, which effectively moves most of this subsystem to the OS side (making this hardly related to CDI at all :) ) So the routine at boot-time might be something like this, for a monolithic kernel: 1. Probe the PCI bus and develop a list of devices that are present 2. Use this list to find drivers to load based on the PCI->driver map 3. Load each driver, calling the necessary initialisation function for each relevant device. 4. (optional) Install hooks for hotplugging Point 4 may need explanation. The kernel will need to provide some form of callback to be called when a new device becomes available (eg, a USB device is plugged in). Whilst non-PCI devices are out of the scope of this initial proposal, it cannot hurt to look into the crystal ball and add support for future expansion. This proposal covers the concept of adding a dynamic driver loading system to CDI in order to reduce memory footprint, improve loading times of OS's utilising CDI, and to also establish initial steps towards supporting proper hotplugging of more complex devices. The proposal can be interpreted as being completely unrelated to CDI; this is only true if features such as `cdi_load_driver' are removed and the PCI->device map is not kept within CDI. As an aside, this might also be a good time to mention that it might be nice to start a wiki or something somewhere to document CDI, how to port CDI to a new OS, and some of the optional features like the one proposed here. Cheers, Matt From kevin at tyndur.org Sat Jan 2 12:46:50 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Sat, 2 Jan 2010 12:46:50 +0100 Subject: [cdi-devel] Proposed Dynamic Driver Loading System In-Reply-To: References: Message-ID: <20100102114646.GA20662@silvanus> On Sat, Jan 02, 2010 at 04:58:39PM +1000, Matthew Iselin wrote: > Hi, > > I have been able to get access to a WiFi hotspot, so this mail comes a > little earlier than I thought it would. :) > > This proposal covers the addition of a feature to CDI which enables drivers > to be loaded dynamically and on-demand rather than statically at a single > point in time. > > Now that drivers no longer do their own probe of devices, but rather provide > a set of initialisation functions to the OS which are called at a convenient > time by the OS, it is possible to implement an (optional) scheme through > which drivers can be loaded on-demand. The benefits of this include reducing > the memory footprint for the OS (especially in the case of monolithic OS's) > and greater flexibility. > > The idea is that the OS stores a map of device identifiers (at this stage the > proposal considers the use of PCI vendor and device codes) which detail the > name of a driver which is to be loaded if the given device is detected. This > list may be OS-specific, or there may be a generic list provided as part of > CDI. Either way, the OS is open to interpret the driver name as it sees fit: > for example, appending ".o" in the case of Pedigree. > > This map might look something like this: > > /** OS-specific map of PCI identifiers -> driver names */ > > struct cdi_os_pci_driver_map = { > 0x8086, 0x1230, "piix", // Vendor, Device, Driver name > ... > }; This would be an additional top-level C file, right? I don't think it's a good idea to manually create it and keep it in sync (especially considering that many OSes don't use all drivers), but generating such a file looks fine to me. > I would like for this map to be implemented as part of CDI, in order to ensure > that the list is kept up-to-date with drivers as they are written for CDI. > Keeping the list in CDI also decreases the amount of work required to port CDI > to a new OS and take advantage of these kind of features. > > In this early draft of the concept, there is no support for non-PCI devices. > Things such as USB with each device having a class code (eg, mass storage, or > human interface device) may need their own list. This would be logical as the > method for loading drivers dynamically upon a hotplug or similar event could > be quite different to that of detecting static PCI devices at boot-time. Hot > plug PCI devices are considered to be out of the scope of this proposal. No, we need to do it right. And this definitely means considering more than coldplugged PCI devices. So what I would like too see in drivers is something like this: static struct cdi_bus_data* supported_devices[] = { CDI_PCI_VENDOR_DEVICE(0x8086, 0x1230), }; static struct cdi_driver piix_driver = { .name = "piix", .devices = &supported_devices, ... } Accordingly, I would change the generated file to contain cdi_bus_data structs instead of a fixed vendor ID/device ID/name schema. > At a time defined by the OS implementing CDI, the list of PCI devices will be > iterated, and each device will be checked against the known PCI->driver list. > Should a driver be found in this list, the driver will be loaded (if not > already) and used to initialise the detected device. > > Now, this brings up a small tangent: it is my belief that driver loading could > be added to the CDI interface, as something like: > > /* Returns -1 if the driver could not be loaded, zero otherwise */ > int cdi_load_driver(const char *); > > However, this may be difficult to justify. After all, how many actual drivers > really need to load another driver? The alternative is to have the OS perform > driver loading itself, which effectively moves most of this subsystem to the > OS side (making this hardly related to CDI at all :) ) Right, I'm pretty sure that it's hard to justify. Maybe I'm missing something, so let me ask some questions: Which driver is supposed to load the right other drivers? Does that mean that automatic loading is only done by other drivers or would the OS still load some by itself? And what is the benefit of having cdi_load_driver()? Can we share any more code with it? In fact, the implementation would still be OS specific. I think we're slowly crossing to border to device initialisation here, which is what I've been thinking about a lot. I agree that drivers need some way to launch other drivers - however they should do so implicitly rather that explicitly asking for a driver name. To be precise, what drivers want to do is to say "Hey CDI, I can provide this and that device" and the CDI implementation would load the driver and call init_device() there. > So the routine at boot-time might be something like this, for a monolithic > kernel: > 1. Probe the PCI bus and develop a list of devices that are present > 2. Use this list to find drivers to load based on the PCI->driver map > 3. Load each driver, calling the necessary initialisation function for each > relevant device. > 4. (optional) Install hooks for hotplugging > > Point 4 may need explanation. The kernel will need to provide some form of > callback to be called when a new device becomes available (eg, a USB device > is plugged in). Whilst non-PCI devices are out of the scope of this initial > proposal, it cannot hurt to look into the crystal ball and add support for > future expansion. Personally, I tend to consider coldplugging some kind of hotplugging that incidentally happens at driver startup. > As an aside, this might also be a good time to mention that it might be nice > to start a wiki or something somewhere to document CDI, how to port CDI to a > new OS, and some of the optional features like the one proposed here. Yeah, maybe. I guess the problem is to find someone to write the documentation. ;-) I'm not sure what kind of documentation you are aiming for. I think we can still improve the Doxygen documentation a lot. My recent patch to add documentation for the Core module was only a start. Doxygen has one important advantage over a wiki: The documentation is inside the repository. It's always available, even if you're offline (or the server is), and I think external resources are more likely to outdate. For more high-level tutorials or such I haven't had a look yet if this can be integrated into the Doxygen documentation in a helpful way. We could consider setting up a wiki for that, or - if it's only a single tutorial - a wiki page in the osdev.org wiki. What do other people think? I'm open for suggestions. Kevin From max at tyndur.org Sat Jan 2 13:21:23 2010 From: max at tyndur.org (Max Reitz) Date: Sat, 02 Jan 2010 13:21:23 +0100 Subject: [cdi-devel] Proposed Dynamic Driver Loading System In-Reply-To: References: Message-ID: <4B3F3A43.9090605@tyndur.org> So you want to create something like a new CDI header containing a list of all available drivers or include this list in an existing header file? I think I don't like this idea a lot. There are two problems I can think of now. The first one is that I don't like the idea to put "driver-specific" stuff into "generic" CDI header files. OK, maybe there is no other way to keep it simple. But there's another problem: What about non-PCI drivers? You said they might not fit in this list. And I'm sure they won't. Apart from non-existing or non-working drivers such as USB, there are CDI drivers that won't fit in this list (in my opinion). Think of ata. It doesn't need to be a PCI device so how do you plan to start it? It would be possible to create a new list of drivers to be started always. Anyway, your list is not complete, there are also PCI drivers which are capable of handling different devices just by identifying them on their class code, subclass code and programming interface (i. e. USB host controllers). So you need to add those fields to the list (but that just by the way). But let's continue that problem about non-PCI drivers and let's have a look on those non-existing / non-working drivers. A USB device can be identified by looking on five fields (as far as I know): device ID, vendor ID, class code, subclass code, protocol ID. Hey, we're lucky, if we map the protocol ID to the PCI field "programming interface", we are able to include all USB device drivers in the PCI driver list. But, wait, it's possible that we encounter a PCI device whose fields are equal to those of a USB device. It would be wrong to load the appropriate USB device driver. So we need an additional list for USB devices. But there are also other bus drivers, i. e. Firewire. Let's make a new list for Firewire devices. See the problem? In my opinion, it's a bad idea to "hardcode" all these list types in CDI "headers". So we need a generic list at least, we need to add a field for the bus type. Then every element of the list has to contain a pointer to a bus-specific structure, for PCI its elements would be "vendor ID, device ID, base class, subclass, programming interface", for USB those elements would be named "vendor ID, device ID, class ID, subclass ID, protocol ID" and so on. But I still don't like this idea a lot... Don't know why. Maybe it's my opinion that every driver should be "self-explaining" without "help" from the Common Driver _Interface_ itself. My idea would be a new section in each CDI driver where information about its supported devices is stored. The list proposed by you would be created on every startup by scanning all available drivers or on every build of the OS. Yeah, it's the same list but it's created "on the fly", without help of CDI itself. The problem is of course that this would be slower than your proposal, but I think it to be more beautiful. :D Oh, I nearly forgot: What's about operating systems without full CDI support or such that don't need all CDI drivers? They need to remove all drivers from the list which they don't use. Hence they are unable to keep their list "in sync" with the CDI repository because they have to add every driver manually to their private list. "My" proposal (or at least brainstorming) wouldn't have that problem because drivers being not available aren't added to the list of drivers. You could also add drivers to the OS while it's running just by doing the scan again (or simply adding a new driver to the internal list as if it was found during a complete scan). I think it would be hard to complete the list proposed by you while the system is running (or we need a "hack", a basic list with all drivers available at startup and a dynamically growing list with all drivers added on runtime). From redelman at gmail.com Sat Jan 2 18:13:42 2010 From: redelman at gmail.com (Rich Edelman) Date: Sat, 2 Jan 2010 11:13:42 -0600 Subject: [cdi-devel] Proposed Dynamic Driver Loading System In-Reply-To: <20100102114646.GA20662@silvanus> References: <20100102114646.GA20662@silvanus> Message-ID: <61acd8d31001020913p581b48f8m338c1c277d7b3500@mail.gmail.com> On Sat, Jan 2, 2010 at 5:46 AM, Kevin Wolf wrote: > On Sat, Jan 02, 2010 at 04:58:39PM +1000, Matthew Iselin wrote: >> The idea is that the OS stores a map of device identifiers (at this stage the >> proposal considers the use of PCI vendor and device codes) which detail the >> name of a driver which is to be loaded if the given device is detected. This >> list may be OS-specific, or there may be a generic list provided as part of >> CDI. Either way, the OS is open to interpret the driver name as it sees fit: >> for example, appending ".o" in the case of Pedigree. >> >> This map might look something like this: >> >> /** OS-specific map of PCI identifiers -> driver names */ >> >> struct cdi_os_pci_driver_map = { >> ? ? 0x8086, 0x1230, "piix", // Vendor, Device, Driver name >> ? ? ... >> }; > > This would be an additional top-level C file, right? I don't think it's > a good idea to manually create it and keep it in sync (especially > considering that many OSes don't use all drivers), but generating such a > file looks fine to me. I also agree that such a file should be generated. It'd not be too hard to generate this list just from the drivers that were compiled, rather than containing all the drivers. >> I would like for this map to be implemented as part of CDI, in order to ensure >> that the list is kept up-to-date with drivers as they are written for CDI. >> Keeping the list in CDI also decreases the amount of work required to port CDI >> to a new OS and take advantage of these kind of features. >> >> In this early draft of the concept, there is no support for non-PCI devices. >> Things such as USB with each device having a class code (eg, mass storage, or >> human interface device) may need their own list. This would be logical as the >> method for loading drivers dynamically upon a hotplug or similar event could >> be quite different to that of detecting static PCI devices at boot-time. Hot >> plug PCI devices are considered to be out of the scope of this proposal. > > No, we need to do it right. And this definitely means considering more > than coldplugged PCI devices. So what I would like too see in drivers is > something like this: > > static struct cdi_bus_data* supported_devices[] = { > ? ?CDI_PCI_VENDOR_DEVICE(0x8086, 0x1230), > }; > > static struct cdi_driver piix_driver = { > ? ?.name = "piix", > ? ?.devices = &supported_devices, > ? ?... > } > > Accordingly, I would change the generated file to contain cdi_bus_data > structs instead of a fixed vendor ID/device ID/name schema. I'm in agreement here as well. We need to consider PCI, USB, etc all from the start. Also, using a separate struct like this would make it easier to scan through the compiled drivers and generate the mapping file as described above. >> At a time defined by the OS implementing CDI, the list of PCI devices will be >> iterated, and each device will be checked against the known PCI->driver list. >> Should a driver be found in this list, the driver will be loaded (if not >> already) and used to initialise the detected device. >> >> Now, this brings up a small tangent: it is my belief that driver loading could >> be added to the CDI interface, as something like: >> >> /* Returns -1 if the driver could not be loaded, zero otherwise */ >> int cdi_load_driver(const char *); I think this prototype is all wrong. Whatever it is that wants to load another driver needs to pass a structure that describes the device a driver is needed for. Driver's shouldn't be expected to know the name of the driver they need for another device. Sure, they can get this from the mapping file discussed previously, but I think that's wrong as well. Such a file needs to really be internal to the CDI core, and not something used by the drivers (only contributed to by the drivers). I've got some other issues with this as well, though... >> However, this may be difficult to justify. After all, how many actual drivers >> really need to load another driver? The alternative is to have the OS perform >> driver loading itself, which effectively moves most of this subsystem to the >> OS side (making this hardly related to CDI at all :) ) > > Right, I'm pretty sure that it's hard to justify. Maybe I'm missing > something, so let me ask some questions: Which driver is supposed to > load the right other drivers? Does that mean that automatic loading is > only done by other drivers or would the OS still load some by itself? > And what is the benefit of having cdi_load_driver()? Can we share any > more code with it? In fact, the implementation would still be OS > specific. > > I think we're slowly crossing to border to device initialisation here, > which is what I've been thinking about a lot. I agree that drivers need > some way to launch other drivers - however they should do so implicitly > rather that explicitly asking for a driver name. To be precise, what > drivers want to do is to say "Hey CDI, I can provide this and that > device" and the CDI implementation would load the driver and call > init_device() there. I've been thinking in terms of bus drivers here. At first I was thinking bus drivers would really be the only drivers that would use cdi_load_driver(). They would scan their bus and then tell CDI to load drivers for any devices found. I talked to Kevin on IRC about this though, and we pretty quickly agreed that bus drivers shouldn't load other drivers. This is just a hotplugging step, really. Bus drivers should just register their child devices with CDI. What is done next is left entirely up to the CDI implementation. The event count be ignored completely, it could automatically locate and load the proper driver, or it could launch a userspace program to notify the user a new device was detected. Whatever is done would be implementation specific. We just need to make sure we provide the opportunity for CDI to support hotplugging. Of course, all this relies on bus drivers. It also means we need to be able to say "stop the driver for device X" and "unregister device X". Hotplugging isn't only about plugging in new devices, it's also about correctly handling when a device suddenly disappears. > Personally, I tend to consider coldplugging some kind of hotplugging > that incidentally happens at driver startup. +1. coldplugging is really nothing other than a device that was hotplugged at boot time. :) Rich From matthew at theiselins.net Sun Jan 3 00:23:30 2010 From: matthew at theiselins.net (Matthew Iselin) Date: Sun, 3 Jan 2010 09:23:30 +1000 Subject: [cdi-devel] Proposed Dynamic Driver Loading System In-Reply-To: <61acd8d31001020913p581b48f8m338c1c277d7b3500@mail.gmail.com> References: <20100102114646.GA20662@silvanus> <61acd8d31001020913p581b48f8m338c1c277d7b3500@mail.gmail.com> Message-ID: On Sun, Jan 3, 2010 at 3:13 AM, Rich Edelman wrote: > On Sat, Jan 2, 2010 at 5:46 AM, Kevin Wolf wrote: >> On Sat, Jan 02, 2010 at 04:58:39PM +1000, Matthew Iselin wrote: >>> The idea is that the OS stores a map of device identifiers (at this stage the >>> proposal considers the use of PCI vendor and device codes) which detail the >>> name of a driver which is to be loaded if the given device is detected. This >>> list may be OS-specific, or there may be a generic list provided as part of >>> CDI. Either way, the OS is open to interpret the driver name as it sees fit: >>> for example, appending ".o" in the case of Pedigree. >>> >>> This map might look something like this: >>> >>> /** OS-specific map of PCI identifiers -> driver names */ >>> >>> struct cdi_os_pci_driver_map = { >>> ? ? 0x8086, 0x1230, "piix", // Vendor, Device, Driver name >>> ? ? ... >>> }; >> >> This would be an additional top-level C file, right? I don't think it's >> a good idea to manually create it and keep it in sync (especially >> considering that many OSes don't use all drivers), but generating such a >> file looks fine to me. > > I also agree that such a file should be generated. It'd not be too > hard to generate this list just from the drivers that were compiled, > rather than containing all the drivers. A simple script could be added and called to update the list during the build of CDI. >>> I would like for this map to be implemented as part of CDI, in order to ensure >>> that the list is kept up-to-date with drivers as they are written for CDI. >>> Keeping the list in CDI also decreases the amount of work required to port CDI >>> to a new OS and take advantage of these kind of features. >>> >>> In this early draft of the concept, there is no support for non-PCI devices. >>> Things such as USB with each device having a class code (eg, mass storage, or >>> human interface device) may need their own list. This would be logical as the >>> method for loading drivers dynamically upon a hotplug or similar event could >>> be quite different to that of detecting static PCI devices at boot-time. Hot >>> plug PCI devices are considered to be out of the scope of this proposal. >> >> No, we need to do it right. And this definitely means considering more >> than coldplugged PCI devices. So what I would like too see in drivers is >> something like this: >> >> static struct cdi_bus_data* supported_devices[] = { >> ? ?CDI_PCI_VENDOR_DEVICE(0x8086, 0x1230), >> }; >> >> static struct cdi_driver piix_driver = { >> ? ?.name = "piix", >> ? ?.devices = &supported_devices, >> ? ?... >> } >> >> Accordingly, I would change the generated file to contain cdi_bus_data >> structs instead of a fixed vendor ID/device ID/name schema. > > I'm in agreement here as well. We need to consider PCI, USB, etc all > from the start. > Also, using a separate struct like this would make it easier to scan > through the compiled drivers > and generate the mapping file as described above. I agree - simplifying the generation script is very important. >>> At a time defined by the OS implementing CDI, the list of PCI devices will be >>> iterated, and each device will be checked against the known PCI->driver list. >>> Should a driver be found in this list, the driver will be loaded (if not >>> already) and used to initialise the detected device. >>> >>> Now, this brings up a small tangent: it is my belief that driver loading could >>> be added to the CDI interface, as something like: >>> >>> /* Returns -1 if the driver could not be loaded, zero otherwise */ >>> int cdi_load_driver(const char *); > > I think this prototype is all wrong. Whatever it is that wants to load > another driver needs to pass a structure that describes the device a > driver is needed for. Driver's shouldn't be expected to know the name > of the driver they need for another device. Sure, they can get this > from the mapping file discussed previously, but I think that's wrong > as well. Such a file needs to really be internal to the CDI core, and > not something used by the drivers (only contributed to by the > drivers). Yes, this specifically is one thing I was very unsure about when I thought out the initial proposal. The main reason I brought it up was for a situation like this: 1. Plug in a USB device 2. The USB controller driver tells the OS a new device is plugged in. Now the OS needs to figure out what driver to load for the device. The `cdi_load_driver' function is certainly incorrect here, but some sort of hook in CDI to inform the OS of a new device that has been added would help here. > Of course, all this relies on bus drivers. It also means we need to be > able to say "stop the driver for device X" and "unregister device X". > Hotplugging isn't only about plugging in new devices, it's also about > correctly handling when a device suddenly disappears. Unregistering the device, yes, but perhaps not stopping the driver (which is significantly less complex). Again, hooks in CDI could provide an interface for drivers which facilitate hotplugging to notify the OS of new devices _and_ removed devices. What the OS does next is not important; what is important is that the controller notifies the OS of these events. >> Personally, I tend to consider coldplugging some kind of hotplugging >> that incidentally happens at driver startup. > > +1. coldplugging is really nothing other than a device that was > hotplugged at boot time. :) I have never seen it this way, but that's a very good way of looking at it. Thanks for the feedback! Matt From kevin at tyndur.org Sun Jan 3 00:38:59 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Sun, 3 Jan 2010 00:38:59 +0100 Subject: [cdi-devel] Proposed Dynamic Driver Loading System In-Reply-To: References: <20100102114646.GA20662@silvanus> <61acd8d31001020913p581b48f8m338c1c277d7b3500@mail.gmail.com> Message-ID: <20100102233857.GB20662@silvanus> On Sun, Jan 03, 2010 at 09:23:30AM +1000, Matthew Iselin wrote: > On Sun, Jan 3, 2010 at 3:13 AM, Rich Edelman wrote: > > On Sat, Jan 2, 2010 at 5:46 AM, Kevin Wolf wrote: > >> On Sat, Jan 02, 2010 at 04:58:39PM +1000, Matthew Iselin wrote: > >>> The idea is that the OS stores a map of device identifiers (at this stage the > >>> proposal considers the use of PCI vendor and device codes) which detail the > >>> name of a driver which is to be loaded if the given device is detected. This > >>> list may be OS-specific, or there may be a generic list provided as part of > >>> CDI. Either way, the OS is open to interpret the driver name as it sees fit: > >>> for example, appending ".o" in the case of Pedigree. > >>> > >>> This map might look something like this: > >>> > >>> /** OS-specific map of PCI identifiers -> driver names */ > >>> > >>> struct cdi_os_pci_driver_map = { > >>> ? ? 0x8086, 0x1230, "piix", // Vendor, Device, Driver name > >>> ? ? ... > >>> }; > >> > >> This would be an additional top-level C file, right? I don't think it's > >> a good idea to manually create it and keep it in sync (especially > >> considering that many OSes don't use all drivers), but generating such a > >> file looks fine to me. > > > > I also agree that such a file should be generated. It'd not be too > > hard to generate this list just from the drivers that were compiled, > > rather than containing all the drivers. > > A simple script could be added and > called to update the list during the build of CDI. Actually I think C would be the right tool. Link all object files in the whole tree together and add a small main() function that enumerates all the drivers in it. All the parsing is done by the compiler. > >>> At a time defined by the OS implementing CDI, the list of PCI devices will be > >>> iterated, and each device will be checked against the known PCI->driver list. > >>> Should a driver be found in this list, the driver will be loaded (if not > >>> already) and used to initialise the detected device. > >>> > >>> Now, this brings up a small tangent: it is my belief that driver loading could > >>> be added to the CDI interface, as something like: > >>> > >>> /* Returns -1 if the driver could not be loaded, zero otherwise */ > >>> int cdi_load_driver(const char *); > > > > I think this prototype is all wrong. Whatever it is that wants to load > > another driver needs to pass a structure that describes the device a > > driver is needed for. Driver's shouldn't be expected to know the name > > of the driver they need for another device. Sure, they can get this > > from the mapping file discussed previously, but I think that's wrong > > as well. Such a file needs to really be internal to the CDI core, and > > not something used by the drivers (only contributed to by the > > drivers). > > Yes, this specifically is one thing I was very unsure about when I > thought out the initial proposal. The main reason I brought it up was > for a situation like this: > 1. Plug in a USB device > 2. The USB controller driver tells the OS a new device is plugged in. > Now the OS needs to figure out what driver to load for the device. > The `cdi_load_driver' function is certainly incorrect here, but some > sort of hook in CDI to inform the OS of a new device that has been > added would help here. Right, we're mostly complete on the device driver side, but the bus driver side (providing/removing devices) is completely missing. However, we seem to agree that this is the right interface for loading drivers, so maybe the next step would be specifying the bus driver interface. Actually, I think's quite boring. Some cdi_provide_device(struct cdi_bus_addr*), a function for removing (probably takes the cdi_bus_addr again?) and we're done. Finding good names might be the most difficult thing in it. ;-) Kevin From matthew at theiselins.net Sun Jan 3 01:27:53 2010 From: matthew at theiselins.net (Matthew Iselin) Date: Sun, 3 Jan 2010 10:27:53 +1000 Subject: [cdi-devel] Proposed Dynamic Driver Loading System In-Reply-To: <20100102233857.GB20662@silvanus> References: <20100102114646.GA20662@silvanus> <61acd8d31001020913p581b48f8m338c1c277d7b3500@mail.gmail.com> <20100102233857.GB20662@silvanus> Message-ID: On Sun, Jan 3, 2010 at 9:38 AM, Kevin Wolf wrote: > On Sun, Jan 03, 2010 at 09:23:30AM +1000, Matthew Iselin wrote: >> On Sun, Jan 3, 2010 at 3:13 AM, Rich Edelman wrote: >> > On Sat, Jan 2, 2010 at 5:46 AM, Kevin Wolf wrote: >> >> On Sat, Jan 02, 2010 at 04:58:39PM +1000, Matthew Iselin wrote: >> >>> The idea is that the OS stores a map of device identifiers (at this stage the >> >>> proposal considers the use of PCI vendor and device codes) which detail the >> >>> name of a driver which is to be loaded if the given device is detected. This >> >>> list may be OS-specific, or there may be a generic list provided as part of >> >>> CDI. Either way, the OS is open to interpret the driver name as it sees fit: >> >>> for example, appending ".o" in the case of Pedigree. >> >>> >> >>> This map might look something like this: >> >>> >> >>> /** OS-specific map of PCI identifiers -> driver names */ >> >>> >> >>> struct cdi_os_pci_driver_map = { >> >>> ? ? 0x8086, 0x1230, "piix", // Vendor, Device, Driver name >> >>> ? ? ... >> >>> }; >> >> >> >> This would be an additional top-level C file, right? I don't think it's >> >> a good idea to manually create it and keep it in sync (especially >> >> considering that many OSes don't use all drivers), but generating such a >> >> file looks fine to me. >> > >> > I also agree that such a file should be generated. It'd not be too >> > hard to generate this list just from the drivers that were compiled, >> > rather than containing all the drivers. >> >> A simple script could be added and >> called to update the list during the build of CDI. > > Actually I think C would be the right tool. Link all object files in the whole > tree together and add a small main() function that enumerates all the drivers > in it. All the parsing is done by the compiler. Hm, good point. A little more complicated, but also comes with the bonus of needing no new dependency on Perl or Python or . >> >>> At a time defined by the OS implementing CDI, the list of PCI devices will be >> >>> iterated, and each device will be checked against the known PCI->driver list. >> >>> Should a driver be found in this list, the driver will be loaded (if not >> >>> already) and used to initialise the detected device. >> >>> >> >>> Now, this brings up a small tangent: it is my belief that driver loading could >> >>> be added to the CDI interface, as something like: >> >>> >> >>> /* Returns -1 if the driver could not be loaded, zero otherwise */ >> >>> int cdi_load_driver(const char *); >> > >> > I think this prototype is all wrong. Whatever it is that wants to load >> > another driver needs to pass a structure that describes the device a >> > driver is needed for. Driver's shouldn't be expected to know the name >> > of the driver they need for another device. Sure, they can get this >> > from the mapping file discussed previously, but I think that's wrong >> > as well. Such a file needs to really be internal to the CDI core, and >> > not something used by the drivers (only contributed to by the >> > drivers). >> >> Yes, this specifically is one thing I was very unsure about when I >> thought out the initial proposal. The main reason I brought it up was >> for a situation like this: >> 1. Plug in a USB device >> 2. The USB controller driver tells the ?OS a new device is plugged in. >> Now the OS needs to figure out what driver to load for the device. >> The `cdi_load_driver' function is certainly incorrect here, but some >> sort of hook in CDI to inform the OS of a new device that has been >> added would help here. > > Right, we're mostly complete on the device driver side, but the bus > driver side (providing/removing devices) is completely missing. However, > we seem to agree that this is the right interface for loading drivers, > so maybe the next step would be specifying the bus driver interface. And so the fun begins ;) > Actually, I think's quite boring. Some cdi_provide_device(struct > cdi_bus_addr*), a function for removing (probably takes the cdi_bus_addr > again?) and we're done. Right, this is kind of what I was thinking of when I considered the feedback given to the original proposal. The question is: can a USB device be fully... explained, I guess, in a cdi_bus_addr? What about Firewire? Max raises an excellent point in his mail; I don't understand cdi_bus_addr enough yet to comment on whether or not it suffices for these purposes. If a cdi_bus_addr struct can describe the wider range of potential devices (and therefore drivers), this will not be a problem. > Finding good names might be the most difficult thing in it. ;-) One can only hope ;) Also, apologies for any duplicate emails... My connection is quite temperamental and may tell me the mail did not get sent, when in fact it did, so I re-send the mail. Just ignore multiple copies of the same message. Cheers, Matt From kevin at tyndur.org Sun Jan 3 11:33:02 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Sun, 3 Jan 2010 11:33:02 +0100 Subject: [cdi-devel] Proposed Dynamic Driver Loading System In-Reply-To: References: <20100102114646.GA20662@silvanus> <61acd8d31001020913p581b48f8m338c1c277d7b3500@mail.gmail.com> <20100102233857.GB20662@silvanus> Message-ID: <20100103103300.GA509@silvanus> On Sun, Jan 03, 2010 at 10:27:53AM +1000, Matthew Iselin wrote: > On Sun, Jan 3, 2010 at 9:38 AM, Kevin Wolf wrote: > > On Sun, Jan 03, 2010 at 09:23:30AM +1000, Matthew Iselin wrote: > >> A simple script could be added and > >> called to update the list during the build of CDI. > > > > Actually I think C would be the right tool. Link all object files in the whole > > tree together and add a small main() function that enumerates all the drivers > > in it. All the parsing is done by the compiler. > > Hm, good point. A little more complicated, but also comes with the > bonus of needing no new dependency on Perl or Python or scripting language here>. Hm, I was just missing that driver enumeration is OS specific. So with this approach we wouldn't be able to share the tool (unless you want to compile everything twice: once for the OS and once with a different cdi-osdep.h for the generation of this list). I'm not even sure that all OSes want to have the list in the same format, so probably it's better anyway if we only describe how you can do it and leave it to the CDI implementations. > > Actually, I think's quite boring. Some cdi_provide_device(struct > > cdi_bus_addr*), a function for removing (probably takes the cdi_bus_addr > > again?) and we're done. > > Right, this is kind of what I was thinking of when I considered the > feedback given to the original proposal. > > The question is: can a USB device be fully... explained, I guess, in a > cdi_bus_addr? What about Firewire? Max raises an excellent point in > his mail; I don't understand cdi_bus_addr enough yet to comment on > whether or not it suffices for these purposes. If a cdi_bus_addr > struct can describe the wider range of potential devices (and > therefore drivers), this will not be a problem. It's the same question as asking if a USB device state can be fully explained in a cdi_device. Consider it a base class, so the USB module would extend it, of course. This is why my table consists of pointers instead of directly putting the data there - it's not a static size. Kevin From matthew at theiselins.net Sun Jan 3 11:48:33 2010 From: matthew at theiselins.net (Matthew Iselin) Date: Sun, 3 Jan 2010 20:48:33 +1000 Subject: [cdi-devel] Proposed Dynamic Driver Loading System In-Reply-To: <20100103103300.GA509@silvanus> References: <20100102114646.GA20662@silvanus> <61acd8d31001020913p581b48f8m338c1c277d7b3500@mail.gmail.com> <20100102233857.GB20662@silvanus> <20100103103300.GA509@silvanus> Message-ID: On Sun, Jan 3, 2010 at 8:33 PM, Kevin Wolf wrote: > On Sun, Jan 03, 2010 at 10:27:53AM +1000, Matthew Iselin wrote: >> On Sun, Jan 3, 2010 at 9:38 AM, Kevin Wolf wrote: >> > On Sun, Jan 03, 2010 at 09:23:30AM +1000, Matthew Iselin wrote: >> >> A simple script could be added and >> >> called to update the list during the build of CDI. >> > >> > Actually I think C would be the right tool. Link all object files in the whole >> > tree together and add a small main() function that enumerates all the drivers >> > in it. All the parsing is done by the compiler. >> >> Hm, good point. A little more complicated, but also comes with the >> bonus of needing no new dependency on Perl or Python or > scripting language here>. > > Hm, I was just missing that driver enumeration is OS specific. So with > this approach we wouldn't be able to share the tool (unless you want to > compile everything twice: once for the OS and once with a different > cdi-osdep.h for the generation of this list). I'm not even sure that all > OSes want to have the list in the same format, so probably it's better > anyway if we only describe how you can do it and leave it to the CDI > implementations. Right, leaving the method for list generation up to the implementation is an easy way to get out of that tough problem ;) Seriously though, this is a good idea, as it gives the implementor significantly more power over the format of the data in this list (and therefore can implement their hotplug handling in the most effective manner for that OS, using the data in their own format). >> > Actually, I think's quite boring. Some cdi_provide_device(struct >> > cdi_bus_addr*), a function for removing (probably takes the cdi_bus_addr >> > again?) and we're done. >> >> Right, this is kind of what I was thinking of when I considered the >> feedback given to the original proposal. >> >> The question is: can a USB device be fully... explained, I guess, in a >> cdi_bus_addr? What about Firewire? Max raises an excellent point in >> his mail; I don't understand cdi_bus_addr enough yet to comment on >> whether or not it suffices for these purposes. If a cdi_bus_addr >> struct can describe the wider range of potential devices (and >> therefore drivers), this will not be a problem. > > It's the same question as asking if a USB device state can be fully > explained in a cdi_device. Consider it a base class, so the USB module > would extend it, of course. This is why my table consists of pointers > instead of directly putting the data there - it's not a static size. I understand. I think we are reaching the stage where we need to now determine a proper interface and define the requirements of the OS in order to support this kind of behaviour. In other words, take the results of this discussion and turn them into a proper design for the feature. Up to you though, if you feel more discussion is necessary, then by all means, let us discuss this further. :) Cheers, Matt From kevin at tyndur.org Sun Jan 3 12:24:09 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Sun, 3 Jan 2010 12:24:09 +0100 Subject: [cdi-devel] Proposed Dynamic Driver Loading System In-Reply-To: References: <20100102114646.GA20662@silvanus> <61acd8d31001020913p581b48f8m338c1c277d7b3500@mail.gmail.com> <20100102233857.GB20662@silvanus> <20100103103300.GA509@silvanus> Message-ID: <20100103112409.GB509@silvanus> On Sun, Jan 03, 2010 at 08:48:33PM +1000, Matthew Iselin wrote: > On Sun, Jan 3, 2010 at 8:33 PM, Kevin Wolf wrote: > > On Sun, Jan 03, 2010 at 10:27:53AM +1000, Matthew Iselin wrote: > >> On Sun, Jan 3, 2010 at 9:38 AM, Kevin Wolf wrote: > >> > On Sun, Jan 03, 2010 at 09:23:30AM +1000, Matthew Iselin wrote: > >> >> A simple script could be added and > >> >> called to update the list during the build of CDI. > >> > > >> > Actually I think C would be the right tool. Link all object files in the whole > >> > tree together and add a small main() function that enumerates all the drivers > >> > in it. All the parsing is done by the compiler. > >> > >> Hm, good point. A little more complicated, but also comes with the > >> bonus of needing no new dependency on Perl or Python or >> scripting language here>. > > > > Hm, I was just missing that driver enumeration is OS specific. So with > > this approach we wouldn't be able to share the tool (unless you want to > > compile everything twice: once for the OS and once with a different > > cdi-osdep.h for the generation of this list). I'm not even sure that all > > OSes want to have the list in the same format, so probably it's better > > anyway if we only describe how you can do it and leave it to the CDI > > implementations. > > Right, leaving the method for list generation up to the implementation > is an easy way to get out of that tough problem ;) Right, I know I'm a genius. ;-) > I think we are reaching the stage where we need to now determine a > proper interface and define the requirements of the OS in order to > support this kind of behaviour. In other words, take the results of > this discussion and turn them into a proper design for the feature. Up > to you though, if you feel more discussion is necessary, then by all > means, let us discuss this further. :) I'm happy with what we've discussed. I'm even happier that we seem to be all on the same page, as Rich already said yesterday. Unless Rich or Max have objections, let's move forward with patches. Kevin From max at tyndur.org Sun Jan 3 12:34:53 2010 From: max at tyndur.org (Max Reitz) Date: Sun, 03 Jan 2010 12:34:53 +0100 Subject: [cdi-devel] Proposed Dynamic Driver Loading System In-Reply-To: <20100103103300.GA509@silvanus> References: <20100102114646.GA20662@silvanus> <61acd8d31001020913p581b48f8m338c1c277d7b3500@mail.gmail.com> <20100102233857.GB20662@silvanus> <20100103103300.GA509@silvanus> Message-ID: <4B4080DD.9060107@tyndur.org> Kevin Wolf wrote: > On Sun, Jan 03, 2010 at 10:27:53AM +1000, Matthew Iselin wrote: >> On Sun, Jan 3, 2010 at 9:38 AM, Kevin Wolf wrote: >>> On Sun, Jan 03, 2010 at 09:23:30AM +1000, Matthew Iselin wrote: >>>> A simple script could be added and >>>> called to update the list during the build of CDI. >>> Actually I think C would be the right tool. Link all object files in the whole >>> tree together and add a small main() function that enumerates all the drivers >>> in it. All the parsing is done by the compiler. >> Hm, good point. A little more complicated, but also comes with the >> bonus of needing no new dependency on Perl or Python or > scripting language here>. > > Hm, I was just missing that driver enumeration is OS specific. So with > this approach we wouldn't be able to share the tool (unless you want to > compile everything twice: once for the OS and once with a different > cdi-osdep.h for the generation of this list). I'm not even sure that all > OSes want to have the list in the same format, so probably it's better > anyway if we only describe how you can do it and leave it to the CDI > implementations. Just wanted to say that this is also what I proposed to do but my mail seems to be too long to be readable and answerable. ;-) (I proposed to scan all the available drivers either on startup of the system or after everything is built and to create a list of drivers which would be driver-specific and... > [...] > This is why my table consists of pointers instead of directly putting > the data there - it's not a static size. ...which would contain pointers to bus-specific structures. Yes, it's a good idea to use the cdi_bus_data structure here.) Max aka XanClic From kevin at tyndur.org Mon Jan 4 20:55:30 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Mon, 4 Jan 2010 20:55:30 +0100 Subject: [cdi-devel] [PATCH 0/5] Forward ported USB patches Message-ID: <1262634935-24109-1-git-send-email-kevin@tyndur.org> These are Max' USB patches rebased on the latest CDI Core changes. Only compile tested on Linux. Max Reitz (5): CDI.usb, CDI.usb-hcd OHCI UHCI USB 1.1 USB MSD include/cdi/usb-hcd.h | 178 +++++++++ include/cdi/usb.h | 868 ++++++++++++++++++++++++++++++++++++++++++ ohci/hcd.c | 307 +++++++++++++++ ohci/include/ohci-hcd.h | 35 ++ ohci/include/ohci-init.h | 31 ++ ohci/include/ohci-transfer.h | 30 ++ ohci/include/ohci.h | 283 ++++++++++++++ ohci/init.c | 236 ++++++++++++ ohci/transfer.c | 85 ++++ uhci/hcd.c | 207 ++++++++++ uhci/include/uhci-hcd.h | 35 ++ uhci/include/uhci-init.h | 31 ++ uhci/include/uhci-transfer.h | 30 ++ uhci/include/uhci.h | 138 +++++++ uhci/init.c | 242 ++++++++++++ uhci/transfer.c | 91 +++++ usb-msd/include/msd.h | 121 ++++++ usb-msd/main.c | 68 ++++ usb-msd/msd.c | 485 +++++++++++++++++++++++ usb11/control.c | 252 ++++++++++++ usb11/include/control.h | 31 ++ usb11/include/transfer.h | 38 ++ usb11/include/usb-structs.h | 184 +++++++++ usb11/include/usb11.h | 41 ++ usb11/main.c | 58 +++ usb11/transfer.c | 223 +++++++++++ 26 files changed, 4328 insertions(+), 0 deletions(-) create mode 100644 include/cdi/usb-hcd.h create mode 100644 include/cdi/usb.h create mode 100644 ohci/hcd.c create mode 100644 ohci/include/ohci-hcd.h create mode 100644 ohci/include/ohci-init.h create mode 100644 ohci/include/ohci-transfer.h create mode 100644 ohci/include/ohci.h create mode 100644 ohci/init.c create mode 100644 ohci/transfer.c create mode 100644 uhci/hcd.c create mode 100644 uhci/include/uhci-hcd.h create mode 100644 uhci/include/uhci-init.h create mode 100644 uhci/include/uhci-transfer.h create mode 100644 uhci/include/uhci.h create mode 100644 uhci/init.c create mode 100644 uhci/transfer.c create mode 100644 usb-msd/include/msd.h create mode 100644 usb-msd/main.c create mode 100644 usb-msd/msd.c create mode 100644 usb11/control.c create mode 100644 usb11/include/control.h create mode 100644 usb11/include/transfer.h create mode 100644 usb11/include/usb-structs.h create mode 100644 usb11/include/usb11.h create mode 100644 usb11/main.c create mode 100644 usb11/transfer.c From kevin at tyndur.org Mon Jan 4 20:55:31 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Mon, 4 Jan 2010 20:55:31 +0100 Subject: [cdi-devel] [PATCH 1/5] CDI.usb, CDI.usb-hcd In-Reply-To: <1262634935-24109-1-git-send-email-kevin@tyndur.org> References: <1262634935-24109-1-git-send-email-kevin@tyndur.org> Message-ID: <1262634935-24109-2-git-send-email-kevin@tyndur.org> From: Max Reitz + Added CDI.usb header + Added CDI.usb-hcd header Signed-off-by: Max Reitz Signed-off-by: Kevin Wolf --- include/cdi/usb-hcd.h | 178 ++++++++++ include/cdi/usb.h | 868 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1046 insertions(+), 0 deletions(-) create mode 100644 include/cdi/usb-hcd.h create mode 100644 include/cdi/usb.h diff --git a/include/cdi/usb-hcd.h b/include/cdi/usb-hcd.h new file mode 100644 index 0000000..60b0a01 --- /dev/null +++ b/include/cdi/usb-hcd.h @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2009 Max Reitz + * + * This program is free software. It comes without any warranty, to + * the extent permitted by applicable law. You can redistribute it + * and/or modify it under the terms of the Do What The Fuck You Want + * To Public License, Version 2, as published by Sam Hocevar. See + * http://sam.zoy.org/projects/COPYING.WTFPL for more details. + */ + +/** + * \if german + * USB-Hostcontrollertreiber + * \elseif english + * USB host controller drivers + * \endif + * \defgroup USBHCD + */ +/*\@{*/ + +#ifndef _CDI_USB_HCD_H_ +#define _CDI_USB_HCD_H_ + +#include "cdi/misc.h" +#include "cdi/usb.h" + +struct cdi_usb_hc { + struct cdi_device dev; + + /** + * \if german + * USB-Geschwindigkeit + * \elseif english + * USB speed + * \endif + */ + cdi_usb_speed_t speed; +}; + +struct cdi_usb_hcd { + struct cdi_driver drv; + + /** + * \if german + * + * Listet alle Geraete auf, die an den Rootports haengen und ruft ggf. + * cdi_usb_device_init auf + * + * @param device Der Hostcontroller + * + * \elseif english + * + * Lists all devices hanging at the root ports and calls (if necessary) + * cdi_usb_device_init + * + * @param device The host controller + * + * \endif + */ + void (*find_devices)(struct cdi_usb_hc* device); + + /** + * \if german + * + * Aktiviert den zum angegebenen Geraet gehoerigen Rootport + * + * @param usb_device Das USB-Geraet (muss an einem Rootport haengen) + * + * \elseif english + * + * Activates the root port corresponding to the device + * + * @param usb_device The USB device (must be located at a root port) + * + * \endif + */ + void (*activate_device)(struct cdi_usb_device* usb_device); + + /** + * \if german + * + * Verarbeitet USB-Pakete + * + * @param packets Array zu sendender Pakete + * @param num_packets Anzahl der Pakete + * + * @return Gibt den Status an (z. B. USB_NO_ERROR fuer keinen Fehler) + * + * \elseif english + * + * Sends USB packets + * + * @param packets Array of packages to be sent + * @param num_packages Number of packages + * + * \endif + */ + cdi_usb_status_t (*send_packets)(struct cdi_usb_packet* packets, + size_t num_packets); + + /** + * \if german + * + * Erstellt eine neue Pipe + * + * @param pipe Die Pipe + * + * \elseif english + * + * Creates a new pipe + * + * @param pipe The pipe + * + * \endif + */ + void (*add_pipe)(struct cdi_usb_pipe* pipe); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \if german + * + * Initialisiert einen HCD + * + * @param driver Der HCD + * + * \elseif english + * + * Initializes an HCD + * + * @param driver The HCD + * + * \endif + */ +void cdi_usb_hcd_init(struct cdi_usb_hcd* driver); + +/** + * \if german + * + * Gibt einen HCD frei + * + * @param driver Freizugebender HCD + * + * \elseif english + * + * Removes an HCD + * + * @param driver HCD to be removed + * + * \endif + */ +void cdi_usb_hcd_destroy(struct cdi_usb_hcd* driver); + +/** + * \if german + * + * Registriert einen HCD + * + * @param driver Zu registrierender HCD + * + * \elseif english + * + * Registers an HCD + * + * @param driver HCD to be registered + * + * \endif + */ +void cdi_usb_hcd_register(struct cdi_usb_hcd* driver); + +#ifdef __cplusplus +} //extern "C" +#endif + +#endif diff --git a/include/cdi/usb.h b/include/cdi/usb.h new file mode 100644 index 0000000..54ce1a0 --- /dev/null +++ b/include/cdi/usb.h @@ -0,0 +1,868 @@ +/* + * Copyright (c) 2009 Max Reitz + * + * This program is free software. It comes without any warranty, to + * the extent permitted by applicable law. You can redistribute it + * and/or modify it under the terms of the Do What The Fuck You Want + * To Public License, Version 2, as published by Sam Hocevar. See + * http://sam.zoy.org/projects/COPYING.WTFPL for more details. + */ + +/** + * \if german + * USB-Bustreiber + * \elseif english + * USB bus drivers + * \endif + * \defgroup USB + */ +/*\@{*/ + +#ifndef _CDI_USB_H_ +#define _CDI_USB_H_ + +#include "stddef.h" +#include "stdint.h" + +typedef enum { + /// Low-Speed (1,5 Mbit/s) + CDI_USB_LOW_SPEED = 0x01, + /// Full-Speed (12 Mbit/s) + CDI_USB_FULL_SPEED = 0x02, + /// High-Speed (480 Mbit/s) + CDI_USB_HIGH_SPEED = 0x04, + /// SuperSpeed (5 Gbit/s) + CDI_USB_SUPER_SPEED = 0x08, +} cdi_usb_speed_t; + +typedef enum { + /** + * \if german + * SETUP-Paket + * \elseif english + * SETUP packet + * \endif + */ + CDI_USB_PACKET_SETUP = 0x2D, + + /** + * \if german + * Daten vom Geraet zum Host + * \elseif english + * Data from the device to the host + * \endif + */ + CDI_USB_PACKET_IN = 0x69, + + /** + * \if german + * Daten vom Host zum Geraet + * \elseif english + * Data from the host to the device + * \endif + */ + CDI_USB_PACKET_OUT = 0xE1, +} cdi_usb_packet_type_t; + +typedef enum { + /** + * \if german + * Kein Fehler + * \elseif english + * No error + * \endif + */ + CDI_USB_NO_ERROR = 0x0000, + + /// Stalled + CDI_USB_STALLED = 0x0001, + + /** + * \if german + * Bufferfehler (Overflow, underrun, ...) + * \elseif english + * Buffer error (overflow, underrun, ...) + * \endif + */ + CDI_USB_BUFFER_ERROR = 0x0002, + + /** + * \if german + * Babble (Geraet hat zu viele Daten gesendet) + * \elseif english + * Babble (device has sent more data than expected) + * \endif + */ + CDI_USB_BABBLE = 0x0004, + + /** + * \if german + * NAK (Daten sind erneut zu senden) + * \elseif english + * NAK (data has to be sent again) + * \endif + */ + CDI_USB_NAK = 0x0008, + + /** + * \if german + * CRC-Fehler + * \elseif english + * CRC error + * \endif + */ + CDI_USB_CRC = 0x0010, + + /// Timeout + CDI_USB_TIMEOUT = 0x0020, + + /** + * \if german + * Bitstuff/-destuff-Fehler + * \elseif english + * bitstuff/-destuff error + * \endif + */ + CDI_USB_BITSTUFF = 0x0040, + + /** + * \if german + * Reservieren von Speicher fehlgeschlagen, ... + * \elseif english + * Allocating of memory failed, ... + * \endif + */ + CDI_USB_TRIVIAL_ERROR = 0x0080, +} cdi_usb_status_t; + +struct cdi_usb_hc; +struct cdi_usb_pipe; +struct cdi_usb_interface; +struct cdi_usb_driver; + +struct cdi_usb_device { + /** + * \if german + * Der USB-Bustreiber + * \elseif english + * The USB bus driver + * \endif + */ + struct cdi_usb_driver* drv; + + /** + * \if german + * Der Hostcontroller, an dem das Geraet im Endeffekt haengt + * \elseif english + * The host controller where the device is eventually located + * \endif + */ + struct cdi_usb_hc* hc; + + /** + * \if german + * Haengt das Geraet an einem Hub, dann ist dieses Feld ein Pointer auf + * das entsprechende USB-Geraet, haengt es an einem Rootport, dann ist + * dieses Feld NULL. + * \elseif english + * If the device is located at a hub, then this field contains a pointer to + * the corresponding USB device, if it's located at a root port, then this + * field is set to NULL. + * \endif + */ + struct cdi_usb_device* hub; + + /** + * \if german + * Geschwindigkeit(-en) dieses Geraets + * \elseif english + * Speed(-s) supported by this device + * \endif + */ + cdi_usb_speed_t speed; + + /// ID + int id; + + /** + * \if german + * Entweder der Rootport oder der Port des Hubs, an dem das Geraet haengt + * \elseif english + * Either the root port or the port hub's port where the device is located + * \endif + */ + int port; + + /** + * \if german + * Hier darf der Geraetetreiber seine Daten unterbringen + * \elseif english + * The device driver may store its data here + * \endif + */ + void* driver_data; + + /** + * \if german + * Felder, die so auch bei PCI existieren: Vendor-, Device-, Class-, + * Subclass- und Protocol-ID + * \elseif english + * Fields existing at PCI, too: vendor, device, class, subclass and + * protocol ID. + * \endif + */ + int vendor_id; + int device_id; + int class_id; + int subclass_id; + int protocol_id; + + /** + * \if german + * + * Setzt das USB-Geraet zurueck (kann sowohl vom HCD als auch vom Hub + * driver ausgefuehrt werden) + * + * @param usb_device Das Geraet + * + * \elseif english + * + * Resets the USB device (may be executed either by the HCD or the hub + * driver) + * + * @param usb_device The device + * + * \endif + */ + void (*reset)(struct cdi_usb_device* usb_device); + + /** + * \if german + * Ziemlich lowlevelig. Gehoert das hier wirklich rein? + * \elseif english + * Very low level. Does it really fit in here? + * \endif + */ + + /** + * \if german + * Im einzelnen sind das: Pipe fuer Endpoint 0 + * \elseif english + * In particular these things are: Pipe for endpoint 0 + * \endif + */ + struct cdi_usb_pipe* ep0; + + /// Device descriptor + void* device_desc; + + /// Configuration descriptor + void* config_desc; + + /// Interface descriptor + struct cdi_usb_interface* interface_desc; + + /// Class descriptor + void* class_desc; +}; + +enum cdi_usb_toggle { + /** + * \if german + * Das Toggle nehmen, das jetzt dran ist + * \elseif english + * Use the toggle to be used right now + * \endif + */ + TOGGLE_UNSPECIFIC = 0, + + /** + * \if german + * Geloeschtes Togglebit erzwingen + * \elseif english + * Force unset toggle bit + * \endif + */ + TOGGLE_0 = 1, + + /** + * \if german + * Gesetztes Togglebit erzwingen + * \elseif english + * Force set toggle bit + * \endif + */ + TOGGLE_1 = 2 +}; + +struct cdi_usb_endpoint { + /// sizeof(struct cdi_usb_endpoint) + uint8_t length; + + /// 5 + uint8_t descriptor_type; + + /** + * \if german + * Nummer des Endpoints + * \elseif english + * Endpoint's number + * \endif + */ + uint8_t endpoint_address; + + /** + * \if german + * Eigenschaften (IN/OUT, Bulk/Interrupt/..., ...) + * \elseif english + * Attributes (IN/OUT, bulk/interrupt/..., ...) + * \endif + */ + uint8_t attributes; + + /** + * \if german + * Maximale Paketgroesse in Bytes + * \elseif english + * Maximum packet size in bytes + * \endif + */ + uint16_t max_packet_size; + + /// ??? + uint8_t interval; +} __attribute__((packed)); + +struct cdi_usb_interface { + /// sizeof(struct cdi_usb_interface) + uint8_t length; + + /// 4 + uint8_t descriptor_type; + + /** + * \if german + * Nummer des Interface + * \elseif english + * Interface's number + * \endif + */ + uint8_t interface_number; + + /// ??? + uint8_t alternate_setting; + + /** + * \if german + * Anzahl der Endpoints fuer dieses Interface + * \elseif english + * Number of endpoints for this interface + * \endif + */ + uint8_t num_endpoints; + + /** + * \if german + * Class-ID (bei Composite Devices) + * \elseif english + * Class ID (used with composite devices) + * \endif + */ + uint8_t interface_class; + + /// Subclass-ID + uint8_t interface_subclass; + + /// Protocol-ID + uint8_t interface_protocol; + + /** + * \if german + * String-Index, der das Interface beschreibt + * \elseif english + * String index describing the interface + * \endif + */ + uint8_t iInterface; +} __attribute__((packed)); + +/** + * \if german + * Beschreibt eine Pipe + * \elseif english + * Describes a pipe + * \endif + */ +struct cdi_usb_pipe { + /** + * \if german + * Ziel + * \elseif english + * Destination + * \endif + */ + struct cdi_usb_device* device; + + /** + * \if german + * Ein Pointer auf eine den Endpoint beschreibende Struktur + * TODO Das ist eigentlich auch sehr lowlevelig. + * \elseif english + * A pointer to a structure describing the endpoint + * TODO This is on a very low level, too. + */ + struct cdi_usb_endpoint* endpoint; + + /// Data-Toggle + int data_toggle; +}; + +/** + * \if german + * Beschreibt ein USB-Paket + * \elseif english + * Describes a USB packet + * \endif + */ +struct cdi_usb_packet { + /** + * \if german + * Die gewuenschte Pipe + * \elseif english + * The desired pipe + * \endif + */ + struct cdi_usb_pipe* pipe; + + /** + * \if german + * Der Typ des Pakets (PACKET_IN, PACKET_OUT, PACKET_SETUP) + * \elseif english + * Type of packet (PACKET_IN, PACKET_OUT, PACKET_SETUP) + * \endif + */ + cdi_usb_packet_type_t type; + + /** + * \if german + * Zeiger auf den Datenpuffer + * \elseif english + * Pointer to the data buffer + * \endif + */ + void* data; + + /** + * \if german + * Die Laenge des Puffers + * \elseif english + * The buffer's length + * \endif + */ + size_t length; + + /** + * \if german + * Fehlertyp (oder USB_NO_ERROR) + * \elseif english + * Error type (or USB_NO_ERROR) + * \endif + */ + cdi_usb_status_t condition; + + /** + * \if german + * Bestimmtes Data-Toggle benuten + * \elseif english + * Use specific data toggle + * \endif + */ + enum cdi_usb_toggle use_toggle; +}; + +typedef enum { + /** + * \if german + * Host -> Geraet + * \elseif english + * Host -> device + * \endif + */ + CDI_USB_CONTROL_OUT = 0x00, + + /** + * \if german + * Geraet -> Host + * \elseif english + * Device -> host + * \endif + */ + CDI_USB_CONTROL_IN = 0x80 +} cdi_usb_control_direction_t; + +typedef enum { + /** + * \if german + * Standard-Request + * \elseif english + * Standard request + * \endif + */ + CDI_USB_CONTROL_RQ_STANDARD = 0x00, + + /** + * \if german + * Klassenspezifischer Request + * \elseif english + * Class specific request + * \endif + */ + CDI_USB_CONTROL_RQ_CLASS = 0x20, + + /** + * \if german + * Herstellerspezifischer Request + * \elseif english + * Vendor specific request + * \endif + */ + CDI_USB_CONTROL_RQ_VENDOR = 0x40 +} cdi_usb_control_request_type_t; + +typedef enum { + /** + * \if german + * Empfaenger: Geraet + * \elseif english + * Recipient: device + * \endif + */ + CDI_USB_CONTROL_REC_DEVICE = 0x00, + + /** + * \if german + * Empfaenger: Interface + * \elseif english + * Recipient: interface + * \endif + */ + CDI_USB_CONTROL_REC_INTERFACE = 0x01, + + /** + * \if german + * Empfaenger: Endpoint + * \elseif english + * Recipient: endpoint + * \endif + */ + CDI_USB_CONTROL_REC_ENDPOINT = 0x02, + + /** + * \if german + * Empfaenger ist jemand anderes + * \elseif english + * Recipient is another one + * \endif + */ + CDI_USB_CONTROL_REC_OTHER = 0x03 +} cdi_usb_control_recipient_t; + +struct cdi_usb_control_transfer { + /** + * \if german + * Wenn Daten zum Geraet gesendet werden sollen, dann ist hier der + * Speicherbereich anzugeben + * \elseif english + * If data has to be sent to the device, then the memory buffer has to be + * given here + * \endif + */ + void* buffer; + + /** + * \if german + * Laenge der erwarteten bzw. zu sendenden Daten + * \elseif english + * Length of the expected data respectively the data to be sent + * \endif + */ + size_t length; + + /** + * \if german + * Richtung + * \elseif english + * Direction + * \endif + */ + cdi_usb_control_direction_t direction; + + /** + * \if german + * Art des Requests (Standardrequest, klassenspezifisch, + * herstellerspezifisch) + * \elseif english + * Request type (standard request, class specific, vendor specific) + * \endif + */ + cdi_usb_control_request_type_t rtype; + + /** + * \if german + * Ziel (Device, Interface, Endpoint, anderes) + * \elseif english + * Recipient (device, interface, endpoint, other) + * \endif + */ + cdi_usb_control_recipient_t recipient; + + /** + * \if german + * Requestcode (Je nach rtype und recipient) + * \elseif english + * Request code (specific to rtype and recipient) + * \endif + */ + int request; + + /** + * \if german + * Ein zu sendender Wert + * \elseif english + * A value to be sent + * \endif + */ + int value; + + /** + * \if german + * Ein zu sendender Index + * \elseif english + * An index to be sent + * \endif + */ + int index; +}; + +#include "cdi/usb-hcd.h" + +struct cdi_usb_driver { + struct cdi_driver drv; + + /** + * \if german + * Unterstuetzte Geschwindigkeiten + * \elseif english + * Supported speeds + * \endif + */ + cdi_usb_speed_t speeds; + + /** + * \if german + * + * Enumeriert ein USB-Geraet + * + * @param device Das zu enumerierende Geraet + * + * \elseif english + * + * Enumerates a USB device + * + * @param device The device to be enumerated + * + * \endif + */ + void (*enumerate_device)(struct cdi_usb_device* device); + + /** + * \if german + * + * Sendet USB-Pakete + * + * @param packets Array zu sendender Pakete + * @param num_packets Anzahl der Pakete + * + * @return Gibt den Status an (z. B. USB_NO_ERROR fuer keinen Fehler) + * + * \elseif english + * + * Sends USB packets + * + * @param packets Array of packets to be sent + * @param num_packets Number of packets + * + * @return Returns the status (i. e. USB_NO_ERROR to indicate no error) + * + * \endif + */ + cdi_usb_status_t (*send_packets)(struct cdi_usb_packet* packets, + size_t num_packets); + + /** + * \if german + * + * Fuehrt einen Control-Transfer durch + * + * @param device Das Zielgeraet + * @param transfer Eine den Transfer beschreibende Struktur + * + * @return Gibt einen Puffer zurueck, der die ausgetauschen Daten enthaelt, + * im Fehlerfall hingegen NULL, gab es keine Daten, dann + * (void *)0xFFFFFFFF. + * + * \elseif english + * + * Performs a control transfer + * + * @param device The destination device + * @param transfer A structure describing this transfer + * + * @return Returns a buffer containing the transferred data, in case of an + * error the value is NULL and if there was no data, it returns + * (void *)0xFFFFFFFF. + * + * \endif + */ + void* (*do_control)(struct cdi_usb_device* device, + struct cdi_usb_control_transfer* transfer); +}; + +/** + * \if german + * Ein USB-Geraetetreiber uebergibt dem Betriebssystem eine solche Struktur, + * damit ein bestimmter Handler beim Auffinden solcher Geraete aufgerufen wird. + * Jedes Feld enthaelt entweder eine Zahl, die mit der des Geraetes + * uebereinstimmen muss oder -1, dann wird dieses Feld ignoriert. + * \elseif english + * A USB device driver passes this structure to the OS so that a specific + * handler is called upon the detection of such a device. Each field either + * contains a number that has to be equal to that of the driver or -1, so that + * the field will be ignored. + * \endif + */ +struct cdi_usb_device_pattern { + int vendor_id; + int device_id; + int class_id; + int subclass_id; + int protocol_id; + + /** + * \if german + * + * Ueberprueft das angegebene USB-Geraet + * + * @param device Das Geraet + * + * @return 0, wenn dieses Geraet nicht vom Treiber verarbeitet werden kann, + * sonst 1 + * + * \elseif english + * + * Checks the given USB device + * + * @param device The device + * + * @return 0 if the driver is unable to handle this device, else 1 + * + * \endif + */ + int (*take_usb_device)(struct cdi_usb_device* device); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \if german + * + * Entfernt einen USB-Bustreiber + * + * @param driver Der Treiber + * + * \elseif english + * + * Removes a USB bus driver + * + * @param driver The driver + * + * \endif + */ +void cdi_usb_driver_destroy(struct cdi_usb_driver* driver); + +/** + * \if german + * + * Initialisiert einen USB-Bustreiber + * + * @param driver Der Treiber + * + * \elseif english + * + * Initializes a USB bus driver + * + * @param driver The driver + * + * \endif + */ +void cdi_usb_driver_init(struct cdi_usb_driver* driver); + +/** + * \if german + * + * Registriert einen USB-Bustreiber beim System + * + * @param driver Der Treiber + * + * \elseif english + * + * Registers a USB bus driver at the OS + * + * @param driver The driver + * + * \endif + */ +void cdi_usb_driver_register(struct cdi_usb_driver* driver); + +/** + * \if german + * + * Registriert ein gefundenes USB-Geraet beim Betriebssystem - diese Funktion + * wird z. B. vom Host-Controller-Treiber nach einem Aufruf von find_devices + * fuer jedes gefundene Geraet aufgerufen + * + * @param device Das zu registrierende Geraet + * + * \elseif english + * + * Registers a detected USB device at the OS - this function is called i. e. by + * the host controller driver after a find_devices call for every device found + * + * @param device The device to be registered + */ +void cdi_usb_device_init(struct cdi_usb_device* device); + +/** + * \if german + * + * Registriert ein Geraetemuster + * + * @param pattern Das Muster + * + * \elseif english + * + * Registers a device pattern + * + * @param pattern The pattern + * + * \endif + */ +void cdi_usb_register_device_pattern(struct cdi_usb_device_pattern* pattern); + +#ifdef __cplusplus +} //extern "C" +#endif + +#endif -- 1.6.0.2 From kevin at tyndur.org Mon Jan 4 20:55:32 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Mon, 4 Jan 2010 20:55:32 +0100 Subject: [cdi-devel] [PATCH 2/5] OHCI In-Reply-To: <1262634935-24109-1-git-send-email-kevin@tyndur.org> References: <1262634935-24109-1-git-send-email-kevin@tyndur.org> Message-ID: <1262634935-24109-3-git-send-email-kevin@tyndur.org> From: Max Reitz + Added USB open host controller driver Signed-off-by: Max Reitz Signed-off-by: Kevin Wolf --- ohci/hcd.c | 307 ++++++++++++++++++++++++++++++++++++++++++ ohci/include/ohci-hcd.h | 35 +++++ ohci/include/ohci-init.h | 31 +++++ ohci/include/ohci-transfer.h | 30 ++++ ohci/include/ohci.h | 283 ++++++++++++++++++++++++++++++++++++++ ohci/init.c | 236 ++++++++++++++++++++++++++++++++ ohci/transfer.c | 85 ++++++++++++ 7 files changed, 1007 insertions(+), 0 deletions(-) create mode 100644 ohci/hcd.c create mode 100644 ohci/include/ohci-hcd.h create mode 100644 ohci/include/ohci-init.h create mode 100644 ohci/include/ohci-transfer.h create mode 100644 ohci/include/ohci.h create mode 100644 ohci/init.c create mode 100644 ohci/transfer.c diff --git a/ohci/hcd.c b/ohci/hcd.c new file mode 100644 index 0000000..91c165f --- /dev/null +++ b/ohci/hcd.c @@ -0,0 +1,307 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#include +#include + +#include +#include +#include +#include +#include + +#include "ohci.h" +#include "ohci-hcd.h" + +static void reset_device(struct cdi_usb_device *device); + +void ohci_find_devices(struct cdi_usb_hc *device) +{ + struct ohci *ohci = (struct ohci *)device; + struct cdi_usb_device *dev; + int i; + + d0printf("Scanning root ports\n"); + for (i = 0; i < ohci->root_ports; i++) { + if (!(ohci->memory->hc_rh_port_status[i] & OHC_RP_CCS)) { + continue; + } + dev = malloc(sizeof(struct cdi_usb_device)); + dev->hc = device; + dev->id = 0; + dev->port = i; + dev->speed = (ohci->memory->hc_rh_port_status[i] & OHC_RP_LSDA) ? + CDI_USB_LOW_SPEED : CDI_USB_FULL_SPEED; + dev->reset = &reset_device; + cdi_usb_device_init(dev); + } +} + +void ohci_activate_device(struct cdi_usb_device *device) +{ + struct ohci *ohci = (struct ohci *)device->hc; + + if (device->hub != NULL) { + return; + } + + d1printf("Activating device on port %i.\n", device->port); + ohci->memory->hc_rh_port_status[device->port] |= OHC_RP_PES; + cdi_sleep_ms(20); +} + +static void reset_device(struct cdi_usb_device *device) +{ + struct ohci *ohci = (struct ohci *)device->hc; + + if (device->hub != NULL) { + return; + } + + d1printf("Resetting device on port %i.\n", device->port); + ohci->memory->hc_rh_port_status[device->port] |= OHC_RP_PRS; + cdi_sleep_ms(20); +} + +void ohci_add_pipe(struct cdi_usb_pipe *pipe) +{ + struct ohci *ohci = (struct ohci *)pipe->device->hc; + struct ohci_ed *ved; + uintptr_t ped; + struct ohci_ed_desc *dsc; + //TODO Mehr als Control und Bulk + int iscontrol = 0; + + if (cdi_mempool_get(ohci->ed_pool, (void **)&ved, &ped) == -1) { + return; + } + ved->function = pipe->device->id; + ved->endpoint = pipe->endpoint->endpoint_address; + if (ved->endpoint == 0) { + //EP0 + ved->direction = OHC_ED_DIR_TD; + iscontrol = 1; + } else if (pipe->endpoint->endpoint_address & 0x80) { + ved->direction = OHC_ED_DIR_IN; + } else { + ved->direction = OHC_ED_DIR_OUT; + } + ved->low_speed = !!(pipe->device->speed == CDI_USB_LOW_SPEED); + ved->skip = 0; + ved->format = 0; + ved->mps = pipe->endpoint->max_packet_size; + ved->td_queue_tail = 0; + ved->td_queue_head = 0; + dsc = cdi_list_get(ohci->ed_list, 0); + if (dsc == NULL) { + ved->next_ed = 0; + } else { + ved->next_ed = dsc->phys; + } + dsc = malloc(sizeof(*dsc)); + if (dsc == NULL) { + cdi_mempool_put(ohci->ed_pool, ved); + return; + } + dsc->virt = ved; + dsc->phys = ped; + dsc->function = pipe->device->id; + dsc->endpoint = pipe->endpoint->endpoint_address; + dsc->type = iscontrol ? USB_CONTROL : USB_BULK; + dsc->transfers = cdi_list_create(); + cdi_list_push(ohci->ed_list, dsc); + + if (iscontrol) { + ohci->memory->hc_control_head_ed = ped; + } else { + ohci->memory->hc_bulk_head_ed = ped; + } +} + +static inline int _tsl(volatile int *variable) +{ + int rval; + rval = *variable; + *variable = 1; + return rval; +} + +static volatile int locked = 0; + +cdi_usb_status_t ohci_do_packets(struct cdi_usb_packet *packets, + size_t num_packets) +{ + struct ohci_ed_desc *edsc; + struct ohci_td_desc *tdsc, *otdsc; + int i, j, cond, toggle, done_packets; + struct ohci *ohci = (struct ohci *)packets[0].pipe->device->hc; + struct ohci_td *vtd[num_packets]; + uintptr_t ptd[num_packets]; + + for (i = 0; (edsc = cdi_list_get(ohci->ed_list, i)) != NULL; i++) { + if ((edsc->function == packets[0].pipe->device->id) && + (edsc->endpoint == packets[0].pipe->endpoint->endpoint_address)) + { + break; + } + } + if (edsc == NULL) { + return CDI_USB_TIMEOUT; //Genau das w??rde passieren + } + + toggle = packets[0].pipe->data_toggle; + for (i = 0; i < (int)num_packets; i++) { + if (cdi_mempool_get(ohci->transfer_pool, (void **)&vtd[i], &ptd[i]) == -1) + { + return CDI_USB_TRIVIAL_ERROR; + } + if ((packets[i].data != NULL) && + (packets[i].type != CDI_USB_PACKET_IN)) + { + memcpy((void *)((uintptr_t)vtd[i] + sizeof(struct ohci_td)), + packets[i].data, packets[i].length); + } + vtd[i]->rounding = 1; //Warum nicht + switch (packets[i].type) { + case CDI_USB_PACKET_SETUP: + vtd[i]->direction = OHC_TD_DIR_SETUP; + break; + case CDI_USB_PACKET_IN: + vtd[i]->direction = OHC_TD_DIR_IN; + break; + case CDI_USB_PACKET_OUT: + vtd[i]->direction = OHC_TD_DIR_OUT; + break; + default: //Hm, passt nicht ganz + for (j = 0; j <= i; j++) { + cdi_mempool_put(ohci->transfer_pool, vtd[j]); + } + return CDI_USB_TRIVIAL_ERROR; + } + vtd[i]->di = 0; + if (packets[i].use_toggle == TOGGLE_0) { + toggle = 0; + } else if (packets[i].use_toggle == TOGGLE_1) { + toggle = 1; + } + vtd[i]->toggle = 0x2 | toggle; + toggle ^= 1; + vtd[i]->error = 0; + vtd[i]->condition = 15; + if ((packets[i].data == NULL) || !packets[i].length) { + vtd[i]->current_buffer_pointer = 0; + vtd[i]->buffer_end = 0; + } else { + vtd[i]->current_buffer_pointer = ptd[i] + sizeof(struct ohci_td); + vtd[i]->buffer_end = ptd[i] + + sizeof(struct ohci_td) + packets[i].length - 1; + } + vtd[i]->next_td = 0; + tdsc = malloc(sizeof(*tdsc)); + if (tdsc == NULL) { + for (j = 0; j <= i; j++) { + cdi_mempool_put(ohci->transfer_pool, vtd[j]); + } + return CDI_USB_TRIVIAL_ERROR; + } + tdsc->virt = vtd[i]; + tdsc->phys = ptd[i]; + tdsc->endpoint = edsc; + + if (cdi_list_size(edsc->transfers)) { + otdsc = cdi_list_get(edsc->transfers, 0); + otdsc->virt->next_td = ptd[i]; + } + if (!edsc->virt->td_queue_head) { + edsc->virt->td_queue_head = ptd[i]; + } + + cdi_list_push(edsc->transfers, tdsc); + } + packets[0].pipe->data_toggle = toggle; + if (edsc->type == USB_CONTROL) { + ohci->memory->hc_command_status |= OHC_CMST_CLF; + } else if (edsc->type == USB_BULK) { + ohci->memory->hc_command_status |= OHC_CMST_BLF; + } + done_packets = 0; + cond = CDI_USB_NO_ERROR; + while (done_packets < (int)num_packets) { + cdi_sleep_ms(1); + for (i = 0; i < (int)num_packets; i++) { + if (vtd[i]->condition != 15) { + done_packets++; + switch (vtd[i]->condition) { + case 0x00: + packets[i].condition = CDI_USB_NO_ERROR; + break; + case 0x02: + packets[i].condition = CDI_USB_BITSTUFF; + break; + case 0x04: + packets[i].condition = CDI_USB_STALLED; + for (j = 0; j < (int)num_packets; j++) { + //Allet, was nicht fertig ist, ist STALLed + vtd[j]->condition = 0x04; + } + break; + case 0x05: + packets[i].condition = CDI_USB_TIMEOUT; + break; + case 0x08: + packets[i].condition = CDI_USB_BABBLE; + break; + case 0x0C: + case 0x0D: + packets[i].condition = CDI_USB_BUFFER_ERROR; + break; + default: + packets[i].condition = CDI_USB_CRC; + break; + } + cond |= packets[i].condition; + vtd[i]->condition = 15; //Nicht nochmal ??berpr??fen + } + } + } + for (i = 0; i < (int)num_packets; i++) { + if ((packets[i].data != NULL) && + (packets[i].type == CDI_USB_PACKET_IN)) + { + memcpy(packets[i].data, (void *)((uintptr_t)vtd[i] + + sizeof(struct ohci_td)), packets[i].length); + } + if (vtd[i]->next_td == 0) { + edsc->virt->td_queue_head = 0; + } + cdi_mempool_put(ohci->transfer_pool, vtd[i]); + } + if (cond & CDI_USB_STALLED) { + //Transferliste f??r diesen Endpoint leeren + edsc->virt->td_queue_head = 0; + while ((tdsc = cdi_list_pop(edsc->transfers)) != NULL) { + free(tdsc); + } + edsc->virt->td_queue_tail = 0; //Weitermachen + } + return cond; +} diff --git a/ohci/include/ohci-hcd.h b/ohci/include/ohci-hcd.h new file mode 100644 index 0000000..d17168a --- /dev/null +++ b/ohci/include/ohci-hcd.h @@ -0,0 +1,35 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef UHCI_HCD_H +#define UHCI_HCD_H + +#include +#include + +void ohci_find_devices(struct cdi_usb_hc *device); +void ohci_activate_device(struct cdi_usb_device *device); +cdi_usb_status_t ohci_do_packets + (struct cdi_usb_packet *packets, size_t num_packets); +void ohci_add_pipe(struct cdi_usb_pipe *pipe); + +#endif diff --git a/ohci/include/ohci-init.h b/ohci/include/ohci-init.h new file mode 100644 index 0000000..2f19d2c --- /dev/null +++ b/ohci/include/ohci-init.h @@ -0,0 +1,31 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef OHCI_INIT_H +#define OHCI_INIT_H + +#include "ohci.h" + +void find_and_init_ohcis(void); +void ohci_init(struct cdi_device *dev); + +#endif diff --git a/ohci/include/ohci-transfer.h b/ohci/include/ohci-transfer.h new file mode 100644 index 0000000..a6dc6be --- /dev/null +++ b/ohci/include/ohci-transfer.h @@ -0,0 +1,30 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef OHCI_TRANSFER_H +#define OHCI_TRANSFER_H + +#include + +void ohci_handler(struct cdi_device *cdi_hci); + +#endif diff --git a/ohci/include/ohci.h b/ohci/include/ohci.h new file mode 100644 index 0000000..4936960 --- /dev/null +++ b/ohci/include/ohci.h @@ -0,0 +1,283 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef OHCI_H +#define OHCI_H + +#include +#include + +#include +#include +#include + +#include "ohci.h" + + +//#define DEBUG + +#ifdef DEBUG +#define d1printf(...) printf("[ohci] " __VA_ARGS__) +#define _d1printf(...) printf(__VA_ARGS__) +#else +#define d1printf(...) +#define _d1printf(...) +#endif + +#define d0printf(...) printf("[ohci] " __VA_ARGS__) +#define _d0printf(...) printf(__VA_ARGS__) + + +#define OHC_USB_RESET 0x00000000 +#define OHC_USB_RESUME 0x00000040 +#define OHC_USB_OPERATIONAL 0x00000080 +#define OHC_USB_SUSPEND 0x000000C0 + +#define OHC_CTRL_CBSR 0x00000003 //Verh??ltnis zwischen Control und Bulk + //(cbsr+1 zu 1) +#define OHC_CTRL_PLE 0x00000004 //Periodische Transfers aktivieren +#define OHC_CTRL_IE 0x00000008 //Isochronous-Transfers aktivieren +#define OHC_CTRL_CLE 0x00000010 //Control-Transfers aktivieren +#define OHC_CTRL_BLE 0x00000020 //Bulk-Transfers aktivieren +#define OHC_CTRL_HCFS 0x000000C0 //Status des HCs +#define OHC_CTRL_IR 0x00000100 //Wenn gesetzt, dann werden IRQs zum SMB + //geleitet +#define OHC_CTRL_RWC 0x00000200 //Remote wakeup unterset??tzt +#define OHC_CTRL_RW 0x00000400 //Remote wakeup aktivieren + +#define OHC_CMST_RESET 0x00000001 //Reset +#define OHC_CMST_CLF 0x00000002 //Control list filled (muss gesetzt werden, + //wenn ein Eintrag zur Controlliste + //hinzugef??gt wird) +#define OHC_CMST_BLF 0x00000004 //Bulk list filled (muss gesetzt werden, wenn + //ein Eintrag zur Bulkliste hinzugef??gt wird) +#define OHC_CMST_OCR 0x00000008 //Ownership change request +#define OHC_CMST_SOC 0x00030000 //Scheduling overrun count + +#define OHC_INT_SO 0x00000001 //Scheduling overrun +#define OHC_INT_WDH 0x00000002 //Write back done head +#define OHC_INT_SF 0x00000004 //Start of frame (wird bei SOF gesetzt) +#define OHC_INT_RD 0x00000008 //Resume detected (wird bei einem von einem + //Ger??t gesendeten Resume gesetzt) +#define OHC_INT_UE 0x00000010 //Unrecoverable error (wird bei einem HC- + //Fehler gesetzt, der nichts mit USB zu tun + //hat) +#define OHC_INT_FNO 0x00000020 //Frame number overflow (wird gesetzt, wenn + //die Framenummer gr????er als 32767 und + //umgebrochen wird) +#define OHC_INT_RHSC 0x00000040 //Root hub status change (wird gesetzt, wenn + //sich irgendwas am Roothub ge??ndert hat) +#define OHC_INT_OC 0x40000000 //Ownership change +#define OHC_INT_MIE 0x80000000 //(De-)Aktiviert Interrupts + +#define OHC_RHA_NDP 0x000000FF //Anzahl an Rootports (1 bis 15) +#define OHC_RHA_PSM 0x00000100 //Gesetzt, wenn man die Stromzufuhr zu + //einzelnen Ports unabh??ngig setzen kann +#define OHC_RHA_NPS 0x00000200 //Gel??scht, wenn man die Stromzufuhr zu + //einzelnen Ports unabh??ngig setzen kann +#define OHC_RHA_DT 0x00000400 //Immer 0, zeigt so an, dass der Roothub kein + //Compound device ist. +#define OHC_RHA_OCPM 0x00000800 //Gesetzt, wenn ??berspannungen f??r jeden Port + //einzeln gemeldet werden +#define OHC_RHA_NOCP 0x00001000 //Gesetzt, wenn keine ??berspannungen erkannt + //bzw. verhindert werden k??nnen +#define OHC_RHA_POTPGT 0xFF000000 //Power on to power good time (potpgt * 2) + +#define OHC_RHS_LPS 0x00000001 //R: 0 + //W: Strom abdrehen +#define OHC_RHS_OCI 0x00000002 //R: Unspezifische ??berspannung +#define OHC_RHS_DRWE 0x00008000 //R: Irgendwas mit Remote Wakeup Enable + //W: Das aktivieren +#define OHC_RHS_LPSC 0x00010000 //R: 0 + //W: Strom andrehen +#define OHC_RHS_OCIC 0x00020000 //R: Bei ??nderungen von OCI gesetzt + //W: Feld l??schen +#define OHC_RHS_CRWE 0x80000000 //W: Remote Wakeup Enable deaktivieren + +#define OHC_RP_CCS 0x00000001 //R: Ger??t angeschlossen + //W: Deaktiviert den Port +#define OHC_RP_PES 0x00000002 //R: Port aktiviert + //W: Aktiviert den Port +#define OHC_RP_PSS 0x00000004 //R: Port schl??ft + //W: Schl??fert den Port ein +#define OHC_RP_POCI 0x00000008 //R: ??berspannung + //W: Port aufwecken +#define OHC_RP_PRS 0x00000010 //R: Reset l??uft + //W: Reset treiben +#define OHC_RP_PPS 0x00000100 //R: Strom an + //W: Strom andrehen +#define OHC_RP_LSDA 0x00000200 //R: Low-Speed-Ger??t + //W: Strom abdrehen +#define OHC_RP_CSC 0x00010000 //R: Ger??t an- oder abgezogen + //W: Bit l??schen +#define OHC_RP_PESC 0x00020000 //R: Port (de-)aktiviert + //W: Bit l??schen +#define OHC_RP_PSSC 0x00040000 //R: Port wurde geweckt + //W: Bit l??schen +#define OHC_RP_OCIC 0x00080000 //R: ??berspannungsbit ver??ndert + //W: Bit l??schen +#define OHC_RP_PRSC 0x00100000 //R: Reset beendet + //W: Bit l??schen + +struct ohci_registers +{ + uint32_t hc_revision; //Revision + volatile uint32_t hc_control; + volatile uint32_t hc_command_status; + volatile uint32_t hc_interrupt_status; + volatile uint32_t hc_interrupt_enable; + volatile uint32_t hc_interrupt_disable; + uint32_t hc_hcca; //Adresse des HCCA + volatile uint32_t hc_period_current_ed; //Adresse des aktuellen + //Endpointdescriptors der + //periodischen Transfers + uint32_t hc_control_head_ed; //Adresse des ersten Endpointdescriptors der + //Control-Transfers + volatile uint32_t hc_control_current_ed; //Adresse des aktuellen + //Endpointdescriptors der Control- + //Transfers + uint32_t hc_bulk_head_ed; //Adresse des ersten Endpointdescriptors der + //Bulk-Transfers + volatile uint32_t hc_bulk_current_ed; //Adresse des aktuellen + //Endpointdescriptors der Bulk- + //Transfers + volatile uint32_t hc_done_head; //Adresse des zuletzt abgearbeiteten + //Transferdeskriptors, der der Done-Liste + //hinzugef??gt wurde + uint32_t hc_fm_interval; //Gibt die L??nge eines Frames und die maximale + //Paketgr????e an + volatile uint32_t hc_fm_remaining; //Verbleibende Takte des aktuellen + //Frames + volatile uint32_t hc_fm_number; //Nummer des aktuellen Frames + uint32_t hc_periodic_start; //10% von HcFmInterval, wenn HcFmInterval + //diesen Wert erreicht, dann haben periodische + //Transfers Vorrang + uint32_t hc_ls_threshold; //Besser nicht ??ndern + uint32_t hc_rh_descriptor_a; + uint32_t hc_rh_descriptor_b; + volatile uint32_t hc_rh_status; + volatile uint32_t hc_rh_port_status[]; +} __attribute__((packed)); + +struct ohci_legsup +{ + uint32_t hce_control; + uint32_t hce_input; + uint32_t hce_output; + uint32_t hce_status; +} __attribute__((packed)); + +struct ohci_hcca +{ + uint32_t interrupt_table[32]; //Zeiger zu Interrupt-EDs + uint16_t frame_number; //Die Nummer des aktuellen Frames + uint16_t pad; //Wird auf 0 gesetzt, wenn frame_number neu geschrieben wird + //(Ausrichten an DWord-Grenzen vermutlich) + uint32_t done_head; + uint8_t rsvd[116]; +} __attribute__((packed)); + +struct ohci +{ + struct cdi_usb_hc cdidev; + struct cdi_pci_device *pcidev; + + struct ohci_registers *memory; + struct ohci_legsup *legsup; + int root_ports; + struct ohci_hcca *hcca; + + struct cdi_mempool *ed_pool; + struct cdi_mempool *transfer_pool; + + cdi_list_t ed_list; +}; + +#define OHC_ED_DIR_TD 0 //Richtung im TD definiert +#define OHC_ED_DIR_OUT 1 +#define OHC_ED_DIR_IN 2 + +struct ohci_ed +{ + unsigned function : 7; //USB-Adresse des Ger??ts + unsigned endpoint : 4; //Nummer des Endpoints + unsigned direction : 2; //Richtung des Transfers + unsigned low_speed : 1; + unsigned skip : 1; + unsigned format : 1; //Bei Isochronous gesetzt + unsigned mps : 11; //Maximale Paketgr????e + unsigned user : 5; //F??r uns frei verf??gbar + uint32_t td_queue_tail; //Letzter TD in der Warteschlange + volatile uint32_t td_queue_head; //N??chster TD in der Warteschlange + uint32_t next_ed; //N??chster ED +} __attribute__((packed)); + +struct ohci_ed_desc +{ + struct ohci_ed *virt; + uintptr_t phys; + int function; + int endpoint; + cdi_list_t transfers; + enum + { + USB_CONTROL, + USB_BULK + } type; +} __attribute__((packed)); + +#define OHC_TD_DIR_SETUP 0 +#define OHC_TD_DIR_OUT 1 +#define OHC_TD_DIR_IN 2 + +struct ohci_td +{ + unsigned user : 18; //F??r uns frei verf??gbar + unsigned rounding : 1; //Wenn gesetzt, dann sind zu kleine Pakete nicht so + //schlimm + unsigned direction : 2; //Richtung/Typ des Transfers (nur g??ltig, wenn das + //"direction"-Feld im ED 00b oder 11b ist) + unsigned di : 3; //Gibt an, wie viele Frames der HC vor Ausl??sen eines IRQs + //warten soll + unsigned toggle : 2; //Datatoggle (00b oder 01b - Wert muss aus dem ED + //ermittelt werden, 10b = DATA0, 11b = DATA1) + volatile unsigned error : 2; //Anzahl der aufgetretenen Fehler - bei 11b + //wird der Status im "condition"-Feld + //gespeichert. + volatile unsigned condition : 4; //Status + volatile uint32_t current_buffer_pointer; //Pointer zu den Daten (bei 0 + //wurden alle Daten ??bertragen) + uint32_t next_td; //N??chster TD + uint32_t buffer_end; //Letztes Datenbyte des Puffers +} __attribute__((packed)); + +struct ohci_td_desc +{ + struct ohci_td *virt; + uintptr_t phys; + struct ohci_ed_desc *endpoint; +} __attribute__((packed)); + +struct cdi_driver *init_ohcd(void); +void ohci_init(struct cdi_device *cdi_hci); + +#endif diff --git a/ohci/init.c b/ohci/init.c new file mode 100644 index 0000000..6190dab --- /dev/null +++ b/ohci/init.c @@ -0,0 +1,236 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "ohci.h" +#include "ohci-hcd.h" +#include "ohci-init.h" +#include "ohci-transfer.h" + +extern int init_ohci(void); + +#define DRIVER_NAME "ohcd" + +static struct cdi_usb_hcd driver; +static int ohci_counter = 0; + +static int ohci_init_driver(void) +{ + cdi_usb_hcd_init(&driver); + return 0; +} + +struct cdi_device* ohci_init_device(struct cdi_bus_data* bus_data) +{ + struct ohci* ohci; + struct cdi_pci_device* dev = (struct cdi_pci_device*) bus_data; + struct cdi_pci_resource *res; + int i; + uintptr_t phys_hcca; + char* name; + + if ((dev->class_id != 0x0C) || (dev->subclass_id != 0x03) + || (dev->interface_id != 0x10)) + { + return NULL; + } + + ohci = malloc(sizeof(struct ohci)); + name = malloc(7); + sprintf(name, "ohci%i", ohci_counter++); + ohci->cdidev.dev.name = (const char *)name; + ohci->cdidev.speed = CDI_USB_LOW_SPEED | CDI_USB_FULL_SPEED; + ohci->pcidev = dev; + + ohci->memory = NULL; + for (i = 0; (res = cdi_list_get(ohci->pcidev->resources, i)) != NULL; + i++) + { + if (res->type == CDI_PCI_MEMORY) { + ohci->memory = cdi_alloc_phys_addr(res->length, res->start); + if (ohci->memory == NULL) { + d0printf("Wasn't able to allocate memory.\n"); + return NULL; + } + ohci->legsup = (void *)((uintptr_t)ohci->memory + 0x100); + break; + } + } + if (ohci->memory == NULL) { + d1printf("Memory not found!\n"); + return NULL; + } + d1printf("Memory @ 0x%08X\n", (uintptr_t)ohci->memory); + if ((ohci->memory->hc_revision & 0xFF) != 0x10) { + d0printf("This OHCI might be incompatible with this driver" + "(HCI %i.%i, HCD 1.0)\n", (ohci->memory->hc_revision & 0xF0) >> 4, + ohci->memory->hc_revision & 0xF); + } + if (cdi_alloc_phys_mem(sizeof(*ohci->hcca), (void **)&ohci->hcca, + (void **)&phys_hcca) == -1) + { + d0printf("Wasn't able to allocate HCCA.\n"); + return NULL; + } + memset(ohci->hcca, 0, sizeof(*ohci->hcca)); + + d1printf("IRQ: %i\n", ohci->pcidev->irq); + cdi_register_irq(ohci->pcidev->irq, &ohci_handler, &ohci->cdidev.dev); + + ohci->ed_pool = cdi_mempool_create(64 * sizeof(struct ohci_ed), + sizeof(struct ohci_ed)); + if (ohci->ed_pool == NULL) { + d0printf("Wasn't able to create ED memory pool!\n"); + return NULL; + } + + ohci->transfer_pool = cdi_mempool_create(48 * (1024 + sizeof(struct ohci_td)), + 1024 + sizeof(struct ohci_td)); + if (ohci->transfer_pool == NULL) { + d0printf("Wasn't able to create transfer memory pool!\n"); + return NULL; + } + + ohci->memory->hc_interrupt_disable = OHC_INT_MIE; + + if (ohci->memory->hc_control & OHC_CTRL_IR) { + d1printf("Kicking out SMM... "); + //??nderung des "Besitzers" beantragen + ohci->memory->hc_command_status |= OHC_CMST_OCR; + for (i = 0; (ohci->memory->hc_control & OHC_CTRL_IR) && (i < 1000); + i++) + { + cdi_sleep_ms(1); + } + if (i < 100) { + _d1printf("Went fine.\n"); + } else { + _d1printf("Idiot.\n"); + ohci->memory->hc_control &= ~OHC_CTRL_IR; + } + } else if ((ohci->memory->hc_control & OHC_CTRL_CBSR) != OHC_USB_RESET) { + d1printf("BIOS active\n"); + if ((ohci->memory->hc_control & OHC_CTRL_CBSR) != OHC_USB_OPERATIONAL) + { + d1printf("Activating RESUME...\n"); + ohci->memory->hc_control = + (ohci->memory->hc_control & ~OHC_CTRL_CBSR) | OHC_USB_RESUME; + cdi_sleep_ms(10); + } + } else { + //Nix, weder BIOS noch SMM + cdi_sleep_ms(10); //Reset abwarten + } + + if (ohci->legsup->hce_control & 1) { + d1printf("USB legacy support activated, but that won't last for" + "long...\n"); + } + //Harhar, that's mine now! + ohci->legsup->hce_control = 0; + + ohci->memory->hc_command_status |= OHC_CMST_RESET; + //Normalerweise sollte man den Wert von hc_fm_interval von vor dem Reset + //wiederherstellen, aber ich finde das Schwachsinn. Die Werte sind so in + //Ordnung, wie sie jetzt sind. + + cdi_sleep_ms(3); //10 ??s f??r den Reset und 2 ms f??r Resume + if ((ohci->memory->hc_control & OHC_CTRL_CBSR) == OHC_USB_SUSPEND) { + //Boah... + d1printf("Reset not finished yet...\n"); + ohci->memory->hc_control = + (ohci->memory->hc_control & ~OHC_CTRL_CBSR) | OHC_USB_RESUME; + cdi_sleep_ms(10); + } + + ohci->memory->hc_interrupt_disable = OHC_INT_MIE; + + ohci->memory->hc_hcca = phys_hcca; + ohci->memory->hc_interrupt_status = 0xFFFFFFFF; + ohci->memory->hc_interrupt_enable = + OHC_INT_SO | //Scheduling overrun + OHC_INT_WDH | //Write back done head + OHC_INT_RD | //Resume detected + OHC_INT_UE | //Schwerer Fehler + OHC_INT_RHSC | //Root hub status change + OHC_INT_MIE; + //Eigentlich sollte man alle Transfers aktivieren. Aber wir wollen ja noch + //gar keine periodischen Transfers... + //Periodisches Zeug deaktivieren + ohci->memory->hc_control &= ~(OHC_CTRL_PLE | OHC_CTRL_IE); + //Control und Bulk aktivieren + ohci->memory->hc_control |= OHC_CTRL_CLE | OHC_CTRL_BLE; + //Merkw??rdigerweise soll das jetzt nicht auf 10 %, sondern auf 90 % gesetzt + //werden. Aber das klingt total bescheuert, weil nicht erkl??rt wird, wann + //man es denn auf 10 % setzen soll. Deshalb machen wir das gleich. + ohci->memory->hc_periodic_start = 0x4B0; + + d1printf("Activating HC.\n"); + + //DO IT, FAGGOT! + ohci->memory->hc_control = + (ohci->memory->hc_control & ~OHC_CTRL_CBSR) | OHC_USB_OPERATIONAL; + + ohci->memory->hc_rh_status |= OHC_RHS_LPSC; //Strom andrehen + ohci->root_ports = ohci->memory->hc_rh_descriptor_a & OHC_RHA_NDP; + cdi_sleep_ms((ohci->memory->hc_rh_descriptor_a & OHC_RHA_POTPGT) >> 23); + + d0printf("Found %i root ports.\n", ohci->root_ports); + + for (i = 0; i < ohci->root_ports; i++) { + ohci->memory->hc_rh_port_status[i] |= OHC_RP_CCS; //Deaktivieren + } + + ohci->ed_list = cdi_list_create(); + + return &ohci->cdidev.dev; +} + +static struct cdi_usb_hcd driver = { + .drv = { + .type = CDI_USB_HCD, + .name = DRIVER_NAME, + .devices = NULL, + .init_device = &ohci_init_device, + .remove_device = NULL, + .init = &ohci_init_driver, + .destroy = NULL, + }, + + .find_devices = ohci_find_devices, + .activate_device = ohci_activate_device, + .send_packets = ohci_do_packets, + .add_pipe = ohci_add_pipe, +}; + +CDI_DRIVER(DRIVER_NAME, driver) + diff --git a/ohci/transfer.c b/ohci/transfer.c new file mode 100644 index 0000000..24f7c67 --- /dev/null +++ b/ohci/transfer.c @@ -0,0 +1,85 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#include +#include + +#include +#include +#include + +#include "ohci.h" + +void ohci_handler(struct cdi_device *cdi_hci) +{ + struct ohci *ohci = (struct ohci *)cdi_hci; + struct ohci_ed_desc *edsc; + struct ohci_td_desc *tdsc; + uint32_t status, done = 0; + int i, j; + uintptr_t phys; + + status = ohci->memory->hc_interrupt_status; + if (!status) { + return; //Wohl nicht f??r uns + } + + if (status & OHC_INT_RHSC) { + done |= OHC_INT_RHSC; + } + if (status & OHC_INT_UE) { + d0printf("Fatal HC error.\n"); + ohci->memory->hc_command_status |= OHC_CMST_RESET; + done |= OHC_INT_UE; + } + if (status & OHC_INT_SF) { + //??hm... Na ja. Manchmal fragt man sich, ob sich der HC so einsam + //f??hlt, dass er IRQs feuert, obwohl sie deaktiviert sind. + done |= OHC_INT_SF; + } + if (status & OHC_INT_WDH) { + //Paket gesendet + done |= OHC_INT_WDH; + phys = ohci->hcca->done_head; + for (i = 0; (edsc = cdi_list_get(ohci->ed_list, i)) != NULL; i++) { + for (j = 0; (tdsc = cdi_list_get(edsc->transfers, j)) != NULL; j++) + { + if (tdsc->phys == phys) { + //Das ist der fertige Transfer + cdi_list_remove(edsc->transfers, j); + free(tdsc); + break; + } + } + if (tdsc != NULL) { + //Gefunden + break; + } + } + } + + if (status & ~done) { + d1printf("Non-handled interrupt: 0x%08X\n", status & ~done); + } + + ohci->memory->hc_interrupt_status = status; +} -- 1.6.0.2 From kevin at tyndur.org Mon Jan 4 20:55:33 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Mon, 4 Jan 2010 20:55:33 +0100 Subject: [cdi-devel] [PATCH 3/5] UHCI In-Reply-To: <1262634935-24109-1-git-send-email-kevin@tyndur.org> References: <1262634935-24109-1-git-send-email-kevin@tyndur.org> Message-ID: <1262634935-24109-4-git-send-email-kevin@tyndur.org> From: Max Reitz + Added USB universal host controller driver Signed-off-by: Max Reitz Signed-off-by: Kevin Wolf --- uhci/hcd.c | 207 ++++++++++++++++++++++++++++++++++++ uhci/include/uhci-hcd.h | 35 ++++++ uhci/include/uhci-init.h | 31 ++++++ uhci/include/uhci-transfer.h | 30 +++++ uhci/include/uhci.h | 138 ++++++++++++++++++++++++ uhci/init.c | 242 ++++++++++++++++++++++++++++++++++++++++++ uhci/transfer.c | 91 ++++++++++++++++ 7 files changed, 774 insertions(+), 0 deletions(-) create mode 100644 uhci/hcd.c create mode 100644 uhci/include/uhci-hcd.h create mode 100644 uhci/include/uhci-init.h create mode 100644 uhci/include/uhci-transfer.h create mode 100644 uhci/include/uhci.h create mode 100644 uhci/init.c create mode 100644 uhci/transfer.c diff --git a/uhci/hcd.c b/uhci/hcd.c new file mode 100644 index 0000000..bf4d738 --- /dev/null +++ b/uhci/hcd.c @@ -0,0 +1,207 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#include +#include + +#include +#include +#include +#include +#include + +#include "uhci.h" +#include "uhci-hcd.h" + +extern cdi_list_t uhci_active_transfers; + +static void reset_device(struct cdi_usb_device *device); + +void uhci_find_devices(struct cdi_usb_hc *device) +{ + struct uhci *uhci = (struct uhci *)device; + struct cdi_usb_device *dev; + int i; + + d0printf("Scanning root ports\n"); + cdi_outw(uhci->pbase + UHCI_USBCMD, USB_RUN); + for (i = 0; i < uhci->root_ports; i++) { + if (!(cdi_inw(uhci->pbase + UHCI_RPORTS + 2 * i) & RPORT_DEVICE)) { + continue; + } + dev = malloc(sizeof(struct cdi_usb_device)); + dev->hc = device; + dev->id = 0; + dev->port = i; + dev->speed = (cdi_inw(uhci->pbase + UHCI_RPORTS + 2 * i) & + RPORT_LOSPD) ? CDI_USB_LOW_SPEED : CDI_USB_FULL_SPEED; + dev->hub = NULL; + dev->reset = &reset_device; + cdi_usb_device_init(dev); + } +} + +void uhci_activate_device(struct cdi_usb_device *device) +{ + struct uhci *uhci = (struct uhci *)device->hc; + + if (device->hub != NULL) { + return; + } + + d1printf("Activating device on port %i.\n", device->port); + cdi_outw(uhci->pbase + UHCI_RPORTS + 2 * device->port, + RPORT_ENABLE | RPORT_CSC); + cdi_sleep_ms(20); +} + +static void reset_device(struct cdi_usb_device *device) +{ + struct uhci *uhci = (struct uhci *)device->hc; + + if (device->hub != NULL) { + return; + } + + d1printf("Resetting device on port %i.\n", device->port); + cdi_outw(uhci->pbase + UHCI_RPORTS + 2 * device->port, + RPORT_ENABLE | RPORT_RESET | RPORT_CSC); + cdi_sleep_ms(20); +} + +void uhci_add_pipe(struct cdi_usb_pipe *pipe) +{ + //Macht nix, weil das bei UHCI nicht n??tig ist + pipe = NULL; //Aber GCC k??nnen wir trotzdem gl??cklich machen +} + +static inline int _tsl(volatile int *variable) +{ + int rval; + rval = *variable; + *variable = 1; + return rval; +} + +static volatile int locked = 0; + +static cdi_usb_status_t do_packet(struct cdi_usb_packet *packet) +{ + struct cdi_usb_device *usbdev = packet->pipe->device; + struct uhci *uhci = (struct uhci *)usbdev->hc; + struct uhci_td td; + struct transfer addr; + int timeout, frame; + + void *buf; + uintptr_t pbuf; + + memset(&td, 0, sizeof(td)); + td.next = 1; //Invalid + td.active = 1; + td.ioc = 1; + if (packet->use_toggle == TOGGLE_0) { + packet->pipe->data_toggle = 0; + } else if (packet->use_toggle == TOGGLE_1) { + packet->pipe->data_toggle = 1; + } + td.data_toggle = packet->pipe->data_toggle; + packet->pipe->data_toggle ^= 1; + td.low_speed = !!(usbdev->speed == CDI_USB_LOW_SPEED); + td.errors = 1; + td.pid = packet->type; + td.device = usbdev->id; + td.endpoint = packet->pipe->endpoint->endpoint_address & 0x07; + td.maxlen = packet->length ? packet->length - 1 : 0x7FF; + while (_tsl(&locked)); + frame = (cdi_inw(uhci->pbase + UHCI_FRNUM) + 5) & 0x3FF; + while (!(uhci->queue_heads[frame].transfer & 1)) { + frame++; + frame &= 0x3FF; + } + + if (cdi_mempool_get(uhci->buffers, &buf, &pbuf) < 0) { + return CDI_USB_TRIVIAL_ERROR; + } + + addr.virt = buf; + addr.phys = pbuf; + addr.error = 0xFFFF; + + buf = (void *)((uintptr_t)buf + sizeof(td)); + pbuf += sizeof(td); + + if (!packet->length) { + td.buffer = 0; + } else { + td.buffer = pbuf; + if (packet->type != CDI_USB_PACKET_IN) { + memcpy(buf, packet->data, packet->length); + } + } + + memcpy(addr.virt, &td, sizeof(td)); + + + if (uhci_active_transfers == NULL) { + uhci_active_transfers = cdi_list_create(); + } + uhci->queue_heads[frame].transfer = addr.phys; + cdi_list_push(uhci_active_transfers, &addr); + + locked = 0; + for (timeout = 0; !(uhci->queue_heads[frame].transfer & 1) && + (timeout < 1000); timeout++) + { + cdi_sleep_ms(1); + } + while ((timeout < 1000) && (addr.error == 0xFFFF)) { +#ifndef CDI_STANDALONE + __asm__ __volatile__ ("hlt"); +#endif + } + if (packet->type == CDI_USB_PACKET_IN) { + memcpy(packet->data, buf, packet->length); + } + if (addr.error == 0xFFFF) { + addr.error = CDI_USB_TIMEOUT; + } + + cdi_mempool_put(uhci->buffers, addr.virt); + + return addr.error; +} + +cdi_usb_status_t uhci_do_packets(struct cdi_usb_packet *packets, + size_t num_packets) +{ + size_t i; + cdi_usb_status_t cond = CDI_USB_NO_ERROR; + + //TODO + for (i = 0; (i < num_packets) && !cond; i++) { + packets[i].condition = do_packet(&packets[i]); + cond |= packets[i].condition; + } + + return cond; +} diff --git a/uhci/include/uhci-hcd.h b/uhci/include/uhci-hcd.h new file mode 100644 index 0000000..423f23a --- /dev/null +++ b/uhci/include/uhci-hcd.h @@ -0,0 +1,35 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef UHCI_HCD_H +#define UHCI_HCD_H + +#include +#include + +void uhci_find_devices(struct cdi_usb_hc *device); +void uhci_activate_device(struct cdi_usb_device *device); +cdi_usb_status_t uhci_do_packets(struct cdi_usb_packet *packets, + size_t num_packets); +void uhci_add_pipe(struct cdi_usb_pipe *pipe); + +#endif diff --git a/uhci/include/uhci-init.h b/uhci/include/uhci-init.h new file mode 100644 index 0000000..7b357bc --- /dev/null +++ b/uhci/include/uhci-init.h @@ -0,0 +1,31 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef UHCI_INIT_H +#define UHCI_INIT_H + +#include "uhci.h" + +void find_and_init_uhcis(void); +void uhci_init(struct cdi_device *dev); + +#endif diff --git a/uhci/include/uhci-transfer.h b/uhci/include/uhci-transfer.h new file mode 100644 index 0000000..53b46b0 --- /dev/null +++ b/uhci/include/uhci-transfer.h @@ -0,0 +1,30 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef UHCI_TRANSFER_H +#define UHCI_TRANSFER_H + +#include + +void uhci_handler(struct cdi_device *cdi_hci); + +#endif diff --git a/uhci/include/uhci.h b/uhci/include/uhci.h new file mode 100644 index 0000000..c9b3b05 --- /dev/null +++ b/uhci/include/uhci.h @@ -0,0 +1,138 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef UHCI_H +#define UHCI_H + +#include +#include + +#include +#include +#include +#include + + +//#define DEBUG + +#ifdef DEBUG +#define d1printf(...) printf("[uhci] " __VA_ARGS__) +#define _d1printf(...) printf(__VA_ARGS__) +#else +#define d1printf(...) +#define _d1printf(...) +#endif + +#define d0printf(...) printf("[uhci] " __VA_ARGS__) +#define _d0printf(...) printf(__VA_ARGS__) + + +#define UHCI_USBCMD 0x00 //w +#define UHCI_USBSTS 0x02 //w +#define UHCI_USBINTR 0x04 //w +#define UHCI_FRNUM 0x06 //w +#define UHCI_FRBASEADD 0x08 //l +#define UHCI_SOFMOD 0x0C //b +#define UHCI_RPORTS 0x10 +#define UHCI_PORTSC1 0x10 //w +#define UHCI_PORTSC2 0x12 //w + +#define MAXP 0x0080 +#define CONFIGURE 0x0040 +#define GLOB_SUSP_MODE 0x0008 +#define GRESET 0x0004 +#define HCRESET 0x0002 +#define USB_RUN 0x0001 + +#define RPORT_RESET 0x0200 +#define RPORT_LOSPD 0x0100 //Low speed device attached +#define RPORT_ENABLE 0x0004 +#define RPORT_CSC 0x0002 //Connect status change +#define RPORT_DEVICE 0x0001 + +//Legacy support +#define UHCI_PCI_LEGSUP 0xC0 //w + +#define UHCI_LEGSUP_STATUS 0x8F00 //Statusbits, die mittels schreiben einer 1 + //gel??scht werden +#define UHCI_LEGSUP_NO_CHG 0x5040 //Bits, die nicht ver??ndert werden k??nnen + //(RO bzw. reserviert) +#define UHCI_LEGSUP_PIRQ 0x2000 //Interrupt wird als PCI-IRQ ausgef??hrt + + +struct uhci_qh { + volatile uint32_t next; + volatile uint32_t transfer; + uint32_t align[2]; //F??rs korrekte Alignment (an 16 Bytes) +} __attribute__((packed)); + +struct uhci_td { + volatile uint32_t next; + + unsigned trans_len : 11; + unsigned rsvd0 : 6; + unsigned bitstuff_err : 1; + unsigned crc_time_err : 1; + unsigned nak : 1; + unsigned babble : 1; + unsigned buf_err : 1; + unsigned stalled_err : 1; + unsigned active : 1; + unsigned ioc : 1; + unsigned isochronous : 1; + unsigned low_speed : 1; + unsigned errors : 2; + unsigned spd : 1; + unsigned rsvd1 : 2; + + unsigned pid : 8; + unsigned device : 7; + unsigned endpoint : 4; + unsigned data_toggle : 1; + unsigned rsvd2 : 1; + unsigned maxlen : 11; + + uint32_t buffer; + + uint32_t user[4]; +} __attribute__((packed)); + +struct transfer { + void *virt; + uintptr_t phys; + volatile int error; +}; + +struct uhci { + struct cdi_usb_hc cdidev; + struct cdi_pci_device *pcidev; + int pbase; + uintptr_t phys_frame_list; + uint32_t *frame_list; + int root_ports; + struct uhci_qh *queue_heads; + struct uhci_qh *phys_queue_heads; + + struct cdi_mempool *buffers; +}; + +#endif diff --git a/uhci/init.c b/uhci/init.c new file mode 100644 index 0000000..2ddeb36 --- /dev/null +++ b/uhci/init.c @@ -0,0 +1,242 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "uhci.h" +#include "uhci-hcd.h" +#include "uhci-init.h" +#include "uhci-transfer.h" + +#define DRIVER_NAME "uhcd" + +static struct cdi_usb_hcd driver; +static int uhci_counter = 0; + +int uhci_init_driver(void) +{ + cdi_usb_hcd_init(&driver); + return 0; +} + +struct cdi_device* uhci_init_device(struct cdi_bus_data* bus_data) +{ + struct uhci *uhci; + struct cdi_pci_device* dev = (struct cdi_pci_device*) dev; + struct cdi_pci_resource *res; + int size = 0, request_size, cmd, intr, i; +#ifdef CDI_PCI_DIRECT_ACCESS + int legsup; +#endif + char *name; + + if ((dev->class_id != 0x0C) || (dev->subclass_id != 0x03) + || (dev->interface_id != 0x00)) + { + return NULL; + } + + uhci = malloc(sizeof(struct uhci)); + name = malloc(7); + sprintf(name, "uhci%i", uhci_counter++); + uhci->cdidev.dev.name = (const char *)name; + uhci->cdidev.speed = CDI_USB_LOW_SPEED | CDI_USB_FULL_SPEED; + uhci->pcidev = dev; + + d0printf("Trying to init %s at %02x:%02x.%02x...\n", uhci->cdidev.dev.name, + uhci->pcidev->bus, uhci->pcidev->dev, uhci->pcidev->function); + + uhci->pbase = 0; + for (i = 0; (res = cdi_list_get(uhci->pcidev->resources, i)) != NULL; i++) + { + if (res->type == CDI_PCI_IOPORTS) { + size = res->length ? res->length : 0x14; + if (cdi_ioports_alloc(res->start, size) == -1) { + d0printf("Cannot allocate I/O ports.\n"); + return NULL; + } + uhci->pbase = res->start; + break; + } + } + if (!uhci->pbase) { + d0printf("No I/O space found.\n"); + return NULL; + } + request_size = + // Maximale Paketl??nge (Full Speed) ist 1023, Alignment au??erdem + 1024 + + // Transferdeskriptor + sizeof(struct uhci_td); + + uhci->buffers = cdi_mempool_create(8192, request_size); + if (uhci->buffers == NULL) { + d0printf("Cannot create mempool.\n"); + return NULL; + } + + if (cdi_alloc_phys_mem(sizeof(*uhci->queue_heads) * 1024, + (void **)&uhci->queue_heads, (void **)&uhci->phys_queue_heads) == -1) + { + d0printf("Cannot allocate QH memory.\n"); + return NULL; + } + + if (cdi_alloc_phys_mem(4096, (void **)&uhci->frame_list, + (void **)&uhci->phys_frame_list) == -1) + { + d0printf("Cannot allocate frame list.\n"); + return NULL; + } + +#ifdef CDI_PCI_DIRECT_ACCESS + cdi_pci_config_writew(uhci->pcidev, 4, 0x05); +#endif + + cdi_register_irq(uhci->pcidev->irq, &uhci_handler, &uhci->cdidev.dev); + uhci->root_ports = (size - 0x10) >> 1; + //Erstmal testen, wie viele wir genau haben... + for (i = 2; i < uhci->root_ports; i++) { + if (!(cdi_inw(uhci->pbase + UHCI_RPORTS + i * 2) & 0x0080) || + (cdi_inw(uhci->pbase + UHCI_RPORTS + i * 2) == 0xFFFF)) + { + uhci->root_ports = i; + break; + } + } + //Mehr als sieben Rootports, klingt lustig + if (uhci->root_ports > 7) { + uhci->root_ports = 2; + } + + d1printf("I/O 0x%04X (%i ports), IRQ %i\n", uhci->pbase, uhci->root_ports, + uhci->pcidev->irq); + +#ifdef CDI_PCI_DIRECT_ACCESS + legsup = cdi_pci_config_readw(uhci->pcidev, UHCI_PCI_LEGSUP); +#endif + cmd = cdi_inw(uhci->pbase + UHCI_USBCMD); + intr = cdi_inw(uhci->pbase + UHCI_USBINTR); + +#ifdef CDI_PCI_DIRECT_ACCESS + //Wenn der HC l??uft, das Configurebit gesetzt ist, der nicht runtergefahren + //ist oder dieses Interrupt-enable-Bit gesetzt ist, dann war wohl schon + //jemand dran. + //(oder wenn der Legacy Support aktiviert ist, das hei??t, wenn in LEGSUP + //irgendein Bit gesetzt ist, dass nicht RO/reserviert oder ein Statusbit + //ist) + if ((legsup & ~(UHCI_LEGSUP_STATUS | UHCI_LEGSUP_NO_CHG)) || + (cmd & USB_RUN) || !(cmd & CONFIGURE) || !(cmd & GLOB_SUSP_MODE) || + (intr & 0x0002)) + { + //Na, wer hat denn da am HC rumgefummelt. B????????ses BIOS. Oder SMM. Oder + //wer auch immer. + //Alle LEGSUP-Statusbits l??schen + cdi_pci_config_writew(uhci->pcidev, UHCI_PCI_LEGSUP, + UHCI_LEGSUP_STATUS); +#endif + //Resetten + cdi_outw(uhci->pbase + UHCI_USBCMD, HCRESET); + //Warten, bis der Reset beendet ist + for (i = 0; (cdi_inw(uhci->pbase + UHCI_USBCMD) & HCRESET) && + (i < 50); i++) + { + cdi_sleep_ms(10); + } + if (i == 50) { + d1printf("Reset not finished...\n"); + } + + //Interrupts erstmal deaktivieren + cdi_outw(uhci->pbase + UHCI_USBINTR, 0); + //Den gesamten HC ebenso + cdi_outw(uhci->pbase + UHCI_USBCMD, 0); + + //Alle Ports "runterfahren" + for (int port = 0; port < uhci->root_ports; port++) { + cdi_outw(uhci->pbase + UHCI_RPORTS + (port * 2), 0); + } +#ifdef CDI_PCI_DIRECT_ACCESS + } +#endif + + for (i = 0; i < 1024; i++) { + uhci->queue_heads[i].next = 1; //Invalid + uhci->queue_heads[i].transfer = 1; //Invalid + } + for (i = 0; i < 1024; i++) { + uhci->frame_list[i] = (uintptr_t)&uhci->phys_queue_heads[i] | 2; + } + + //Standardwert, jede Millisekunde ein Frame + cdi_outb(uhci->pbase + UHCI_SOFMOD, 0x40); + //Unsere Frameliste eintragen + cdi_outl(uhci->pbase + UHCI_FRBASEADD, uhci->phys_frame_list); + //Frame zur??cksetzen + cdi_outw(uhci->pbase + UHCI_FRNUM, 0); +#ifdef CDI_PCI_DIRECT_ACCESS + //Hier setzen wir das PIRQ-Bit und deaktivieren s??mtlichen Legacy Support. + cdi_pci_config_writew(uhci->pcidev, UHCI_PCI_LEGSUP, UHCI_LEGSUP_PIRQ); +#else + d0printf("Failed to deactivate USB legacy support.\n"); +#endif + + //HC starten + cdi_outw(uhci->pbase + UHCI_USBCMD, USB_RUN | CONFIGURE | MAXP); + //Alle Interrupts aktivieren + cdi_outw(uhci->pbase + UHCI_USBINTR, 0xF); + + //Connect status change l??schen + for (i = 0; i < uhci->root_ports; i++) { + cdi_outw(uhci->pbase + UHCI_RPORTS + i * 2, RPORT_CSC); + } + + return &uhci->cdidev.dev; +} + + +static struct cdi_usb_hcd driver = { + .drv = { + .type = CDI_USB_HCD, + .name = DRIVER_NAME, + .devices = NULL, + .init_device = &uhci_init_device, + .remove_device = NULL, + .init = &uhci_init_driver, + .destroy = NULL, + }, + + .find_devices = uhci_find_devices, + .activate_device = uhci_activate_device, + .send_packets = uhci_do_packets, + .add_pipe = uhci_add_pipe, +}; + +CDI_DRIVER(DRIVER_NAME, driver) diff --git a/uhci/transfer.c b/uhci/transfer.c new file mode 100644 index 0000000..33c60bf --- /dev/null +++ b/uhci/transfer.c @@ -0,0 +1,91 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#include + +#include +#include +#include + +#include "uhci.h" + +cdi_list_t uhci_active_transfers = NULL; + +void uhci_handler(struct cdi_device *cdi_hci) +{ + struct uhci *uhci = (struct uhci *)cdi_hci; + int status = cdi_inw(uhci->pbase + UHCI_USBSTS), i; + struct transfer *addr; + struct uhci_td *td; + + if (!status) { + //Also, von hier kommt der IRQ nicht. + return; + } + //Ist Bit 0 gesetzt, dann ist das ein normaler IOC (Interrupt on + //completion), bei Bit 1 ist ein Fehler aufgetreten, aber das werden wir ja + //unten sehen. + if (status & ~0x0003) { + d1printf("Unerwarteter IRQ 0x%04X von %s\n", status, cdi_hci->name); + } + if (status & 0x10) { + d0printf("SCHWERWIEGENDER FEHLER - HC WIRD ANGEHALTEN\n"); + cdi_outw(uhci->pbase + UHCI_USBCMD, MAXP | HCRESET); //FU! + } else { + for (i = 0; (addr = cdi_list_get(uhci_active_transfers, i)) != NULL; + i++) + { + td = addr->virt; + if (td->active) { + continue; + } + addr->error = CDI_USB_NO_ERROR; + cdi_list_remove(uhci_active_transfers, i--); + if (td->stalled_err) { + d0printf("ENDPOINT STALLED\n"); + addr->error |= CDI_USB_STALLED; + } + if (td->buf_err) { + d1printf("Puffer??berlauf oder Underrun\n"); + addr->error |= CDI_USB_BUFFER_ERROR; + } + if (td->babble) { + d1printf("Da war ein Ger??t wohl sehr gespr??chig: Babble.\n"); + addr->error |= CDI_USB_BABBLE; + } + if (td->nak) { + d1printf("NAK empfangen\n"); + addr->error |= CDI_USB_NAK; + } + if (td->crc_time_err) { + d1printf("CRC-Fehler oder Timeout\n"); + addr->error |= CDI_USB_CRC | CDI_USB_TIMEOUT; + } + if (td->bitstuff_err) { + d1printf("Bitstufffehler\n"); + addr->error |= CDI_USB_BITSTUFF; + } + //TODO: free(td) - dazu w??re eine CDI-Funktion n??tzlich + } + } + cdi_outw(uhci->pbase + UHCI_USBSTS, status); +} -- 1.6.0.2 From kevin at tyndur.org Mon Jan 4 20:55:34 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Mon, 4 Jan 2010 20:55:34 +0100 Subject: [cdi-devel] [PATCH 4/5] USB 1.1 In-Reply-To: <1262634935-24109-1-git-send-email-kevin@tyndur.org> References: <1262634935-24109-1-git-send-email-kevin@tyndur.org> Message-ID: <1262634935-24109-5-git-send-email-kevin@tyndur.org> From: Max Reitz + Added USB 1.1 bus driver Signed-off-by: Max Reitz Signed-off-by: Kevin Wolf --- usb11/control.c | 252 +++++++++++++++++++++++++++++++++++++++++++ usb11/include/control.h | 31 ++++++ usb11/include/transfer.h | 38 +++++++ usb11/include/usb-structs.h | 184 +++++++++++++++++++++++++++++++ usb11/include/usb11.h | 41 +++++++ usb11/main.c | 58 ++++++++++ usb11/transfer.c | 223 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 827 insertions(+), 0 deletions(-) create mode 100644 usb11/control.c create mode 100644 usb11/include/control.h create mode 100644 usb11/include/transfer.h create mode 100644 usb11/include/usb-structs.h create mode 100644 usb11/include/usb11.h create mode 100644 usb11/main.c create mode 100644 usb11/transfer.c diff --git a/usb11/control.c b/usb11/control.c new file mode 100644 index 0000000..170341d --- /dev/null +++ b/usb11/control.c @@ -0,0 +1,252 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#include + +#include +#include +#include + +#include "usb11.h" +#include "usb-structs.h" +#include "transfer.h" + +static int usb_dev_ids = 1; + +static void enumerate_hub(struct cdi_usb_device *usbdev); + +static int usb11_real_enumerate(struct cdi_usb_device *device) +{ + struct endpoint_desc *ep0; + struct device_desc *dev_desc; + struct cdi_usb_hcd *hcd; + int id; + char *name; + void *position; + struct config_desc *conf_desc; + struct interface_desc *if_desc, *best_if; + + hcd = (struct cdi_usb_hcd *)device->hc->dev.driver; + + //EP0 initialisieren + device->ep0 = malloc(sizeof(*device->ep0)); + device->ep0->endpoint = malloc(sizeof(struct endpoint_desc)); + ep0 = (struct endpoint_desc *)device->ep0->endpoint; + ep0->length = sizeof(struct endpoint_desc); + ep0->descriptor_type = DESC_ENDPOINT; + ep0->endpoint_address = 0; + ep0->attributes = 0; + ep0->max_packet_size = 8; + ep0->interval = 0; + device->ep0->device = device; + device->ep0->data_toggle = 0; + + //Zur??cksetzen + device->reset(device); + + //Pipe erzeugen + hcd->add_pipe(device->ep0); + + //Erste acht Bytes des Device-Descriptors abrufen und die maximale + //Paketgr????e von EP0 feststellen + dev_desc = usb11_do_control(device, DEV_TO_HOST, NULL, 8, STD_REQUEST, + REC_DEVICE, GET_DESCRIPTOR, DESC_DEVICE << 8, 0); + if (dev_desc == NULL) { + return 0; + } + ep0->max_packet_size = dev_desc->max_packet_size0; + + //Nochmals zur??cksetzen + device->reset(device); + + //USB-Adresse zuweisen + usb11_do_control(device, HOST_TO_DEV | NO_DATA, NULL, 0, STD_REQUEST, + REC_DEVICE, SET_ADDRESS, (id = usb_dev_ids++), 0); + device->id = id; + if (usb_dev_ids >= 128) { + d0printf("Warning: USB device ID overflow.\n"); + usb_dev_ids = 1; + } + + //So, jetzt haben wir eine Adresse, da gibts auch eine neue Pipe + hcd->add_pipe(device->ep0); + + //Den ganzen Device-Descriptor einlesen + dev_desc = usb11_do_control(device, DEV_TO_HOST, NULL, sizeof(*dev_desc), + STD_REQUEST, REC_DEVICE, GET_DESCRIPTOR, DESC_DEVICE << 8, 0); + device->device_desc = dev_desc; + device->vendor_id = dev_desc->vendor_id; + device->device_id = dev_desc->device_id; + + if (dev_desc->iManufacturer) { + name = usb11_do_control(device, DEV_TO_HOST, NULL, 64, STD_REQUEST, + REC_DEVICE, GET_DESCRIPTOR, + (DESC_STRING << 8) | dev_desc->iManufacturer, 0); + if (name == NULL) { + return 0; + } + d1printf(" -> Manufacturer: "); + for (int i = 2; i < name[0]; i += 2) { + _d1printf("%c", name[i]); + } + _d1printf("\n"); + } + if (dev_desc->iProduct) { + name = usb11_do_control(device, DEV_TO_HOST, NULL, 64, STD_REQUEST, + REC_DEVICE, GET_DESCRIPTOR, + (DESC_STRING << 8) | dev_desc->iProduct, 0); + if (name == NULL) { + return 0; + } + d1printf(" -> Product: "); + for (int i = 2; i < name[0]; i += 2) { + _d1printf("%c", name[i]); + } + _d1printf("\n"); + } + //TODO: Man kann doch nicht immer den ersten nehmen... + conf_desc = usb11_do_control(device, DEV_TO_HOST, NULL, + sizeof(struct config_desc), STD_REQUEST, REC_DEVICE, GET_DESCRIPTOR, + DESC_CONFIGURATION << 8, 0); + if (conf_desc == NULL) { + return 0; + } + conf_desc = usb11_do_control(device, DEV_TO_HOST, NULL, + conf_desc->total_length, STD_REQUEST, REC_DEVICE, GET_DESCRIPTOR, + DESC_CONFIGURATION << 8, 0); + if (conf_desc == NULL) { + return 0; + } + device->config_desc = conf_desc; + usb11_do_control(device, HOST_TO_DEV, NULL, 0, STD_REQUEST, REC_DEVICE, + SET_CONFIGURATION, conf_desc->config_value, 0); + if (conf_desc->iConfiguration) { + name = usb11_do_control(device, DEV_TO_HOST, NULL, 64, STD_REQUEST, + REC_DEVICE, GET_DESCRIPTOR, + (DESC_STRING << 8) | conf_desc->iConfiguration, 0); + if (name == NULL) { + return 0; + } + d1printf("Using configuration "); + for (int i = 2; i < name[0]; i += 2) { + _d1printf("%c", name[i]); + } + _d1printf(".\n"); + } + position = conf_desc; + position = (void *)((uintptr_t)position + sizeof(struct config_desc)); + best_if = position; //Standard-IF + for (int i = 0; i < conf_desc->num_interfaces; i++) { + if_desc = position; + //TODO MSD ist zwar h??bsch. Aber andere auch ;-) + if (if_desc->interface_class == 8) { + best_if = if_desc; + break; + } + position = (void *)((uintptr_t)position + + sizeof(struct interface_desc) + + if_desc->num_endpoints * sizeof(struct endpoint_desc)); + } + usb11_do_control(device, HOST_TO_DEV, NULL, 0, STD_REQUEST, REC_DEVICE, + SET_INTERFACE, best_if->interface_number, 0); + device->interface_desc = (void *)best_if; + if (best_if->iInterface) { + name = usb11_do_control(device, DEV_TO_HOST, NULL, 64, STD_REQUEST, + REC_DEVICE, GET_DESCRIPTOR, + (DESC_STRING << 8) | best_if->iInterface, 0); + if (name == NULL) { + return 0; + } + d1printf("Using interface "); + for (int i = 2; i < name[0]; i += 2) { + _d1printf("%c", name[i]); + } + _d1printf(".\n"); + } + d1printf("Configuration: %i:%i (%i)\n", conf_desc->config_value, + best_if->interface_number, best_if->interface_class); + + if (!dev_desc->class_id) { //Composite Device + device->class_id = best_if->interface_class; + device->subclass_id = best_if->interface_subclass; + device->protocol_id = best_if->interface_protocol; + } else { + device->class_id = dev_desc->class_id; + device->subclass_id = dev_desc->subclass_id; + device->protocol_id = dev_desc->protocol_id; + } + + if (best_if->interface_class == USBDC_HUB) { + enumerate_hub(device); + } + + return 1; +} + +void usb11_enumerate(struct cdi_usb_device *device) +{ + if (!usb11_real_enumerate(device)) { + free(device->ep0->endpoint); + free(device->ep0); + } +} + +static void reset_hub_device(struct cdi_usb_device *usbdev) +{ + usb11_do_control(usbdev->hub, HOST_TO_DEV, NULL, 0, CLS_REQUEST, REC_OTHER, + SET_FEATURE, PORTF_RESET, usbdev->port + 1); + cdi_sleep_ms(20); +} + +static void enumerate_hub(struct cdi_usb_device *usbdev) +{ + struct hub_desc *hub_desc; + struct cdi_usb_device *down; + uint16_t *port_status; + int i; + + //Mehr als 8 Ports sollte es nicht geben, die Gr????e des Deskriptors wird + //daher wohl nicht gr????er als sizeof()+16 werden + hub_desc = usb11_do_control(usbdev, DEV_TO_HOST, NULL, + sizeof(*hub_desc) + 16, CLS_REQUEST, REC_DEVICE, GET_DESCRIPTOR, + DESC_DEVICE << 8, 0); + for (i = 0; i < hub_desc->nbr_ports; i++) { + port_status = usb11_do_control(usbdev, DEV_TO_HOST, NULL, 4, + CLS_REQUEST,REC_OTHER, GET_STATUS, 0, i + 1); + if (!(port_status[0] & PORT_DEVICE)) { + continue; + } + //Strom an + usb11_do_control(usbdev, HOST_TO_DEV, NULL, 0, CLS_REQUEST, REC_OTHER, + SET_FEATURE, PORTF_POWER, i + 1); + cdi_sleep_ms(hub_desc->pwron2pwrgood * 2); + down = malloc(sizeof(struct cdi_usb_device)); + down->hc = usbdev->hc; + down->hub = usbdev; + down->id = 0; + down->port = i; + down->speed = (port_status[0] & PORT_LOWSPEED) ? + CDI_USB_LOW_SPEED : CDI_USB_FULL_SPEED; + down->reset = &reset_hub_device; + cdi_usb_device_init(down); + } +} diff --git a/usb11/include/control.h b/usb11/include/control.h new file mode 100644 index 0000000..97edefc --- /dev/null +++ b/usb11/include/control.h @@ -0,0 +1,31 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef CONTROL_H +#define CONTROL_H + +#include +#include + +void usb11_enumerate(struct cdi_usb_device *device); + +#endif diff --git a/usb11/include/transfer.h b/usb11/include/transfer.h new file mode 100644 index 0000000..3b0f086 --- /dev/null +++ b/usb11/include/transfer.h @@ -0,0 +1,38 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef TRANSFER_H +#define TRANSFER_H + +#include + +#include + +void *usb11_do_control(struct cdi_usb_device *device, int direction, + void *buffer, int length, int rtype, int recipient, int request, int value, + int index); +void *usb11_export_control(struct cdi_usb_device *device, + struct cdi_usb_control_transfer *transfer); +cdi_usb_status_t usb11_send_packets(struct cdi_usb_packet *packets, + size_t num_packets); + +#endif diff --git a/usb11/include/usb-structs.h b/usb11/include/usb-structs.h new file mode 100644 index 0000000..427d0e5 --- /dev/null +++ b/usb11/include/usb-structs.h @@ -0,0 +1,184 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef USB_STRUCTS_H +#define USB_STRUCTS_H + +#include + + +#define NO_DATA 0x01 +#define DEV_TO_HOST 0x80 +#define HOST_TO_DEV 0x00 +#define STD_REQUEST 0x00 +#define CLS_REQUEST 0x20 +#define VEN_REQUEST 0x40 +#define REC_DEVICE 0x00 +#define REC_INTERFACE 0x01 +#define REC_ENDPOINT 0x02 +#define REC_OTHER 0x03 + +#define GET_STATUS 0 +#define CLEAR_FEATURE 1 +#define SET_FEATURE 3 +#define SET_ADDRESS 5 +#define GET_DESCRIPTOR 6 +#define SET_DESCRIPTOR 7 +#define GET_CONFIGURATION 8 +#define SET_CONFIGURATION 9 +#define GET_INTERFACE 10 +#define SET_INTERFACE 11 +#define SYNC_FRAME 12 + +#define PORT_DEVICE 0x0001 +#define PORT_ENABLED 0x0002 +#define PORT_SUSPENDED 0x0004 +#define PORT_OVERCURRENT 0x0008 +#define PORT_RESET 0x0010 +#define PORT_POWER 0x0100 +#define PORT_LOWSPEED 0x0200 +#define PORT_HIGHSPEED 0x0400 +#define PORT_TEST 0x0800 +#define PORT_INDICATOR 0x1000 + +#define PORTF_CONNECTION 0 +#define PORTF_ENABLE 1 +#define PORTF_SUSPEND 2 +#define PORTF_OVERCURRENT 3 +#define PORTF_RESET 4 +#define PORTF_POWER 8 +#define PORTF_LOWSPEED 9 +#define PORTF_HIGHSPEED 10 +#define PORTF_C_CONNECTION 16 +#define PORTF_C_ENABLE 17 +#define PORTF_C_SUSPEND 18 +#define PORTF_C_OVERCURRENT 19 +#define PORTF_C_RESET 20 +#define PORTF_TEST 21 +#define PORTF_INDICATOR 22 + +#define DESC_DEVICE 1 +#define DESC_CONFIGURATION 2 +#define DESC_STRING 3 +#define DESC_INTERFACE 4 +#define DESC_ENDPOINT 5 +#define DESC_DEVICE_QUALIFIER 6 +#define DESC_OTHER_SPEED_CONFIGURATION 7 +#define DESC_INTERFACE_POWER 8 + + +struct setup_packet +{ + uint8_t request_type; + uint8_t request; + uint16_t value; + uint16_t index; + uint16_t length; +} __attribute__((packed)); + +struct device_desc +{ + uint8_t length; + uint8_t descriptor_type; + uint16_t bcdUSB; + uint8_t class_id; + uint8_t subclass_id; + uint8_t protocol_id; + uint8_t max_packet_size0; + uint16_t vendor_id; + uint16_t device_id; + uint16_t bcdDevice; + uint8_t iManufacturer; + uint8_t iProduct; + uint8_t iSerialNumber; + uint8_t num_configurations; +} __attribute__((packed)); + +struct config_desc +{ + uint8_t length; + uint8_t descriptor_type; + uint16_t total_length; + uint8_t num_interfaces; + uint8_t config_value; + uint8_t iConfiguration; + uint8_t attributes; + uint8_t max_power; +} __attribute__((packed)); + +struct interface_desc +{ + uint8_t length; + uint8_t descriptor_type; + uint8_t interface_number; + uint8_t alternate_setting; + uint8_t num_endpoints; + uint8_t interface_class; + uint8_t interface_subclass; + uint8_t interface_protocol; + uint8_t iInterface; +} __attribute__((packed)); + +struct endpoint_desc +{ + uint8_t length; + uint8_t descriptor_type; + uint8_t endpoint_address; + uint8_t attributes; + uint16_t max_packet_size; + uint8_t interval; +} __attribute__((packed)); + +struct hub_desc +{ + uint8_t length; + uint8_t descriptor_type; + uint8_t nbr_ports; + uint16_t hub_characteristics; + uint8_t pwron2pwrgood; + uint8_t hub_contr_current; +} __attribute__((packed)); + +typedef enum +{ + USBDC_COMPOSITE = 0x00, + USBDC_AUDIO = 0x01, + USBDC_COMM_CDC = 0x02, + USBDC_HID = 0x03, + USBDC_PID = 0x05, + USBDC_IMAGE = 0x06, + USBDC_PRINTER = 0x07, + USBDC_MSC = 0x08, + USBDC_HUB = 0x09, + USBDC_CDC_DATA = 0x0A, + USBDC_CHIP = 0x0B, + USBDC_SECURITY = 0x0D, + USBDC_VIDEO = 0x0E, + USBDC_HEALTH = 0x0F, + USBDC_DIAGNOSIS = 0xDC, + USBDC_WIRELESS = 0xE0, + USBDC_MISC = 0xEF, + USBDC_SOFT_SPEC = 0xFE, + USBDC_VENDOR_SPEC = 0xFF +} usb_class_t; + +#endif diff --git a/usb11/include/usb11.h b/usb11/include/usb11.h new file mode 100644 index 0000000..77634e9 --- /dev/null +++ b/usb11/include/usb11.h @@ -0,0 +1,41 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef USB11_H +#define USB11_H + +#include + +//#define DEBUG + +#ifdef DEBUG +#define d1printf(...) printf("[usb 1.1] " __VA_ARGS__) +#define _d1printf(...) printf(__VA_ARGS__) +#else +#define d1printf(...) +#define _d1printf(...) +#endif + +#define d0printf(...) printf("[usb 1.1] " __VA_ARGS__) +#define _d0printf(...) printf(__VA_ARGS__) + +#endif diff --git a/usb11/main.c b/usb11/main.c new file mode 100644 index 0000000..e381062 --- /dev/null +++ b/usb11/main.c @@ -0,0 +1,58 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#include +#include + +#include "control.h" +#include "transfer.h" + +#define DRIVER_NAME "USB 1.1" + +int init_usb11(void); + +static struct cdi_usb_driver driver = { + .drv = { + .type = CDI_USB, + .name = DRIVER_NAME, + .devices = NULL, + .init_device = NULL, + .remove_device = NULL, + .init = &init_usb11, + .destroy = NULL + }, + .speeds = CDI_USB_LOW_SPEED | CDI_USB_FULL_SPEED, + .enumerate_device = &usb11_enumerate, + .send_packets = &usb11_send_packets, + .do_control = &usb11_export_control +}; + +CDI_DRIVER(DRIVER_NAME, driver) + +int init_usb11() +{ + cdi_init(); + + cdi_usb_driver_init(&driver); + + return 0; +} diff --git a/usb11/transfer.c b/usb11/transfer.c new file mode 100644 index 0000000..eb4f949 --- /dev/null +++ b/usb11/transfer.c @@ -0,0 +1,223 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#include +#include + +#include + +#include "transfer.h" +#include "usb11.h" +#include "usb-structs.h" + +#define MIN(a, b) ((a) < (b) ? (a) : (b)) + +/** + * Verarbeitet USB-Pakete. + * + * @param packet Die Paketliste + * @param num_packets Anzahl der Pakete + * + * @return Status + */ + +cdi_usb_status_t usb11_send_packets(struct cdi_usb_packet *packets, + size_t num_packets) +{ + cdi_usb_status_t error = CDI_USB_NAK; + int i = 0, mps; + int num_out_packets; + struct cdi_usb_pipe *pipe; + struct cdi_usb_device *device; + struct cdi_usb_packet *out_packets; + struct endpoint_desc *ep; + struct cdi_usb_hcd *hcd; + + if (num_packets < 1) { + return CDI_USB_TRIVIAL_ERROR; + } + + // Alle Pakete muessen dieselbe Pipe benutzen + pipe = packets[0].pipe; + for (i = 1; i < (int)num_packets; i++) { + if (packets[i].pipe != pipe) { + return CDI_USB_TRIVIAL_ERROR; + } + } + + device = pipe->device; + hcd = (struct cdi_usb_hcd *)device->hc->dev.driver; + ep = (struct endpoint_desc *)pipe->endpoint; + + // Pruefen, wie viele Pakete wir draus machen muessen + mps = ep->max_packet_size; + num_out_packets = 0; + for (i = 0; i < (int)num_packets; i++) { + int num = (packets[i].length + mps - 1) / mps; + if (num > 0) { + num_out_packets += num; + } else { + // Pakete ohne Daten wollen auch gesendet werden + num_out_packets++; + } + } + + // Ggf. Pakete kopieren und splitten + if (num_out_packets == (int)num_packets) { + out_packets = packets; + } else { + int j; + int cur = 0; + + out_packets = calloc(num_out_packets, sizeof(*out_packets)); + for (i = 0; i < (int)num_packets; i++) { + int num = (packets[i].length + mps - 1) / mps; + if (num == 0) { + num = 1; + } + + for (j = 0; j < num; j++) { + out_packets[cur].pipe = pipe; + out_packets[cur].type = packets[i].type; + out_packets[cur].data = packets[i].data; + out_packets[cur].length = MIN((int)packets[i].length, mps); + out_packets[cur].condition = CDI_USB_NAK; + + packets[i].data = (void *)((uintptr_t)packets[i].data + + out_packets[cur].length); + packets[i].length -= out_packets[cur].length; + cur++; + } + } + } + + error = hcd->send_packets(out_packets, num_out_packets); + if (error & CDI_USB_STALLED) { + d0printf("ENDPOINT 0x%02X OF DEVICE %i STALLED!\n", + ep->endpoint_address, device->id); + usb11_do_control(device, HOST_TO_DEV | NO_DATA, NULL, 0, STD_REQUEST, + REC_ENDPOINT, CLEAR_FEATURE, 0, ep->endpoint_address); + } else if (error & CDI_USB_NAK) { + // Nicht angenommene Pakete (FIXME: einzeln) senden + for (i = 0; i < num_out_packets; i++) { + if (!(out_packets[i].condition & CDI_USB_NAK)) { + continue; + } + error = CDI_USB_NAK; + while (error & CDI_USB_NAK) { + error = hcd->send_packets(&out_packets[i], 1); + if (error & CDI_USB_NAK) { + cdi_sleep_ms(5); + } + } + } + } + + if (out_packets != packets) { + free(out_packets); + } + + return error; +} + +void *usb11_do_control(struct cdi_usb_device *device, int direction, + void *buffer, int length, int rtype, int recipient, int request, int value, + int index) +{ + int no_data, alloced_here = 0; + cdi_usb_status_t rval; + struct setup_packet _setup; + struct setup_packet *setup = &_setup; + + no_data = direction & NO_DATA; + direction &= 0x80; + + setup->request_type = direction | (rtype & 0x60) | (recipient & 0x1F); + setup->request = request; + setup->value = value; + setup->index = index; + setup->length = length; + + struct cdi_usb_packet setup_packet = { + .pipe = device->ep0, + .type = CDI_USB_PACKET_SETUP, + .data = setup, + .length = sizeof(*setup), + .use_toggle = TOGGLE_UNSPECIFIC + }; + + if (usb11_send_packets(&setup_packet, 1)) { + return NULL; + } + + if (no_data) { + rval = CDI_USB_NO_ERROR; + buffer = (void *)0xFFFFFFFF; //Kein Fehler, aber auch keine Daten + } else { + if ((direction != HOST_TO_DEV) || (length && (buffer == NULL))) { + buffer = malloc(length); + alloced_here = 1; + } + + struct cdi_usb_packet data_packet = { + .pipe = device->ep0, + .type = (direction == DEV_TO_HOST ? + CDI_USB_PACKET_IN : CDI_USB_PACKET_OUT), + .data = buffer, + .length = length, + .use_toggle = TOGGLE_UNSPECIFIC + }; + + rval = usb11_send_packets(&data_packet, 1); + } + + if (rval == CDI_USB_NO_ERROR) { + struct cdi_usb_packet ack_packet = { + .pipe = device->ep0, + .data = NULL, + .length = 0, + .use_toggle = TOGGLE_1 + }; + + if (no_data || (direction == HOST_TO_DEV)) { + ack_packet.type = CDI_USB_PACKET_IN; + } else { + ack_packet.type = CDI_USB_PACKET_OUT; + } + + rval = usb11_send_packets(&ack_packet, 1); + } + + if ((rval != CDI_USB_NO_ERROR) && alloced_here) { + free(buffer); + } + + return (rval == CDI_USB_NO_ERROR) ? buffer : NULL; +} + +void *usb11_export_control(struct cdi_usb_device *device, + struct cdi_usb_control_transfer *transfer) +{ + return usb11_do_control(device, transfer->direction, transfer->buffer, + transfer->length, transfer->rtype, transfer->recipient, + transfer->request, transfer->value, transfer->index); +} -- 1.6.0.2 From kevin at tyndur.org Mon Jan 4 20:55:35 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Mon, 4 Jan 2010 20:55:35 +0100 Subject: [cdi-devel] [PATCH 5/5] USB MSD In-Reply-To: <1262634935-24109-1-git-send-email-kevin@tyndur.org> References: <1262634935-24109-1-git-send-email-kevin@tyndur.org> Message-ID: <1262634935-24109-6-git-send-email-kevin@tyndur.org> From: Max Reitz + Added USB mass storage driver (currently just bulk-only devices supported) Signed-off-by: Max Reitz Signed-off-by: Kevin Wolf --- usb-msd/include/msd.h | 121 ++++++++++++ usb-msd/main.c | 68 +++++++ usb-msd/msd.c | 485 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 674 insertions(+), 0 deletions(-) create mode 100644 usb-msd/include/msd.h create mode 100644 usb-msd/main.c create mode 100644 usb-msd/msd.c diff --git a/usb-msd/include/msd.h b/usb-msd/include/msd.h new file mode 100644 index 0000000..bb6cf51 --- /dev/null +++ b/usb-msd/include/msd.h @@ -0,0 +1,121 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#ifndef MSD_H +#define MSD_H + +#include +#include + +//#define DEBUG + +#ifdef DEBUG +#define d1printf(...) printf("[usb-msd] " __VA_ARGS__) +#define _d1printf(...) printf(__VA_ARGS__) +#else +#define d1printf(...) +#define _d1printf(...) +#endif + +#define d0printf(...) printf("[usb-msd] " __VA_ARGS__) +#define _d0printf(...) printf(__VA_ARGS__) + +//"USBC" +#define CBW_SIGNATURE 0x43425355 +struct command_block_wrapper +{ + uint32_t cbw_signature; + uint32_t cbw_tag; + uint32_t cbw_data_transfer_length; + uint8_t cbw_flags; + uint8_t cbw_lun; + uint8_t cbw_cb_length; + uint8_t cbw_cb[16]; +} __attribute__((packed)); + +//"USBS" +#define CSW_SIGNATURE 0x53425355 +struct command_status_wrapper +{ + uint32_t csw_signature; + uint32_t csw_tag; + uint32_t csw_data_residue; + uint8_t csw_status; +} __attribute__((packed)); + +struct msc_sense +{ + unsigned error : 7; + unsigned valid : 1; + uint8_t rsvd0; + unsigned sense_key : 4; + unsigned rsvd1 : 4; + uint32_t information; + uint8_t additional_length; + uint32_t rsvd2; + uint8_t additional_code; + uint8_t additional_code_qualifier; + uint32_t rsvd; +} __attribute__((packed)); + +struct msd_capacity +{ + uint32_t last_lba; + uint32_t block_length; +} __attribute__((packed)); + +struct cdi_msd +{ + struct cdi_storage_device cdi_device; + struct cdi_usb_device *usb_device; + struct cdi_usb_pipe *bulk_in; + struct cdi_usb_pipe *bulk_out; + uint32_t offset; //F??r Partitionen +}; + +struct part_table_entry +{ + uint8_t active; + uint8_t begin_chs[3]; + uint8_t type; + uint8_t end_chs[3]; + uint32_t start; + uint32_t size; +} __attribute__((packed)); + + +#define MSC_CMD_REZERO 0x01 +#define MSC_CMD_SENSE 0x03 +#define MSC_CMD_CAPACITY 0x25 +#define MSC_CMD_READ10 0x28 +#define MSC_CMD_WRITE10 0x2A +#define MSC_CMD_SEEK 0x2B +#define MSC_CMD_READ12 0xA8 +#define MSC_CMD_WRITE12 0xAA + +int check_msd(struct cdi_usb_device *device); +int msd_read_blocks(struct cdi_storage_device *device, uint64_t start, + uint64_t count, void *buffer); +int msd_write_blocks(struct cdi_storage_device *device, uint64_t start, + uint64_t count, void *buffer); + +#endif diff --git a/usb-msd/main.c b/usb-msd/main.c new file mode 100644 index 0000000..c5c401f --- /dev/null +++ b/usb-msd/main.c @@ -0,0 +1,68 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#include +#include +#include + +#include "msd.h" + +#define DRIVER_NAME "usb-msd" + +static int init_msd(void); + +struct cdi_storage_driver msc_driver = { + .drv = { + .type = CDI_STORAGE, + .name = DRIVER_NAME, + .devices = NULL, + .init_device = NULL, + .remove_device = NULL, + .init = &init_msd, + .destroy = NULL + }, + .read_blocks = &msd_read_blocks, + .write_blocks = &msd_write_blocks +}; + +CDI_DRIVER(DRIVER_NAME, msc_driver) + +static struct cdi_usb_device_pattern msd_pattern = { + .vendor_id = -1, + .device_id = -1, + .class_id = 8, + .subclass_id = -1, + .protocol_id = -1, + + .take_usb_device = &check_msd +}; + +static int init_msd() +{ + cdi_init(); + + cdi_storage_driver_init(&msc_driver); + + cdi_usb_register_device_pattern(&msd_pattern); + + return 0; +} diff --git a/usb-msd/msd.c b/usb-msd/msd.c new file mode 100644 index 0000000..0385389 --- /dev/null +++ b/usb-msd/msd.c @@ -0,0 +1,485 @@ +/***************************************************************************** +* Copyright (c) 2009 Max Reitz * +* * +* Permission is hereby granted, free of charge, to any person obtaining a * +* copy of this software and associated documentation files (the "Software"), * +* to deal in the Software without restriction, including without limitation * +* the rights to use, copy, modify, merge, publish, distribute, sublicense, * +* and/or sell copies of the Software, and to permit persons to whom the * +* Software is furnished to do so, subject to the following conditions: * +* * +* The above copyright notice and this permission notice shall be included in * +* all copies or substantial portions of the Software. * +* * +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * +* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * +* DEALINGS IN THE SOFTWARE. * +*****************************************************************************/ + +#include +#include +#include + +#include +#include +#include +#include + +#include "msd.h" + +//TODO: CDI-Funktion w??re hier sicher n??tzlich... +#define CPU_IS_LITTLE_ENDIAN + +#define change_endianess_32(_) ((((_) & \ + 0xFF000000) >> \ + 24) | \ + (((_) & \ + 0xFF0000) >> \ + 8) | \ + (((_) & 0xFF00) << 8) | (((_) & 0xFF) << 24)) +#ifdef CPU_IS_LITTLE_ENDIAN +#define CPU2BE(_) change_endianess_32(_) +#define CPU2LE(_) (_) +#define BE2CPU(_) change_endianess_32(_) +#define LE2CPU(_) (_) +#else +#define CPU2BE(_) (_) +#define CPU2LE(_) change_endianess_32(_) +#define BE2CPU(_) (_) +#define LE2CPU(_) change_endianess_32(_) +#endif + +extern struct cdi_storage_driver msc_driver; +static uint32_t cbw_tag = 1; + +static int msd_cdi_read(struct cdi_storage_device *strgdev, uint64_t start, + uint64_t count, void *buffer); +static int msd_cdi_write(struct cdi_storage_device *strgdev, uint64_t start, + uint64_t count, void *buffer); + +int msd_read_blocks(struct cdi_storage_device *device, uint64_t start, + uint64_t count, void *buffer) +{ + return msd_cdi_read(device, start, count, buffer); +} + +int msd_write_blocks(struct cdi_storage_device *device, uint64_t start, + uint64_t count, void *buffer) +{ + return msd_cdi_write(device, start, count, buffer); +} + +static int msd_get_capacity(struct cdi_usb_device *usbdev, + uint32_t *block_size, uint32_t *block_count); + +int check_msd(struct cdi_usb_device *device) +{ + struct cdi_storage_device *strgdev; + struct cdi_usb_endpoint *ep_desc; + struct cdi_msd *cdimsd; + struct cdi_usb_hcd *hcd; + void *address; + int i; + uint32_t bs, bc; + uint64_t size; + static int msdnum = 0; + + //Nur Bulk-Only + if (device->protocol_id != 0x50) { + return 0; + } + + d0printf("MSD detected.\n"); + + cdimsd = malloc(sizeof(struct cdi_msd)); + if (cdimsd == NULL) { + return 0; + } + cdimsd->usb_device = device; + cdimsd->offset = 0; + strgdev = (struct cdi_storage_device *)cdimsd; + strgdev->dev.name = malloc(10); + if (strgdev->dev.name == NULL) { + free(strgdev); + return 0; + } + sprintf((char *)strgdev->dev.name, "usb-msd%i", msdnum++); + strgdev->dev.driver = (struct cdi_driver *)&msc_driver; + device->driver_data = cdimsd; + cdimsd->bulk_in = malloc(sizeof(*cdimsd->bulk_in)); + cdimsd->bulk_in->device = device; + cdimsd->bulk_in->endpoint = NULL; + cdimsd->bulk_in->data_toggle = 0; + cdimsd->bulk_out = malloc(sizeof(*cdimsd->bulk_out)); + cdimsd->bulk_out->device = device; + cdimsd->bulk_out->endpoint = NULL; + cdimsd->bulk_out->data_toggle = 0; + address = (void *)((uintptr_t)device->interface_desc + + sizeof(struct cdi_usb_interface)); + for (i = 0; i < device->interface_desc->num_endpoints; i++) { + ep_desc = address; + if ((ep_desc->endpoint_address & 0x80) && + (ep_desc->attributes == 0x02) && + (cdimsd->bulk_in->endpoint == NULL)) + { + //BULK-IN + cdimsd->bulk_in->endpoint = ep_desc; + } + else if (!(ep_desc->endpoint_address & 0x80) && + (ep_desc->attributes == 0x02) && + (cdimsd->bulk_out->endpoint == NULL)) + { + //BULK-OUT + cdimsd->bulk_out->endpoint = ep_desc; + } + address = (void *)((uintptr_t)address + + sizeof(struct cdi_usb_endpoint)); + } + if ((cdimsd->bulk_in->endpoint == NULL) || + (cdimsd->bulk_out->endpoint == NULL)) + { + d0printf("Not enough endpoints found.\n"); + return 0; + } + hcd = (struct cdi_usb_hcd *)device->hc->dev.driver; + hcd->add_pipe(cdimsd->bulk_in); + hcd->add_pipe(cdimsd->bulk_out); + if (!msd_get_capacity(device, &bs, &bc)) { + strgdev->block_size = 0; + strgdev->block_count = 0; + d1printf("Wasn't able to determine size of %s.\n", strgdev->dev.name); + } else { + strgdev->block_size = bs; + strgdev->block_count = bc; + size = bs; + size *= bc; + d1printf("%s: %i * %i B (about %d MB).\n", strgdev->dev.name, bc, bs, + (int)(size >> 20)); + } + cdi_storage_device_init(strgdev); + cdi_list_push(msc_driver.drv.devices, strgdev); + + return 1; +} + +static int write_cmd(struct cdi_usb_device *usbdev, void *src) +{ + struct cdi_msd *cdimsd = usbdev->driver_data; + struct cdi_usb_packet cmd_packet = { + .pipe = cdimsd->bulk_out, + .type = CDI_USB_PACKET_OUT, + .data = src, + .length = 0x1F, + .use_toggle = TOGGLE_UNSPECIFIC + }; + + return usbdev->drv->send_packets(&cmd_packet, 1); +} + +/** + * Liest den Status von einem MSD + * + * @param usbdev Das bewusste Ger??t + * @param expected_tag Das erwartete Tag + * + * @return Wenn der Status OK ist USB_NO_ERROR, sonst entsprechender Fehler + */ + +static int read_status(struct cdi_usb_device *usbdev, uint32_t expected_tag) +{ + struct cdi_msd *msc = usbdev->driver_data; + struct command_status_wrapper _csw; + struct command_status_wrapper *csw = &_csw; + cdi_usb_status_t error; + + struct cdi_usb_packet status_packet = { + .pipe = msc->bulk_in, + .type = CDI_USB_PACKET_IN, + .data = csw, + .length = 0x0D, + .use_toggle = TOGGLE_UNSPECIFIC + }; + + error = usbdev->drv->send_packets(&status_packet, 1); + if (error != CDI_USB_NO_ERROR) { + return error; + } + if ((csw->csw_signature != CSW_SIGNATURE) || + (csw->csw_tag != expected_tag) || csw->csw_status) + { + d1printf("0x%08X %i==%i 0x%08X\n", csw->csw_signature, csw->csw_tag, + expected_tag, csw->csw_status); + return CDI_USB_TRIVIAL_ERROR; + } + + return CDI_USB_NO_ERROR; +} + +static int msd_get_capacity(struct cdi_usb_device *usbdev, + uint32_t *block_size, uint32_t *block_count) +{ + struct cdi_msd *msc; + struct command_block_wrapper _cbw; + struct command_block_wrapper *cbw = &_cbw; + struct msd_capacity _cap; + struct msd_capacity *cap = &_cap; + uint32_t expected_tag; + + if ((usbdev == NULL) || (block_size == NULL) || (block_count == NULL)) { + return 0; + } + + msc = usbdev->driver_data; + memset(cbw, 0, 0x1F); + cbw->cbw_signature = CBW_SIGNATURE; + cbw->cbw_tag = (expected_tag = cbw_tag++); + cbw->cbw_data_transfer_length = sizeof(struct msd_capacity); + cbw->cbw_flags = 0x80; //IN + cbw->cbw_lun = 0; //Was wei?? ich, wie viele LUNs datt Dingens hat? + cbw->cbw_cb_length = 12; + cbw->cbw_cb[0] = MSC_CMD_CAPACITY; + cbw->cbw_cb[1] = 0; //LUN: 0 + + if (write_cmd(usbdev, cbw) != CDI_USB_NO_ERROR) { + return 0; + } + + struct cdi_usb_packet in_packet = { + .pipe = msc->bulk_in, + .type = CDI_USB_PACKET_IN, + .data = cap, + .length = sizeof(*cap), + .use_toggle = TOGGLE_UNSPECIFIC + }; + + if (usbdev->drv->send_packets(&in_packet, 1) != CDI_USB_NO_ERROR) { + return 0; + } + + if (read_status(usbdev, expected_tag) != CDI_USB_NO_ERROR) { + return 0; + } + + *block_size = BE2CPU(cap->block_length); + *block_count = BE2CPU(cap->last_lba) + 1; + + return 1; +} + +#ifdef WAIT_FOR_MSD_READY +static int msd_ready(struct cdi_usb_device *usbdev) +{ + struct msclass_data *msc; + struct command_block_wrapper _cbw; + struct command_block_wrapper *cbw = &_cbw; + uint32_t expected_tag; + + msc = (struct msclass_data *)usbdev->driver_data; + memset(cbw, 0, 0x1F); + cbw->cbw_signature = CBW_SIGNATURE; + cbw->cbw_tag = (expected_tag = cbw_tag++); + cbw->cbw_data_transfer_length = 0; + cbw->cbw_flags = 0x80; //IN + cbw->cbw_lun = 0; //Was wei?? ich, wie viele LUNs datt Dingens hat? + cbw->cbw_cb_length = 12; //Alles null, also "Test unit ready" + + if (write_cmd(usbdev, cbw) != USB_NO_ERROR) { + return 0; + } + + if (read_status(usbdev, expected_tag) != USB_NO_ERROR) { + return 0; + } + + return 1; +} +#endif + +#define MAX_ACCESS_BLOCKS 32 + +static uint32_t msd_read(struct cdi_usb_device *usbdev, uint32_t lba, + uint16_t sectors, void *buffer, size_t length); + +static int msd_cdi_read(struct cdi_storage_device *strgdev, uint64_t start, + uint64_t count, void *buffer) +{ + int bs = strgdev->block_size, error; +#ifdef WAIT_FOR_MSD_READY + int i; +#endif + struct cdi_usb_device *usbdev = ((struct cdi_msd *)strgdev)->usb_device; + int j, bbs; + + d1printf("read(%i, %i)\n", (int)start, (int)count); + start += ((struct cdi_msd *)strgdev)->offset; + + if (!count) { + d1printf("Empty read request.\n"); + return 0; + } + for (j = 0; j < (int)count; j += MAX_ACCESS_BLOCKS) { +#ifdef WAIT_FOR_MSD_READY + for (i = 0; !msd_ready(usbdev) && (i < 10); i++) { + cdi_sleep_ms(20); + } +#endif + bbs = (count - j > MAX_ACCESS_BLOCKS) ? MAX_ACCESS_BLOCKS : count - j; + error = msd_read(usbdev, start + j, bbs, + (void *)((uintptr_t)buffer + j * bs), bbs * bs); + if (error != CDI_USB_NO_ERROR) { + d0printf("Read error 0x%X at block %lld.\n", error, start + j); + return -1; + } + } + return 0; +} + +static uint32_t msd_read(struct cdi_usb_device *usbdev, uint32_t lba, + uint16_t sectors, void *buffer, size_t length) +{ + struct cdi_msd *msc; + struct command_block_wrapper _cbw; + struct command_block_wrapper *cbw = &_cbw; + uint32_t expected_tag; + int error; + + if ((buffer == NULL) || !length) { + return CDI_USB_TRIVIAL_ERROR; + } + msc = usbdev->driver_data; + memset(cbw, 0, 0x1F); + cbw->cbw_signature = CBW_SIGNATURE; + cbw->cbw_tag = (expected_tag = cbw_tag++); + cbw->cbw_data_transfer_length = length; + cbw->cbw_flags = 0x80; //IN + cbw->cbw_lun = 0; //Was wei?? ich, wie viele LUNs datt Dingens hat? + cbw->cbw_cb_length = 12; + cbw->cbw_cb[0] = MSC_CMD_READ10; + cbw->cbw_cb[1] = 0; //LUN: 0 + cbw->cbw_cb[2] = (lba & 0xFF000000) >> 24; + cbw->cbw_cb[3] = (lba & 0x00FF0000) >> 16; + cbw->cbw_cb[4] = (lba & 0x0000FF00) >> 8; + cbw->cbw_cb[5] = lba & 0x000000FF; + cbw->cbw_cb[7] = (sectors & 0x0000FF00) >> 8; + cbw->cbw_cb[8] = sectors & 0x000000FF; + + error = write_cmd(usbdev, cbw); + if (error != CDI_USB_NO_ERROR) { + return error; + } + + struct cdi_usb_packet in_packet = { + .pipe = msc->bulk_in, + .type = CDI_USB_PACKET_IN, + .data = buffer, + .length = length, + .use_toggle = TOGGLE_UNSPECIFIC + }; + + error = usbdev->drv->send_packets(&in_packet, 1); + if (error != CDI_USB_NO_ERROR) { + return error; + } + + error = read_status(usbdev, expected_tag); + if (error != CDI_USB_NO_ERROR) { + return error; + } + + return CDI_USB_NO_ERROR; +} + +static uint32_t msd_write(struct cdi_usb_device *usbdev, uint32_t lba, + uint16_t sectors, void *buffer, size_t length); + +static int msd_cdi_write(struct cdi_storage_device *strgdev, uint64_t start, + uint64_t count, void *buffer) +{ + int bs = strgdev->block_size, error; +#ifdef WAIT_FOR_MSD_READY + int i; +#endif + struct cdi_usb_device *usbdev = ((struct cdi_msd *)strgdev)->usb_device; + int j, bbs; + + d1printf("write(%i, %i)\n", (int)start, (int)count); + start += ((struct cdi_msd *)strgdev)->offset; + + if (!count) { + d1printf("Empty write request.\n"); + return 0; + } + for (j = 0; j < (int)count; j += MAX_ACCESS_BLOCKS) { +#ifdef WAIT_FOR_MSD_READY + for (i = 0; !msd_ready(usbdev) && (i < 10); i++) + cdi_sleep_ms(20); +#endif + bbs = (count - j > MAX_ACCESS_BLOCKS) ? MAX_ACCESS_BLOCKS : count - j; + error = msd_write(usbdev, start + j, bbs, + (void *)((uintptr_t)buffer + j * bs), bbs * bs); + if (error != CDI_USB_NO_ERROR) { + d0printf("Write error 0x%X at block %lld.\n", error, start + j); + return -1; + } + } + return 0; +} + +static uint32_t msd_write(struct cdi_usb_device *usbdev, uint32_t lba, + uint16_t sectors, void *buffer, size_t length) +{ + struct cdi_msd *msc; + struct command_block_wrapper _cbw; + struct command_block_wrapper* cbw = &_cbw; + uint32_t expected_tag; + int error; + + if ((buffer == NULL) || !length) { + return CDI_USB_TRIVIAL_ERROR; + } + msc = usbdev->driver_data; + memset(cbw, 0, 0x1F); + cbw->cbw_signature = CBW_SIGNATURE; + cbw->cbw_tag = (expected_tag = cbw_tag++); + cbw->cbw_data_transfer_length = length; + cbw->cbw_flags = 0x00; //OUT + cbw->cbw_lun = 0; //Was wei?? ich, wie viele LUNs datt Dingens hat? + cbw->cbw_cb_length = 12; + cbw->cbw_cb[0] = MSC_CMD_WRITE10; + cbw->cbw_cb[1] = 0; //LUN: 0 + cbw->cbw_cb[2] = (lba & 0xFF000000) >> 24; + cbw->cbw_cb[3] = (lba & 0x00FF0000) >> 16; + cbw->cbw_cb[4] = (lba & 0x0000FF00) >> 8; + cbw->cbw_cb[5] = lba & 0x000000FF; + cbw->cbw_cb[7] = (sectors & 0x0000FF00) >> 8; + cbw->cbw_cb[8] = sectors & 0x000000FF; + + error = write_cmd(usbdev, cbw); + if (error != CDI_USB_NO_ERROR) { + return error; + } + + struct cdi_usb_packet out_packet = { + .pipe = msc->bulk_out, + .type = CDI_USB_PACKET_OUT, + .data = buffer, + .length = length, + .use_toggle = TOGGLE_UNSPECIFIC + }; + + error = usbdev->drv->send_packets(&out_packet, 1); + if (error != CDI_USB_NO_ERROR) { + return error; + } + + error = read_status(usbdev, expected_tag); + if (error != CDI_USB_NO_ERROR) { + return error; + } + + return CDI_USB_NO_ERROR; +} -- 1.6.0.2 From redelman at gmail.com Sat Jan 9 01:01:29 2010 From: redelman at gmail.com (Rich Edelman) Date: Fri, 8 Jan 2010 18:01:29 -0600 Subject: [cdi-devel] [PATCH] Add English translations to cdi/lists.h Message-ID: <61acd8d31001081601h4972c803ic2a12b8ef406c636@mail.gmail.com> This patch adds English translations to include/cdi/lists.h. Signed-off-by: Rich Edelman --- include/cdi/lists.h | 116 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 files changed, 115 insertions(+), 1 deletions(-) diff --git a/include/cdi/lists.h b/include/cdi/lists.h index 53c3def..48190fa 100644 --- a/include/cdi/lists.h +++ b/include/cdi/lists.h @@ -8,16 +8,36 @@ * http://sam.zoy.org/projects/COPYING.WTFPL for more details. */ +/** + * @file lists.h + * \german + * Funktionen zur Verwaltung von Listen + * \endgerman + * + * \english + * CDI specific functions for list management + * \endenglish + */ + #ifndef _CDI_LISTS_ #define _CDI_LISTS_ #include #include /** + * \german * Repraesentiert eine Liste. * * Der Felder der Struktur sind implementierungsabhaengig. Zum Zugriff auf * Listen muessen immer die spezifizierten Funktionen benutzt werden. + * \endgerman + * + * \english + * Represents a list. + * + * The fields of this structure are implementation dependent. To access list + * elements, specific list functions must be used. + * \endenglish */ typedef struct cdi_list_implementation* cdi_list_t; @@ -25,21 +45,38 @@ typedef struct cdi_list_implementation* cdi_list_t; extern "C" { #endif -/** +/** + * \german * Erzeugt eine neue Liste * * @return Neu erzeugte Liste oder NULL, falls kein Speicher reserviert werden * konnte + * \endgerman + * + * \english + * Creates a new list. + * + * @return Returns a new list, or NULL is no memory could be allocated for the + * list. + * \endenglish */ cdi_list_t cdi_list_create(void); /** + * \german * Gibt eine Liste frei (Werte der Listenglieder m?ssen bereits * freigegeben sein) + * \endgerman + * + * \english + * Frees the memory associated with a list. (Values of the list members must + * already be free.) + * \endenglish */ void cdi_list_destroy(cdi_list_t list); /** + * \german * Fuegt ein neues Element am Anfang (Index 0) der Liste ein * * @param list Liste, in die eingefuegt werden soll @@ -47,27 +84,58 @@ void cdi_list_destroy(cdi_list_t list); * * @return Die Liste, in die eingefuegt wurde, oder NULL, wenn das Element * nicht eingefuegt werden konnte (z.B. kein Speicher frei). + * \endgerman + * + * \english + * Adds a new element to the head of the list. + * + * @param list The list to insert into. + * @param value The element to be added. + * + * @return The list @a value has been inserted into, or NULL if @a value could + * not be inserted (for example, because no memory could be allocated). + * \endenglish */ cdi_list_t cdi_list_push(cdi_list_t list, void* value); /** + * \german * Entfernt ein Element am Anfang (Index 0) der Liste und gibt seinen Wert * zurueck. * * @param list Liste, aus der das Element entnommen werden soll * @return Das entfernte Element oder NULL, wenn die Liste leer war + * \endgerman + * + * \english + * Removes an element from the head of the list and returns that element's + * value. + * + * @param list The list from which the leading element (head) will be removed. + * @return The removed element, or NULL is the list was empty. + * \endenglish */ void* cdi_list_pop(cdi_list_t list); /** + * \german * Prueft, ob die Liste leer ist. * * @param list Liste, die ueberprueft werden soll * @return 1, wenn die Liste leer ist; 0, wenn sie Elemente enthaelt + * \endgerman + * + * \english + * Tests is a list is empty. + * + * @param list The list to test. + * @return 1 if the list is empty, otherwise 0. + * \endenglish */ size_t cdi_list_empty(cdi_list_t list); /** + * \german * Gibt ein Listenelement zurueck * * @param list Liste, aus der das Element gelesen werden soll @@ -75,10 +143,22 @@ size_t cdi_list_empty(cdi_list_t list); * * @return Das angeforderte Element oder NULL, wenn kein Element mit dem * angegebenen Index existiert. + * \endgerman + * + * \english + * Returns the value of a list element at a specified index. + * + * @param list The list from which @a index will be read + * @param index The index of the element to return the value of + * + * @return The list element requested or NULL if no element exists at the + * specified index. + * \endenglish */ void* cdi_list_get(cdi_list_t list, size_t index); /** + * \german * Fuegt ein neues Listenelement ein. Der Index aller Elemente, die bisher * einen groesseeren oder gleich grossen Index haben, verschieben sich * um eine Position nach hinten. @@ -89,10 +169,25 @@ void* cdi_list_get(cdi_list_t list, size_t index); * * @return Die Liste, in die eingefuegt wurde, oder NULL, wenn nicht eingefuegt * werden konnte (z.B. weil der Index zu gross ist) + * \endgerman + * + * \english + * Adds a new element (@a value) to @a list. The element is added at index + * @a index. The index of all elements before @a value shall remain the same, + * while the index of elements after @a value shall increase by one. + * + * @param list The list to insert into + * @param index The index to be used for the new element + * @param value The element to be inserted + * + * @return The newly ordered list, or NULL if the element could not be added + * (for example, because the index is too large). + * \endenglish */ cdi_list_t cdi_list_insert(cdi_list_t list, size_t index, void* value); /** + * \german * Loescht ein Listenelement * * @param list Liste, aus der entfernt werden soll @@ -100,13 +195,32 @@ cdi_list_t cdi_list_insert(cdi_list_t list, size_t index, void* value); * * @return Das entfernte Element oder NULL, wenn kein Element mit dem * angegebenen Index existiert. + * \endgerman + * + * \english + * Removes an element from a list. + * + * @param list The list to remove an element from + * @param index The index in the list that will be removed + * + * @return The element that was removed, or NULL if the element at the + * specified index does not exist. + * \endenglish */ void* cdi_list_remove(cdi_list_t list, size_t index); /** + * \german * Gibt die Laenge der Liste zurueck * * @param list Liste, deren Laenge zurueckgegeben werden soll + * \endgerman + * + * \english + * Get the size (length) of a list + * + * @param list The list whose length is to be returned + * \endenglish */ size_t cdi_list_size(cdi_list_t list); -- 1.6.5.2 From kevin at tyndur.org Sat Jan 9 18:32:47 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Sat, 9 Jan 2010 18:32:47 +0100 Subject: [cdi-devel] [PATCH] Add English translations to cdi/lists.h In-Reply-To: <61acd8d31001081601h4972c803ic2a12b8ef406c636@mail.gmail.com> References: <61acd8d31001081601h4972c803ic2a12b8ef406c636@mail.gmail.com> Message-ID: <20100109173247.GA2204@silvanus> On Fri, Jan 08, 2010 at 06:01:29PM -0600, Rich Edelman wrote: > This patch adds English translations to include/cdi/lists.h. > > Signed-off-by: Rich Edelman Thanks, applied. From kevin at tyndur.org Sun Jan 17 12:03:58 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Sun, 17 Jan 2010 12:03:58 +0100 Subject: [cdi-devel] Interrupts Message-ID: <20100117110355.GA26897@silvanus> Hi all, I'm currently implementing CDI for a small monolithic kernel. Besides getting drivers, my goal in doing so is to find pontential problems with CDI. I think with interrupt handling I've found a first thing that needs clarification on what drivers can expect. In particular, I remember Matt's change to pcnet to use cdi_wait_irq instead of doing it manually. So the question is: Has pcnet ever been right in doing it manually? Was it just ugly or was it wrong? The point is that currently in my kernel CDI drivers generally run with IRQs turned off as the kernel lacks proper locking, so I'm not sure what would happen if I would allow IRQs in any place (or even let it be preempted). So pcnet would wait forever for an IRQ to happen. We should clarify who would be right in this scenario: The kernel or pcnet? Basically I'd say it is reasonable to define that CDI drivers may not assume that they can receive IRQs while running another function. The only exception is when using cdi_wait_irq. If you prefer we could define instead that OSes must always allow IRQs (in the long run you need to make the drivers preemptible anyway). What do you think? Do all other OSes implementing CDI so far allow IRQs at any time or does it just happen to work? (I think meanwhile all drivers are well-behaved and don't do it manually) Kevin From max at tyndur.org Sun Jan 17 14:04:19 2010 From: max at tyndur.org (Max Reitz) Date: Sun, 17 Jan 2010 14:04:19 +0100 Subject: [cdi-devel] Interrupts In-Reply-To: <20100117110355.GA26897@silvanus> References: <20100117110355.GA26897@silvanus> Message-ID: <4B530AD3.1010007@tyndur.org> Kevin Wolf wrote: > What do you think? Do all other OSes implementing CDI so far allow IRQs > at any time or does it just happen to work? I personally allow them all the time and I haven't ever thought about not doing so until now. ;-) Max From matthew at theiselins.net Sun Jan 17 22:28:45 2010 From: matthew at theiselins.net (Matthew Iselin) Date: Mon, 18 Jan 2010 07:28:45 +1000 Subject: [cdi-devel] Interrupts In-Reply-To: <20100117110355.GA26897@silvanus> References: <20100117110355.GA26897@silvanus> Message-ID: On Sun, Jan 17, 2010 at 9:03 PM, Kevin Wolf wrote: > Hi all, > > I'm currently implementing CDI for a small monolithic kernel. Besides > getting drivers, my goal in doing so is to find pontential problems with > CDI. I think with interrupt handling I've found a first thing that needs > clarification on what drivers can expect. In particular, I remember > Matt's change to pcnet to use cdi_wait_irq instead of doing it manually. > > So the question is: Has pcnet ever been right in doing it manually? Was > it just ugly or was it wrong? I would say that pcnet's implementation of its own solution when cdi_wait_irq already exists was fundamentally wrong. There is no point reinventing the wheel in each driver when you already have the functionality available in the interface. > The point is that currently in my kernel CDI drivers generally run with > IRQs turned off as the kernel lacks proper locking, so I'm not sure what > would happen if I would allow IRQs in any place (or even let it be > preempted). So pcnet would wait forever for an IRQ to happen. Perhaps cdi_wait_irq needs a timeout parameter. This way we can also enforce a decent timeframe in which an IRQ should occur, and avoid the case where a driver hangs because an IRQ never arrives. > What do you think? Do all other OSes implementing CDI so far allow IRQs > at any time or does it just happen to work? (I think meanwhile all > drivers are well-behaved and don't do it manually) Drivers that use interrupts should be able to assume interrupts are enabled and working properly. The alternative is to have a function such as cdi_irqs_enabled (probably not called that though) that the driver can call and determine if it should poll or wait for an IRQ. This would probably create multiple code paths for each driver however, and I feel that IRQs are one of the most basic (and required) elements of any operating system. Cheers, Matt From kevin at tyndur.org Sun Jan 17 22:56:22 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Sun, 17 Jan 2010 22:56:22 +0100 Subject: [cdi-devel] Interrupts In-Reply-To: References: <20100117110355.GA26897@silvanus> Message-ID: <20100117215621.GB26897@silvanus> On Mon, Jan 18, 2010 at 07:28:45AM +1000, Matthew Iselin wrote: > On Sun, Jan 17, 2010 at 9:03 PM, Kevin Wolf wrote: > > Hi all, > > > > I'm currently implementing CDI for a small monolithic kernel. Besides > > getting drivers, my goal in doing so is to find pontential problems with > > CDI. I think with interrupt handling I've found a first thing that needs > > clarification on what drivers can expect. In particular, I remember > > Matt's change to pcnet to use cdi_wait_irq instead of doing it manually. > > > > So the question is: Has pcnet ever been right in doing it manually? Was > > it just ugly or was it wrong? > > I would say that pcnet's implementation of its own solution when > cdi_wait_irq already exists was fundamentally wrong. There is no point > reinventing the wheel in each driver when you already have the > functionality available in the interface. Reinventing the wheel is just ugliness, it doesn't lead to fundamentally broken code. But at least you don't seem to be opposed to forbid such things in a better specification. > > The point is that currently in my kernel CDI drivers generally run with > > IRQs turned off as the kernel lacks proper locking, so I'm not sure what > > would happen if I would allow IRQs in any place (or even let it be > > preempted). So pcnet would wait forever for an IRQ to happen. > > Perhaps cdi_wait_irq needs a timeout parameter. This way we can also > enforce a decent timeframe in which an IRQ should occur, and avoid the > case where a driver hangs because an IRQ never arrives. It already has this parameter. > > What do you think? Do all other OSes implementing CDI so far allow IRQs > > at any time or does it just happen to work? (I think meanwhile all > > drivers are well-behaved and don't do it manually) > > Drivers that use interrupts should be able to assume interrupts are > enabled and working properly. I fully agree that driver should be safe to assume that interrupts work. The question is what "working properly" means. Basically this is about whether a driver function can be interrupted for a IRQ handler (like for a Unix signal handler) or if the IRQs are queued. I strongly suggest the latter - in the example of pcnet this would mean that the code was completely wrong and could not even have worked (which shows that tyndur doesn't implement this semantics yet). I've though a bit more about it, and in fact I think what we need to clearly define is semantics with respect to concurrency and/or signal-like interruptions. IDC message handling is another thing of this type, should it ever be implemented. If we want to allow concurrency/interruption, we need to define things like locks, signal blocking etc. I really don't want to get into that business with CDI because I fear trouble with the different types of OSes here. So maybe the most reasonable approach is to defined that at the same time at most one driver function per device is running and that it may not be interrupted as in signals. The library can then define the necessary message queues, threading with locks or whatever model it likes. The drivers themselves can be kept simple then. Kevin From matthew at theiselins.net Mon Jan 18 05:32:42 2010 From: matthew at theiselins.net (Matthew Iselin) Date: Mon, 18 Jan 2010 14:32:42 +1000 Subject: [cdi-devel] Interrupts In-Reply-To: <20100117215621.GB26897@silvanus> References: <20100117110355.GA26897@silvanus> <20100117215621.GB26897@silvanus> Message-ID: On Mon, Jan 18, 2010 at 7:56 AM, Kevin Wolf wrote: >> I would say that pcnet's implementation of its own solution when >> cdi_wait_irq already exists was fundamentally wrong. There is no point >> reinventing the wheel in each driver when you already have the >> functionality available in the interface. > > Reinventing the wheel is just ugliness, it doesn't lead to fundamentally > broken code. But at least you don't seem to be opposed to forbid such > things in a better specification. Right, the interface provides things like cdi_wait_irq for a reason. I should have elaborated further when I stated that I felt the code was fundamentally wrong. Pedigree for example implements cdi_wait_irq in such a way that the calling thread can be put to sleep until the IRQ fires, at which point it can be woken up directly. Tyndur might define cdi_wait_irq in a different way, with its own unique semantics. This is why I feel it is fundamentally wrong to write a CDI driver which implements interface-provided functionality itself. You are free to disagree, of course. I will not hold that against you, but I do want to assert how I feel about the issue. >> > The point is that currently in my kernel CDI drivers generally run with >> > IRQs turned off as the kernel lacks proper locking, so I'm not sure what >> > would happen if I would allow IRQs in any place (or even let it be >> > preempted). So pcnet would wait forever for an IRQ to happen. >> >> Perhaps cdi_wait_irq needs a timeout parameter. This way we can also >> enforce a decent timeframe in which an IRQ should occur, and avoid the >> case where a driver hangs because an IRQ never arrives. > > It already has this parameter. I should have checked, but I was a little rushed. So if it does have this parameter, you could have a cdi_wait_irq(2000) in pcnet that waits 2 seconds for an IRQ rather than hang the system forever for an interrupt which will never arrive. Maybe cdi_wait_irq could also check and enable interrupts to be absolutely certain (this is an OS-specific thing though). In my opinion, IRQ support should be a requirement for the CDI interface. The alternative is that drivers have multiple code paths: one for "IRQs available", the other for "No IRQs available" (and throw an error when the device can't run without IRQs). >> > What do you think? Do all other OSes implementing CDI so far allow IRQs >> > at any time or does it just happen to work? (I think meanwhile all >> > drivers are well-behaved and don't do it manually) >> >> Drivers that use interrupts should be able to assume interrupts are >> enabled and working properly. > > I fully agree that driver should be safe to assume that interrupts work. > The question is what "working properly" means. Basically this is about > whether a driver function can be interrupted for a IRQ handler (like for > a Unix signal handler) or if the IRQs are queued. I strongly suggest the > latter - in the example of pcnet this would mean that the code was > completely wrong and could not even have worked (which shows that tyndur > doesn't implement this semantics yet). Keep in mind that I come from the monolithic school of thought, where I can say that the driver is just another function call and therefore can be interrupted easily. You come from microkernel land, where drivers are actually running outside the kernel. > I've though a bit more about it, and in fact I think what we need to > clearly define is semantics with respect to concurrency and/or > signal-like interruptions. IDC message handling is another thing of this > type, should it ever be implemented. Semantics are always fun to discuss :-) > If we want to allow concurrency/interruption, we need to define things > like locks, signal blocking etc. I really don't want to get into that > business with CDI because I fear trouble with the different types of > OSes here. So maybe the most reasonable approach is to defined that at > the same time at most one driver function per device is running and that > it may not be interrupted as in signals. The library can then define the > necessary message queues, threading with locks or whatever model it > likes. The drivers themselves can be kept simple then. I agree with the concept of only one driver function per device. This avoids race conditions when accessing device-specific data in the driver (eg, rx/tx buffers on a NIC) and also helps implementors to visualise the way CDI is used a little easier. If IRQs are queued until after a driver function is complete, cdi_wait_irq may need to actually break from convention here. cdi_wait_irq is, in my opinion, one of the most important functions in CDI. Drivers often need to wait for an IRQ to determine if a network packet got sent correctly, or to find out that a disk sector has been transferred. Perhaps cdi_wait_irq could set a flag which allows IRQs to be called? Something like this: cdi_wait_irq: check irq queue, run irq handler and return "success" set "interruptible" flag wait for IRQ, run irq handler if one comes in before timeout unset "interruptible" flag return timeout or success This may entail a cdi_os_wait_irq function (or something like that) to actually perform the wait for an IRQ in order to remove this complicated CDI trickery from the OS-provided implementation. I'm interested to hear yours and Max's thoughts. Cheers, Matt From kevin at tyndur.org Fri Jan 22 20:28:15 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Fri, 22 Jan 2010 20:28:15 +0100 Subject: [cdi-devel] [PATCH] ata: Remove partition handling Message-ID: <1264188495-25269-1-git-send-email-kevin@tyndur.org> Handling partitions is not the disk driver's job. Remove the corresponding code. Signed-off-by: Kevin Wolf --- ata/device.c | 57 ---------------------------------- ata/libpartition.c | 86 ---------------------------------------------------- ata/libpartition.h | 58 ----------------------------------- 3 files changed, 0 insertions(+), 201 deletions(-) delete mode 100644 ata/libpartition.c delete mode 100644 ata/libpartition.h diff --git a/ata/device.c b/ata/device.c index 7339d65..dd087c3 100644 --- a/ata/device.c +++ b/ata/device.c @@ -36,7 +36,6 @@ #include "cdi/scsi.h" #include "device.h" -#include "libpartition.h" // IRQ-Handler static inline void ata_controller_irq(struct cdi_device* dev); @@ -157,59 +156,6 @@ int ata_wait_irq(struct ata_controller* controller, uint32_t timeout) return 1; } -/** - * Partitionstabelle auf einem ATA-Geraet verarbeiten - */ -void ata_parse_partitions(struct ata_device* dev) -{ - struct partition_table partition_table; - uint8_t mbr[ATA_SECTOR_SIZE]; - int i; - - // Die Partitionstabelle liegt im MBR - if (!dev->read_sectors(dev, 0, 1, mbr)) { - DEBUG("Fehler beim Einlesen der Partitionstabelle"); - return; - } - - // Partitionstabelle Verarbeiten - if (!partition_table_fill(&partition_table, mbr)) { - DEBUG("Fehler beim Verarbeiten der Partitionstabelle"); - return; - } - - // Ansonsten wird die Tabelle jetzt verarbeitet - for (i = 0; i < 4; i++) { - if (partition_table.entries[i].used) { - // Erweiterter Eintrag => ueberspringen - if (partition_table.entries[i].type == PARTITION_TYPE_EXTENDED) { - DEBUG("TODO Erweiterte Partitionstabelleneintraege\n"); - continue; - } - - struct ata_partition* partition = malloc(sizeof(*partition)); - partition->realdev = dev; - partition->null = NULL; - partition->start = partition_table.entries[i].start; - partition->dev.storage.block_size = ATA_SECTOR_SIZE; - partition->dev.storage.block_count = partition_table.entries[i].size; - DEBUG("Partition von %d bis %d\n", partition->start, partition->dev.storage.block_count + partition->start - 1); - asprintf((char**) &(partition->dev.storage.dev.name), "ata%01d%01d_p%01d", - (uint32_t) dev->controller->id, dev->id, cdi_list_size(dev-> - partition_list)); - - // Geraet registrieren - partition->dev.storage.dev.driver = &dev->controller->storage->drv; - ata_init_device((struct ata_device*) partition); - cdi_list_push(dev->controller->storage->drv.devices, partition); - - // An Partitionsliste fuer das aktuelle Geraet anhaengen - cdi_list_push(dev->partition_list, partition); - } - } -} - - /** @@ -296,9 +242,6 @@ void ata_init_controller(struct ata_controller* controller) asprintf((char**) &(dev->dev.storage.dev.name), "ata%01d%01d", (uint32_t) controller->id, i); - // Partitionen parsen - ata_parse_partitions(dev); - // Geraet registrieren dev->dev.storage.dev.driver = &controller->storage->drv; ata_init_device(dev); diff --git a/ata/libpartition.c b/ata/libpartition.c deleted file mode 100644 index 17c41e1..0000000 --- a/ata/libpartition.c +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2007 The tyndur Project. All rights reserved. - * - * This code is derived from software contributed to the tyndur Project - * by Antoine Kaufmann. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "libpartition.h" -#include - -/** - * Roher Partitionstabelleneintrag - */ -struct raw_entry { - uint8_t active; - uint8_t begin_chs[3]; - uint8_t type; - uint8_t end_chs[3]; - uint32_t start; - uint32_t size; -} PACKED; - -/** - * Uebergebene Partitionstabelle anhand des Sektors fuellen - * - * @return 1 wenn die Tabelle erfolgreich gefuellt wurde, 0 sonst - */ -int partition_table_fill(struct partition_table* table, void* sector) -{ - struct raw_entry* entry = (struct raw_entry*) (sector + - PARTITION_TABLE_OFFSET); - uint16_t* signature = sector + PARTITION_TABLE_SIG_OFFSET; - int i; - - // Zuerst die Signatur pruefen, denn ohne die muss garnicht weiter gesucht - // werden. - if (*signature != PARTITION_TABLE_SIGNATURE) { - return 0; - } - - // Wenn die Signatur existiert koennen die einzelnen Eintraege ausgelesen - // werden - for (i = 0; i < 4; i++) { - // Wenn 0 als Groesse eingetragen ist, ist der Eintrag unbenutzt - if (entry->size == 0) { - table->entries[i].used = 0; - } else { - table->entries[i].used = 1; - - // Fuer erweiterte Partitionen wollen wir generell Typ 0x5, die - // anderen aus Windows und Linux werden deshalb ausgetauscht. - if ((entry->type == 0x0F) || (entry->type == 0x85)) { - table->entries[i].type = PARTITION_TYPE_EXTENDED; - } else { - table->entries[i].type = entry->type; - } - - table->entries[i].start = entry->start; - table->entries[i].size = entry->size; - } - entry++; - } - return 1; -} - diff --git a/ata/libpartition.h b/ata/libpartition.h deleted file mode 100644 index e8d2837..0000000 --- a/ata/libpartition.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2007 The tyndur Project. All rights reserved. - * - * This code is derived from software contributed to the tyndur Project - * by Antoine Kaufmann. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _LIBPARTITION_H_ -#define _LIBPARTITION_H_ - -#include - -#define PACKED __attribute__((packed)) -#define PARTITION_TABLE_OFFSET 446 -#define PARTITION_TABLE_SIG_OFFSET 510; -#define PARTITION_TABLE_SIGNATURE 0xAA55 - -// Typ fuer eine Erweiterte Partition, deren Startsektor wieder eine -// Partitionstabelle beinhaltet. -#define PARTITION_TYPE_EXTENDED 0x05 - -struct partition { - uint8_t used; - uint8_t type; - uint32_t start; - uint32_t size; -}; - -struct partition_table { - struct partition entries[4]; -}; - -// Fuellt die Angegebene Partitionstabelle anhand des uebergebenen Sektors auf -int partition_table_fill(struct partition_table* table, void* sector); - -#endif // ifndef _LIBPARTITION_H_ - -- 1.6.0.2 From max at tyndur.org Sat Jan 23 10:28:07 2010 From: max at tyndur.org (Max Reitz) Date: Sat, 23 Jan 2010 10:28:07 +0100 Subject: [cdi-devel] [PATCH] ata: Remove partition handling In-Reply-To: <1264188495-25269-1-git-send-email-kevin@tyndur.org> References: <1264188495-25269-1-git-send-email-kevin@tyndur.org> Message-ID: <4B5AC127.8020807@tyndur.org> Kevin Wolf wrote: > Handling partitions is not the disk driver's job. Remove the > corresponding code. > > Signed-off-by: Kevin Wolf Sounds good. Acked-by: Max Reitz From redelman at gmail.com Sat Jan 23 18:22:17 2010 From: redelman at gmail.com (Rich Edelman) Date: Sat, 23 Jan 2010 11:22:17 -0600 Subject: [cdi-devel] [PATCH] ata: Remove partition handling In-Reply-To: <1264188495-25269-1-git-send-email-kevin@tyndur.org> References: <1264188495-25269-1-git-send-email-kevin@tyndur.org> Message-ID: <61acd8d31001230922m616b5b88n4c2406249bd5a654@mail.gmail.com> On Fri, Jan 22, 2010 at 1:28 PM, Kevin Wolf wrote: > Handling partitions is not the disk driver's job. Remove the > corresponding code. > > Signed-off-by: Kevin Wolf Looks good here. Acked-by: Rich Edelman From kevin at tyndur.org Sun Jan 24 15:55:46 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Sun, 24 Jan 2010 15:55:46 +0100 Subject: [cdi-devel] [PATCH] misc.h: Improved documentation of cdi_wait_irq Message-ID: <1264344946-30782-1-git-send-email-kevin@tyndur.org> Signed-off-by: Kevin Wolf --- include/cdi/misc.h | 17 +++++++++++++---- 1 files changed, 13 insertions(+), 4 deletions(-) diff --git a/include/cdi/misc.h b/include/cdi/misc.h index 2049c62..183d32b 100644 --- a/include/cdi/misc.h +++ b/include/cdi/misc.h @@ -39,10 +39,19 @@ void cdi_register_irq(uint8_t irq, void (*handler)(struct cdi_device*), int cdi_reset_wait_irq(uint8_t irq); /** - * Wartet bis der IRQ aufgerufen wurde. Der interne Zaehler muss zuerst mit - * cdi_reset_wait_irq zurueckgesetzt werden, damit auch die IRQs abgefangen - * werden koennen, die kurz vor dem Aufruf von dieser Funktion aufgerufen - * werden. + * Wartet bis der IRQ aufgerufen wurde. Der interne Z??hler muss zuerst mit + * cdi_reset_wait_irq zur??ckgesetzt werden. Damit auch die IRQs abgefangen + * werden k??nnen, die kurz vor dem Aufruf von dieser Funktion aufgerufen + * werden, sieht der korrekte Ablauf wie folgt aus: + * + * -# cdi_reset_wait_irq + * -# Hardware ansprechen und Aktionen ausf??hren, die schlie??lich den IRQ + * ausl??sen + * -# cdi_wait_irq + * + * Der entsprechende IRQ muss zuvor mit cdi_register_irq registriert worden + * sein. Der registrierte Handler wird ausgef??hrt, bevor diese Funktion + * erfolgreich zur??ckkehrt. * * @param irq Nummer des IRQ auf den gewartet werden soll * @param timeout Anzahl der Millisekunden, die maximal gewartet werden sollen -- 1.6.0.2 From kevin at tyndur.org Sun Jan 24 17:03:01 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Sun, 24 Jan 2010 17:03:01 +0100 Subject: [cdi-devel] [PATCH] Documentation: Add general interface description (German) Message-ID: <1264348981-17226-1-git-send-email-kevin@tyndur.org> Start documentation on general subjects that cannot be associated with any module or data structure. The page is linked from the Doxygen main page. Signed-off-by: Kevin Wolf --- doc/doc.h | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ doc/doxyfile.in | 2 +- 2 files changed, 57 insertions(+), 1 deletions(-) create mode 100644 doc/doc.h diff --git a/doc/doc.h b/doc/doc.h new file mode 100644 index 0000000..d1f60e5 --- /dev/null +++ b/doc/doc.h @@ -0,0 +1,56 @@ +/** + * \mainpage + * - \ref general_interface + */ + +/** + * \page general_interface Allgemeine Schnittstellenbeschreibung + * + * Diese Seite beschreibt allgemeine Regeln f??r das Zusammenspiel von Treibern + * und Betriebssystem, die nicht einem bestimmtem Modul oder einer bestimmten + * Datenstruktur zugeordnet werden k??nnen. + * + * Die zwei wesentlichen Teile sind Bedingungen, die das Betriebssystem auf + * Quellcode-Ebene garantieren muss (z.B. Bereitstellung von bestimmten + * Funktionen) und Bedingungen, die zur Laufzeit gelten. + * + * \section gi_source Quellcode-Ebene + * \subsection gi_source_naming Namensregeln + * Um Namenskonflikte zu vermeiden, sind folgende Regeln zu beachten: + * - ??ffentliche Namen der CDI-Implementierung (d.h. global sichtbare Namen + * und in CDI-Headerdateien verwendete Namen) beginnen mit cdi_ oder CDI_. + * - ??ffentliche Namen eines CDI-Treibers beginnen mit dem Treibernamen + * gefolgt von einem Unterstrich (z.B. e1000_send_packet) + * + * \subsection gi_source_libc Funktionen der C-Standardbibliothek + * Die CDI-Implementierung muss keine vollst??ndige C-Standardbibliothek zur + * Verf??gung stellen. Treiber m??ssen sich auf folgende Teile beschr??nken + * (oder die Benutzung weiterer Funktionen durch \#ifdef optional machen): + * - Alles aus stddef.h + * - Alles aus stdint.h + * - Alles aus string.h + * - Speicherverwaltungsfunktionen aus stdlib.h: malloc, calloc, realloc, free + * - printf-Familie aus stdio.h, ohne fprintf und vfprintf. Au??erdem asprintf. + * \todo Gebrauch von stdio.h einschr??nken + * + * \section gi_runtime Laufzeit + * \subsection gi_runtime_intr Nebenl??ufigkeit und Unterbrechungen + * Nebenl??ufigkeit ist das gleichzeitige oder quasi-gleichzeitige Ablaufen von + * Code (z.B. Multithreading). Eine Unterbrechung bedeutet, dass ausgef??hrter + * Code angehalten wird, um anderen Code auszuf??hren, und erst anschlie??end + * der angehaltene Code wieder fortgesetzt wird (z.B. Unix-Signale). + * + * Die Nutzung beider Konzepte erfordert es, dass der Quellcode sich gegen + * unerw??nschte Effekt wie Race Conditions sch??tzt, z.B. durch Locks. Da die + * jeweiligen Methoden OS-abh??ngig sind und um Treiber einfach zu halten, + * gelten f??r CDI die folgenden Einschr??nkungen: + * + * - Treibercode wird niemals unterbrochen. Die einzige Ausnahme ist die + * Funktion cdi_wait_irq, w??hrend der IRQ-Handler ausgef??hrt werden + * d??rfen. + * - Nebenl??ufigkeit ist erlaubt, sofern die CDI-Implementierung sicherstellt, + * dass f??r jedes Ger??t gleichzeitig nur eine Funktion ausgef??hrt wird + * (z.B. durch ein Lock auf das cdi_device). Treiber d??rfen nicht davon + * ausgehen, dass irgendwelche Funktionen nebenl??ufig ausgef??hrt werden. + * Nebenl??ufigkeit ist f??r die Implementierung optional. + */ diff --git a/doc/doxyfile.in b/doc/doxyfile.in index bf51713..af4fad1 100644 --- a/doc/doxyfile.in +++ b/doc/doxyfile.in @@ -80,7 +80,7 @@ WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- -INPUT = include +INPUT = include doc/doc.h INPUT_ENCODING = UTF-8 FILE_PATTERNS = RECURSIVE = YES -- 1.6.0.2 From max at tyndur.org Sun Jan 24 17:31:50 2010 From: max at tyndur.org (Max Reitz) Date: Sun, 24 Jan 2010 17:31:50 +0100 Subject: [cdi-devel] [PATCH] misc.h: Improved documentation of cdi_wait_irq In-Reply-To: <1264344946-30782-1-git-send-email-kevin@tyndur.org> References: <1264344946-30782-1-git-send-email-kevin@tyndur.org> Message-ID: <4B5C75F6.8000806@tyndur.org> Kevin Wolf wrote: > Signed-off-by: Kevin Wolf > --- > include/cdi/misc.h | 17 +++++++++++++---- > 1 files changed, 13 insertions(+), 4 deletions(-) Looks good. Acked-by: Max Reitz From max at tyndur.org Sun Jan 24 17:37:06 2010 From: max at tyndur.org (Max Reitz) Date: Sun, 24 Jan 2010 17:37:06 +0100 Subject: [cdi-devel] [PATCH] Documentation: Add general interface description (German) In-Reply-To: <1264348981-17226-1-git-send-email-kevin@tyndur.org> References: <1264348981-17226-1-git-send-email-kevin@tyndur.org> Message-ID: <4B5C7732.1060101@tyndur.org> Kevin Wolf schrieb: > Start documentation on general subjects that cannot be associated with > any module or data structure. The page is linked from the Doxygen main > page. > > Signed-off-by: Kevin Wolf Looks good, too. But I do not acknowledge it, because: http://de.wiktionary.org/wiki/z._B. as well as http://de.wiktionary.org/wiki/d._h. "z.B." and "d.h." are wrong. ;-) (English wiktionary states that, too) From kevin at tyndur.org Sun Jan 24 18:18:23 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Sun, 24 Jan 2010 18:18:23 +0100 Subject: [cdi-devel] [PATCH] Documentation: Add general interface description (German) In-Reply-To: <4B5C7732.1060101@tyndur.org> References: <1264348981-17226-1-git-send-email-kevin@tyndur.org> <4B5C7732.1060101@tyndur.org> Message-ID: <20100124171821.GA14384@silvanus> On Sun, Jan 24, 2010 at 05:37:06PM +0100, Max Reitz wrote: > Kevin Wolf schrieb: > >Start documentation on general subjects that cannot be associated with > >any module or data structure. The page is linked from the Doxygen main > >page. > > > >Signed-off-by: Kevin Wolf > > Looks good, too. > But I do not acknowledge it, because: http://de.wiktionary.org/wiki/z._B. > as well as http://de.wiktionary.org/wiki/d._h. > "z.B." and "d.h." are wrong. ;-) > (English wiktionary states that, too) I really don't feel like discussing the merits of the spelling reform, but in fixed-width fonts it just looks awful. Consider it Austrian German and we're fine. ;-) Kevin From toni at tyndur.org Sun Jan 24 18:22:34 2010 From: toni at tyndur.org (Antoine Kaufmann) Date: Sun, 24 Jan 2010 18:22:34 +0100 Subject: [cdi-devel] [PATCH] Documentation: Add general interface description (German) In-Reply-To: <1264348981-17226-1-git-send-email-kevin@tyndur.org> References: <1264348981-17226-1-git-send-email-kevin@tyndur.org> Message-ID: <20100124172233.GA11909@neo.geekcave.lan> On Sun, Jan 24 17:03, Kevin Wolf wrote: > Start documentation on general subjects that cannot be associated with > any module or data structure. The page is linked from the Doxygen main > page. > > Signed-off-by: Kevin Wolf Acked-by: Antoine Kaufmann -- Antoine Kaufmann -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: not available URL: From max at tyndur.org Sun Jan 24 19:00:07 2010 From: max at tyndur.org (Max Reitz) Date: Sun, 24 Jan 2010 19:00:07 +0100 Subject: [cdi-devel] [PATCH] Documentation: Add general interface description (German) In-Reply-To: <20100124171821.GA14384@silvanus> References: <1264348981-17226-1-git-send-email-kevin@tyndur.org> <4B5C7732.1060101@tyndur.org> <20100124171821.GA14384@silvanus> Message-ID: <4B5C8AA7.7050902@tyndur.org> Kevin Wolf wrote: > but in fixed-width fonts it just looks awful. Consider it Austrian > German and we're fine. ;-) I really dislike such a spelling (also in fixed-width fonts), so I won't ack this---you may commit it, but I don't support you explicitly in doing so. ;-) Max From kevin at tyndur.org Sun Jan 24 22:37:13 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Sun, 24 Jan 2010 22:37:13 +0100 Subject: [cdi-devel] [RFC PATCH] mem.h: Handling memory areas Message-ID: <1264369033-13615-1-git-send-email-kevin@tyndur.org> This adds a new CDI header cdi/mem.h which I consider a major step before we can start with the IDC stuff. It unifies page-aligned memory allocations for different types of DMA, allows the OS layer to back it by shared memory (makes sense in a microkernel approach) and probably some more nice things. What cdi_mem_alloc/free are good for is obvious, I hope. To explain the use of the other functions, consider the following. Let's take a disk driver as an example. Instead of buffer/size its write function will directly get a memory area from the OS. The OS might already have allocated the memory physically contiguous, but it doesn't need to do so. The driver calls cdi_mem_require_flags which copies the data into a suited buffer - but if the OS already did the right thing, it's a no-op. cdi_mem_copy is for the other way round. Now the disk driver wants to read something from its disk. It gets a memory area from the OS and uses cdi_mem_require_flags to get something usable for DMA, which may or may not involve a copy. When the disk has transferred all the data, the driver uses cdi_mem_copy to make sure that the read data ends up in the buffer it was passed - and again, if the buffer had already the right flags this will be a no-op. Signed-off-by: Kevin Wolf --- include/cdi/mem.h | 160 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 160 insertions(+), 0 deletions(-) create mode 100644 include/cdi/mem.h diff --git a/include/cdi/mem.h b/include/cdi/mem.h new file mode 100644 index 0000000..852c258 --- /dev/null +++ b/include/cdi/mem.h @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2007 Kevin Wolf + * + * This program is free software. It comes without any warranty, to + * the extent permitted by applicable law. You can redistribute it + * and/or modify it under the terms of the Do What The Fuck You Want + * To Public License, Version 2, as published by Sam Hocevar. See + * http://sam.zoy.org/projects/COPYING.WTFPL for more details. + */ + +#ifndef _CDI_MEM_H_ +#define _CDI_MEM_H_ + +#include +#include "cdi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \german + * Beschreibt Anforderungen an einen Speicherbereich + * \endgerman + * \english + * Describes requirements for a memory area + * \endenglish + */ +typedef enum { + /** + * \german + * Physisch zusammenh??ngenden Speicher anfordern + * \endgerman + * \english + * Request physically contiguous memory + * \endenglish + */ + CDI_MEM_PHYS_CONTIGUOUS = 0x1, + + /** + * \german + * Physischen Speicher < 16 MB anfordern + * \endgerman + * \english + * Request physical memory < 16 MB + * \endenglish + */ + CDI_MEM_DMA_16M = 0x2, + + /** + * \german + * Physischen Speicher < 4 GB anfordern + * \endgerman + * \english + * Request physical memory < 4 GB + * \endenglish + */ + CDI_MEM_DMA_4G = 0x4, + + /** + * \german + * Speicher muss nicht initialisiert werden (verhindert Kopie bei + * cdi_mem_require_flags) + * \endgerman + * \english + * Memory doesn't need to be initialised (avoids copy in + * cdi_mem_require_flags) + * \endenglish + */ + CDI_MEM_NOINIT = 0x8, +} cdi_mem_flags_t; + +struct cdi_mem_area { + size_t size; + void* vaddr; + uintptr_t paddr; + + cdi_mem_osdep osdep; +} + +/** + * \german + * Reserviert einen Speicherbereich. Die Funktion arbeitet nur mit ganzen + * Pages. + * + * @param size Gr????e des Speicherbereichs in Bytes + * @param flags Flags, die zus??tzliche Anforderungen beschreiben + * \endgerman + * \english + * Allocates a memory area. The function only works with complete pages. + * + * @param size Size of the memory area in bytes + * @param flags Flags that describe additional requirements + * \endenglish + */ +struct cdi_mem_area* cdi_mem_alloc(size_t size, cdi_mem_flags_t flags); + +/** + * \german + * Gibt einen durch cdi_mem_alloc reservierten Speicherbereich frei + * \endgerman + * \english + * Frees a memory area that was previously allocated by cdi_mem_alloc + * \endenglish + */ +void cdi_mem_free(struct cdi_memory_area* p); + +/** + * \german + * Gibt einen Speicherbereich zur??ck, der dieselben Daten wie @a p beschreibt, + * aber mindestens die gegebenen Flags gesetzt hat. + * + * Diese Funktion kann denselben virtuellen und physischen Speicherbereich wie + * @p benutzen oder sogar @p selbst zur??ckzugeben, solange der gemeinsam + * benutzte Speicher erst dann freigegeben wird, wenn sowohl @a p als auch der + * R??ckgabewert durch cdi_mem_free freigegeben worden sind. + * + * Ansonsten wird ein neuer Speicherbereich reserviert und (au??er wenn das + * Flag CDI_MEM_NOINIT gesetzt ist) die Daten werden aus @a p in den neu + * reservierten Speicher kopiert. + * \endgerman + * \english + * Returns a memory area that describes the same data as @a p does, but for + * which at least the given flags are set. + * + * This function may use the same virtual and physical memory areas as used in + * @a p, or it may even return @a p itself. In this case it must ensure that + * the commonly used memory is only freed when both @a p and the return value + * of this function have been freed by cdi_mem_free. + * + * Otherwise, a new memory area is allocated and data is copied from @a p into + * the newly allocated memory (unless CDI_MEM_NOINIT is set). + * \endenglish + */ +struct cdi_mem_area* cdi_mem_require_flags(struct cdi_mem_area* p, + cdi_mem_flags_t flags); + +/** + * \german + * Kopiert die Daten von @a src nach @a dest. Beide Speicherbereiche m??ssen + * gleich gro?? sein. + * + * @return 0 bei Erfolg, -1 sonst + * \endgerman + * \english + * Copies data from @a src to @a dest. Both memory areas must be of the same + * size. + * + * + * @return 0 on success, -1 otherwise + * \endenglish + */ +int cdi_mem_copy(struct cdi_mem_area* dest, struct cdi_mem_area* src); + +#ifdef __cplusplus +}; // extern "C" +#endif + +#endif + -- 1.6.0.2 From matthew at theiselins.net Tue Jan 26 21:54:06 2010 From: matthew at theiselins.net (Matthew Iselin) Date: Wed, 27 Jan 2010 06:54:06 +1000 Subject: [cdi-devel] [RFC PATCH] mem.h: Handling memory areas In-Reply-To: <1264369033-13615-1-git-send-email-kevin@tyndur.org> References: <1264369033-13615-1-git-send-email-kevin@tyndur.org> Message-ID: On Mon, Jan 25, 2010 at 7:37 AM, Kevin Wolf wrote: > > > To explain the use of the other functions, consider the following. > Let's take a disk driver as an example. Instead of buffer/size its > write function will directly get a memory area from the OS. The OS might > already have allocated the memory physically contiguous, but it doesn't > need to do so. The driver calls cdi_mem_require_flags which copies the > data into a suited buffer - but if the OS already did the right thing, > it's a no-op. Hmm, I don't actually like the sounds of that. I'd prefer that when the driver gets memory from the OS it specifies the flags it requires for the memory area rather than get the memory then change flags on the area (potentially requiring a full reallocation of the buffer itself) later. I also don't think cdi_mem_require_flags should perform a copy: semantics like that are not intuitive. I may have mis-interpreted of course. > cdi_mem_copy is for the other way round. Now the disk driver wants to > read something from its disk. It gets a memory area from the OS and uses > cdi_mem_require_flags to get something usable for DMA, which may or may > not involve a copy. When the disk has transferred all the data, the > driver uses cdi_mem_copy to make sure that the read data ends up in the > buffer it was passed - and again, if the buffer had already the right > flags this will be a no-op. Again, cdi_mem_require_flags probably shouldn't perform a copy. It just sounds like the interface could be cleaned up a bit, and especially could be modified to reduce the amount of copying that the CDI implementation might have to do. Drivers at least should know what they need from the very beginning. Apart from these nitpicks I like where you're going with the interface. Cheers, Matt From kevin at tyndur.org Tue Jan 26 22:54:54 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Tue, 26 Jan 2010 22:54:54 +0100 Subject: [cdi-devel] [RFC PATCH] mem.h: Handling memory areas In-Reply-To: References: <1264369033-13615-1-git-send-email-kevin@tyndur.org> Message-ID: <20100126215452.GA7676@silvanus> On Wed, Jan 27, 2010 at 06:54:06AM +1000, Matthew Iselin wrote: > On Mon, Jan 25, 2010 at 7:37 AM, Kevin Wolf wrote: > > > > > > To explain the use of the other functions, consider the following. > > Let's take a disk driver as an example. Instead of buffer/size its > > write function will directly get a memory area from the OS. The OS might > > already have allocated the memory physically contiguous, but it doesn't > > need to do so. The driver calls cdi_mem_require_flags which copies the > > data into a suited buffer - but if the OS already did the right thing, > > it's a no-op. > > Hmm, I don't actually like the sounds of that. I'd prefer that when > the driver gets memory from the OS it specifies the flags it requires > for the memory area rather than get the memory then change flags on > the area (potentially requiring a full reallocation of the buffer > itself) later. I'm not sure if we're talking about the same thing here. There are basically two different scenarios to consider and you could mean any of them: 1) The driver needs some memory internally. This one is easy, it simply calls cdi_mem_alloc with the right flags and gets what it requested. 2) The driver doesn't explicitly allocate memory but gets it from the OS as a parameter to a function like the buffer for send_packet. This is more tricky. The data usually comes from a userspace program in this case, so the memory can only have the flag it happens to fulfill when the memory is passed to the kernel (assuming a monolithic model). At this point, we have two possibilities: The kernel can just pass the unchanged memory area down and the driver needs to make it fit its requrements (this is what I was trying to achieve with cdi_mem_require_flags). The only alternative that I see is to specify the required flags for each memory area parameter of any callback function in the driver struct. I personally consider this really awkward. But maybe you have another idea how this could be solved. > I also don't think cdi_mem_require_flags should perform > a copy: semantics like that are not intuitive. I may have > mis-interpreted of course. Not sure what it should do instead? > > cdi_mem_copy is for the other way round. Now the disk driver wants to > > read something from its disk. It gets a memory area from the OS and uses > > cdi_mem_require_flags to get something usable for DMA, which may or may > > not involve a copy. When the disk has transferred all the data, the > > driver uses cdi_mem_copy to make sure that the read data ends up in the > > buffer it was passed - and again, if the buffer had already the right > > flags this will be a no-op. > > Again, cdi_mem_require_flags probably shouldn't perform a copy. > > It just sounds like the interface could be cleaned up a bit, and > especially could be modified to reduce the amount of copying that the > CDI implementation might have to do. Drivers at least should know what > they need from the very beginning. The whole thing was made to avoid copies in the first place. But there are cases where you just need to copy data. So what I tried is to introduce functions which transparently do the copy or are a no-op when no copy is needed. Obviously I failed with either designing or explaining them. ;-) > Apart from these nitpicks I like where you're going with the interface. This is not nitpicks. It's important questions on the interface and I'm happy that you're asking them. I feel much more comfortable with committing some code after a discussion because I know that people have really thought about it. I'd like to hear your suggestions for the memory interface. By the way, one more thing that I wasn't sure about is if it's really helpful to restrict the whole thing to a page granularity. Maybe this should just be a flag CDI_MEM_PAGE_ALIGN which could be used by drivers whenever it's helpful to use complete pages. Or maybe leave it completely to the OS. Kevin From matthew at theiselins.net Wed Jan 27 12:51:24 2010 From: matthew at theiselins.net (Matthew Iselin) Date: Wed, 27 Jan 2010 21:51:24 +1000 Subject: [cdi-devel] [RFC PATCH] mem.h: Handling memory areas In-Reply-To: <20100126215452.GA7676@silvanus> References: <1264369033-13615-1-git-send-email-kevin@tyndur.org> <20100126215452.GA7676@silvanus> Message-ID: On Wed, Jan 27, 2010 at 7:54 AM, Kevin Wolf wrote: > On Wed, Jan 27, 2010 at 06:54:06AM +1000, Matthew Iselin wrote: >> On Mon, Jan 25, 2010 at 7:37 AM, Kevin Wolf wrote: >> > >> > >> > To explain the use of the other functions, consider the following. >> > Let's take a disk driver as an example. Instead of buffer/size its >> > write function will directly get a memory area from the OS. The OS might >> > already have allocated the memory physically contiguous, but it doesn't >> > need to do so. The driver calls cdi_mem_require_flags which copies the >> > data into a suited buffer - but if the OS already did the right thing, >> > it's a no-op. >> >> Hmm, I don't actually like the sounds of that. I'd prefer that when >> the driver gets memory from the OS it specifies the flags it requires >> for the memory area rather than get the memory then change flags on >> the area (potentially requiring a full reallocation of the buffer >> itself) later. > > > > At this point, we have two possibilities: The kernel can just pass the > unchanged memory area down and the driver needs to make it fit its > requrements (this is what I was trying to achieve with > cdi_mem_require_flags). The only alternative that I see is to specify > the required flags for each memory area parameter of any callback > function in the driver struct. I personally consider this really awkward. I must have misunderstood your initial explanation of cdi_mem_require_flags. In light of the information in this newest mail... So cdi_mem_require_flags would take a buffer that might be passed from an external source, and ensure that the buffer matches the given flags? If so that's a good idea and my only nitpick would be to ask for a rename ;) >> Again, cdi_mem_require_flags probably shouldn't perform a copy. >> >> It just sounds like the interface could be cleaned up a bit, and >> especially could be modified to reduce the amount of copying that the >> CDI implementation might have to do. Drivers at least should know what >> they need from the very beginning. > > The whole thing was made to avoid copies in the first place. But there > are cases where you just need to copy data. So what I tried is to > introduce functions which transparently do the copy or are a no-op when > no copy is needed. Right. I think this is one spot where the semantics of the functions need to be unambiguously defined (very clearly ;) )... Documentation here should be very in-depth in order to avoid misunderstandings like the one I experienced. > By the way, one more thing that I wasn't sure about is if it's really > helpful to restrict the whole thing to a page granularity. Maybe this > should just be a flag CDI_MEM_PAGE_ALIGN which could be used by drivers > whenever it's helpful to use complete pages. Or maybe leave it > completely to the OS. I'd say leave it up to the driver to ask for a page-aligned area. In fact, a better idea would be to have alignments on different word boundaries, as some devices are more than happy to accept buffers which are not page aligned but rather aligned on an n-word or n-byte boundary. Cheers, Matt From kevin at tyndur.org Wed Jan 27 21:58:20 2010 From: kevin at tyndur.org (Kevin Wolf) Date: Wed, 27 Jan 2010 21:58:20 +0100 Subject: [cdi-devel] [RFC PATCH] mem.h: Handling memory areas In-Reply-To: References: <1264369033-13615-1-git-send-email-kevin@tyndur.org> <20100126215452.GA7676@silvanus> Message-ID: <20100127205817.GA23284@silvanus> On Wed, Jan 27, 2010 at 09:51:24PM +1000, Matthew Iselin wrote: > On Wed, Jan 27, 2010 at 7:54 AM, Kevin Wolf wrote: > > At this point, we have two possibilities: The kernel can just pass the > > unchanged memory area down and the driver needs to make it fit its > > requrements (this is what I was trying to achieve with > > cdi_mem_require_flags). The only alternative that I see is to specify > > the required flags for each memory area parameter of any callback > > function in the driver struct. I personally consider this really awkward. > > I must have misunderstood your initial explanation of > cdi_mem_require_flags. In light of the information in this newest > mail... > > So cdi_mem_require_flags would take a buffer that might be passed from > an external source, and ensure that the buffer matches the given > flags? If so that's a good idea and my only nitpick would be to ask > for a rename ;) Yes, I think this is what I meant. I'm open for suggestions for a better name. > >> Again, cdi_mem_require_flags probably shouldn't perform a copy. > >> > >> It just sounds like the interface could be cleaned up a bit, and > >> especially could be modified to reduce the amount of copying that the > >> CDI implementation might have to do. Drivers at least should know what > >> they need from the very beginning. > > > > The whole thing was made to avoid copies in the first place. But there > > are cases where you just need to copy data. So what I tried is to > > introduce functions which transparently do the copy or are a no-op when > > no copy is needed. > > Right. I think this is one spot where the semantics of the functions > need to be unambiguously defined (very clearly ;) )... Documentation > here should be very in-depth in order to avoid misunderstandings like > the one I experienced. Unfortunately, it seems when I try to explain things very clearly it's almost guaranteed that you are going to misunderstand them. ;-) Maybe you could modify the patch so it fits your idea of a well-documented clean header? > > By the way, one more thing that I wasn't sure about is if it's really > > helpful to restrict the whole thing to a page granularity. Maybe this > > should just be a flag CDI_MEM_PAGE_ALIGN which could be used by drivers > > whenever it's helpful to use complete pages. Or maybe leave it > > completely to the OS. > > I'd say leave it up to the driver to ask for a page-aligned area. In > fact, a better idea would be to have alignments on different word > boundaries, as some devices are more than happy to accept buffers > which are not page aligned but rather aligned on an n-word or n-byte > boundary. That's a very good point, actually. Should we reserve some bits in the flags for it, make it another parameter or even a new function for allocating/requiring aligned memory? Another point that came to my mind today is that maybe we shouldn't have a single paddr in the memory area, but maintain a scatter/gather list of physical addresses. Kevin From matthew at theiselins.net Thu Jan 28 09:01:32 2010 From: matthew at theiselins.net (Matthew Iselin) Date: Thu, 28 Jan 2010 18:01:32 +1000 Subject: [cdi-devel] [RFC PATCH] mem.h: Handling memory areas In-Reply-To: References: <1264369033-13615-1-git-send-email-kevin@tyndur.org> <20100126215452.GA7676@silvanus> <20100127205817.GA23284@silvanus> Message-ID: On Thu, Jan 28, 2010 at 6:58 AM, Kevin Wolf wrote: > On Wed, Jan 27, 2010 at 09:51:24PM +1000, Matthew Iselin wrote: >> On Wed, Jan 27, 2010 at 7:54 AM, Kevin Wolf wrote: >> > At this point, we have two possibilities: The kernel can just pass the >> > unchanged memory area down and the driver needs to make it fit its >> > requrements (this is what I was trying to achieve with >> > cdi_mem_require_flags). The only alternative that I see is to specify >> > the required flags for each memory area parameter of any callback >> > function in the driver struct. I personally consider this really awkward. >> >> I must have misunderstood your initial explanation of >> cdi_mem_require_flags. In light of the information in this newest >> mail... >> >> So cdi_mem_require_flags would take a buffer that might be passed from >> an external source, and ensure that the buffer matches the given >> flags? If so that's a good idea and my only nitpick would be to ask >> for a rename ;) > > Yes, I think this is what I meant. I'm open for suggestions for a better > name. cdi_adjust_buffer perhaps? Something that actually says "this function may adjust the buffer's characteristics to that of the flags in the parameter list"... >> >> Again, cdi_mem_require_flags probably shouldn't perform a copy. >> >> >> >> It just sounds like the interface could be cleaned up a bit, and >> >> especially could be modified to reduce the amount of copying that the >> >> CDI implementation might have to do. Drivers at least should know what >> >> they need from the very beginning. >> > >> > The whole thing was made to avoid copies in the first place. But there >> > are cases where you just need to copy data. So what I tried is to >> > introduce functions which transparently do the copy or are a no-op when >> > no copy is needed. >> >> Right. I think this is one spot where the semantics of the functions >> need to be unambiguously defined (very clearly ;) )... Documentation >> here should be very in-depth in order to avoid misunderstandings like >> the one I experienced. > > Unfortunately, it seems when I try to explain things very clearly it's > almost guaranteed that you are going to misunderstand them. ;-) I try ;) > Maybe you could modify the patch so it fits your idea of a > well-documented clean header? If you want I can do that tonight. >> > By the way, one more thing that I wasn't sure about is if it's really >> > helpful to restrict the whole thing to a page granularity. Maybe this >> > should just be a flag CDI_MEM_PAGE_ALIGN which could be used by drivers >> > whenever it's helpful to use complete pages. Or maybe leave it >> > completely to the OS. >> >> I'd say leave it up to the driver to ask for a page-aligned area. In >> fact, a better idea would be to have alignments on different word >> boundaries, as some devices are more than happy to accept buffers >> which are not page aligned but rather aligned on an n-word or n-byte >> boundary. > > That's a very good point, actually. Should we reserve some bits in the > flags for it, make it another parameter or even a new function for > allocating/requiring aligned memory? Perhaps a new function in which you can specify the number of bytes to align against, such as cdi_buffer_align(void *, int). > Another point that came to my mind today is that maybe we shouldn't have > a single paddr in the memory area, but maintain a scatter/gather list of > physical addresses. You mean the CDI implementation provides a set of buffers which CDI drivers ask for and use? What would be its purpose? Cheers, Matt From matthew at theiselins.net Fri Jan 29 10:30:08 2010 From: matthew at theiselins.net (Matthew Iselin) Date: Fri, 29 Jan 2010 19:30:08 +1000 Subject: [cdi-devel] [RFC PATCH] mem.h: Handling memory areas [edit: documentation] Message-ID: Just updated the header documentation a little to make cdi_mem_require_flags make more sense. I'm now happy for this to be committed when necessary. Signed-off-by: Matthew Iselin Signed-off-by: Kevin Wolf --- include/cdi/mem.h | 165 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 165 insertions(+), 0 deletions(-) create mode 100644 include/cdi/mem.h diff --git a/include/cdi/mem.h b/include/cdi/mem.h new file mode 100644 index 0000000..852c258 --- /dev/null +++ b/include/cdi/mem.h @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2007 Kevin Wolf + * + * This program is free software. It comes without any warranty, to + * the extent permitted by applicable law. You can redistribute it + * and/or modify it under the terms of the Do What The Fuck You Want + * To Public License, Version 2, as published by Sam Hocevar. See + * http://sam.zoy.org/projects/COPYING.WTFPL for more details. + */ + +#ifndef _CDI_MEM_H_ +#define _CDI_MEM_H_ + +#include +#include "cdi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \german + * Beschreibt Anforderungen an einen Speicherbereich + * \endgerman + * \english + * Describes requirements for a memory area + * \endenglish + */ +typedef enum { + /** + * \german + * Physisch zusammenh?ngenden Speicher anfordern + * \endgerman + * \english + * Request physically contiguous memory + * \endenglish + */ + CDI_MEM_PHYS_CONTIGUOUS = 0x1, + + /** + * \german + * Physischen Speicher < 16 MB anfordern + * \endgerman + * \english + * Request physical memory < 16 MB + * \endenglish + */ + CDI_MEM_DMA_16M = 0x2, + + /** + * \german + * Physischen Speicher < 4 GB anfordern + * \endgerman + * \english + * Request physical memory < 4 GB + * \endenglish + */ + CDI_MEM_DMA_4G = 0x4, + + /** + * \german + * Speicher muss nicht initialisiert werden (verhindert Kopie bei + * cdi_mem_require_flags) + * \endgerman + * \english + * Memory doesn't need to be initialised (avoids copy in + * cdi_mem_require_flags) + * \endenglish + */ + CDI_MEM_NOINIT = 0x8, +} cdi_mem_flags_t; + +struct cdi_mem_area { + size_t size; + void* vaddr; + uintptr_t paddr; + + cdi_mem_osdep osdep; +} + +/** + * \german + * Reserviert einen Speicherbereich. Die Funktion arbeitet nur mit ganzen + * Pages. + * + * @param size Gr??e des Speicherbereichs in Bytes + * @param flags Flags, die zus?tzliche Anforderungen beschreiben + * \endgerman + * \english + * Allocates a memory area. The function only works with complete pages. + * + * @param size Size of the memory area in bytes + * @param flags Flags that describe additional requirements + * \endenglish + */ +struct cdi_mem_area* cdi_mem_alloc(size_t size, cdi_mem_flags_t flags); + +/** + * \german + * Gibt einen durch cdi_mem_alloc reservierten Speicherbereich frei + * \endgerman + * \english + * Frees a memory area that was previously allocated by cdi_mem_alloc + * \endenglish + */ +void cdi_mem_free(struct cdi_memory_area* p); + +/** + * \german + * Gibt einen Speicherbereich zur?ck, der dieselben Daten wie @a p beschreibt, + * aber mindestens die gegebenen Flags gesetzt hat. + * + * Diese Funktion kann denselben virtuellen und physischen Speicherbereich wie + * @p benutzen oder sogar @p selbst zur?ckzugeben, solange der gemeinsam + * benutzte Speicher erst dann freigegeben wird, wenn sowohl @a p als auch der + * R?ckgabewert durch cdi_mem_free freigegeben worden sind. + * + * Ansonsten wird ein neuer Speicherbereich reserviert und (au?er wenn das + * Flag CDI_MEM_NOINIT gesetzt ist) die Daten werden aus @a p in den neu + * reservierten Speicher kopiert. + * \endgerman + * \english + * Returns a memory area that describes the same data as @a p does, but for + * which at least the given flags are set. + * + * This function may use the same virtual and physical memory areas as used in + * @a p, or it may even return @a p itself. In this case it must ensure that + * the commonly used memory is only freed when both @a p and the return value + * of this function have been freed by cdi_mem_free. + * + * Otherwise, a new memory area is allocated and data is copied from @a p into + * the newly allocated memory (unless CDI_MEM_NOINIT is set). + * \endenglish + */ +struct cdi_mem_area* cdi_mem_require_flags(struct cdi_mem_area* p, + cdi_mem_flags_t flags); + +/** + * \german + * Kopiert die Daten von @a src nach @a dest. Beide Speicherbereiche m?ssen + * gleich gro? sein. + * + * @return 0 bei Erfolg, -1 sonst + * \endgerman + * \english + * Copies data from @a src to @a dest. Both memory areas must be of the same + * size. + * + * + * @return 0 on success, -1 otherwise + * \endenglish + */ +int cdi_mem_copy(struct cdi_mem_area* dest, struct cdi_mem_area* src); + +#ifdef __cplusplus +}; // extern "C" +#endif + +#endif +