From max at tyndur.org Wed Dec 9 12:41:36 2015 From: max at tyndur.org (Max Reitz) Date: Wed, 9 Dec 2015 12:41:36 +0100 Subject: [cdi-devel] [PATCH v3 08/10] ehci: Add EHCI driver In-Reply-To: <20151011210257.GA3279@silvanus> References: <1431374370-17120-1-git-send-email-max@tyndur.org> <1431374370-17120-9-git-send-email-max@tyndur.org> <20151011210257.GA3279@silvanus> Message-ID: <56681370.9030105@tyndur.org> On 11.10.2015 at 23:03, Kevin Wolf wrote: > On Mon, May 11, 2015 at 09:59:28PM +0200, Max Reitz wrote: >> + This adds an EHCI USB host controller driver. It is missing support >> for periodic schedule (interrupt and isochronous transfers), >> hotplugging, suspend/resume, etc. pp.. >> >> Signed-off-by: Max Reitz >> --- >> ehci/ehci.c | 643 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ >> ehci/ehci.h | 290 +++++++++++++++++++++++++++ >> ehci/main.c | 68 +++++++ >> 3 files changed, 1001 insertions(+) >> create mode 100644 ehci/ehci.c >> create mode 100644 ehci/ehci.h >> create mode 100644 ehci/main.c >> +static void retire_qtd(ehci_fat_qtd_t *qtd) >> +{ >> + ehci_fat_qh_t *qh = qtd->qh; >> + >> + uint32_t err_mask = (qh->qh.ep_state[0] & EHCI_QHES0_EPS_MASK) >> + == EHCI_QHES0_EPS_HS >> + ? EHCI_QTDS_HS_ERR_MASK >> + : EHCI_QTDS_LFS_ERR_MASK; >> + >> + if (qtd->qtd.status & err_mask) { >> + if (qtd->qtd.status & EHCI_QTDS_BABBLE) { >> + *qtd->result = CDI_USB_BABBLE; >> + } else if (qtd->qtd.status & (EHCI_QTDS_XACTERR | EHCI_QTDS_P_ERR)) { >> + *qtd->result = CDI_USB_BAD_RESPONSE; >> + } else if (qtd->qtd.status & (EHCI_QTDS_BUFERR | EHCI_QTDS_MuF)) { >> + *qtd->result = CDI_USB_HC_ERROR; >> + } else if (qtd->qtd.status & EHCI_QTDS_HALTED) { >> + *qtd->result = CDI_USB_STALL; >> + } else { >> + *qtd->result = CDI_USB_HC_ERROR; >> + } >> + } >> + >> + if (qtd->write_back) { >> + size_t rem = qtd->write_back_size; >> + for (int i = 0; i < 5 && rem; i++) { >> + size_t sz = rem > 4096 ? 4096 : rem; >> + memcpy((void *)((uintptr_t)qtd->write_back + i * 4096), >> + qtd->buffers[i]->vaddr, sz); >> + rem -= sz; >> + } >> + assert(!rem); >> + } >> + >> + qh->first_qtd = qtd->next; >> + if (qh->last_qtd == qtd) { >> + qh->last_qtd = NULL; >> + } > Worth an assert(qh->first_qtd == qtd) before doing this? It would probably be better to rename this function to retire_first_qtd() with the only parameter being the QH. >> + for (int i = 0; i < 5; i++) { >> + if (qtd->buffers[i]) { >> + cdi_mem_free(qtd->buffers[i]); >> + } >> + } >> + >> + cdi_mem_free(qtd->cdi_mem_area); >> +} >> + >> + >> +static void enter_qtd(ehci_fat_qh_t *qh, ehci_fat_qtd_t *qtd) >> +{ >> + bool first; >> + >> + qtd->qh = qh; >> + qtd->qtd.next_qtd = EHCI_T; >> + qtd->qtd.alt_next_qtd = EHCI_T; >> + >> + while (qh->first_qtd) { >> + // Break if an active qTD is encountered >> + if (qh->first_qtd->qtd.status & EHCI_QTDS_ACTIVE) { >> + break; >> + } >> + >> + retire_qtd(qh->first_qtd); >> + } >> + >> + first = !qh->first_qtd; >> + >> + // Note: Race condition (a qTD might retire here and we are thus appending >> + // the one to be queued to an inactive qTD); it's fine as long as we are >> + // constantly rescanning the queue (here and in ehci_wait_transaction()) >> + >> + if (first) { >> + qh->first_qtd = qtd; >> + } else { >> + qh->last_qtd->next = qtd; >> + } >> + qh->last_qtd = qtd; >> + >> + if (!first) { >> + qh->last_qtd->qtd.next_qtd = qtd->paddr; >> + } >> + >> + // If the QH is not active, it's done with its queue of qTDs and we should >> + // continue from this qTD >> + if (!(qh->qh.overlay.status & EHCI_QTDS_ACTIVE)) { >> + qh->qh.overlay.next_qtd = qh->first_qtd->paddr; >> + } > Is this racy? If you enter two qTDs and the hardware hasn't copied the > active bit of the first entered qTD into the overlay yet before the > second one is entered, it looks to me as if the QH pointed to the second > one now and the first one got ignored. Good thing I am not entering qtd->paddr but qh->first_qtd->paddr (independently of whether qh->first_qtd == qtd). ;-) The comment is wrong, though. It should read something like "If the QH has stopped operation we need to point it to the first qTD". Hm... Now that I think about it, maybe there is a race in the opposite direction. The active bit was not set, but then the qTD is copied into the overlay and we overwrite next_qtd by a pointer to itself. It probably would not be horrible, because that means that the HC will stop operation once the qTD is processed (because the active bit is cleared then), and we would then fix this condition in ehci_wait_transaction(). But it still is bad. Should be fixable by checking whether qh->qh.current_qtd == qh->qh.overlay.next_qtd after having set qh->qh.overlay.next_qtd, and while that is the case, replace qh->qh.overlay.next_qtd by qh->first_qtd->qtd.next_qtd (?while? so we can handle multiple races; the ?if (!active)? then maybe needs to be some kind of while loop, too). Max From max at tyndur.org Sat Dec 12 21:10:36 2015 From: max at tyndur.org (Max Reitz) Date: Sat, 12 Dec 2015 21:10:36 +0100 Subject: [cdi-devel] [PATCH v4 0/4] USB support Message-ID: <1449951040-16452-1-git-send-email-max@tyndur.org> The changes from v3 to v4 have not been tested, because it's more fun this way. v4: - Less patches, because some have already been applied - Patch 1: - Added cdi_usb_device_osdep - Added start_transaction() to cdi_usb_hcd - Patch 2: - Replace fprintf(stderr, ...) by printf(...) - Rename retire_qtd() to retire_first_qtd() and take a QH instead of a qTD - Never call enter_qh() on QH that may currently be processed by the HC - Subsequently, do not call enter_async_qh() from ehci_create_transaction() (invoked by ehci_enqueue()) - Implement ehci_start_transaction() - Patch 3: - Replace fprintf(stderr, ...) by printf(...) - Call start_transaction() where necessary - Never try to assign addresses greater than 127 (fail instead) - Fix calloc() call - Explain why there are two reset calls in new_hub() - Clean up the USB hub driver by pulling out functions like SetPortFeature() (as hub_set_port_feature()) - Patch 4: - Copy cdi_usb_device instead of keeping the reference - Fix the bulk_in vs. bulk_out stuff - Use integers for the device names instead of characters (e.g. "msd0" instead of "msda") git-backport-diff against v3: Key: [----] : patches are identical [####] : number of functional differences between upstream/downstream patch [down] : patch is downstream-only The flags [FC] indicate (F)unctional and (C)ontextual differences, respectively 001/4:[0041] [FC] 'cdi/usb: Add headers' 002/4:[0056] [FC] 'ehci: Add EHCI driver' 003/4:[0172] [FC] 'usb: Add USB 2.0 bus driver' 004/4:[0035] [FC] 'usb-storage: Add USB mass storage driver' Max Reitz (4): cdi/usb: Add headers ehci: Add EHCI driver usb: Add USB 2.0 bus driver usb-storage: Add USB mass storage driver ehci/ehci.c | 640 +++++++++++++++++++++++++++++++ ehci/ehci.h | 292 ++++++++++++++ ehci/main.c | 69 ++++ include/cdi-osdep.h | 21 + include/cdi/usb-structures.h | 174 +++++++++ include/cdi/usb.h | 211 ++++++++++ include/cdi/usb_hcd.h | 168 ++++++++ usb-storage/main.c | 76 ++++ usb-storage/usb-storage.c | 217 +++++++++++ usb-storage/usb-storage.h | 60 +++ usb/main.c | 61 +++ usb/usb-hubs.h | 78 ++++ usb/usb.c | 893 +++++++++++++++++++++++++++++++++++++++++++ usb/usb.h | 86 +++++ 14 files changed, 3046 insertions(+) create mode 100644 ehci/ehci.c create mode 100644 ehci/ehci.h create mode 100644 ehci/main.c create mode 100644 include/cdi/usb-structures.h create mode 100644 include/cdi/usb.h create mode 100644 include/cdi/usb_hcd.h create mode 100644 usb-storage/main.c create mode 100644 usb-storage/usb-storage.c create mode 100644 usb-storage/usb-storage.h create mode 100644 usb/main.c create mode 100644 usb/usb-hubs.h create mode 100644 usb/usb.c create mode 100644 usb/usb.h -- 2.6.3 From max at tyndur.org Sat Dec 12 21:10:37 2015 From: max at tyndur.org (Max Reitz) Date: Sat, 12 Dec 2015 21:10:37 +0100 Subject: [cdi-devel] [PATCH v4 1/4] cdi/usb: Add headers In-Reply-To: <1449951040-16452-1-git-send-email-max@tyndur.org> References: <1449951040-16452-1-git-send-email-max@tyndur.org> Message-ID: <1449951040-16452-2-git-send-email-max@tyndur.org> + Add headers to be used by USB host controller drivers, the USB bus driver, and USB device drivers. These headers are still lacking functions for periodic transactions (interrupt/isochronous), hotplugging, suspend/resume, etc. pp.. Signed-off-by: Max Reitz --- include/cdi-osdep.h | 21 +++++ include/cdi/usb-structures.h | 174 +++++++++++++++++++++++++++++++++++ include/cdi/usb.h | 211 +++++++++++++++++++++++++++++++++++++++++++ include/cdi/usb_hcd.h | 168 ++++++++++++++++++++++++++++++++++ 4 files changed, 574 insertions(+) create mode 100644 include/cdi/usb-structures.h create mode 100644 include/cdi/usb.h create mode 100644 include/cdi/usb_hcd.h diff --git a/include/cdi-osdep.h b/include/cdi-osdep.h index 726aab0..2a80be8 100644 --- a/include/cdi-osdep.h +++ b/include/cdi-osdep.h @@ -46,6 +46,27 @@ typedef struct /** * \german + * OS-spezifische Daten zu USB-Ger?ten. + * \endgerman + * \english + * OS-specific USB device data. + * \endenglish + * \thuringiansaxonian + * Vonn? j?wailschn Bedriebssysd??m abh?ngsche D?hdn, nu f?r so USB-Ger?ide. + * \endthuringiansaxonian + * \french + * Des donn?es tributaires du syst?me d'exploitation pour des p?riph?riques + * USB. + * \endfrench + * \japanese + * USB??????????OS???????? + * \endjapanese + */ +typedef struct { +} cdi_usb_device_osdep; + +/** + * \german * OS-spezifische Daten fuer einen ISA-DMA-Zugriff * \endgerman * \english diff --git a/include/cdi/usb-structures.h b/include/cdi/usb-structures.h new file mode 100644 index 0000000..fecb609 --- /dev/null +++ b/include/cdi/usb-structures.h @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2015 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. + */ + +/** + * This file contains some standard USB structures such as descriptors. + */ + +#ifndef _CDI_USB_STRUCTURES_H_ +#define _CDI_USB_STRUCTURES_H_ + +#include + + +struct cdi_usb_device_descriptor { + uint8_t b_length; + uint8_t b_descriptor_type; + uint16_t bcd_usb; + uint8_t b_device_class; + uint8_t b_device_sub_class; + uint8_t b_device_protocol; + uint8_t b_max_packet_size_0; + uint16_t id_vendor; + uint16_t id_product; + uint16_t bcd_device; + uint8_t i_manufacturer; + uint8_t i_product; + uint8_t i_serial_number; + uint8_t b_num_configurations; +} __attribute__((packed)); + +struct cdi_usb_configuration_descriptor { + uint8_t b_length; + uint8_t b_descriptor_type; + uint16_t w_total_length; + uint8_t b_num_interfaces; + uint8_t b_configuration_value; + uint8_t i_configuration; + uint8_t bm_attributes; + uint8_t b_max_power; +} __attribute__((packed)); + +struct cdi_usb_string_descriptor { + uint8_t b_length; + uint8_t b_descriptor_type; + uint16_t b_string[127]; +} __attribute__((packed)); + +struct cdi_usb_interface_descriptor { + uint8_t b_length; + uint8_t b_descriptor_type; + uint8_t b_interface_number; + uint8_t b_alternate_setting; + uint8_t b_num_endpoints; + uint8_t b_interface_class; + uint8_t b_interface_sub_class; + uint8_t b_interface_protocol; + uint8_t i_interface; +} __attribute__((packed)); + + +struct cdi_usb_endpoint_descriptor { + uint8_t b_length; + uint8_t b_descriptor_type; + uint8_t b_endpoint_address; + uint8_t bm_attributes; + uint16_t w_max_packet_size; + uint8_t b_interval; +} __attribute__((packed)); + +/// cdi_usb_endpoint_descriptor.b_endpoint_address +#define CDI_USB_EPDSC_EPADR_ID(x) ((x) & 0xf) +#define CDI_USB_EPDSC_EPADR_DIR (1 << 7) // IN if set + +/// cdi_usb_endpoint_descriptor.bm_attributes +#define CDI_USB_EPDSC_ATTR_XFER_TYPE_MASK 0x03 // Transfer Type mask +#define CDI_USB_EPDSC_ATTR_CONTROL 0x00 +#define CDI_USB_EPDSC_ATTR_ISOCHRONOUS 0x01 +#define CDI_USB_EPDSC_ATTR_BULK 0x02 +#define CDI_USB_EPDSC_ATTR_INTERRUPT 0x03 +#define CDI_USB_EPDSC_ATTR_SYNC_TYPE_MASK 0x0c // Synchronization Type mask +#define CDI_USB_EPDSC_ATTR_NO_SYNC 0x00 +#define CDI_USB_EPDSC_ATTR_ASYNC 0x04 +#define CDI_USB_EPDSC_ATTR_ADAPTIVE 0x08 +#define CDI_USB_EPDSC_ATTR_SYNC 0x0c +#define CDI_USB_EPDSC_ATTR_USAGE_TYPE_MASK 0x30 // Usage Type mask +#define CDI_USB_EPDSC_ATTR_DATA 0x00 +#define CDI_USB_EPDSC_ATTR_FEEDBACK 0x10 +#define CDI_USB_EPDSC_ATTR_IMPL_FB_DATA 0x20 // Implicit Feedback Data + +/// cdi_usb_endpoint_descriptor.w_max_packet_size +#define CDI_USB_EPDSC_MPS_MPS(x) ((x) & 0x7ff) + + +struct cdi_usb_setup_packet { + uint8_t bm_request_type; + uint8_t b_request; + uint16_t w_value; + uint16_t w_index; + uint16_t w_length; +} __attribute__((packed)); + +/// Values constituting cdi_usb_setup_packet.bm_request_type +#define CDI_USB_CREQ_DEVICE 0 +#define CDI_USB_CREQ_INTERFACE 1 +#define CDI_USB_CREQ_ENDPOINT 2 +#define CDI_USB_CREQ_OTHER 3 +#define CDI_USB_CREQ_CLASS (1 << 5) +#define CDI_USB_CREQ_OUT (0 << 7) +#define CDI_USB_CREQ_IN (1 << 7) + +/// Control request numbers (cdi_usb_setup_packet.b_request) +enum { + CDI_USB_CREQ_GET_STATUS = 0, + CDI_USB_CREQ_CLEAR_FEATURE = 1, + CDI_USB_CREQ_SET_FEATURE = 3, + CDI_USB_CREQ_SET_ADDRESS = 5, + CDI_USB_CREQ_GET_DESCRIPTOR = 6, + CDI_USB_CREQ_SET_DESCRIPTOR = 7, + CDI_USB_CREQ_GET_CONFIGURATION = 8, + CDI_USB_CREQ_SET_CONFIGURATION = 9, + CDI_USB_CREQ_GET_INTERFACE = 10, + CDI_USB_CREQ_SET_INTERFACE = 11, + CDI_USB_CREQ_SYNCH_FRAME = 12, +}; + +/// Descriptor IDs +enum { + CDI_USB_DESC_DEVICE = 1, + CDI_USB_DESC_CONFIGURATION = 2, + CDI_USB_DESC_STRING = 3, + CDI_USB_DESC_INTERFACE = 4, + CDI_USB_DESC_ENDPOINT = 5, +}; + +/// USB class codes. Defined here because they are not part of their respective +/// specifications. + +/// USB class codes on the device level +#define CDI_USB_DEVCLS_NONE 0x00 // No device-wide class, use interfaces +#define CDI_USB_DEVCLS_CCDCC 0x02 // Communications and CDC Control +#define CDI_USB_DEVCLS_HUB 0x09 // Hub +#define CDI_USB_DEVCLS_BILLBD 0x11 // Billboard Device +#define CDI_USB_DEVCLS_DIAG 0xdc // Diagnostic Device +#define CDI_USB_DEVCLS_MISC 0xef // Miscellaneous +#define CDI_USB_DEVCLS_VENDOR 0xff // Vendor-specific + +/// USB class codes on the interface level +#define CDI_USB_IFCCLS_AUDIO 0x01 // Audio +#define CDI_USB_IFCCLS_CCDCC CDI_USB_DEVCLS_CCDCC +#define CDI_USB_IFCCLS_HID 0x03 // Human Interface Device +#define CDI_USB_IFCCLS_PHYS 0x05 // Physical +#define CDI_USB_IFCCLS_IMAGE 0x06 // Image +#define CDI_USB_IFCCLS_PRINTER 0x07 // Printer +#define CDI_USB_IFCCLS_STORAGE 0x08 // Mass Storage +#define CDI_USB_IFCCLS_CDCDATA 0x0a // CDC Data +#define CDI_USB_IFCCLS_SMARTCD 0x0b // Smart Card +#define CDI_USB_IFCCLS_CNTTSEC 0x0d // Content Security +#define CDI_USB_IFCCLS_VIDEO 0x0e // Video +#define CDI_USB_IFCCLS_HEALTH 0x0f // Personal Healthcare +#define CDI_USB_IFCCLS_AV 0x10 // Audio/Video +#define CDI_USB_IFCCLS_DIAG CDI_USB_DEVCLS_DIAG +#define CDI_USB_IFCCLS_WIRELESS 0xe0 // Wireless Controller +#define CDI_USB_IFCCLS_MISC CDI_USB_DEVCLS_MISC +#define CDI_USB_IFCCLS_APP 0xfe // Application-specific +#define CDI_USB_IFCCLS_VENDOR CDI_USB_DEVCLS_VENDOR + +#endif diff --git a/include/cdi/usb.h b/include/cdi/usb.h new file mode 100644 index 0000000..d30e7b0 --- /dev/null +++ b/include/cdi/usb.h @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2015 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. + */ + +#ifndef _CDI_USB_H_ +#define _CDI_USB_H_ + +#include + +#include +#include +#include + + +struct cdi_usb_hc; + +typedef enum { + CDI_USB_CONTROL, + CDI_USB_BULK, + CDI_USB_INTERRUPT, + CDI_USB_ISOCHRONOUS, +} cdi_usb_endpoint_type_t; + +typedef enum { + CDI_USB_LOW_SPEED, + CDI_USB_FULL_SPEED, + CDI_USB_HIGH_SPEED, + CDI_USB_SUPERSPEED, +} cdi_usb_speed_t; + +typedef enum { + CDI_USB_OK = 0, + + CDI_USB_DRIVER_ERROR, + CDI_USB_TIMEOUT, + CDI_USB_BABBLE, + CDI_USB_STALL, + CDI_USB_HC_ERROR, + CDI_USB_BAD_RESPONSE, +} cdi_usb_transmission_result_t; + +/* Bitmask of CDI_USB_PORT_* and CDI_USB_*_SPEED values */ +typedef uint32_t cdi_usb_port_status_t; + +#define CDI_USB_PORT_SPEED_MASK (0x7) +#define CDI_USB_PORT_CONNECTED (1 << 3) + +struct cdi_usb_hub; + +/** + * Describes a hub driver. This is not a CDI driver in the common sense. When + * used for a root hub, it is part of the host controller driver; when used for + * a device hub, it is only used internally by the USB driver. + */ +struct cdi_usb_hub_driver { + /** + * Makes a port unreachable by traffic which reaches the hub. @index is a + * 0-based index. + */ + void (*port_disable)(struct cdi_usb_hub* hub, int index); + + /** + * Makes a port reachable by traffic which reaches the hub and drives the + * reset signal for at least 50 ms on the port. @index is a 0-based index. + */ + void (*port_reset_enable)(struct cdi_usb_hub* hub, int index); + + /** + * Retrieves information about the given port. This should only be called + * after the port has been reset using port_reset_enable(). @index is a + * 0-based index. + */ + cdi_usb_port_status_t (*port_status)(struct cdi_usb_hub* hub, int index); +}; + +/** + * Describes a USB hub. This is not a CDI device in the common sense. When used + * for a root hub, it is part of the host controller object; when used for a + * device hub, it is only used internally by the USB driver. + * + * For this reason, there is no struct cdi_usb_hub_driver object reachable from + * this object. If it is a root hub, the hub driver will be part of the host + * controller driver. Otherwise (if it is a device hub), the hub driver will be + * internal to the USB driver. + */ +struct cdi_usb_hub { + /** + * Number of ports provided by this hub. + */ + int ports; +}; + +/** + * Describes a USB device as given to cdi_provide_device() and the init_device() + * function provided by USB device drivers. + */ +struct cdi_usb_device { + struct cdi_bus_data bus_data; + + /** + * Various information which can be used for identifying a USB device. + */ + uint16_t vendor_id, product_id; + uint8_t class_id, subclass_id, protocol_id; + + /** + * If negative, this logical device is defined on the USB device level; + * otherwise, this is the index of the interface which this logical device + * represents. + */ + int interface; + + /** + * Number of endpoints available for this device; this does include the + * default pipe (endpoint 0) which can be used both on the physical device + * level and from any interface. + */ + int endpoint_count; + + cdi_usb_device_osdep meta; +}; + +/** + * Describes the USB bus driver. + */ +struct cdi_usb_driver { + struct cdi_driver drv; + + /** + * Returns the endpoint descriptor for endpoint @ep (0 up until + * dev->endpoint_count - 1) of device @dev in @desc. + */ + void (*get_endpoint_descriptor)(struct cdi_usb_device* dev, int ep, + struct cdi_usb_endpoint_descriptor* desc); + + /** + * Executes a control transfer to endpoint @ep (0 up until + * dev->endpoint_count - 1) of device @dev, using @setup for the setup stage + * and @data for the data stage. The length and direction of transfer is + * deduced from @setup. + */ + cdi_usb_transmission_result_t + (*control_transfer)(struct cdi_usb_device* dev, int ep, + const struct cdi_usb_setup_packet* setup, + void* data); + + /** + * Executes a bulk transfer to endpoint @ep (0 up until + * dev->endpoint_count - 1) of device @dev, transferring @size bytes from/to + * @data. The direction of transfer is deduced from the endpoint given. + */ + cdi_usb_transmission_result_t (*bulk_transfer)(struct cdi_usb_device* dev, + int ep, void* data, + size_t size); +}; + +/** + * Describes patterns for USB devices a device driver can use to specify which + * devices it can handle. + */ +struct cdi_usb_bus_device_pattern { + struct cdi_bus_device_pattern pattern; + + /** + * Any field may be negative to signify "don't care". + */ + int vendor_id, product_id; + int class_id, subclass_id, protocol_id; +}; + + +/** + * Registers a USB bus driver. Should be called by the CDI library, ideally, + * after the USB bus driver's init() function has run. + */ +void cdi_usb_driver_register(struct cdi_usb_driver* drv); + +/** + * Returns the endpoint descriptor for endpoint @ep (0 up until + * dev->endpoint_count - 1) of device @dev in @desc. + */ +void cdi_usb_get_endpoint_descriptor(struct cdi_usb_device* dev, int ep, + struct cdi_usb_endpoint_descriptor* desc); + +/** + * Executes a control transfer to endpoint @ep (0 up until + * dev->endpoint_count - 1) of device @dev, using @setup for the setup stage and + * @data for the data stage. The length and direction of transfer is deduced + * from @setup. + */ +cdi_usb_transmission_result_t + cdi_usb_control_transfer(struct cdi_usb_device* dev, int ep, + const struct cdi_usb_setup_packet* setup, + void* data); + +/** + * Executes a bulk transfer to endpoint @ep (0 up until dev->endpoint_count - 1) + * of device @dev, transferring @size bytes from/to @data. The direction of + * transfer is deduced from the endpoint given. + */ +cdi_usb_transmission_result_t cdi_usb_bulk_transfer(struct cdi_usb_device* dev, + int ep, void* data, + size_t size); + +#endif diff --git a/include/cdi/usb_hcd.h b/include/cdi/usb_hcd.h new file mode 100644 index 0000000..842ae73 --- /dev/null +++ b/include/cdi/usb_hcd.h @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2015 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. + */ + +#ifndef _CDI_USB_HCD_H_ +#define _CDI_USB_HCD_H_ + +#include +#include + + +/** + * Opaque value identifying a transaction for the host controller. + */ +typedef void* cdi_usb_hc_transaction_t; + +typedef enum { + CDI_USB_IN, + CDI_USB_OUT, + CDI_USB_SETUP, +} cdi_usb_transfer_token_t; + + +/** + * Describes a USB host controller. + */ +struct cdi_usb_hc { + struct cdi_device dev; + + /** + * Root hub provided by the HC. The hub driver responsible for this root hub + * is part of the cdi_usb_hcd structure. + */ + struct cdi_usb_hub rh; +}; + +/** + * Describes the USB bus provided by a USB host controller and its root hub. All + * buses are handled by the USB bus driver, therefore there are no "identifying" + * fields in this structure. + */ +struct cdi_usb_hc_bus { + struct cdi_bus_data bus_data; + struct cdi_usb_hc* hc; +}; + +/** + * Contains information about a communication pipe to a USB device endpoint used + * for USB transactions. + */ +struct cdi_usb_hc_ep_info { + /// Device ID + uint8_t dev; + + /// Endpoint ID + uint8_t ep; + + /// Endpoint type + cdi_usb_endpoint_type_t ep_type; + + /// Transfer speed + cdi_usb_speed_t speed; + + /// Maximum packet size for this endpoint + size_t mps; + + /** + * For low and full speed devices operated behind a high speed hub: @tt_addr + * is the USB device address of the translating USB hub (the last high speed + * hub), @tt_port is the port (0-based index) of that hub where the first + * non-high-speed device of this device's tree is plugged into. + */ + uint8_t tt_addr, tt_port; +}; + +/** + * Describes a single USB transmission. + */ +struct cdi_usb_hc_transmission { + /// Transaction this transmission is part of + cdi_usb_hc_transaction_t ta; + + /// Type of transfer to be performed + cdi_usb_transfer_token_t token; + + /// Buffer to be used (may be NULL if @size is 0) + void* buffer; + + /// Number of bytes to be transferred (may be 0, and may exceed the MPS) + size_t size; + + /** + * Toggle bit to be used for the first packet issued in this transmission. + * If @size exceeds the MPS and thus multiple packets are transmitted, the + * toggle bit will be toggled automatically. + */ + unsigned toggle; + + /** + * Result of this transmission. Only valid after wait_transaction() has + * returned. + */ + cdi_usb_transmission_result_t* result; +}; + +/** + * Describes a USB host controller driver. + */ +struct cdi_usb_hcd { + struct cdi_driver drv; + + /** + * USB hub driver which is responsible for all root hubs provided by this + * HCD. + */ + struct cdi_usb_hub_driver rh_drv; + + /** + * Creates a USB transaction. A transaction consists of one or more + * transmissions to a single endpoint. + */ + cdi_usb_hc_transaction_t + (*create_transaction)(struct cdi_usb_hc* hc, + const struct cdi_usb_hc_ep_info* target); + + /** + * Enters a transmission into a transaction. The transmission will not be + * executed until start_transaction() is invoked. + * + * This function may not be called after start_transaction() has been used. + */ + void (*enqueue)(struct cdi_usb_hc* hc, + const struct cdi_usb_hc_transmission* trans); + + /** + * Starts asynchronous execution of a transaction. + */ + void (*start_transaction)(struct cdi_usb_hc* hc, + cdi_usb_hc_transaction_t ta); + + /** + * Wait until all transmissions enqueued in the given transaction have been + * executed. The variables pointed to by the @result field of the + * transmissions enqueued will only be valid when this function returns. + * + * This function may not be invoked before start_transaction(). + */ + void (*wait_transaction)(struct cdi_usb_hc* hc, + cdi_usb_hc_transaction_t ta); + + /** + * Destroys a transaction. Transmissions which have not been waited on may + * or may not have been executed by the time this function returns. The + * values of the variables pointed to by the @result field of unwaited-for + * transmissions are not valid, neither are the buffer contents for + * receiving transmissions. + */ + void (*destroy_transaction)(struct cdi_usb_hc* hc, + cdi_usb_hc_transaction_t ta); +}; + +#endif -- 2.6.3 From max at tyndur.org Sat Dec 12 21:10:38 2015 From: max at tyndur.org (Max Reitz) Date: Sat, 12 Dec 2015 21:10:38 +0100 Subject: [cdi-devel] [PATCH v4 2/4] ehci: Add EHCI driver In-Reply-To: <1449951040-16452-1-git-send-email-max@tyndur.org> References: <1449951040-16452-1-git-send-email-max@tyndur.org> Message-ID: <1449951040-16452-3-git-send-email-max@tyndur.org> + This adds an EHCI USB host controller driver. It is missing support for periodic schedule (interrupt and isochronous transfers), hotplugging, suspend/resume, etc. pp.. Signed-off-by: Max Reitz --- ehci/ehci.c | 640 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ehci/ehci.h | 292 +++++++++++++++++++++++++++ ehci/main.c | 69 +++++++ 3 files changed, 1001 insertions(+) create mode 100644 ehci/ehci.c create mode 100644 ehci/ehci.h create mode 100644 ehci/main.c diff --git a/ehci/ehci.c b/ehci/ehci.c new file mode 100644 index 0000000..7f3838c --- /dev/null +++ b/ehci/ehci.c @@ -0,0 +1,640 @@ +/****************************************************************************** + * Copyright (c) 2015 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 +#include + +#include "ehci.h" + + +#define EHCI_TIMEOUT 1000 // ms + + +static void bios_handoff(struct cdi_pci_device *pci_dev, struct ehci *hc); +static void irq_handler(struct cdi_device *dev); + + +struct cdi_device *ehci_init_device(struct cdi_bus_data *bus_data) +{ + struct cdi_pci_device *pci_dev = (struct cdi_pci_device *)bus_data; + static int dev_counter = 0; + + if (pci_dev->class_id != PCI_CLASS_SERIAL_BUS_CONTROLLER || + pci_dev->subclass_id != PCI_SUBCLASS_USB_HOST_CONTROLLER || + pci_dev->interface_id != PCI_INTERFACE_EHCI) + { + return NULL; + } + + struct ehci *hc = calloc(1, sizeof(*hc)); + + hc->hc.dev.name = malloc(8); + sprintf((char *)hc->hc.dev.name, "ehci%i", dev_counter++); + + hc->retired_qhs = cdi_list_create(); + + cdi_pci_alloc_memory(pci_dev); + + struct cdi_pci_resource *res; + for (int i = 0; (res = cdi_list_get(pci_dev->resources, i)); i++) { + if (res->type == CDI_PCI_MEMORY && !res->index) { + hc->caps = res->address; + hc->regs = (struct ehci_registers *)((uintptr_t)res->address + + hc->caps->caplength); + break; + } + } + if (!hc->regs) { + goto fail; + } + + bios_handoff(pci_dev, hc); + + // Stop operation + hc->regs->usbcmd = (hc->regs->usbcmd & EHCI_CMD_RSVD) | EHCI_CMD_ITC(8); + + // Wait until HCHALTED becomes true + CDI_CONDITION_WAIT(hc->regs->usbsts & EHCI_STS_HCH, 50); + if (!(hc->regs->usbsts & EHCI_STS_HCH)) { + goto fail; + } + + hc->regs->usbcmd |= EHCI_CMD_HCRES; // Reset + CDI_CONDITION_WAIT(!(hc->regs->usbcmd & EHCI_CMD_HCRES), 50); + if (hc->regs->usbcmd & EHCI_CMD_HCRES) { + goto fail; + } + + if (hc->caps->hccparams & EHCI_HCC_64) { + // 64-bit addressing capability + hc->regs->ctrldssegment = 0; + } + + hc->regs->usbintr = 0; + hc->regs->usbsts = hc->regs->usbsts; + + hc->periodic_list_mem = cdi_mem_alloc(4096, 12 + | CDI_MEM_PHYS_CONTIGUOUS + | CDI_MEM_DMA_4G + | CDI_MEM_NOINIT); + hc->periodic_list = hc->periodic_list_mem->vaddr; + for (int i = 0; i < 1024; i++) { + hc->periodic_list[i] = EHCI_T; + } + hc->regs->periodiclistbase = hc->periodic_list_mem->paddr.items[0].start; + + // Create anchor + struct cdi_mem_area *anchor_qh; + anchor_qh = cdi_mem_alloc(sizeof(ehci_fat_qh_t), 6 + | CDI_MEM_PHYS_CONTIGUOUS + | CDI_MEM_DMA_4G + | CDI_MEM_NOINIT); + + hc->async_start = anchor_qh->vaddr; + memset(hc->async_start, 0, sizeof(*hc->async_start)); + + hc->async_start->cdi_mem_area = anchor_qh; + hc->async_start->paddr = anchor_qh->paddr.items[0].start + + offsetof(ehci_fat_qh_t, qh); + + hc->async_start->next = hc->async_start; + hc->async_start->previous = hc->async_start; + + hc->async_start->qh.next_qh = hc->async_start->paddr | EHCI_QH; + hc->async_start->qh.ep_state[0] = EHCI_QHES0_RL(0) | EHCI_QHES0_MPL(8) + | EHCI_QHES0_EP(0) | EHCI_QHES0_DEV(0) + | EHCI_QHES0_H | EHCI_QHES0_DTC + | EHCI_QHES0_EPS_HS; + hc->async_start->qh.ep_state[1] = EHCI_QHES1_MULT(1) | EHCI_QHES1_SCM(0xff); + + hc->async_start->qh.overlay.next_qtd = EHCI_T; + hc->async_start->qh.overlay.alt_next_qtd = EHCI_T; + + hc->regs->asynclistaddr = hc->async_start->paddr; + + // Start operation + hc->regs->usbcmd = (hc->regs->usbcmd & EHCI_CMD_RSVD) + | EHCI_CMD_ITC(8) | EHCI_CMD_ASE | EHCI_CMD_PSE + | EHCI_CMD_FLS_1K | EHCI_CMD_RS; + + // Wait until HCHalted becomes false and the schedules are running + CDI_CONDITION_WAIT((hc->regs->usbsts + & (EHCI_STS_ASS | EHCI_STS_PSS | EHCI_STS_HCH)) + == (EHCI_STS_ASS | EHCI_STS_PSS), 50); + if ((hc->regs->usbsts & (EHCI_STS_ASS | EHCI_STS_PSS | EHCI_STS_HCH)) + != (EHCI_STS_ASS | EHCI_STS_PSS)) + { + goto fail; + } + + cdi_register_irq(pci_dev->irq, &irq_handler, &hc->hc.dev); + + // async advance doorbell + hc->regs->usbintr = EHCI_INT_IAA; + + // Route everything to this HC + hc->regs->configflag |= EHCI_CF_CF; + + cdi_sleep_ms(5); + + hc->hc.rh.ports = EHCI_HCS_N_PORTS(hc->caps->hcsparams); + + // Power up all ports + for (int i = 0; i < hc->hc.rh.ports; i++) { + hc->regs->portsc[i] |= EHCI_PSC_PP; + } + + return &hc->hc.dev; + +fail: + if (hc->async_start) { + cdi_mem_free(hc->async_start->cdi_mem_area); + } + if (hc->periodic_list_mem) { + cdi_mem_free(hc->periodic_list_mem); + } + cdi_list_destroy(hc->retired_qhs); + free((void *)hc->hc.dev.name); + free(hc); + cdi_pci_free_memory(pci_dev); + + return NULL; +} + + +static void bios_handoff(struct cdi_pci_device *pci_dev, struct ehci *hc) +{ + int eecp = EHCI_HCC_EECP(hc->caps->hccparams); + + // Iterate through the list of capabilities + while (eecp >= 0x40) { + uint32_t cap = cdi_pci_config_readl(pci_dev, eecp); + + // Look for USBLEGSUP + if (EHCI_EEC_ID(cap) == EHCI_EECID_LEGSUP) { + // Set OS semaphore + cdi_pci_config_writeb(pci_dev, eecp + 3, 1); + + // Wait for BIOS semaphore to get unset + CDI_CONDITION_WAIT(!(cdi_pci_config_readb(pci_dev, eecp + 2) & 1), + 5000); + if (cdi_pci_config_readb(pci_dev, eecp + 2) & 1) { + // Okay Max, stay calm, don't swear + printf("[ehci] Warning: Clean BIOS handoff failed\n"); + // Disable all SMI sources (0xff000000 is the R/WC mask of this + // register) + cdi_pci_config_writel(pci_dev, eecp + 4, + cdi_pci_config_readl(pci_dev, eecp + 4) & 0xff000000u); + // Unset BIOS semaphore + cdi_pci_config_writeb(pci_dev, eecp + 2, 0); + } + } + + eecp = EHCI_EEC_NEXT(cap); + } +} + + +static void irq_handler(struct cdi_device *dev) +{ + struct cdi_usb_hc *cdi_hc = CDI_UPCAST(dev, struct cdi_usb_hc, dev); + struct ehci *hc = CDI_UPCAST(cdi_hc, struct ehci, hc); + + uint32_t usbsts = hc->regs->usbsts; + hc->regs->usbsts = usbsts; + + // async advance doorbell + if (!(usbsts & EHCI_STS_IAA)) { + return; + } + + ehci_fat_qh_t *rqh; + while ((rqh = cdi_list_pop(hc->retired_qhs))) { + cdi_mem_free(rqh->cdi_mem_area); + } +} + + +void ehci_rh_port_down(struct cdi_usb_hub *hub, int index) +{ + struct cdi_usb_hc *cdi_hc = CDI_UPCAST(hub, struct cdi_usb_hc, rh); + struct ehci *hc = CDI_UPCAST(cdi_hc, struct ehci, hc); + + hc->regs->portsc[index] &= ~EHCI_PSC_PED; +} + + +void ehci_rh_port_up(struct cdi_usb_hub *hub, int index) +{ + struct cdi_usb_hc *cdi_hc = CDI_UPCAST(hub, struct cdi_usb_hc, rh); + struct ehci *hc = CDI_UPCAST(cdi_hc, struct ehci, hc); + uint32_t portsc = hc->regs->portsc[index]; + + if ((portsc & EHCI_PSC_LS_MASK) == EHCI_PSC_LS_K) { + // Low-speed device, release ownership + hc->regs->portsc[index] = portsc | EHCI_PSC_PO; + return; + } + + // Assert reset signal + hc->regs->portsc[index] = ((portsc & ~(EHCI_PSC_PO | EHCI_PSC_SUS | + EHCI_PSC_FPR | EHCI_PSC_PED)) + | EHCI_PSC_RES); + cdi_sleep_ms(50); + + // De-assert reset signal + hc->regs->portsc[index] = portsc & ~EHCI_PSC_RES; + CDI_CONDITION_WAIT(!(hc->regs->portsc[index] & EHCI_PSC_RES), 50); + + portsc = hc->regs->portsc[index]; + if (portsc & EHCI_PSC_RES) { + // Disable port, route on to companion controller + // (maybe it can do at least something with it) + hc->regs->portsc[index] = (portsc & ~EHCI_PSC_PED) | EHCI_PSC_PO; + } else if ((portsc & (EHCI_PSC_PED | EHCI_PSC_CCS)) == EHCI_PSC_CCS) { + // Device connected but port disabled: + // Full-speed device, release ownership + hc->regs->portsc[index] = portsc | EHCI_PSC_PO; + } +} + + +cdi_usb_port_status_t ehci_rh_port_status(struct cdi_usb_hub *hub, int index) +{ + struct cdi_usb_hc *cdi_hc = CDI_UPCAST(hub, struct cdi_usb_hc, rh); + struct ehci *hc = CDI_UPCAST(cdi_hc, struct ehci, hc); + uint32_t portsc = hc->regs->portsc[index]; + cdi_usb_port_status_t status = 0; + + if ((portsc & (EHCI_PSC_PED | EHCI_PSC_CCS)) == + (EHCI_PSC_PED | EHCI_PSC_CCS)) + { + // Device connected and port enabled + status |= CDI_USB_PORT_CONNECTED | CDI_USB_HIGH_SPEED; + } + + return status; +} + + +static void enter_async_qh(struct ehci *hc, ehci_fat_qh_t *qh) +{ + // Enter the new QH as last + + qh->next = hc->async_start; + qh->previous = hc->async_start->previous; + + qh->previous->next = qh; + hc->async_start->previous = qh; + + qh->qh.next_qh = hc->async_start->paddr | EHCI_QH; + qh->previous->qh.next_qh = qh->paddr | EHCI_QH; +} + + +static void retire_qh(struct ehci *hc, ehci_fat_qh_t *qh) +{ + qh->previous->qh.next_qh = qh->qh.next_qh; + + qh->previous->next = qh->next; + qh->next->previous = qh->previous; + + cdi_list_push(hc->retired_qhs, qh); + // Request async advance doorbell + hc->regs->usbcmd |= EHCI_CMD_IAADB; +} + + +static void retire_first_qtd(ehci_fat_qh_t *qh) +{ + ehci_fat_qtd_t *qtd = qh->first_qtd; + + assert(qtd); + + uint32_t err_mask = (qh->qh.ep_state[0] & EHCI_QHES0_EPS_MASK) + == EHCI_QHES0_EPS_HS + ? EHCI_QTDS_HS_ERR_MASK + : EHCI_QTDS_LFS_ERR_MASK; + + if (qtd->qtd.status & err_mask) { + if (qtd->qtd.status & EHCI_QTDS_BABBLE) { + *qtd->result = CDI_USB_BABBLE; + } else if (qtd->qtd.status & (EHCI_QTDS_XACTERR | EHCI_QTDS_P_ERR)) { + *qtd->result = CDI_USB_BAD_RESPONSE; + } else if (qtd->qtd.status & (EHCI_QTDS_BUFERR | EHCI_QTDS_MuF)) { + *qtd->result = CDI_USB_HC_ERROR; + } else if (qtd->qtd.status & EHCI_QTDS_HALTED) { + *qtd->result = CDI_USB_STALL; + } else { + *qtd->result = CDI_USB_HC_ERROR; + } + } + + if (qtd->write_back) { + size_t rem = qtd->write_back_size; + for (int i = 0; i < 5 && rem; i++) { + size_t sz = rem > 4096 ? 4096 : rem; + memcpy((void *)((uintptr_t)qtd->write_back + i * 4096), + qtd->buffers[i]->vaddr, sz); + rem -= sz; + } + assert(!rem); + } + + qh->first_qtd = qtd->next; + if (qh->last_qtd == qtd) { + qh->last_qtd = NULL; + } + + for (int i = 0; i < 5; i++) { + if (qtd->buffers[i]) { + cdi_mem_free(qtd->buffers[i]); + } + } + + cdi_mem_free(qtd->cdi_mem_area); +} + + +/** + * Enters a qTD into a QH that has not yet been entered into the async schedule. + */ +static void enter_qtd(ehci_fat_qh_t *qh, ehci_fat_qtd_t *qtd) +{ + bool first; + + qtd->qh = qh; + qtd->qtd.next_qtd = EHCI_T; + qtd->qtd.alt_next_qtd = EHCI_T; + + first = !qh->first_qtd; + + if (first) { + qh->first_qtd = qtd; + } else { + qh->last_qtd->next = qtd; + } + qh->last_qtd = qtd; + + if (first) { + qh->qh.overlay.next_qtd = qh->first_qtd->paddr; + } else { + qh->last_qtd->qtd.next_qtd = qtd->paddr; + } +} + + +cdi_usb_hc_transaction_t ehci_create_transaction(struct cdi_usb_hc *cdi_hc, + const struct cdi_usb_hc_ep_info *target) +{ + (void)cdi_hc; + + struct cdi_mem_area *qh_mem; + + qh_mem = cdi_mem_alloc(sizeof(ehci_fat_qh_t), 6 + | CDI_MEM_PHYS_CONTIGUOUS + | CDI_MEM_DMA_4G + | CDI_MEM_NOINIT); + ehci_fat_qh_t *qh = qh_mem->vaddr; + + memset(qh, 0, sizeof(*qh)); + + int non_high_speed_control = target->speed != CDI_USB_HIGH_SPEED + && target->ep_type == CDI_USB_CONTROL; + + qh->qh.ep_state[0] = EHCI_QHES0_RL(0) + | (non_high_speed_control ? EHCI_QHES0_C : 0) + | EHCI_QHES0_MPL(target->mps) + | EHCI_QHES0_DTC + | EHCI_QHES0_EP(target->ep) + | EHCI_QHES0_DEV(target->dev); + switch (target->speed) { + case CDI_USB_LOW_SPEED: qh->qh.ep_state[0] |= EHCI_QHES0_EPS_LS; break; + case CDI_USB_FULL_SPEED: qh->qh.ep_state[0] |= EHCI_QHES0_EPS_FS; break; + case CDI_USB_HIGH_SPEED: qh->qh.ep_state[0] |= EHCI_QHES0_EPS_HS; break; + case CDI_USB_SUPERSPEED: + default: + abort(); + } + + qh->qh.ep_state[1] = EHCI_QHES1_MULT(1) + | EHCI_QHES1_PORT(target->tt_port + 1) + | EHCI_QHES1_HUB(target->tt_addr) + | EHCI_QHES1_SCM(0xff); + + qh->qh.overlay.next_qtd = EHCI_T; + qh->qh.overlay.alt_next_qtd = EHCI_T; + + qh->cdi_mem_area = qh_mem; + qh->paddr = qh_mem->paddr.items[0].start + offsetof(ehci_fat_qh_t, qh); + + return qh; +} + + +static void create_qtd(ehci_fat_qh_t *qh, cdi_usb_transfer_token_t token, + int toggle, void *buffer, size_t size, + cdi_usb_transmission_result_t *result) +{ + struct cdi_mem_area *qtd_mem; + + qtd_mem = cdi_mem_alloc(sizeof(ehci_fat_qtd_t), 6 + | CDI_MEM_PHYS_CONTIGUOUS + | CDI_MEM_DMA_4G + | CDI_MEM_NOINIT); + ehci_fat_qtd_t *qtd = qtd_mem->vaddr; + + memset(qtd, 0, sizeof(*qtd)); + + qtd->qtd.status = EHCI_QTDS_DT(toggle) + | EHCI_QTDS_XFLEN(size) + | EHCI_QTDS_CP(0) + | EHCI_QTDS_CERR(3) + | EHCI_QTDS_ACTIVE; + + switch (token) { + case CDI_USB_IN: qtd->qtd.status |= EHCI_QTDS_PID_IN; break; + case CDI_USB_OUT: qtd->qtd.status |= EHCI_QTDS_PID_OUT; break; + case CDI_USB_SETUP: qtd->qtd.status |= EHCI_QTDS_PID_SETUP; break; + default: + abort(); + } + + if (token == CDI_USB_IN) { + qtd->write_back = buffer; + qtd->write_back_size = size; + } + + for (int i = 0; i < 5 && size; i++) { + size_t sz = size > 4096 ? 4096 : size; + + qtd->buffers[i] = cdi_mem_alloc(4096, 12 + | CDI_MEM_PHYS_CONTIGUOUS + | CDI_MEM_DMA_4G + | CDI_MEM_NOINIT); + qtd->qtd.buffers[i] = qtd->buffers[i]->paddr.items[0].start; + + if (token == CDI_USB_OUT || token == CDI_USB_SETUP) { + memcpy(qtd->buffers[i]->vaddr, + (void *)((uintptr_t)buffer + i * 4096), sz); + } + + size -= sz; + } + + qtd->cdi_mem_area = qtd_mem; + qtd->paddr = qtd_mem->paddr.items[0].start + offsetof(ehci_fat_qtd_t, qtd); + + qtd->result = result; + + enter_qtd(qh, qtd); +} + + +void ehci_enqueue(struct cdi_usb_hc *cdi_hc, + const struct cdi_usb_hc_transmission *trans) +{ + (void)cdi_hc; + + ehci_fat_qh_t *qh = trans->ta; + bool first = true; + size_t sz = trans->size; + char *buf = trans->buffer; + int toggle = trans->toggle; + size_t mps = EHCI_QHES0_READ_MPL(qh->qh.ep_state[0]); + + *trans->result = CDI_USB_OK; + + while (sz || first) { + first = false; + + size_t iter_sz = sz > 4096 * 5 ? 4096 * 5 : sz; + + create_qtd(qh, trans->token, toggle, buf, iter_sz, trans->result); + + buf += iter_sz; + sz -= iter_sz; + + toggle ^= ((iter_sz + mps - 1) / mps) & 1; + } +} + + +void ehci_start_transaction(struct cdi_usb_hc *cdi_hc, + cdi_usb_hc_transaction_t ta) +{ + struct ehci *hc = CDI_UPCAST(cdi_hc, struct ehci, hc); + ehci_fat_qh_t *qh = ta; + + enter_async_qh(hc, qh); +} + + +void ehci_wait_transaction(struct cdi_usb_hc *cdi_hc, + cdi_usb_hc_transaction_t ta) +{ + (void)cdi_hc; + + ehci_fat_qh_t *qh = ta; + bool had_timeout = false; + + irq_handler(&cdi_hc->dev); + + while (qh->first_qtd) { + if (!had_timeout) { + if (!(qh->qh.overlay.status & EHCI_QTDS_ACTIVE)) { + qh->qh.overlay.next_qtd = qh->first_qtd->paddr; + } + + uint64_t timestamp = cdi_elapsed_ms(); + + while ((qh->first_qtd->qtd.status & EHCI_QTDS_ACTIVE) && + cdi_elapsed_ms() - timestamp < EHCI_TIMEOUT) + { + // I don't really know who's to blame for this (qemu or + // t?ndur), and actually, I don't even want to know. + // As a matter of fact, qemu will not work on the async + // schedule if the async advance doorbell is set but the driver + // has not acknowledged this; however, the interrupt handler + // will always clear that bit and the interrupt handler is + // active all the time, so something is apparently sometimes + // blocking the handler from being executed. Force it here to + // prevent qemu's HC from stalling. + irq_handler(&cdi_hc->dev); + } + + had_timeout = qh->first_qtd->qtd.status & EHCI_QTDS_ACTIVE; + } + + if (had_timeout) { + // Stop this queue + qh->qh.overlay.next_qtd = EHCI_T; + qh->qh.overlay.status &= ~(uint32_t)EHCI_QTDS_ACTIVE; + + *qh->first_qtd->result = CDI_USB_TIMEOUT; + } + + retire_first_qtd(qh); + } +} + + +void ehci_destroy_transaction(struct cdi_usb_hc *cdi_hc, + cdi_usb_hc_transaction_t ta) +{ + struct ehci *hc = CDI_UPCAST(cdi_hc, struct ehci, hc); + ehci_fat_qh_t *qh = ta; + + qh->qh.overlay.next_qtd = EHCI_T; + + uint64_t timestamp = cdi_elapsed_ms(); + + while ((qh->qh.overlay.status & EHCI_QTDS_ACTIVE) && + cdi_elapsed_ms() - timestamp < EHCI_TIMEOUT) + { + // See above. + irq_handler(&cdi_hc->dev); + } + + if (qh->qh.overlay.status & EHCI_QTDS_ACTIVE) { + qh->qh.overlay.status &= ~(uint32_t)EHCI_QTDS_ACTIVE; + // Could probably be solved more elegantly, but we are in a timeout + // already, so waiting a bit longer will not be that big of a problem + // (the sleep is here to ensure that the HC is no longer trying to work + // on the qTDs belonging to this QH) + cdi_sleep_ms(100); + } + + while (qh->first_qtd) { + retire_first_qtd(qh); + } + retire_qh(hc, qh); +} diff --git a/ehci/ehci.h b/ehci/ehci.h new file mode 100644 index 0000000..d37f141 --- /dev/null +++ b/ehci/ehci.h @@ -0,0 +1,292 @@ +/****************************************************************************** + * Copyright (c) 2015 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 EHCI_H +#define EHCI_H + +#include +#include + +#include +#include +#include +#include + + +struct ehci_registers { + uint32_t usbcmd; + uint32_t usbsts; + uint32_t usbintr; + uint32_t frindex; + uint32_t ctrldssegment; + uint32_t periodiclistbase; + uint32_t asynclistaddr; + uint8_t reserved[0x24]; + uint32_t configflag; + uint32_t portsc[]; +} __attribute__((packed)); + +struct ehci_capabilities { + uint8_t caplength; + uint8_t reserved; + uint16_t hciversion; + uint32_t hcsparams; + uint32_t hccparams; + uint64_t hcsp_portroute; +} __attribute__((packed)); + +struct ehci_qtd { + uint32_t next_qtd; + uint32_t alt_next_qtd; + uint32_t status; + uint32_t buffers[5]; + + // 64-bit structures + uint32_t ext_buffer[5]; +} __attribute__((packed)); + +struct ehci_qh { + uint32_t next_qh; + uint32_t ep_state[2]; + uint32_t current_qtd; + struct ehci_qtd overlay; +} __attribute__((packed)); + +typedef struct ehci_fat_qh ehci_fat_qh_t; +typedef struct ehci_fat_qtd ehci_fat_qtd_t; + +#define DIFF_TO_MULTIPLE(value, divisor) \ + ((divisor) - ((((value) + (divisor) - 1) % (divisor)) + 1)) + +struct ehci_fat_qh { + volatile struct ehci_qh qh; + + // Align the QH to 128 bytes (something with cache lines?). Otherwise, + // there may be conflicts between data we are writing to our very own + // fields provided by ehci_fat_qh_t and writes done by the HC to this + // structure. + uint8_t alignment[DIFF_TO_MULTIPLE(sizeof(struct ehci_qh), 128)]; + + struct cdi_mem_area *cdi_mem_area; + uintptr_t paddr; + + ehci_fat_qh_t *next, *previous; + ehci_fat_qtd_t *first_qtd, *last_qtd; +}; + +struct ehci_fat_qtd { + volatile struct ehci_qtd qtd; + + // Align the qTD to a multiple of 128 bytes. + uint8_t alignment[DIFF_TO_MULTIPLE(sizeof(struct ehci_qtd), 128)]; + + struct cdi_mem_area *cdi_mem_area; + uintptr_t paddr; + + ehci_fat_qh_t *qh; + ehci_fat_qtd_t *next; + + struct cdi_mem_area *buffers[5]; + + void *write_back; + size_t write_back_size; + + cdi_usb_transmission_result_t *result; +}; + +struct ehci { + struct cdi_usb_hc hc; + + volatile struct ehci_capabilities *caps; + volatile struct ehci_registers *regs; + + struct cdi_mem_area *periodic_list_mem; + volatile uint32_t *periodic_list; + + ehci_fat_qh_t *async_start; + cdi_list_t retired_qhs; +}; + +#define PCI_CLASS_SERIAL_BUS_CONTROLLER 0x0c +#define PCI_SUBCLASS_USB_HOST_CONTROLLER 0x03 +#define PCI_INTERFACE_EHCI 0x20 + +#define EHCI_T (1u << 0) +#define EHCI_ITD (0u << 1) +#define EHCI_QH (1u << 1) +#define EHCI_SITD (2u << 1) +#define EHCI_FSTN (3u << 1) + +// Operational Registers: USBCMD +#define EHCI_CMD_RSVD 0xff00ff00u // Consider async sched park mode reserved +#define EHCI_CMD_ITC(x) ((x) << 16) // Interrupt Threshold Control +#define EHCI_CMD_LHCRES (1 << 7) // Light Host Controller Reset +#define EHCI_CMD_IAADB (1 << 6) // Interrupt on Async Advance Doorbell +#define EHCI_CMD_ASE (1 << 5) // Async Schedule Enable +#define EHCI_CMD_PSE (1 << 4) // Periodic Schedule Enable +#define EHCI_CMD_FLS_1K (0 << 2) // Frame List Size: 1024 elements (default) +#define EHCI_CMD_HCRES (1 << 1) // Host Controller Reset +#define EHCI_CMD_RS (1 << 0) // Run/Stop (1 = Run) + +// Operational Registers: USBINTR +#define EHCI_INT_IAA (1 << 5) // Interrupt on Async Advance Enable +#define EHCI_INT_HSE (1 << 4) // Host System Error Enable +#define EHCI_INT_FLR (1 << 3) // Frame List Rollover Enable +#define EHCI_INT_PCD (1 << 2) // Port Change Detect Enable +#define EHCI_INT_USBERR (1 << 1) // USB Error Interrupt +#define EHCI_INT_USBINT (1 << 0) // USB Interrupt + +// Operational Registers: USBSTS +#define EHCI_STS_ASS (1 << 15) // Async Schedule Status +#define EHCI_STS_PSS (1 << 14) // Periodic Schedule Status +#define EHCI_STS_REC (1 << 13) // Reclamation bit +#define EHCI_STS_HCH (1 << 12) // Host Controller Halted +#define EHCI_STS_IAA EHCI_INT_IAA // Interrupt on Async Advance +#define EHCI_STS_HSE EHCI_INT_HSE // Host System Error +#define EHCI_STS_FLR EHCI_INT_FLR // Frame List Rollover +#define EHCI_STS_PCD EHCI_INT_PCD // Port Change Detect +#define EHCI_STS_USBERR EHCI_INT_USBERR // USB Error Interrupt +#define EHCI_STS_USBINT EHCI_INT_USBINT // USB Interrupt + +// Operational Registers: FRINDEX +#define EHCI_FI_FI(x) (((x) >> 3) & 0x3ff) // Frame Index + +// Operational Registers: CONFIGFLAG +#define EHCI_CF_CF (1 << 0) // Configure Flag + +// Operational Registers: PORTSC +#define EHCI_PSC_WKOC_E (1 << 22) // Wake on Over-current Enable +#define EHCI_PSC_WKDSCNNT_E (1 << 21) // Wake on Disconnect Enable +#define EHCI_PSC_WKCNNT_E (1 << 20) // Wake on Connect Enable +#define EHCI_PSC_PTC_DIS (0 << 16) // Port Test Control: disabled +#define EHCI_PSC_PTC_J (1 << 16) // Port Test Control: J-State +#define EHCI_PSC_PTC_K (2 << 16) // Port Test Control: K-State +#define EHCI_PSC_PTC_SE0 (3 << 16) // Port Test Control: SE0 Nak +#define EHCI_PSC_PTC_PKT (4 << 16) // Port Test Control: Packet +#define EHCI_PSC_PTC_FEN (5 << 16) // Port Test Control: Force Enable +#define EHCI_PSC_PI_OFF (0 << 14) // Port Indicators: off +#define EHCI_PSC_PI_AMBER (1 << 14) // Port Indicators: amber +#define EHCI_PSC_PI_GREEN (2 << 14) // Port Indicators: green +#define EHCI_PSC_PO (1 << 13) // Port Owner +#define EHCI_PSC_PP (1 << 12) // Port Power +#define EHCI_PSC_LS_MASK (3 << 10) // Line Status mask +#define EHCI_PSC_LS_SE0 (0 << 10) // Line Status: SE0 +#define EHCI_PSC_LS_K (1 << 10) // Line Status: K-State +#define EHCI_PSC_LS_J (2 << 10) // Line Status: J-State +#define EHCI_PSC_RES (1 << 8) // Port Reset +#define EHCI_PSC_SUS (1 << 7) // Suspend +#define EHCI_PSC_FPR (1 << 6) // Force Port Resume +#define EHCI_PSC_OCC (1 << 5) // Over-current Change +#define EHCI_PSC_OCA (1 << 4) // Over-current Active +#define EHCI_PSC_PEDC (1 << 3) // Port Enable/Disable Change +#define EHCI_PSC_PED (1 << 2) // Port Enabled/Disabled +#define EHCI_PSC_CSC (1 << 1) // Connect Status Change +#define EHCI_PSC_CCS (1 << 0) // Current Connect Status + +// Capability Registers: HCSPARAMS +#define EHCI_HCS_N_CC(x) (((x) >> 12) & 0xf) // Number of Companion + // Controllers +#define EHCI_HCS_N_PCC(x) (((x) >> 8) & 0xf) // Number of Ports per CC +#define EHCI_HCS_PRR (1 << 7) // Port Routing Rules +#define EHCI_HCS_PPC (1 << 4) // Port Power Control +#define EHCI_HCS_N_PORTS(x) (((x) >> 0) & 0xf) // Number of Ports + +// Capability Registers: HCCPARAMS +#define EHCI_HCC_EECP(x) (((x) >> 8) & 0xff) // EHCI Extended Capabilities + // Pointer +#define EHCI_HCC_64 (1 << 0) // 64-bit Addressing Capability + +// EHCI Extended Capability +#define EHCI_EEC_NEXT(x) (((x) >> 8) & 0xff) +#define EHCI_EEC_ID(x) (((x) >> 0) & 0xff) + +#define EHCI_EECID_LEGSUP 0x01 + +// QH.ep_state[0] (Endpoint Characteristics) +#define EHCI_QHES0_RL(x) ((uint32_t)(x) << 28) // Nak Count Reload +#define EHCI_QHES0_C (1 << 27) // Control Endpoint Flag +#define EHCI_QHES0_MPL(x) ((x) << 16) // Maximum Packet Length +#define EHCI_QHES0_READ_MPL(x) (((x) >> 16) & 0x7ff) +#define EHCI_QHES0_H (1 << 15) // Head of Reclamation List flag +#define EHCI_QHES0_DTC (1 << 14) // Data Toggle Control +#define EHCI_QHES0_EPS_MASK (3 << 12) // Endpoint Speed mask +#define EHCI_QHES0_EPS_FS (0 << 12) // Endpoint Speed: Full Speed +#define EHCI_QHES0_EPS_LS (1 << 12) // Endpoint Speed: Low Speed +#define EHCI_QHES0_EPS_HS (2 << 12) // Endpoint Speed: High Speed +#define EHCI_QHES0_EP(x) ((x) << 8) // Endpoint Number +#define EHCI_QHES0_I (1 << 7) // Inactive on Next Transaction +#define EHCI_QHES0_DEV(x) ((x) << 0) // Device Address + +// QH.ep_state[1] (Endpoint Capabilities) +#define EHCI_QHES1_MULT(x) ((uint32_t)(x) << 30) // High-Bandwidth Pipe + // Multiplier +#define EHCI_QHES1_PORT(x) ((x) << 23) // Port Number +#define EHCI_QHES1_HUB(x) ((x) << 16) // Hub Address +#define EHCI_QHES1_SCM(x) ((x) << 8) // Split Completion Mask +#define EHCI_QHES1_ISM(x) ((x) << 0) // Interrupt Schedule Mask + +// qTD.status (Token) +#define EHCI_QTDS_DT(x) ((uint32_t)(x) << 31) // Data Toggle +#define EHCI_QTDS_XFLEN(x) ((x) << 16) // Total Bytes to Transfer +#define EHCI_QTDS_IOC (1 << 15) // Interrupt on Complete +#define EHCI_QTDS_CP(x) ((x) << 12) // Current Page +#define EHCI_QTDS_CERR(x) ((x) << 10) // Error Counter +#define EHCI_QTDS_PID_OUT (0 << 8) // PID: OUT +#define EHCI_QTDS_PID_IN (1 << 8) // PID: IN +#define EHCI_QTDS_PID_SETUP (2 << 8) // PID: SETUP +#define EHCI_QTDS_ACTIVE (1 << 7) // Status: Active +#define EHCI_QTDS_HALTED (1 << 6) // Status: Halted +#define EHCI_QTDS_BUFERR (1 << 5) // Status: Data Buffer Error +#define EHCI_QTDS_BABBLE (1 << 4) // Status: Babble Detected +#define EHCI_QTDS_XACTERR (1 << 3) // Status: Transaction Error +#define EHCI_QTDS_MuF (1 << 2) // Status: Missed Microframe +#define EHCI_QTDS_SPLITXS (1 << 1) // Status: Split Transaction State +#define EHCI_QTDS_P_ERR (1 << 0) // Status: Ping State / Error + +// High Speed Error Mask +#define EHCI_QTDS_HS_ERR_MASK \ + (EHCI_QTDS_HALTED | EHCI_QTDS_BUFERR | EHCI_QTDS_BABBLE | \ + EHCI_QTDS_XACTERR | EHCI_QTDS_MuF) + +// Low/Full Speed Error Mask +#define EHCI_QTDS_LFS_ERR_MASK \ + (EHCI_QTDS_HS_ERR_MASK | EHCI_QTDS_P_ERR) + + +struct cdi_device *ehci_init_device(struct cdi_bus_data *bus_data); + +void ehci_rh_port_down(struct cdi_usb_hub *hub, int index); +void ehci_rh_port_up(struct cdi_usb_hub *hub, int index); +cdi_usb_port_status_t ehci_rh_port_status(struct cdi_usb_hub *hub, int index); + +cdi_usb_hc_transaction_t + ehci_create_transaction(struct cdi_usb_hc *hc, + const struct cdi_usb_hc_ep_info *target); +void ehci_enqueue(struct cdi_usb_hc *hc, + const struct cdi_usb_hc_transmission *trans); +void ehci_start_transaction(struct cdi_usb_hc *cdi_hc, + cdi_usb_hc_transaction_t ta); +void ehci_wait_transaction(struct cdi_usb_hc *hc, cdi_usb_hc_transaction_t ta); +void ehci_destroy_transaction(struct cdi_usb_hc *hc, + cdi_usb_hc_transaction_t ta); + +#endif diff --git a/ehci/main.c b/ehci/main.c new file mode 100644 index 0000000..5623819 --- /dev/null +++ b/ehci/main.c @@ -0,0 +1,69 @@ +/****************************************************************************** + * Copyright (c) 2015 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 "ehci.h" + + +#define DRIVER_NAME "ehci" + + +static struct cdi_usb_hcd ehcd; + +static int ehcd_init(void) +{ + cdi_driver_init(&ehcd.drv); + return 0; +} + +static int ehcd_destroy(void) +{ + cdi_driver_destroy(&ehcd.drv); + return 0; +} + +static struct cdi_usb_hcd ehcd = { + .drv = { + .name = DRIVER_NAME, + .type = CDI_USB_HCD, + .bus = CDI_PCI, + .init = ehcd_init, + .destroy = ehcd_destroy, + .init_device = ehci_init_device, + }, + + .rh_drv = { + .port_disable = ehci_rh_port_down, + .port_reset_enable = ehci_rh_port_up, + .port_status = ehci_rh_port_status, + }, + + .create_transaction = ehci_create_transaction, + .enqueue = ehci_enqueue, + .start_transaction = ehci_start_transaction, + .wait_transaction = ehci_wait_transaction, + .destroy_transaction = ehci_destroy_transaction, +}; + +CDI_DRIVER(DRIVER_NAME, ehcd) -- 2.6.3 From max at tyndur.org Sat Dec 12 21:10:39 2015 From: max at tyndur.org (Max Reitz) Date: Sat, 12 Dec 2015 21:10:39 +0100 Subject: [cdi-devel] [PATCH v4 3/4] usb: Add USB 2.0 bus driver In-Reply-To: <1449951040-16452-1-git-send-email-max@tyndur.org> References: <1449951040-16452-1-git-send-email-max@tyndur.org> Message-ID: <1449951040-16452-4-git-send-email-max@tyndur.org> + This adds a USB 2.0 bus driver. It is missing support for USB 3.x (obviously), and also interrupt and isochronous transfers (and other things, too). Also, it is probably bad (e.g. there is only a single counter for device IDs instead of keeping track of which IDs are used and which are not). Signed-off-by: Max Reitz --- usb/main.c | 61 ++++ usb/usb-hubs.h | 78 +++++ usb/usb.c | 893 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ usb/usb.h | 86 ++++++ 4 files changed, 1118 insertions(+) create mode 100644 usb/main.c create mode 100644 usb/usb-hubs.h create mode 100644 usb/usb.c create mode 100644 usb/usb.h diff --git a/usb/main.c b/usb/main.c new file mode 100644 index 0000000..3add372 --- /dev/null +++ b/usb/main.c @@ -0,0 +1,61 @@ +/****************************************************************************** + * Copyright (c) 2015 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 "usb.h" + + +#define DRIVER_NAME "usb" + + +static struct cdi_usb_driver usbd; + +static int usbd_init(void) +{ + cdi_driver_init(&usbd.drv); + return 0; +} + +static int usbd_destroy(void) +{ + cdi_driver_destroy(&usbd.drv); + return 0; +} + +static struct cdi_usb_driver usbd = { + .drv = { + .name = DRIVER_NAME, + .type = CDI_USB, + .bus = CDI_USB_HCD, + .init = usbd_init, + .destroy = usbd_destroy, + .init_device = usb_init_hc, + }, + + .get_endpoint_descriptor = usb_get_endpoint_descriptor, + .control_transfer = usb_control_transfer, + .bulk_transfer = usb_bulk_transfer, +}; + +CDI_DRIVER(DRIVER_NAME, usbd) diff --git a/usb/usb-hubs.h b/usb/usb-hubs.h new file mode 100644 index 0000000..da8ac3e --- /dev/null +++ b/usb/usb-hubs.h @@ -0,0 +1,78 @@ +/****************************************************************************** + * Copyright (c) 2015 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_HUBS_H +#define USB_HUBS_H + +#include + +#include "usb.h" + + +struct usb_hub_descriptor { + uint8_t b_length; + uint8_t b_descriptor_type; + uint8_t b_nbr_ports; + uint16_t w_hub_characteristics; + uint8_t b_pwr_on_2_pwr_good; + uint8_t b_hub_contr_current; + uint8_t device_removable[]; +} __attribute__((packed)); + + +enum { + USB_DESC_HUB = 0x29, +}; + +// hub device features +enum { + C_HUB_LOCAL_POWER = 0, + C_HUB_OVER_CURRENT, +}; + +// hub port features +enum { + PORT_CONNECTION = 0, + PORT_ENABLE, + PORT_SUSPEND, + PORT_OVER_CURRENT, + PORT_RESET, + + PORT_POWER = 8, + PORT_LOW_SPEED, + PORT_HIGH_SPEED, + + C_PORT_CONNECTION = 16, + C_PORT_ENABLE, + C_PORT_SUSPEND, + C_PORT_OVER_CURRENT, + C_PORT_RESET, + PORT_TEST, + PORT_INDICATOR, +}; + +typedef struct usb_hub_device { + struct cdi_usb_hub cdi; + usb_hub_t *hub; +} usb_hub_device_t; + +#endif diff --git a/usb/usb.c b/usb/usb.c new file mode 100644 index 0000000..62ef989 --- /dev/null +++ b/usb/usb.c @@ -0,0 +1,893 @@ +/****************************************************************************** + * Copyright (c) 2015 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 + +#include "usb.h" +#include "usb-hubs.h" + + +// #define DEBUG + +#ifdef DEBUG +#define DPRINTF(...) printf(__VA_ARGS__) +#else +#define DPRINTF(...) +#endif + + +static int current_usb_addr = 1; + + +static cdi_usb_transmission_result_t + do_control_transfer(struct cdi_usb_hc *hc, int dev, cdi_usb_speed_t speed, + int tt_addr, int tt_port, const usb_endpoint_t *ep, + const struct cdi_usb_setup_packet *setup, void *data) +{ + struct cdi_usb_hcd *hcd = CDI_UPCAST(hc->dev.driver, struct cdi_usb_hcd, + drv); + cdi_usb_hc_transaction_t ta; + cdi_usb_transmission_result_t r1, r2, r3; + + ta = hcd->create_transaction(hc, &(struct cdi_usb_hc_ep_info){ + .dev = dev, + .ep = ep->ep, + .ep_type = ep->type, + .speed = speed, + .mps = ep->mps, + .tt_addr = tt_addr, + .tt_port = tt_port + }); + + hcd->enqueue(hc, &(struct cdi_usb_hc_transmission){ + .ta = ta, + .token = CDI_USB_SETUP, + .buffer = (void *)setup, + .size = sizeof(*setup), + .toggle = 0, + .result = &r1 + }); + + if (data) { + hcd->enqueue(hc, &(struct cdi_usb_hc_transmission){ + .ta = ta, + .token = setup->bm_request_type & CDI_USB_CREQ_IN + ? CDI_USB_IN : CDI_USB_OUT, + .buffer = data, + .size = setup->w_length, + .toggle = 1, + .result = &r2 + }); + } else { + r2 = CDI_USB_OK; + } + + hcd->enqueue(hc, &(struct cdi_usb_hc_transmission){ + .ta = ta, + .token = setup->bm_request_type & CDI_USB_CREQ_IN ? CDI_USB_OUT + : CDI_USB_IN, + .toggle = 1, + .result = &r3 + }); + + hcd->start_transaction(hc, ta); + hcd->wait_transaction(hc, ta); + hcd->destroy_transaction(hc, ta); + + return r1 ? r1 : r2 ? r2 : r3; +} + +static cdi_usb_transmission_result_t + control_transfer(const usb_device_t *dev, const usb_endpoint_t *ep, + const struct cdi_usb_setup_packet *setup, void *data) +{ + return do_control_transfer(dev->hc, dev->id, dev->speed, dev->tt_addr, + dev->tt_port, ep, setup, data); +} + + +static int get_mps0(usb_hub_t *hub, int hub_port, cdi_usb_speed_t speed) +{ + cdi_usb_transmission_result_t res; + struct cdi_usb_device_descriptor device_descriptor; + int tt_addr = 0, tt_port = 0; + + if (speed < CDI_USB_HIGH_SPEED && hub->ldev) { + if (hub->ldev->dev->speed < CDI_USB_HIGH_SPEED) { + tt_addr = hub->ldev->dev->tt_addr; + tt_port = hub->ldev->dev->tt_port; + } else { + tt_addr = hub->ldev->dev->id; + tt_port = hub_port; + } + } + + res = do_control_transfer(hub->hc, 0, speed, tt_addr, tt_port, + &(usb_endpoint_t){ + .type = CDI_USB_CONTROL, + .mps = 8 + }, &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_DEVICE | CDI_USB_CREQ_IN, + .b_request = CDI_USB_CREQ_GET_DESCRIPTOR, + .w_value = (CDI_USB_DESC_DEVICE << 8) | 0, + .w_length = 8 + }, &device_descriptor); + + if (res != CDI_USB_OK) { + return -EIO; + } + + return device_descriptor.b_max_packet_size_0; +} + + +static usb_device_t *enumerate(usb_hub_t *hub, int hub_port, + cdi_usb_speed_t speed, int mps0) +{ + cdi_usb_transmission_result_t res; + usb_device_t *dev = calloc(1, sizeof(*dev)); + + int new_id = current_usb_addr++; + if (new_id > 127) { + // TODO: Per-bus ID, and detection of device disconnects so we can reuse + // old (stale) addresses + printf("[usb] USB address space exhausted, cannot enumerate device\n"); + free(dev); + return NULL; + } + + dev->hc = hub->hc; + dev->speed = speed; + + if (speed < CDI_USB_HIGH_SPEED && hub->ldev) { + if (hub->ldev->dev->speed < CDI_USB_HIGH_SPEED) { + dev->tt_addr = hub->ldev->dev->tt_addr; + dev->tt_port = hub->ldev->dev->tt_port; + } else { + dev->tt_addr = hub->ldev->dev->id; + dev->tt_port = hub_port; + } + } + + dev->eps[0][0].type = CDI_USB_CONTROL; + dev->eps[0][0].mps = mps0; + + res = control_transfer(dev, &dev->eps[0][0], &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_DEVICE | CDI_USB_CREQ_OUT, + .b_request = CDI_USB_CREQ_SET_ADDRESS, + .w_value = new_id + }, NULL); + if (res != CDI_USB_OK) { + free(dev); + return NULL; + } + + dev->id = new_id; + + res = control_transfer(dev, &dev->eps[0][0], &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_DEVICE | CDI_USB_CREQ_IN, + .b_request = CDI_USB_CREQ_GET_DESCRIPTOR, + .w_value = (CDI_USB_DESC_DEVICE << 8) | 0, + .w_length = sizeof(dev->dev_desc) + }, &dev->dev_desc); + if (res != CDI_USB_OK) { + free(dev); + return NULL; + } + + return dev; +} + + +#ifdef DEBUG +static void get_string_descriptor(usb_device_t *dev, int index, + struct cdi_usb_string_descriptor *dst) +{ + cdi_usb_transmission_result_t res; + + res = control_transfer(dev, &dev->eps[0][0], &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_DEVICE | CDI_USB_CREQ_IN, + .b_request = CDI_USB_CREQ_GET_DESCRIPTOR, + .w_value = (CDI_USB_DESC_STRING << 8) | index, + .w_length = 1 + }, dst); + if (res != CDI_USB_OK || !dst->b_length) { + dst->b_length = 0; + return; + } + + res = control_transfer(dev, &dev->eps[0][0], &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_DEVICE | CDI_USB_CREQ_IN, + .b_request = CDI_USB_CREQ_GET_DESCRIPTOR, + .w_value = (CDI_USB_DESC_STRING << 8) | index, + .w_length = dst->b_length + }, dst); + if (res != CDI_USB_OK) { + dst->b_length = 0; + return; + } +} +#endif + + +static int get_configurations(usb_device_t *dev) +{ + cdi_usb_transmission_result_t res; + struct cdi_usb_configuration_descriptor config; + + dev->configs = calloc(dev->dev_desc.b_num_configurations, + sizeof(dev->configs[0])); + + for (int i = 0; i < (int)dev->dev_desc.b_num_configurations; i++) { + res = control_transfer(dev, &dev->eps[0][0], + &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_DEVICE | CDI_USB_CREQ_IN, + .b_request = CDI_USB_CREQ_GET_DESCRIPTOR, + .w_value = (CDI_USB_DESC_CONFIGURATION << 8) | i, + .w_length = sizeof(config) + }, &config); + if (res != CDI_USB_OK) { + goto fail; + } + + dev->configs[i] = malloc(config.w_total_length); + res = control_transfer(dev, &dev->eps[0][0], + &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_DEVICE | CDI_USB_CREQ_IN, + .b_request = CDI_USB_CREQ_GET_DESCRIPTOR, + .w_value = (CDI_USB_DESC_CONFIGURATION << 8) | i, + .w_length = config.w_total_length + }, dev->configs[i]); + if (res != CDI_USB_OK) { + goto fail; + } + } + + return 0; + +fail: + for (int i = 0; i < (int)dev->dev_desc.b_num_configurations; i++) { + free(dev->configs[i]); + } + free(dev->configs); + return -EIO; +} + + +static bool compare_configurations(usb_device_t *dev, int i, int j) +{ + // TODO: Prefer self-powered + if (dev->configs[i]->b_max_power != dev->configs[j]->b_max_power) { + return dev->configs[i]->b_max_power > dev->configs[j]->b_max_power; + } + + if (dev->configs[i]->b_num_interfaces != dev->configs[j]->b_num_interfaces) + { + return dev->configs[i]->b_num_interfaces + > dev->configs[j]->b_num_interfaces; + } + + return false; +} + + +static int choose_configuration(usb_device_t *dev) +{ + cdi_usb_transmission_result_t res; + int best_config = 0; + + for (int i = 1; i < (int)dev->dev_desc.b_num_configurations; i++) { + if (compare_configurations(dev, i, best_config)) { + best_config = i; + } + } + + dev->config = dev->configs[best_config]; + + res = control_transfer(dev, &dev->eps[0][0], &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_DEVICE | CDI_USB_CREQ_OUT, + .b_request = CDI_USB_CREQ_SET_CONFIGURATION, + .w_value = dev->config->b_configuration_value, + }, NULL); + if (res != CDI_USB_OK) { + dev->config = NULL; + return -EIO; + } + + return 0; +} + + +#ifdef DEBUG +static void debug_device(usb_device_t *dev) +{ + printf("[usb] new %s device %04x:%04x (%x.%x.%x) ", + dev->speed == CDI_USB_LOW_SPEED ? "low speed" : + dev->speed == CDI_USB_FULL_SPEED ? "full speed" : + dev->speed == CDI_USB_HIGH_SPEED ? "high speed" : + dev->speed == CDI_USB_SUPERSPEED ? "superspeed" : + "futurespeed", + dev->dev_desc.id_vendor, dev->dev_desc.id_product, + dev->dev_desc.b_device_class, + dev->dev_desc.b_device_sub_class, + dev->dev_desc.b_device_protocol); + + struct cdi_usb_string_descriptor str; + + if (dev->dev_desc.i_manufacturer) { + get_string_descriptor(dev, dev->dev_desc.i_manufacturer, &str); + for (int i = 0; i < (str.b_length - 2) / 2; i++) { + putchar(str.b_string[i] > 0x7f ? '?' : str.b_string[i]); + } + putchar(' '); + } + + if (dev->dev_desc.i_product) { + get_string_descriptor(dev, dev->dev_desc.i_product, &str); + for (int i = 0; i < (str.b_length - 2) / 2; i++) { + putchar(str.b_string[i] > 0x7f ? '?' : str.b_string[i]); + } + putchar(' '); + } + + putchar('\n'); +} + +static void debug_configuration(usb_device_t *dev) +{ + printf("[usb] chose configuration %i ", dev->config->b_configuration_value); + + struct cdi_usb_string_descriptor str; + + if (dev->config->i_configuration) { + get_string_descriptor(dev, dev->config->i_configuration, &str); + putchar('('); + for (int i = 0; i < (str.b_length - 2) / 2; i++) { + putchar(str.b_string[i] > 0x7f ? '?' : str.b_string[i]); + } + putchar(')'); + putchar(' '); + } + + printf("with %i interface(s):\n", dev->config->b_num_interfaces); + + struct cdi_usb_interface_descriptor *ifc = (void *)(dev->config + 1); + for (int i = 0; i < (int)dev->config->b_num_interfaces; i++) { + printf("[usb] "); + if (ifc->i_interface) { + get_string_descriptor(dev, ifc->i_interface, &str); + for (int j = 0; j < (int)dev->config->b_num_interfaces; j++) { + putchar(str.b_string[j] > 0x7f ? '?' : str.b_string[j]); + } + putchar(' '); + } + printf("%x.%x.%x\n", ifc->b_interface_class, + ifc->b_interface_sub_class, ifc->b_interface_protocol); + + ifc = (void *)((struct cdi_usb_endpoint_descriptor *)(ifc + 1) + + ifc->b_num_endpoints); + } +} +#endif + + +static void new_hub_device(usb_logical_device_t *ldev); + +static void new_hub(usb_hub_t *hub) +{ + for (int i = 0; i < hub->cdi->ports; i++) { + hub->drv->port_disable(hub->cdi, i); + } + + DPRINTF("[usb] new hub with %i ports detected\n", hub->cdi->ports); + + for (int i = 0; i < hub->cdi->ports; i++) { + hub->drv->port_reset_enable(hub->cdi, i); + cdi_sleep_ms(5); + + cdi_usb_port_status_t status = hub->drv->port_status(hub->cdi, i); + if (!(status & CDI_USB_PORT_CONNECTED)) { + hub->drv->port_disable(hub->cdi, i); + continue; + } + + int mps0 = get_mps0(hub, i, status & CDI_USB_PORT_SPEED_MASK); + if (mps0 < 0) { + printf("[usb] failed to inquire MPS0\n"); + hub->drv->port_disable(hub->cdi, i); + continue; + } + + // Reset the device a second time. Maybe the device is broken and still + // wants to send more data even though we only requested the first eight + // bytes of the device descriptor (which we cannot receive without + // knowing the MPS0). A reset will solve the problem and will not do any + // harm otherwise. + hub->drv->port_reset_enable(hub->cdi, i); + cdi_sleep_ms(5); + + status = hub->drv->port_status(hub->cdi, i); + if (!(status & CDI_USB_PORT_CONNECTED)) { + hub->drv->port_disable(hub->cdi, i); + continue; + } + + usb_device_t *dev = enumerate(hub, i, status & CDI_USB_PORT_SPEED_MASK, + mps0); + if (!dev) { + printf("[usb] failed to enumerate device\n"); + hub->drv->port_disable(hub->cdi, i); + continue; + } + +#ifdef DEBUG + debug_device(dev); +#endif + + usb_logical_device_t *ldev = NULL; + int ldev_ep_idx = 0; + bool interface_level; + + interface_level = dev->dev_desc.b_device_class == CDI_USB_DEVCLS_NONE; + if (!interface_level) { + ldev = calloc(1, sizeof(*ldev)); + ldev->cdi.bus_data.bus_type = CDI_USB; + ldev->cdi.interface = -1; + ldev->cdi.endpoint_count = 1; // EP0 + ldev->cdi.vendor_id = dev->dev_desc.id_vendor; + ldev->cdi.product_id = dev->dev_desc.id_product; + ldev->cdi.class_id = dev->dev_desc.b_device_class; + ldev->cdi.subclass_id = dev->dev_desc.b_device_sub_class; + ldev->cdi.protocol_id = dev->dev_desc.b_device_protocol; + + ldev->dev = dev; + + ldev->endpoints = malloc(1 * sizeof(ldev->endpoints[0])); + ldev->endpoints[0] = 0; // EP0 + ldev_ep_idx = 1; + } + + if (get_configurations(dev) < 0) { + printf("[usb] failed to get device configurations\n"); + free(ldev->endpoints); + free(ldev); + free(dev); + hub->drv->port_disable(hub->cdi, i); + continue; + } + if (choose_configuration(dev) < 0) { + printf("[usb] failed to select device configuration\n"); + free(ldev->endpoints); + free(ldev); + for (int j = 0; j < (int)dev->dev_desc.b_num_configurations; j++) { + free(dev->configs[j]); + } + free(dev->config); + free(dev); + hub->drv->port_disable(hub->cdi, i); + continue; + } + +#ifdef DEBUG + debug_configuration(dev); +#endif + + struct cdi_usb_interface_descriptor *ifc = (void *)(dev->config + 1); + for (int j = 0; j < (int)dev->config->b_num_interfaces; j++) { + if (interface_level) { + ldev = calloc(1, sizeof(*ldev)); + ldev->cdi.bus_data.bus_type = CDI_USB; + ldev->cdi.interface = j; + // Include EP0 + ldev->cdi.endpoint_count = ifc->b_num_endpoints + 1; + ldev->cdi.vendor_id = dev->dev_desc.id_vendor; + ldev->cdi.product_id = dev->dev_desc.id_product; + ldev->cdi.class_id = ifc->b_interface_class; + ldev->cdi.subclass_id = ifc->b_interface_sub_class; + ldev->cdi.protocol_id = ifc->b_interface_protocol; + + ldev->dev = dev; + + ldev->endpoints = malloc(ldev->cdi.endpoint_count + * sizeof(ldev->endpoints[0])); + ldev->endpoints[0] = 0; // EP0 + ldev_ep_idx = 1; + } else { + ldev->cdi.endpoint_count += ifc->b_num_endpoints; + ldev->endpoints = realloc(ldev->endpoints, + ldev->cdi.endpoint_count + * sizeof(ldev->endpoints[0])); + } + + struct cdi_usb_endpoint_descriptor *ep = (void *)(ifc + 1); + for (int k = 0; k < (int)ifc->b_num_endpoints; k++, ep++) { + bool in = ep->b_endpoint_address & CDI_USB_EPDSC_EPADR_DIR; + int id = CDI_USB_EPDSC_EPADR_ID(ep->b_endpoint_address); + + dev->eps[in][id].ep = id; + dev->eps[in][id].mps + = CDI_USB_EPDSC_MPS_MPS(ep->w_max_packet_size); + dev->eps[in][id].desc = ep; + + switch (ep->bm_attributes & CDI_USB_EPDSC_ATTR_XFER_TYPE_MASK) { + case CDI_USB_EPDSC_ATTR_CONTROL: + dev->eps[in][id].type = CDI_USB_CONTROL; + break; + case CDI_USB_EPDSC_ATTR_ISOCHRONOUS: + dev->eps[in][id].type = CDI_USB_ISOCHRONOUS; + break; + case CDI_USB_EPDSC_ATTR_BULK: + dev->eps[in][id].type = CDI_USB_BULK; + break; + case CDI_USB_EPDSC_ATTR_INTERRUPT: + dev->eps[in][id].type = CDI_USB_INTERRUPT; + break; + } + + ldev->endpoints[ldev_ep_idx++] = ((int)in << 4) | id; + } + + if (interface_level) { + if (ldev->cdi.class_id == CDI_USB_DEVCLS_HUB) { + new_hub_device(ldev); + } else { + cdi_provide_device(&ldev->cdi.bus_data); + } + } + + ifc = (void *)ep; + } + + if (!interface_level) { + if (ldev->cdi.class_id == CDI_USB_DEVCLS_HUB) { + new_hub_device(ldev); + } else { + cdi_provide_device(&ldev->cdi.bus_data); + } + } + } +} + +struct cdi_device *usb_init_hc(struct cdi_bus_data *bus_data) +{ + struct cdi_usb_hc_bus *hc_bus = CDI_UPCAST(bus_data, struct cdi_usb_hc_bus, + bus_data); + struct cdi_usb_hc *hc = hc_bus->hc; + struct cdi_usb_hcd *hcd = CDI_UPCAST(hc->dev.driver, struct cdi_usb_hcd, + drv); + + usb_hub_t *hub = calloc(1, sizeof(*hub)); + hub->cdi = &hc->rh; + hub->hc = hc; + hub->drv = &hcd->rh_drv; + + new_hub(hub); + + return NULL; +} + + +void usb_get_endpoint_descriptor(struct cdi_usb_device *dev, int ep, + struct cdi_usb_endpoint_descriptor *desc) +{ + usb_logical_device_t *ldev = CDI_UPCAST(dev, usb_logical_device_t, cdi); + + if (ep < 0 || ep >= dev->endpoint_count) { + return; + } + + int ep_idx = ldev->endpoints[ep]; + usb_endpoint_t *ep_info = &ldev->dev->eps[ep_idx >> 4][ep_idx & 0xf]; + + if (ep_idx) { + assert(ep_info->desc); + memcpy(desc, ep_info->desc, sizeof(*desc)); + } else { + *desc = (struct cdi_usb_endpoint_descriptor){ + .b_length = sizeof(*desc), + .b_descriptor_type = CDI_USB_DESC_ENDPOINT, + .b_endpoint_address = 0, + .bm_attributes = 0x00, + .w_max_packet_size = ep_info->mps, + .b_interval = 0 + }; + } +} + + +cdi_usb_transmission_result_t + usb_control_transfer(struct cdi_usb_device *dev, int ep, + const struct cdi_usb_setup_packet *setup, void *data) +{ + usb_logical_device_t *ldev = CDI_UPCAST(dev, usb_logical_device_t, cdi); + + if (ep < 0 || ep >= dev->endpoint_count) { + return CDI_USB_DRIVER_ERROR; + } + + int ep_idx = ldev->endpoints[ep]; + usb_endpoint_t *ep_info = &ldev->dev->eps[ep_idx >> 4][ep_idx & 0xf]; + + if (ep_info->type != CDI_USB_CONTROL) { + return CDI_USB_DRIVER_ERROR; + } + + return control_transfer(ldev->dev, ep_info, setup, data); +} + + +cdi_usb_transmission_result_t usb_bulk_transfer(struct cdi_usb_device *dev, + int ep, void *data, size_t size) +{ + usb_logical_device_t *ldev = CDI_UPCAST(dev, usb_logical_device_t, cdi); + + if (ep < 0 || ep >= dev->endpoint_count) { + return CDI_USB_DRIVER_ERROR; + } + + int ep_idx = ldev->endpoints[ep]; + usb_endpoint_t *ep_info = &ldev->dev->eps[ep_idx >> 4][ep_idx & 0xf]; + + if (ep_info->type != CDI_USB_BULK) { + return CDI_USB_DRIVER_ERROR; + } + + struct cdi_usb_hcd *hcd = CDI_UPCAST(ldev->dev->hc->dev.driver, + struct cdi_usb_hcd, drv); + cdi_usb_hc_transaction_t ta; + cdi_usb_transmission_result_t res; + + ta = hcd->create_transaction(ldev->dev->hc, &(struct cdi_usb_hc_ep_info){ + .dev = ldev->dev->id, + .ep = ep_info->ep, + .ep_type = ep_info->type, + .speed = ldev->dev->speed, + .mps = ep_info->mps, + .tt_addr = ldev->dev->tt_addr, + .tt_port = ldev->dev->tt_port + }); + + hcd->enqueue(ldev->dev->hc, &(struct cdi_usb_hc_transmission){ + .ta = ta, + .token = ep_idx >> 4 ? CDI_USB_IN : CDI_USB_OUT, + .buffer = data, + .size = size, + .toggle = ep_info->toggle, + .result = &res + }); + ep_info->toggle ^= (((size + ep_info->mps - 1) / ep_info->mps) & 1); + + hcd->start_transaction(ldev->dev->hc, ta); + hcd->wait_transaction(ldev->dev->hc, ta); + hcd->destroy_transaction(ldev->dev->hc, ta); + + return res; +} + + +static struct cdi_usb_hub_driver hub_drv; + + +static cdi_usb_transmission_result_t + hub_set_hub_feature(usb_hub_device_t *hub, uint16_t feature) +{ + return usb_control_transfer(&hub->hub->ldev->cdi, 0, + &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_DEVICE + | CDI_USB_CREQ_CLASS + | CDI_USB_CREQ_OUT, + .b_request = CDI_USB_CREQ_SET_FEATURE, + .w_value = feature + }, NULL); +} + + +static cdi_usb_transmission_result_t + hub_clear_port_feature(usb_hub_device_t *hub, + uint16_t feature, uint16_t port) +{ + return usb_control_transfer(&hub->hub->ldev->cdi, 0, + &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_OTHER + | CDI_USB_CREQ_CLASS + | CDI_USB_CREQ_OUT, + .b_request = CDI_USB_CREQ_CLEAR_FEATURE, + .w_value = feature, + .w_index = port + 1 + }, NULL); +} + + +static uint32_t hub_get_port_status(usb_hub_device_t *hub, uint16_t port) +{ + cdi_usb_transmission_result_t res; + uint32_t portsc; + + res = usb_control_transfer(&hub->hub->ldev->cdi, 0, + &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_OTHER + | CDI_USB_CREQ_CLASS + | CDI_USB_CREQ_IN, + .b_request = CDI_USB_CREQ_GET_STATUS, + .w_index = port + 1, + .w_length = sizeof(portsc) + }, &portsc); + if (res != CDI_USB_OK) { + return 0; + } + + return portsc; +} + + +static cdi_usb_transmission_result_t + hub_set_port_feature(usb_hub_device_t *hub, + uint16_t feature, uint16_t port) +{ + return usb_control_transfer(&hub->hub->ldev->cdi, 0, + &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_OTHER + | CDI_USB_CREQ_CLASS + | CDI_USB_CREQ_OUT, + .b_request = CDI_USB_CREQ_SET_FEATURE, + .w_value = feature, + .w_index = port + 1 + }, NULL); +} + + +static void new_hub_device(usb_logical_device_t *ldev) +{ + cdi_usb_transmission_result_t res; + usb_hub_device_t *hub; + struct usb_hub_descriptor *hub_desc = NULL; + + assert(ldev->cdi.interface < 0); + + hub = calloc(1, sizeof(*hub)); + + hub->hub = calloc(1, sizeof(*hub->hub)); + hub->hub->cdi = &hub->cdi; + hub->hub->drv = &hub_drv; + hub->hub->hc = ldev->dev->hc; + hub->hub->ldev = ldev; + + uint8_t hub_desc_length; + res = usb_control_transfer(&ldev->cdi, 0, &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_DEVICE | CDI_USB_CREQ_CLASS + | CDI_USB_CREQ_IN, + .b_request = CDI_USB_CREQ_GET_DESCRIPTOR, + .w_value = (USB_DESC_HUB << 8) | 0, + .w_length = 1 + }, &hub_desc_length); + if (res != CDI_USB_OK || + hub_desc_length < sizeof(struct usb_hub_descriptor)) + { + goto fail; + } + + hub_desc = malloc(hub_desc_length); + res = usb_control_transfer(&ldev->cdi, 0, &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_DEVICE | CDI_USB_CREQ_CLASS + | CDI_USB_CREQ_IN, + .b_request = CDI_USB_CREQ_GET_DESCRIPTOR, + .w_value = (USB_DESC_HUB << 8) | 0, + .w_length = hub_desc_length + }, hub_desc); + if (res != CDI_USB_OK) { + goto fail; + } + + int ports = hub_desc->b_nbr_ports; + hub->cdi.ports = ports; + + // Enable port power + if (!(hub_desc->w_hub_characteristics & (1 << 1))) { + // Hub supports power switching, enable global power + if (hub_set_hub_feature(hub, C_HUB_LOCAL_POWER) != CDI_USB_OK) { + goto fail; + } + } + + if ((hub_desc->w_hub_characteristics & 0x3) == 1) { + // Hub supports per-port power switching, enable power for each port + for (int port = 0; port < ports; port++) { + if (hub_set_port_feature(hub, PORT_POWER, port) != CDI_USB_OK) { + goto fail; + } + } + } + + cdi_sleep_ms(hub_desc->b_pwr_on_2_pwr_good * 2); + + free(hub_desc); + + new_hub(hub->hub); + + return; + +fail: + free(hub_desc); + free(hub->hub); + free(hub); + return; +} + + +static void hub_port_down(struct cdi_usb_hub *cdi_hub, int index) +{ + usb_hub_device_t *hub = CDI_UPCAST(cdi_hub, usb_hub_device_t, cdi); + hub_clear_port_feature(hub, PORT_ENABLE, index); +} + + +static void hub_port_up(struct cdi_usb_hub *cdi_hub, int index) +{ + usb_hub_device_t *hub = CDI_UPCAST(cdi_hub, usb_hub_device_t, cdi); + + hub_clear_port_feature(hub, C_PORT_RESET, index); + hub_set_port_feature(hub, PORT_RESET, index); + + CDI_CONDITION_WAIT(hub_get_port_status(hub, index) & (1 << C_PORT_RESET), + 100); +} + + +static cdi_usb_port_status_t hub_port_status(struct cdi_usb_hub *cdi_hub, + int index) +{ + usb_hub_device_t *hub = CDI_UPCAST(cdi_hub, usb_hub_device_t, cdi); + + uint32_t portsc = hub_get_port_status(hub, index); + + cdi_usb_port_status_t status = 0; + + if (portsc & ((1 << PORT_ENABLE) | (1 << PORT_CONNECTION))) { + status |= CDI_USB_PORT_CONNECTED; + if (portsc & (1 << PORT_LOW_SPEED)) { + status |= CDI_USB_LOW_SPEED; + } else if (portsc & (1 << PORT_HIGH_SPEED)) { + status |= CDI_USB_HIGH_SPEED; + } else { + status |= CDI_USB_FULL_SPEED; + } + } + + return status; +} + + +static struct cdi_usb_hub_driver hub_drv = { + .port_disable = hub_port_down, + .port_reset_enable = hub_port_up, + .port_status = hub_port_status, +}; diff --git a/usb/usb.h b/usb/usb.h new file mode 100644 index 0000000..27dc061 --- /dev/null +++ b/usb/usb.h @@ -0,0 +1,86 @@ +/****************************************************************************** + * Copyright (c) 2015 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_H +#define USB_H + +#include +#include + +#include +#include +#include + + +typedef struct usb_logical_device usb_logical_device_t; + +typedef struct usb_hub { + struct cdi_usb_hub *cdi; + + const struct cdi_usb_hub_driver *drv; + struct cdi_usb_hc *hc; + usb_logical_device_t *ldev; +} usb_hub_t; + +typedef struct usb_endpoint { + int ep; + cdi_usb_endpoint_type_t type; + int mps; + int toggle; + struct cdi_usb_endpoint_descriptor *desc; +} usb_endpoint_t; + +typedef struct usb_device { + struct cdi_usb_hc *hc; + int id; + cdi_usb_speed_t speed; + + int tt_addr, tt_port; + + // First index: OUT (0) / IN (1) + usb_endpoint_t eps[2][16]; + + struct cdi_usb_device_descriptor dev_desc; + struct cdi_usb_configuration_descriptor **configs, *config; +} usb_device_t; + +struct usb_logical_device { + struct cdi_usb_device cdi; + usb_device_t *dev; + int *endpoints; +}; + + +struct cdi_device *usb_init_hc(struct cdi_bus_data *bus_data); + +void usb_get_endpoint_descriptor(struct cdi_usb_device *dev, int ep, + struct cdi_usb_endpoint_descriptor *desc); + +cdi_usb_transmission_result_t + usb_control_transfer(struct cdi_usb_device *dev, int ep, + const struct cdi_usb_setup_packet *setup, void *data); + +cdi_usb_transmission_result_t usb_bulk_transfer(struct cdi_usb_device *dev, + int ep, void *data, + size_t size); + +#endif -- 2.6.3 From max at tyndur.org Sat Dec 12 21:10:40 2015 From: max at tyndur.org (Max Reitz) Date: Sat, 12 Dec 2015 21:10:40 +0100 Subject: [cdi-devel] [PATCH v4 4/4] usb-storage: Add USB mass storage driver In-Reply-To: <1449951040-16452-1-git-send-email-max@tyndur.org> References: <1449951040-16452-1-git-send-email-max@tyndur.org> Message-ID: <1449951040-16452-5-git-send-email-max@tyndur.org> + This adds a USB mass storage device driver. It is missing proper error handling (e.g. for STALLed endpoints) and support for any USB MSD class other than bulk-only (e.g. control-bulk-interrupt for USB floppy drives). Signed-off-by: Max Reitz --- usb-storage/main.c | 76 ++++++++++++++++ usb-storage/usb-storage.c | 217 ++++++++++++++++++++++++++++++++++++++++++++++ usb-storage/usb-storage.h | 60 +++++++++++++ 3 files changed, 353 insertions(+) create mode 100644 usb-storage/main.c create mode 100644 usb-storage/usb-storage.c create mode 100644 usb-storage/usb-storage.h diff --git a/usb-storage/main.c b/usb-storage/main.c new file mode 100644 index 0000000..aa896ca --- /dev/null +++ b/usb-storage/main.c @@ -0,0 +1,76 @@ +/****************************************************************************** + * Copyright (c) 2015 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 "usb-storage.h" + + +#define DRIVER_NAME "usb-storage" + + +static struct cdi_scsi_driver drv; +static struct cdi_usb_bus_device_pattern bus_pattern; + +static int drv_init(void) +{ + cdi_scsi_driver_init(&drv); + cdi_handle_bus_device(&drv.drv, &bus_pattern.pattern); + return 0; +} + +static int drv_destroy(void) +{ + cdi_driver_destroy(&drv.drv); + return 0; +} + + +static struct cdi_scsi_driver drv = { + .drv = { + .name = DRIVER_NAME, + .type = CDI_SCSI, + .bus = CDI_USB, + .init = drv_init, + .destroy = drv_destroy, + .init_device = init_usb_device, + }, + + .request = usb_storage_request, +}; + +static struct cdi_usb_bus_device_pattern bus_pattern = { + .pattern = { + .bus_type = CDI_USB, + }, + + .vendor_id = -1, + .product_id = -1, + + .class_id = CDI_USB_IFCCLS_STORAGE, + .subclass_id = -1, + .protocol_id = -1, +}; + +CDI_DRIVER(DRIVER_NAME, drv) diff --git a/usb-storage/usb-storage.c b/usb-storage/usb-storage.c new file mode 100644 index 0000000..d77a110 --- /dev/null +++ b/usb-storage/usb-storage.c @@ -0,0 +1,217 @@ +/****************************************************************************** + * Copyright (c) 2015 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 + +#include "usb-storage.h" + + +#define CBW_IN 0x80 +#define CBW_OUT 0x00 + +#define CBW_SIGNATURE 0x43425355 // 'USBC' => USB command +#define CSW_SIGNATURE 0x53425355 // 'USBS' => USB status + +struct msd_bo_cbw { + uint32_t signature; + uint32_t tag; + uint32_t data_length; + uint8_t flags; + uint8_t lun; + uint8_t cb_length; + uint8_t cb[16]; +} __attribute__((packed)); + +struct msd_bo_csw { + uint32_t signature; + uint32_t tag; + uint32_t data_residue; + uint8_t status; +} __attribute__((packed)); + + +typedef enum usb_mass_storage_type { + USBMS_BULK_ONLY, +} usb_mass_storage_type_t; + + +typedef struct usb_mass_storage_device { + struct cdi_scsi_device dev; + struct cdi_usb_device usb; + + usb_mass_storage_type_t type; + int luns; + + // FIXME: put into own class + int bulk_in, bulk_out; +} usb_mass_storage_device_t; + + +static int bulk_only_reset(usb_mass_storage_device_t *dev) +{ + cdi_usb_transmission_result_t res; + + res = cdi_usb_control_transfer(&dev->usb, 0, &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_CLASS | CDI_USB_CREQ_INTERFACE + | CDI_USB_CREQ_OUT, + .b_request = USBMS_REQ_BOMSR, + .w_index = dev->usb.interface + }, NULL); + if (res != CDI_USB_OK) { + return -EIO; + } + + if (dev->luns > 0) { + return 0; + } + + uint8_t lun_count; + res = cdi_usb_control_transfer(&dev->usb, 0, &(struct cdi_usb_setup_packet) { + .bm_request_type = CDI_USB_CREQ_CLASS | CDI_USB_CREQ_INTERFACE + | CDI_USB_CREQ_IN, + .b_request = USBMS_REQ_GML, + .w_index = dev->usb.interface, + .w_length = 1 + }, &lun_count); + if (res == CDI_USB_OK) { + dev->luns = lun_count + 1; + } else { + dev->luns = 1; + } + + return 0; +} + + +struct cdi_device *init_usb_device(struct cdi_bus_data *bus_data) +{ + static int dev_counter = 0; + usb_mass_storage_device_t *dev = calloc(1, sizeof(*dev)); + dev->usb = *CDI_UPCAST(bus_data, struct cdi_usb_device, bus_data); + + if ((dev->usb.subclass_id == USBMS_SUBCLS_SCSILEG || + dev->usb.subclass_id == USBMS_SUBCLS_SCSI) && + dev->usb.protocol_id == USBMS_PROTO_BBB) + { + dev->type = USBMS_BULK_ONLY; + } else { + free(dev); + return NULL; + } + + if (dev->type == USBMS_BULK_ONLY) { + if (bulk_only_reset(dev) < 0) { + free(dev); + return NULL; + } + + struct cdi_usb_endpoint_descriptor ep_desc; + for (int ep = 1; ep < dev->usb.endpoint_count; ep++) { + cdi_usb_get_endpoint_descriptor(&dev->usb, ep, &ep_desc); + + if ((ep_desc.bm_attributes & CDI_USB_EPDSC_ATTR_XFER_TYPE_MASK) + == CDI_USB_EPDSC_ATTR_BULK) + { + bool is_in; + is_in = ep_desc.b_endpoint_address & CDI_USB_EPDSC_EPADR_DIR; + if (!dev->bulk_in && is_in) { + dev->bulk_in = ep; + } + if (!dev->bulk_out && !is_in) { + dev->bulk_out = ep; + } + } + } + + if (!dev->bulk_in || !dev->bulk_out) { + free(dev); + return NULL; + } + } + + dev->dev.dev.name = malloc(5); + sprintf((char *)dev->dev.dev.name, "msd%i", dev_counter++); + + dev->dev.type = CDI_STORAGE; + dev->dev.lun_count = dev->luns; + + return &dev->dev.dev; +} + + +int usb_storage_request(struct cdi_scsi_device *device, + struct cdi_scsi_packet *packet) +{ + cdi_usb_transmission_result_t res; + usb_mass_storage_device_t *dev = CDI_UPCAST(device, + usb_mass_storage_device_t, dev); + + struct msd_bo_cbw cbw = { + .signature = CBW_SIGNATURE, + .tag = 42, + .data_length = packet->bufsize, + .flags = packet->direction == CDI_SCSI_READ ? CBW_IN : CBW_OUT, + .lun = packet->lun, + .cb_length = packet->cmdsize + }; + memcpy(cbw.cb, packet->command, sizeof(cbw.cb)); + + res = cdi_usb_bulk_transfer(&dev->usb, dev->bulk_out, &cbw, sizeof(cbw)); + if (res != CDI_USB_OK) { + bulk_only_reset(dev); + return -1; + } + + if (packet->direction == CDI_SCSI_READ) { + res = cdi_usb_bulk_transfer(&dev->usb, dev->bulk_in, + packet->buffer, packet->bufsize); + } else if (packet->direction == CDI_SCSI_WRITE) { + res = cdi_usb_bulk_transfer(&dev->usb, dev->bulk_out, + packet->buffer, packet->bufsize); + } + + if (res != CDI_USB_OK) { + bulk_only_reset(dev); + return -1; + } + + struct msd_bo_csw csw; + res = cdi_usb_bulk_transfer(&dev->usb, dev->bulk_in, &csw, sizeof(csw)); + + if (res != CDI_USB_OK || csw.signature != CSW_SIGNATURE || csw.tag != 42 || + csw.data_residue || csw.status) + { + bulk_only_reset(dev); + return -1; + } + + return 0; +} diff --git a/usb-storage/usb-storage.h b/usb-storage/usb-storage.h new file mode 100644 index 0000000..eed3462 --- /dev/null +++ b/usb-storage/usb-storage.h @@ -0,0 +1,60 @@ +/****************************************************************************** + * Copyright (c) 2015 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_STORAGE_H +#define USB_STORAGE_H + +#include +#include + + +// Mass storage subclass codes +#define USBMS_SUBCLS_SCSILEG 0x00 // SCSI legacy ("command set not reported") +#define USBMS_SUBCLS_RBC 0x01 // RBC +#define USBMS_SUBCLS_MMC5 0x02 // MMC-5 (ATAPI) +#define USBMS_SUBCLS_UFI 0x04 // UFI for Floppy Disk Drives +#define USBMS_SUBCLS_SCSI 0x06 // SCSI transparent command set +#define USBMS_SUBCLS_LSDFS 0x07 // LSD FS for negotiating SCSI access +#define USBMS_SUBCLS_IEEE1667 0x08 // IEEE 1667 +#define USBMS_SUBCLS_VENDOR 0xff // Vendor-specific + +// Mass storage protocol codes +#define USBMS_PROTO_CBI_CCI 0x00 // Control/Bulk/Interrupt with + // Command Completion Interrupt +#define USBMS_PROTO_CBI 0x01 // CBI without CCI +#define USBMS_PROTO_BBB 0x50 // Bulk-only +#define USBMS_PROTO_UAS 0x62 // UAS +#define USBMS_PROTO_VENDOR 0xff // Vendor-specific + +// Mass storage request codes +#define USBMS_REQ_ADSC 0x00 // Accept Device-Specific Command (CBI) +#define USBMS_REQ_GETRQ 0xfc // Get Requests (LSD FS) +#define USBMS_REQ_PUTRQ 0xfd // Put Requests (LSD FS) +#define USBMS_REQ_GML 0xfe // Get Max LUN (Bulk-only) +#define USBMS_REQ_BOMSR 0xff // Bulk-Only Mass Storage Reset (Bulk-only) + + +struct cdi_device *init_usb_device(struct cdi_bus_data *bus_data); +int usb_storage_request(struct cdi_scsi_device *device, + struct cdi_scsi_packet *packet); + +#endif -- 2.6.3 From max at tyndur.org Sat Dec 12 23:26:26 2015 From: max at tyndur.org (Max Reitz) Date: Sat, 12 Dec 2015 23:26:26 +0100 Subject: [cdi-devel] [PATCH] ata: Temporary buffer for ATAPI commands Message-ID: <1449959186-10888-1-git-send-email-max@tyndur.org> ! ATAPI commands need to be of size 12. However, general SCSI packets may have any length and thus the SCSI command to be sent has to be copied to a temporary buffer before it can be passed to the ATAPI device. Signed-off-by: Max Reitz --- ata/atapi.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/ata/atapi.c b/ata/atapi.c index 31c7263..78f7f29 100644 --- a/ata/atapi.c +++ b/ata/atapi.c @@ -28,6 +28,7 @@ #include #include +#include #include "cdi.h" #include "cdi/storage.h" @@ -92,6 +93,12 @@ void atapi_remove_device(struct cdi_device* device) int atapi_request(struct cdi_scsi_device* scsi,struct cdi_scsi_packet* packet) { + uint8_t atapi_request[12]; + if (packet->cmdsize > 12) { + return -1; + } + memcpy(atapi_request, packet->command, sizeof(atapi_request)); + struct ata_device *dev = (struct ata_device*)scsi; struct ata_request request = { .dev = dev, @@ -111,9 +118,9 @@ int atapi_request(struct cdi_scsi_device* scsi,struct cdi_scsi_packet* packet) } }, .block_count = 1, - .block_size = packet->cmdsize, + .block_size = sizeof(atapi_request), .blocks_done = 0, - .buffer = packet->command, + .buffer = atapi_request, .error = 0 }; -- 2.6.3 From kevin at tyndur.org Sat Dec 12 23:28:04 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Sat, 12 Dec 2015 23:28:04 +0100 Subject: [cdi-devel] [PATCH 04/11] cdi/fs: Add .fs_probe callback In-Reply-To: <1449959291-24784-1-git-send-email-kevin@tyndur.org> References: <1449959291-24784-1-git-send-email-kevin@tyndur.org> Message-ID: <1449959291-24784-5-git-send-email-kevin@tyndur.org> The .fs_probe callback checks whether the file system could be mounted on a given storage device without actually mounting it. On success, it can return the volume name of the file system. Cc: cdi-devel at tyndur.org Signed-off-by: Kevin Wolf --- src/modules/cdi/include/cdi/fs.h | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/modules/cdi/include/cdi/fs.h b/src/modules/cdi/include/cdi/fs.h index 31ef4a0..ea64b69 100644 --- a/src/modules/cdi/include/cdi/fs.h +++ b/src/modules/cdi/include/cdi/fs.h @@ -29,6 +29,34 @@ struct cdi_fs_driver { struct cdi_driver drv; /** + * \german + * Pr?fen, ob sich ein g?ltiges Dateisystem auf dem Ger?t befindet. Falls + * das der Fall ist und das Dateisystem einen Namen hat, wird der Name + * in einem per malloc() neu allozierten String zur?ckgegeben. + * + * @fs ist kein vollst?ndig initialisiertes Dateisystem; es kann nur + * verwendet werden, um auf das Ger?t zuzugreifen. + * + * Diese Funktion ist f?r Dateisystemtreiber optional. + * + * @return Wenn das Dateisystem g?ltig ist 1, sonst 0. + * \endgerman + * \english + * Check whether there is a valid file system on the device. If so, and the + * file system has a name, the name is returned in a string newly allocated + * with malloc(). + * + * @fs isn't a fully initialised file system; it can only be used to access + * the storage device. + * + * This function is optional for file system drivers. + * + * @return If the file system is valid 1, otherwise 0. + * \endenglish + */ + int (*fs_probe)(struct cdi_fs_filesystem* fs, char** volname); + + /** * Neues Dateisystem initialisieren; Diese Funktion muss das root_object in * der Dateisystemstruktur eintragen. * -- 2.1.4 From kevin at tyndur.org Sat Dec 12 23:28:05 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Sat, 12 Dec 2015 23:28:05 +0100 Subject: [cdi-devel] [PATCH 05/11] ext2: Implement .fs_probe In-Reply-To: <1449959291-24784-1-git-send-email-kevin@tyndur.org> References: <1449959291-24784-1-git-send-email-kevin@tyndur.org> Message-ID: <1449959291-24784-6-git-send-email-kevin@tyndur.org> Cc: cdi-devel at tyndur.org Signed-off-by: Kevin Wolf --- src/modules/cdi/ext2/ext2_cdi.h | 1 + src/modules/cdi/ext2/init.c | 22 ++++++++++++++++++++++ src/modules/cdi/ext2/main.c | 1 + 3 files changed, 24 insertions(+) diff --git a/src/modules/cdi/ext2/ext2_cdi.h b/src/modules/cdi/ext2/ext2_cdi.h index 00de2a2..7ad9c46 100644 --- a/src/modules/cdi/ext2/ext2_cdi.h +++ b/src/modules/cdi/ext2/ext2_cdi.h @@ -57,6 +57,7 @@ struct ext2_fs_res { // CDI-IF +int ext2_fs_probe(struct cdi_fs_filesystem* cdi_fs, char** volname); int ext2_fs_init(struct cdi_fs_filesystem* fs); int ext2_fs_destroy(struct cdi_fs_filesystem* fs); diff --git a/src/modules/cdi/ext2/init.c b/src/modules/cdi/ext2/init.c index d20f647..2da556f 100644 --- a/src/modules/cdi/ext2/init.c +++ b/src/modules/cdi/ext2/init.c @@ -51,6 +51,28 @@ static int dev_write(uint64_t start, size_t size, const void* data, void* prv) return cdi_fs_data_write(fs, start, size, data); } +int ext2_fs_probe(struct cdi_fs_filesystem* cdi_fs, char** volname) +{ + ext2_superblock_t sb; + int ret; + + ext2_fs_t fs = { + .dev_read = dev_read, + .dev_private = cdi_fs, + }; + + ret = ext2_sb_read(&fs, &sb); + if (ret == 0) { + return 0; + } + + *volname = malloc(sizeof(sb.volume_name) + 1); + memcpy(*volname, sb.volume_name, sizeof(sb.volume_name)); + (*volname)[sizeof(sb.volume_name)] = '\0'; + + return 1; +} + int ext2_fs_init(struct cdi_fs_filesystem* cdi_fs) { struct ext2_fs_res* root_res; diff --git a/src/modules/cdi/ext2/main.c b/src/modules/cdi/ext2/main.c index a1d597f..24f4594 100644 --- a/src/modules/cdi/ext2/main.c +++ b/src/modules/cdi/ext2/main.c @@ -72,6 +72,7 @@ static struct cdi_fs_driver ext2_driver = { .init = ext2_driver_init, .destroy = ext2_driver_destroy, }, + .fs_probe = ext2_fs_probe, .fs_init = ext2_fs_init, .fs_destroy = ext2_fs_destroy, }; -- 2.1.4 From kevin at tyndur.org Sat Dec 12 23:28:06 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Sat, 12 Dec 2015 23:28:06 +0100 Subject: [cdi-devel] [PATCH 06/11] iso9660: Implement .fs_probe In-Reply-To: <1449959291-24784-1-git-send-email-kevin@tyndur.org> References: <1449959291-24784-1-git-send-email-kevin@tyndur.org> Message-ID: <1449959291-24784-7-git-send-email-kevin@tyndur.org> Cc: cdi-devel at tyndur.org Signed-off-by: Kevin Wolf --- src/modules/cdi/iso9660/init.c | 25 +++++++++++++++++++++++++ src/modules/cdi/iso9660/iso9660_cdi.h | 1 + src/modules/cdi/iso9660/main.c | 1 + 3 files changed, 27 insertions(+) diff --git a/src/modules/cdi/iso9660/init.c b/src/modules/cdi/iso9660/init.c index 641d4f3..f2e8a0d 100644 --- a/src/modules/cdi/iso9660/init.c +++ b/src/modules/cdi/iso9660/init.c @@ -17,6 +17,7 @@ */ #include +#include #include "cdi/fs.h" #include "cdi/cache.h" @@ -25,6 +26,30 @@ #include "volume_descriptor.h" +int iso9660_fs_probe(struct cdi_fs_filesystem* cdi_fs, char** volname) +{ + struct iso9660_voldesc_prim voldesc; + size_t len; + int ret; + + ret = iso9660_voldesc_load(cdi_fs, ISO9660_VOLDESC_PRIM, &voldesc); + if (ret != 0) { + return 0; + } + + len = sizeof(voldesc.volume_identifier); + *volname = malloc(len + 1); + memcpy(*volname, voldesc.volume_identifier, len); + (*volname)[len] = '\0'; + + /* Remove padding */ + while (--len && (*volname)[len] == ' ') { + (*volname)[len] = '\0'; + } + + return 1; +} + /** * Initializes a ISO9660 filesystem * @param fs Filesystem to initialize diff --git a/src/modules/cdi/iso9660/iso9660_cdi.h b/src/modules/cdi/iso9660/iso9660_cdi.h index 25a4a14..483d506 100644 --- a/src/modules/cdi/iso9660/iso9660_cdi.h +++ b/src/modules/cdi/iso9660/iso9660_cdi.h @@ -59,6 +59,7 @@ struct iso9660_fs_res { }; // init.c +int iso9660_fs_probe(struct cdi_fs_filesystem* cdi_fs, char** volname); int iso9660_fs_init(struct cdi_fs_filesystem *fs); int iso9660_fs_destroy(struct cdi_fs_filesystem *fs); diff --git a/src/modules/cdi/iso9660/main.c b/src/modules/cdi/iso9660/main.c index 1e81779..56930d0 100644 --- a/src/modules/cdi/iso9660/main.c +++ b/src/modules/cdi/iso9660/main.c @@ -76,6 +76,7 @@ static struct cdi_fs_driver iso9660_driver = { }, .fs_init = iso9660_fs_init, .fs_destroy = iso9660_fs_destroy, + .fs_probe = iso9660_fs_probe, }; CDI_DRIVER(DRIVER_NAME, iso9660_driver) -- 2.1.4 From max at tyndur.org Sat Dec 12 23:45:41 2015 From: max at tyndur.org (Max Reitz) Date: Sat, 12 Dec 2015 23:45:41 +0100 Subject: [cdi-devel] [PATCH] ata: Initialize ata_device to 0 Message-ID: <1449960341-23223-1-git-send-email-max@tyndur.org> * struct ata_device inherits cdi_storage_device or cdi_scsi_device. Since this driver does not know all of the fields contained therein for sure, the object has to be initialized to 0. Signed-off-by: Max Reitz --- ata/device.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ata/device.c b/ata/device.c index 9afa102..a287f1e 100644 --- a/ata/device.c +++ b/ata/device.c @@ -222,7 +222,7 @@ void ata_init_controller(struct ata_controller* controller) // Jetzt werden die einzelnen geraete identifiziert. Hier ist es // anscheinend geschickter mit dem Slave zu beginnen. for (i = 1; i >= 0; i--) { - struct ata_device* dev = malloc(sizeof(*dev)); + struct ata_device* dev = calloc(1, sizeof(*dev)); dev->controller = controller; dev->id = i; dev->partition_list = cdi_list_create(); -- 2.6.3 From kevin at tyndur.org Sat Dec 12 23:57:44 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Sat, 12 Dec 2015 23:57:44 +0100 Subject: [cdi-devel] [PATCH v4 4/4] usb-storage: Add USB mass storage driver In-Reply-To: <1449951040-16452-5-git-send-email-max@tyndur.org> References: <1449951040-16452-1-git-send-email-max@tyndur.org> <1449951040-16452-5-git-send-email-max@tyndur.org> Message-ID: <20151212225735.GA2849@silvanus> On Sat, Dec 12, 2015 at 09:10:40PM +0100, Max Reitz wrote: > + This adds a USB mass storage device driver. It is missing proper error > handling (e.g. for STALLed endpoints) and support for any USB MSD > class other than bulk-only (e.g. control-bulk-interrupt for USB floppy > drives). > > Signed-off-by: Max Reitz > +struct cdi_device *init_usb_device(struct cdi_bus_data *bus_data) > +{ > + static int dev_counter = 0; > + usb_mass_storage_device_t *dev = calloc(1, sizeof(*dev)); > + dev->usb = *CDI_UPCAST(bus_data, struct cdi_usb_device, bus_data); > + > + if ((dev->usb.subclass_id == USBMS_SUBCLS_SCSILEG || > + dev->usb.subclass_id == USBMS_SUBCLS_SCSI) && > + dev->usb.protocol_id == USBMS_PROTO_BBB) > + { > + dev->type = USBMS_BULK_ONLY; > + } else { > + free(dev); > + return NULL; > + } > + > + if (dev->type == USBMS_BULK_ONLY) { > + if (bulk_only_reset(dev) < 0) { > + free(dev); > + return NULL; > + } > + > + struct cdi_usb_endpoint_descriptor ep_desc; > + for (int ep = 1; ep < dev->usb.endpoint_count; ep++) { > + cdi_usb_get_endpoint_descriptor(&dev->usb, ep, &ep_desc); > + > + if ((ep_desc.bm_attributes & CDI_USB_EPDSC_ATTR_XFER_TYPE_MASK) > + == CDI_USB_EPDSC_ATTR_BULK) > + { > + bool is_in; > + is_in = ep_desc.b_endpoint_address & CDI_USB_EPDSC_EPADR_DIR; > + if (!dev->bulk_in && is_in) { > + dev->bulk_in = ep; > + } > + if (!dev->bulk_out && !is_in) { > + dev->bulk_out = ep; > + } > + } > + } > + > + if (!dev->bulk_in || !dev->bulk_out) { > + free(dev); > + return NULL; > + } > + } > + > + dev->dev.dev.name = malloc(5); > + sprintf((char *)dev->dev.dev.name, "msd%i", dev_counter++); With asprintf() instead of the potential buffer overflow: Series: Acked-by: Kevin Wolf From kevin at tyndur.org Sun Dec 13 00:01:23 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Sun, 13 Dec 2015 00:01:23 +0100 Subject: [cdi-devel] [PATCH] ata: Initialize ata_device to 0 In-Reply-To: <1449960341-23223-1-git-send-email-max@tyndur.org> References: <1449960341-23223-1-git-send-email-max@tyndur.org> Message-ID: <20151212230123.GB2849@silvanus> On Sat, Dec 12, 2015 at 11:45:41PM +0100, Max Reitz wrote: > * struct ata_device inherits cdi_storage_device or cdi_scsi_device. > Since this driver does not know all of the fields contained therein > for sure, the object has to be initialized to 0. > > Signed-off-by: Max Reitz Acked-by: Kevin Wolf From kevin at tyndur.org Sun Dec 13 00:07:38 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Sun, 13 Dec 2015 00:07:38 +0100 Subject: [cdi-devel] [PATCH] ata: Temporary buffer for ATAPI commands In-Reply-To: <1449959186-10888-1-git-send-email-max@tyndur.org> References: <1449959186-10888-1-git-send-email-max@tyndur.org> Message-ID: <20151212230738.GC2849@silvanus> On Sat, Dec 12, 2015 at 11:26:26PM +0100, Max Reitz wrote: > ! ATAPI commands need to be of size 12. However, general SCSI packets > may have any length and thus the SCSI command to be sent has to be > copied to a temporary buffer before it can be passed to the ATAPI > device. > > Signed-off-by: Max Reitz > --- > ata/atapi.c | 11 +++++++++-- > 1 file changed, 9 insertions(+), 2 deletions(-) > > diff --git a/ata/atapi.c b/ata/atapi.c > index 31c7263..78f7f29 100644 > --- a/ata/atapi.c > +++ b/ata/atapi.c > @@ -28,6 +28,7 @@ > > #include > #include > +#include > > #include "cdi.h" > #include "cdi/storage.h" > @@ -92,6 +93,12 @@ void atapi_remove_device(struct cdi_device* device) > > int atapi_request(struct cdi_scsi_device* scsi,struct cdi_scsi_packet* packet) > { > + uint8_t atapi_request[12]; > + if (packet->cmdsize > 12) { > + return -1; > + } > + memcpy(atapi_request, packet->command, sizeof(atapi_request)); The length should be packet->cmdsize instead (which is already at most 12 bytes) in order to avoid copying uninitialised bytes from the original buffer; we might want to pad with zeros then. With this changed: Acked-by: Kevin Wolf From max at tyndur.org Tue Dec 29 00:53:09 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 00:53:09 +0100 Subject: [cdi-devel] [PATCH 00/10] usb: Some fixes Message-ID: <1451346799-23335-1-git-send-email-max@tyndur.org> Several generic fixes for the USB bus driver, and one for usb-storage. Some usb patches (like the last one) are not strictly fixes, but are nice to have anyway; the same applies to the ehci patch. Max Reitz (10): usb: extern "C" {} usb: Add necessary recovery intervals usb: Ignore hub power switching errors usb: Make descriptors inherit from a common base usb: Store hub and hub_port for each usb_device usb: Create provide_virtual_devices() usb: Fix and simplify debugging code usb: Clear ENDPOINT_HALT on stalling bulk transfer usb-storage: Drop bulk_only_reset()'s return value ehci: Use __attribute__((aligned())) ehci/ehci.c | 3 + ehci/ehci.h | 33 ++-- include/cdi/usb-structures.h | 26 ++- include/cdi/usb.h | 8 + usb-storage/usb-storage.c | 18 +- usb/usb.c | 380 ++++++++++++++++++++++++++----------------- usb/usb.h | 2 + 7 files changed, 282 insertions(+), 188 deletions(-) -- 2.6.4 From max at tyndur.org Tue Dec 29 00:53:10 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 00:53:10 +0100 Subject: [cdi-devel] [PATCH 01/10] usb: extern "C" {} In-Reply-To: <1451346799-23335-1-git-send-email-max@tyndur.org> References: <1451346799-23335-1-git-send-email-max@tyndur.org> Message-ID: <1451346799-23335-2-git-send-email-max@tyndur.org> ! It was missing. Amend this lest it is any longer. Signed-off-by: Max Reitz --- include/cdi/usb.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/include/cdi/usb.h b/include/cdi/usb.h index d30e7b0..c7fa751 100644 --- a/include/cdi/usb.h +++ b/include/cdi/usb.h @@ -175,6 +175,10 @@ struct cdi_usb_bus_device_pattern { }; +#ifdef __cplusplus +extern "C" { +#endif + /** * Registers a USB bus driver. Should be called by the CDI library, ideally, * after the USB bus driver's init() function has run. @@ -208,4 +212,8 @@ cdi_usb_transmission_result_t cdi_usb_bulk_transfer(struct cdi_usb_device* dev, int ep, void* data, size_t size); +#ifdef __cplusplus +}; // extern "C" +#endif + #endif -- 2.6.4 From max at tyndur.org Tue Dec 29 00:53:11 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 00:53:11 +0100 Subject: [cdi-devel] [PATCH 02/10] usb: Add necessary recovery intervals In-Reply-To: <1451346799-23335-1-git-send-email-max@tyndur.org> References: <1451346799-23335-1-git-send-email-max@tyndur.org> Message-ID: <1451346799-23335-3-git-send-email-max@tyndur.org> ! The USB specification requires a 10 ms recovery interval after the reset signal has been deasserted. We should grant that. ! Furthermore, it requires a 2 ms recovery interval after a SetAddress() request. Signed-off-by: Max Reitz --- ehci/ehci.c | 3 +++ usb/usb.c | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/ehci/ehci.c b/ehci/ehci.c index 7f3838c..addec00 100644 --- a/ehci/ehci.c +++ b/ehci/ehci.c @@ -274,6 +274,9 @@ void ehci_rh_port_up(struct cdi_usb_hub *hub, int index) hc->regs->portsc[index] = portsc & ~EHCI_PSC_RES; CDI_CONDITION_WAIT(!(hc->regs->portsc[index] & EHCI_PSC_RES), 50); + // Recovery interval + cdi_sleep_ms(10); + portsc = hc->regs->portsc[index]; if (portsc & EHCI_PSC_RES) { // Disable port, route on to companion controller diff --git a/usb/usb.c b/usb/usb.c index 62ef989..3141176 100644 --- a/usb/usb.c +++ b/usb/usb.c @@ -191,6 +191,9 @@ static usb_device_t *enumerate(usb_hub_t *hub, int hub_port, return NULL; } + // SetAddress() recovery interval + cdi_sleep_ms(2); + dev->id = new_id; res = control_transfer(dev, &dev->eps[0][0], &(struct cdi_usb_setup_packet){ @@ -859,6 +862,9 @@ static void hub_port_up(struct cdi_usb_hub *cdi_hub, int index) CDI_CONDITION_WAIT(hub_get_port_status(hub, index) & (1 << C_PORT_RESET), 100); + + // Recovery interval + cdi_sleep_ms(10); } -- 2.6.4 From max at tyndur.org Tue Dec 29 00:53:12 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 00:53:12 +0100 Subject: [cdi-devel] [PATCH 03/10] usb: Ignore hub power switching errors In-Reply-To: <1451346799-23335-1-git-send-email-max@tyndur.org> References: <1451346799-23335-1-git-send-email-max@tyndur.org> Message-ID: <1451346799-23335-4-git-send-email-max@tyndur.org> ! Aborting hub initialization because it tells us that the request to switch on power failed is a bad idea; maybe the hub simply does not support power switching after all. In any case, if switching on the power actually failed, nothing bad will happen if we go on (we simply will not see any devices). Signed-off-by: Max Reitz --- usb/usb.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/usb/usb.c b/usb/usb.c index 3141176..1f69c1b 100644 --- a/usb/usb.c +++ b/usb/usb.c @@ -816,17 +816,17 @@ static void new_hub_device(usb_logical_device_t *ldev) // Enable port power if (!(hub_desc->w_hub_characteristics & (1 << 1))) { // Hub supports power switching, enable global power - if (hub_set_hub_feature(hub, C_HUB_LOCAL_POWER) != CDI_USB_OK) { - goto fail; - } + hub_set_hub_feature(hub, C_HUB_LOCAL_POWER); + // Ignore the return value, maybe the port just does not support power + // switching after all; in any case, we do not gain anything by aborting + // here instead of just trying to go on anyway. } if ((hub_desc->w_hub_characteristics & 0x3) == 1) { // Hub supports per-port power switching, enable power for each port for (int port = 0; port < ports; port++) { - if (hub_set_port_feature(hub, PORT_POWER, port) != CDI_USB_OK) { - goto fail; - } + hub_set_port_feature(hub, PORT_POWER, port); + // Ignore the return value, for the same reason as above } } -- 2.6.4 From max at tyndur.org Tue Dec 29 00:53:13 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 00:53:13 +0100 Subject: [cdi-devel] [PATCH 04/10] usb: Make descriptors inherit from a common base In-Reply-To: <1451346799-23335-1-git-send-email-max@tyndur.org> References: <1451346799-23335-1-git-send-email-max@tyndur.org> Message-ID: <1451346799-23335-5-git-send-email-max@tyndur.org> * All USB descriptors share a common base which defines the length and the type of the descriptor. In order to have code that does not completely rely on fixed descriptor orderings (such as "configuration (interface (endpoint)*)*"), we need this type to be able to represent descriptors of undetermined type. Signed-off-by: Max Reitz --- include/cdi/usb-structures.h | 18 +++++++++--------- usb/usb.c | 20 +++++++++++--------- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/include/cdi/usb-structures.h b/include/cdi/usb-structures.h index fecb609..f894b9e 100644 --- a/include/cdi/usb-structures.h +++ b/include/cdi/usb-structures.h @@ -18,9 +18,13 @@ #include -struct cdi_usb_device_descriptor { +struct cdi_usb_descriptor { uint8_t b_length; uint8_t b_descriptor_type; +} __attribute__((packed)); + +struct cdi_usb_device_descriptor { + struct cdi_usb_descriptor base; uint16_t bcd_usb; uint8_t b_device_class; uint8_t b_device_sub_class; @@ -36,8 +40,7 @@ struct cdi_usb_device_descriptor { } __attribute__((packed)); struct cdi_usb_configuration_descriptor { - uint8_t b_length; - uint8_t b_descriptor_type; + struct cdi_usb_descriptor base; uint16_t w_total_length; uint8_t b_num_interfaces; uint8_t b_configuration_value; @@ -47,14 +50,12 @@ struct cdi_usb_configuration_descriptor { } __attribute__((packed)); struct cdi_usb_string_descriptor { - uint8_t b_length; - uint8_t b_descriptor_type; + struct cdi_usb_descriptor base; uint16_t b_string[127]; } __attribute__((packed)); struct cdi_usb_interface_descriptor { - uint8_t b_length; - uint8_t b_descriptor_type; + struct cdi_usb_descriptor base; uint8_t b_interface_number; uint8_t b_alternate_setting; uint8_t b_num_endpoints; @@ -66,8 +67,7 @@ struct cdi_usb_interface_descriptor { struct cdi_usb_endpoint_descriptor { - uint8_t b_length; - uint8_t b_descriptor_type; + struct cdi_usb_descriptor base; uint8_t b_endpoint_address; uint8_t bm_attributes; uint16_t w_max_packet_size; diff --git a/usb/usb.c b/usb/usb.c index 1f69c1b..489f362 100644 --- a/usb/usb.c +++ b/usb/usb.c @@ -223,8 +223,8 @@ static void get_string_descriptor(usb_device_t *dev, int index, .w_value = (CDI_USB_DESC_STRING << 8) | index, .w_length = 1 }, dst); - if (res != CDI_USB_OK || !dst->b_length) { - dst->b_length = 0; + if (res != CDI_USB_OK || !dst->base.b_length) { + dst->base.b_length = 0; return; } @@ -232,10 +232,10 @@ static void get_string_descriptor(usb_device_t *dev, int index, .bm_request_type = CDI_USB_CREQ_DEVICE | CDI_USB_CREQ_IN, .b_request = CDI_USB_CREQ_GET_DESCRIPTOR, .w_value = (CDI_USB_DESC_STRING << 8) | index, - .w_length = dst->b_length + .w_length = dst->base.b_length }, dst); if (res != CDI_USB_OK) { - dst->b_length = 0; + dst->base.b_length = 0; return; } } @@ -348,7 +348,7 @@ static void debug_device(usb_device_t *dev) if (dev->dev_desc.i_manufacturer) { get_string_descriptor(dev, dev->dev_desc.i_manufacturer, &str); - for (int i = 0; i < (str.b_length - 2) / 2; i++) { + for (int i = 0; i < (str.base.b_length - 2) / 2; i++) { putchar(str.b_string[i] > 0x7f ? '?' : str.b_string[i]); } putchar(' '); @@ -356,7 +356,7 @@ static void debug_device(usb_device_t *dev) if (dev->dev_desc.i_product) { get_string_descriptor(dev, dev->dev_desc.i_product, &str); - for (int i = 0; i < (str.b_length - 2) / 2; i++) { + for (int i = 0; i < (str.base.b_length - 2) / 2; i++) { putchar(str.b_string[i] > 0x7f ? '?' : str.b_string[i]); } putchar(' '); @@ -374,7 +374,7 @@ static void debug_configuration(usb_device_t *dev) if (dev->config->i_configuration) { get_string_descriptor(dev, dev->config->i_configuration, &str); putchar('('); - for (int i = 0; i < (str.b_length - 2) / 2; i++) { + for (int i = 0; i < (str.base.b_length - 2) / 2; i++) { putchar(str.b_string[i] > 0x7f ? '?' : str.b_string[i]); } putchar(')'); @@ -616,8 +616,10 @@ void usb_get_endpoint_descriptor(struct cdi_usb_device *dev, int ep, memcpy(desc, ep_info->desc, sizeof(*desc)); } else { *desc = (struct cdi_usb_endpoint_descriptor){ - .b_length = sizeof(*desc), - .b_descriptor_type = CDI_USB_DESC_ENDPOINT, + .base = { + .b_length = sizeof(*desc), + .b_descriptor_type = CDI_USB_DESC_ENDPOINT, + }, .b_endpoint_address = 0, .bm_attributes = 0x00, .w_max_packet_size = ep_info->mps, -- 2.6.4 From max at tyndur.org Tue Dec 29 00:53:14 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 00:53:14 +0100 Subject: [cdi-devel] [PATCH 05/10] usb: Store hub and hub_port for each usb_device In-Reply-To: <1451346799-23335-1-git-send-email-max@tyndur.org> References: <1451346799-23335-1-git-send-email-max@tyndur.org> Message-ID: <1451346799-23335-6-git-send-email-max@tyndur.org> + While not having an immediate use, we will probably need this later on (e.g. for device reset after enumeration, or whenever we will implement plugging/unplugging support). Signed-off-by: Max Reitz --- usb/usb.c | 2 ++ usb/usb.h | 2 ++ 2 files changed, 4 insertions(+) diff --git a/usb/usb.c b/usb/usb.c index 489f362..c7a56d3 100644 --- a/usb/usb.c +++ b/usb/usb.c @@ -167,6 +167,8 @@ static usb_device_t *enumerate(usb_hub_t *hub, int hub_port, dev->hc = hub->hc; dev->speed = speed; + dev->hub = hub; + dev->hub_port = hub_port; if (speed < CDI_USB_HIGH_SPEED && hub->ldev) { if (hub->ldev->dev->speed < CDI_USB_HIGH_SPEED) { diff --git a/usb/usb.h b/usb/usb.h index 27dc061..9f1f4ac 100644 --- a/usb/usb.h +++ b/usb/usb.h @@ -54,6 +54,8 @@ typedef struct usb_device { int id; cdi_usb_speed_t speed; + usb_hub_t *hub; + int hub_port; int tt_addr, tt_port; // First index: OUT (0) / IN (1) -- 2.6.4 From max at tyndur.org Tue Dec 29 00:53:15 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 00:53:15 +0100 Subject: [cdi-devel] [PATCH 06/10] usb: Create provide_virtual_devices() In-Reply-To: <1451346799-23335-1-git-send-email-max@tyndur.org> References: <1451346799-23335-1-git-send-email-max@tyndur.org> Message-ID: <1451346799-23335-7-git-send-email-max@tyndur.org> * new_hub() has been getting rather long. This pulls out the code which enumerates and provides the virtual devices to CDI (either the full physical device, or single interfaces, depending on the device and configuration), making it shorter. ! Also, that stuff was broken. It expected a certain order of descriptors without gaps in between; fix it. ! Of course, that is not the only way in which it was broken: cdi_usb_device.interface should *not* be set to the interface descriptor index, but to the value of that descriptor's b_interface_number field. Signed-off-by: Max Reitz --- usb/usb.c | 255 ++++++++++++++++++++++++++++++++++++++------------------------ 1 file changed, 155 insertions(+), 100 deletions(-) diff --git a/usb/usb.c b/usb/usb.c index c7a56d3..a8366e0 100644 --- a/usb/usb.c +++ b/usb/usb.c @@ -405,8 +405,162 @@ static void debug_configuration(usb_device_t *dev) #endif +static struct cdi_usb_descriptor *next_desc(struct cdi_usb_descriptor *desc) +{ + return (struct cdi_usb_descriptor *)((uintptr_t)desc + desc->b_length); +} + static void new_hub_device(usb_logical_device_t *ldev); +static void provide_virtual_devices(usb_device_t *dev) +{ + usb_logical_device_t *ldev = NULL; + int ldev_ep_idx = 0; + bool interface_level; + + struct cdi_usb_descriptor *opaque_desc; + struct cdi_usb_device_descriptor *devd = &dev->dev_desc; + struct cdi_usb_configuration_descriptor *config = dev->config; + struct cdi_usb_interface_descriptor *ifc; + struct cdi_usb_endpoint_descriptor *ep; + + uintptr_t desc_end = (uintptr_t)config + config->w_total_length; + + interface_level = devd->b_device_class == CDI_USB_DEVCLS_NONE; + if (!interface_level) { + ldev = calloc(1, sizeof(*ldev)); + ldev->cdi.bus_data.bus_type = CDI_USB; + ldev->cdi.interface = -1; + ldev->cdi.endpoint_count = 1; // EP0 + ldev->cdi.vendor_id = devd->id_vendor; + ldev->cdi.product_id = devd->id_product; + ldev->cdi.class_id = devd->b_device_class; + ldev->cdi.subclass_id = devd->b_device_sub_class; + ldev->cdi.protocol_id = devd->b_device_protocol; + + ldev->dev = dev; + + ldev->endpoints = malloc(1 * sizeof(ldev->endpoints[0])); + ldev->endpoints[0] = 0; // EP0 + ldev_ep_idx = 1; + } + + + opaque_desc = next_desc(&config->base); + + int i = 0; + while ((uintptr_t)next_desc(opaque_desc) <= desc_end && + i < (int)config->b_num_interfaces) + { + if (opaque_desc->b_descriptor_type == CDI_USB_DESC_INTERFACE) { + i++; + ifc = CDI_UPCAST(opaque_desc, + struct cdi_usb_interface_descriptor, base); + } else { + ifc = NULL; + } + + opaque_desc = next_desc(opaque_desc); + if (!ifc) { + continue; + } + + if (interface_level) { + ldev = calloc(1, sizeof(*ldev)); + ldev->cdi.bus_data.bus_type = CDI_USB; + ldev->cdi.interface = ifc->b_interface_number; + // Include EP0 + ldev->cdi.endpoint_count = ifc->b_num_endpoints + 1; + ldev->cdi.vendor_id = devd->id_vendor; + ldev->cdi.product_id = devd->id_product; + ldev->cdi.class_id = ifc->b_interface_class; + ldev->cdi.subclass_id = ifc->b_interface_sub_class; + ldev->cdi.protocol_id = ifc->b_interface_protocol; + + ldev->dev = dev; + + ldev->endpoints = malloc(ldev->cdi.endpoint_count + * sizeof(ldev->endpoints[0])); + ldev->endpoints[0] = 0; // EP0 + ldev_ep_idx = 1; + } else { + ldev->cdi.endpoint_count += ifc->b_num_endpoints; + ldev->endpoints = realloc(ldev->endpoints, + ldev->cdi.endpoint_count + * sizeof(ldev->endpoints[0])); + } + + int j = 0; + while ((uintptr_t)next_desc(opaque_desc) <= desc_end && + j < (int)ifc->b_num_endpoints) + { + if (opaque_desc->b_descriptor_type == CDI_USB_DESC_ENDPOINT) { + j++; + ep = CDI_UPCAST(opaque_desc, + struct cdi_usb_endpoint_descriptor, base); + } else { + ep = NULL; + } + + opaque_desc = next_desc(opaque_desc); + if (!ep) { + continue; + } + + bool in = ep->b_endpoint_address & CDI_USB_EPDSC_EPADR_DIR; + int id = CDI_USB_EPDSC_EPADR_ID(ep->b_endpoint_address); + + dev->eps[in][id].ep = id; + dev->eps[in][id].mps + = CDI_USB_EPDSC_MPS_MPS(ep->w_max_packet_size); + dev->eps[in][id].desc = ep; + + switch (ep->bm_attributes & CDI_USB_EPDSC_ATTR_XFER_TYPE_MASK) { + case CDI_USB_EPDSC_ATTR_CONTROL: + dev->eps[in][id].type = CDI_USB_CONTROL; + break; + case CDI_USB_EPDSC_ATTR_ISOCHRONOUS: + dev->eps[in][id].type = CDI_USB_ISOCHRONOUS; + break; + case CDI_USB_EPDSC_ATTR_BULK: + dev->eps[in][id].type = CDI_USB_BULK; + break; + case CDI_USB_EPDSC_ATTR_INTERRUPT: + dev->eps[in][id].type = CDI_USB_INTERRUPT; + break; + } + + ldev->endpoints[ldev_ep_idx++] = ((int)in << 4) | id; + } + + // FIXME (should be a graceful failure) + assert(j == ifc->b_num_endpoints); + + if (interface_level) { + if (ldev->cdi.class_id == CDI_USB_DEVCLS_HUB) { + new_hub_device(ldev); + } else { + cdi_provide_device(&ldev->cdi.bus_data); + } + } + + ifc = (void *)opaque_desc; + } + + if (i < config->b_num_interfaces) { + printf("[usb] warning: failed to inquire all device interfaces\n"); + } + + if (!interface_level) { + if (ldev->cdi.class_id == CDI_USB_DEVCLS_HUB) { + new_hub_device(ldev); + } else { + cdi_provide_device(&ldev->cdi.bus_data); + } + } +} + + static void new_hub(usb_hub_t *hub) { for (int i = 0; i < hub->cdi->ports; i++) { @@ -458,41 +612,14 @@ static void new_hub(usb_hub_t *hub) debug_device(dev); #endif - usb_logical_device_t *ldev = NULL; - int ldev_ep_idx = 0; - bool interface_level; - - interface_level = dev->dev_desc.b_device_class == CDI_USB_DEVCLS_NONE; - if (!interface_level) { - ldev = calloc(1, sizeof(*ldev)); - ldev->cdi.bus_data.bus_type = CDI_USB; - ldev->cdi.interface = -1; - ldev->cdi.endpoint_count = 1; // EP0 - ldev->cdi.vendor_id = dev->dev_desc.id_vendor; - ldev->cdi.product_id = dev->dev_desc.id_product; - ldev->cdi.class_id = dev->dev_desc.b_device_class; - ldev->cdi.subclass_id = dev->dev_desc.b_device_sub_class; - ldev->cdi.protocol_id = dev->dev_desc.b_device_protocol; - - ldev->dev = dev; - - ldev->endpoints = malloc(1 * sizeof(ldev->endpoints[0])); - ldev->endpoints[0] = 0; // EP0 - ldev_ep_idx = 1; - } - if (get_configurations(dev) < 0) { printf("[usb] failed to get device configurations\n"); - free(ldev->endpoints); - free(ldev); free(dev); hub->drv->port_disable(hub->cdi, i); continue; } if (choose_configuration(dev) < 0) { printf("[usb] failed to select device configuration\n"); - free(ldev->endpoints); - free(ldev); for (int j = 0; j < (int)dev->dev_desc.b_num_configurations; j++) { free(dev->configs[j]); } @@ -506,79 +633,7 @@ static void new_hub(usb_hub_t *hub) debug_configuration(dev); #endif - struct cdi_usb_interface_descriptor *ifc = (void *)(dev->config + 1); - for (int j = 0; j < (int)dev->config->b_num_interfaces; j++) { - if (interface_level) { - ldev = calloc(1, sizeof(*ldev)); - ldev->cdi.bus_data.bus_type = CDI_USB; - ldev->cdi.interface = j; - // Include EP0 - ldev->cdi.endpoint_count = ifc->b_num_endpoints + 1; - ldev->cdi.vendor_id = dev->dev_desc.id_vendor; - ldev->cdi.product_id = dev->dev_desc.id_product; - ldev->cdi.class_id = ifc->b_interface_class; - ldev->cdi.subclass_id = ifc->b_interface_sub_class; - ldev->cdi.protocol_id = ifc->b_interface_protocol; - - ldev->dev = dev; - - ldev->endpoints = malloc(ldev->cdi.endpoint_count - * sizeof(ldev->endpoints[0])); - ldev->endpoints[0] = 0; // EP0 - ldev_ep_idx = 1; - } else { - ldev->cdi.endpoint_count += ifc->b_num_endpoints; - ldev->endpoints = realloc(ldev->endpoints, - ldev->cdi.endpoint_count - * sizeof(ldev->endpoints[0])); - } - - struct cdi_usb_endpoint_descriptor *ep = (void *)(ifc + 1); - for (int k = 0; k < (int)ifc->b_num_endpoints; k++, ep++) { - bool in = ep->b_endpoint_address & CDI_USB_EPDSC_EPADR_DIR; - int id = CDI_USB_EPDSC_EPADR_ID(ep->b_endpoint_address); - - dev->eps[in][id].ep = id; - dev->eps[in][id].mps - = CDI_USB_EPDSC_MPS_MPS(ep->w_max_packet_size); - dev->eps[in][id].desc = ep; - - switch (ep->bm_attributes & CDI_USB_EPDSC_ATTR_XFER_TYPE_MASK) { - case CDI_USB_EPDSC_ATTR_CONTROL: - dev->eps[in][id].type = CDI_USB_CONTROL; - break; - case CDI_USB_EPDSC_ATTR_ISOCHRONOUS: - dev->eps[in][id].type = CDI_USB_ISOCHRONOUS; - break; - case CDI_USB_EPDSC_ATTR_BULK: - dev->eps[in][id].type = CDI_USB_BULK; - break; - case CDI_USB_EPDSC_ATTR_INTERRUPT: - dev->eps[in][id].type = CDI_USB_INTERRUPT; - break; - } - - ldev->endpoints[ldev_ep_idx++] = ((int)in << 4) | id; - } - - if (interface_level) { - if (ldev->cdi.class_id == CDI_USB_DEVCLS_HUB) { - new_hub_device(ldev); - } else { - cdi_provide_device(&ldev->cdi.bus_data); - } - } - - ifc = (void *)ep; - } - - if (!interface_level) { - if (ldev->cdi.class_id == CDI_USB_DEVCLS_HUB) { - new_hub_device(ldev); - } else { - cdi_provide_device(&ldev->cdi.bus_data); - } - } + provide_virtual_devices(dev); } } -- 2.6.4 From max at tyndur.org Tue Dec 29 00:53:16 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 00:53:16 +0100 Subject: [cdi-devel] [PATCH 07/10] usb: Fix and simplify debugging code In-Reply-To: <1451346799-23335-1-git-send-email-max@tyndur.org> References: <1451346799-23335-1-git-send-email-max@tyndur.org> Message-ID: <1451346799-23335-8-git-send-email-max@tyndur.org> + emit_string_descriptor() makes debugging code simpler. (Incidentally, this fixes a bug in debug_configuration(); the upper limit of the for loop printing the interface name) ! Just as the main code, the debugging code assumed a certain order of descriptors with no gaps in between. Fix it. Signed-off-by: Max Reitz --- usb/usb.c | 81 +++++++++++++++++++++++++++++++++------------------------------ 1 file changed, 42 insertions(+), 39 deletions(-) diff --git a/usb/usb.c b/usb/usb.c index a8366e0..374ba57 100644 --- a/usb/usb.c +++ b/usb/usb.c @@ -333,6 +333,25 @@ static int choose_configuration(usb_device_t *dev) #ifdef DEBUG +static void emit_string_descriptor(usb_device_t *dev, const char *format, int desc_i) +{ + if (!desc_i) { + return; + } + + struct cdi_usb_string_descriptor str_desc; + get_string_descriptor(dev, desc_i, &str_desc); + int str_length = (str_desc.base.b_length - 2) / 2; + char str[str_length + 1]; + + for (int i = 0; i < str_length; i++) { + str[i] = str_desc.b_string[i] > 0x7f ? '?' : str_desc.b_string[i]; + } + str[str_length] = 0; + + printf(format, str); +} + static void debug_device(usb_device_t *dev) { printf("[usb] new %s device %04x:%04x (%x.%x.%x) ", @@ -346,60 +365,44 @@ static void debug_device(usb_device_t *dev) dev->dev_desc.b_device_sub_class, dev->dev_desc.b_device_protocol); - struct cdi_usb_string_descriptor str; - - if (dev->dev_desc.i_manufacturer) { - get_string_descriptor(dev, dev->dev_desc.i_manufacturer, &str); - for (int i = 0; i < (str.base.b_length - 2) / 2; i++) { - putchar(str.b_string[i] > 0x7f ? '?' : str.b_string[i]); - } - putchar(' '); - } - - if (dev->dev_desc.i_product) { - get_string_descriptor(dev, dev->dev_desc.i_product, &str); - for (int i = 0; i < (str.base.b_length - 2) / 2; i++) { - putchar(str.b_string[i] > 0x7f ? '?' : str.b_string[i]); - } - putchar(' '); - } + emit_string_descriptor(dev, "%s ", dev->dev_desc.i_manufacturer); + emit_string_descriptor(dev, "%s ", dev->dev_desc.i_product); putchar('\n'); } +static struct cdi_usb_descriptor *next_desc(struct cdi_usb_descriptor *desc); + static void debug_configuration(usb_device_t *dev) { printf("[usb] chose configuration %i ", dev->config->b_configuration_value); + emit_string_descriptor(dev, "(%s) ", dev->config->i_configuration); + printf("with %i interface(s):\n", dev->config->b_num_interfaces); - struct cdi_usb_string_descriptor str; + uintptr_t desc_end = (uintptr_t)dev->config + dev->config->w_total_length; - if (dev->config->i_configuration) { - get_string_descriptor(dev, dev->config->i_configuration, &str); - putchar('('); - for (int i = 0; i < (str.base.b_length - 2) / 2; i++) { - putchar(str.b_string[i] > 0x7f ? '?' : str.b_string[i]); + struct cdi_usb_descriptor *opaque_desc = next_desc(&dev->config->base); + int i = 0; + while ((uintptr_t)next_desc(opaque_desc) <= desc_end && + i < (int)dev->config->b_num_interfaces) + { + struct cdi_usb_interface_descriptor *ifc = NULL; + + if (opaque_desc->b_descriptor_type == CDI_USB_DESC_INTERFACE) { + i++; + ifc = CDI_UPCAST(opaque_desc, + struct cdi_usb_interface_descriptor, base); } - putchar(')'); - putchar(' '); - } - printf("with %i interface(s):\n", dev->config->b_num_interfaces); + opaque_desc = next_desc(opaque_desc); + if (!ifc) { + continue; + } - struct cdi_usb_interface_descriptor *ifc = (void *)(dev->config + 1); - for (int i = 0; i < (int)dev->config->b_num_interfaces; i++) { printf("[usb] "); - if (ifc->i_interface) { - get_string_descriptor(dev, ifc->i_interface, &str); - for (int j = 0; j < (int)dev->config->b_num_interfaces; j++) { - putchar(str.b_string[j] > 0x7f ? '?' : str.b_string[j]); - } - putchar(' '); - } + emit_string_descriptor(dev, "%s ", ifc->i_interface); printf("%x.%x.%x\n", ifc->b_interface_class, ifc->b_interface_sub_class, ifc->b_interface_protocol); - - ifc = (void *)((struct cdi_usb_endpoint_descriptor *)(ifc + 1) - + ifc->b_num_endpoints); } } #endif -- 2.6.4 From max at tyndur.org Tue Dec 29 00:53:17 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 00:53:17 +0100 Subject: [cdi-devel] [PATCH 08/10] usb: Clear ENDPOINT_HALT on stalling bulk transfer In-Reply-To: <1451346799-23335-1-git-send-email-max@tyndur.org> References: <1451346799-23335-1-git-send-email-max@tyndur.org> Message-ID: <1451346799-23335-9-git-send-email-max@tyndur.org> + If a bulk transfer stalled, it is a good idea to clear the ENDPOINT_HALT feature for the endpoint in question. (We generally do not need this for control transfers, because while they may return a STALL, they should not actually stall (that is, the ENDPOINT_HALT feature will not be set; this is what the USB specification recommends). Also, all of our control transfers currently go to EP 0 which really, really should not get halted. If it is, the device is pretty broken (you need EP 0 to clear the ENDPOINT_HALT feature).) (We will not really need this for interrupt transfers, just because it is more unlikely for them to stall than for bulk transfers.) Signed-off-by: Max Reitz --- include/cdi/usb-structures.h | 8 ++++++++ usb/usb.c | 10 ++++++++++ 2 files changed, 18 insertions(+) diff --git a/include/cdi/usb-structures.h b/include/cdi/usb-structures.h index f894b9e..45b0d98 100644 --- a/include/cdi/usb-structures.h +++ b/include/cdi/usb-structures.h @@ -130,6 +130,14 @@ enum { CDI_USB_CREQ_SYNCH_FRAME = 12, }; +/// Feature selectors for ClearFeature() and SetFeature() +/// (cdi_usb_setup_packet.w_value) +enum { + CDI_USB_FEATURE_ENDPOINT_HALT = 0, + CDI_USB_FEATURE_DEVICE_REMOTE_WAKEUP = 1, + CDI_USB_FEATURE_TEST_MODE = 2, +}; + /// Descriptor IDs enum { CDI_USB_DESC_DEVICE = 1, diff --git a/usb/usb.c b/usb/usb.c index 374ba57..4e1dacc 100644 --- a/usb/usb.c +++ b/usb/usb.c @@ -755,6 +755,16 @@ cdi_usb_transmission_result_t usb_bulk_transfer(struct cdi_usb_device *dev, hcd->wait_transaction(ldev->dev->hc, ta); hcd->destroy_transaction(ldev->dev->hc, ta); + if (res == CDI_USB_STALL) { + usb_control_transfer(dev, 0, &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_ENDPOINT + | CDI_USB_CREQ_OUT, + .b_request = CDI_USB_CREQ_CLEAR_FEATURE, + .w_value = CDI_USB_FEATURE_ENDPOINT_HALT, + .w_index = ep + }, NULL); + } + return res; } -- 2.6.4 From max at tyndur.org Tue Dec 29 00:53:18 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 00:53:18 +0100 Subject: [cdi-devel] [PATCH 09/10] usb-storage: Drop bulk_only_reset()'s return value In-Reply-To: <1451346799-23335-1-git-send-email-max@tyndur.org> References: <1451346799-23335-1-git-send-email-max@tyndur.org> Message-ID: <1451346799-23335-10-git-send-email-max@tyndur.org> ! Not all USB drives support a bulk-only reset, and if one does not, this is definitely not a fatal error which would justify aborting device initialization. Signed-off-by: Max Reitz --- usb-storage/usb-storage.c | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/usb-storage/usb-storage.c b/usb-storage/usb-storage.c index 544c779..7efe5c3 100644 --- a/usb-storage/usb-storage.c +++ b/usb-storage/usb-storage.c @@ -75,22 +75,21 @@ typedef struct usb_mass_storage_device { } usb_mass_storage_device_t; -static int bulk_only_reset(usb_mass_storage_device_t *dev) +static void bulk_only_reset(usb_mass_storage_device_t *dev) { cdi_usb_transmission_result_t res; - res = cdi_usb_control_transfer(&dev->usb, 0, &(struct cdi_usb_setup_packet){ + // Do not check for success; this function does not need to be supported, + // and if it is not, there is not a whole lot we can do about it. + cdi_usb_control_transfer(&dev->usb, 0, &(struct cdi_usb_setup_packet){ .bm_request_type = CDI_USB_CREQ_CLASS | CDI_USB_CREQ_INTERFACE | CDI_USB_CREQ_OUT, .b_request = USBMS_REQ_BOMSR, .w_index = dev->usb.interface }, NULL); - if (res != CDI_USB_OK) { - return -EIO; - } if (dev->luns > 0) { - return 0; + return; } uint8_t lun_count; @@ -106,8 +105,6 @@ static int bulk_only_reset(usb_mass_storage_device_t *dev) } else { dev->luns = 1; } - - return 0; } @@ -128,10 +125,7 @@ struct cdi_device *init_usb_device(struct cdi_bus_data *bus_data) } if (dev->type == USBMS_BULK_ONLY) { - if (bulk_only_reset(dev) < 0) { - free(dev); - return NULL; - } + bulk_only_reset(dev); struct cdi_usb_endpoint_descriptor ep_desc; for (int ep = 1; ep < dev->usb.endpoint_count; ep++) { -- 2.6.4 From max at tyndur.org Tue Dec 29 00:53:19 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 00:53:19 +0100 Subject: [cdi-devel] [PATCH 10/10] ehci: Use __attribute__((aligned())) In-Reply-To: <1451346799-23335-1-git-send-email-max@tyndur.org> References: <1451346799-23335-1-git-send-email-max@tyndur.org> Message-ID: <1451346799-23335-11-git-send-email-max@tyndur.org> * Using that attribute is a bit nicer than trying to do the alignment manually. It will blow up the QH size to 256 bytes, but we can probably live with that. * Use the same attribute for fat QHs and qTDs; we will need this (at least for QHs) when creating an array of QHs/qTDs so that they are properly aligned. Signed-off-by: Max Reitz --- ehci/ehci.h | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/ehci/ehci.h b/ehci/ehci.h index d37f141..fb8dd9e 100644 --- a/ehci/ehci.h +++ b/ehci/ehci.h @@ -23,6 +23,7 @@ #ifndef EHCI_H #define EHCI_H +#include #include #include @@ -62,43 +63,40 @@ struct ehci_qtd { // 64-bit structures uint32_t ext_buffer[5]; -} __attribute__((packed)); +} __attribute__((packed, aligned(128))); + +static_assert(!(sizeof(struct ehci_qtd) % 128), + "sizeof(ehci_qtd) must be a multiple of 128"); struct ehci_qh { uint32_t next_qh; uint32_t ep_state[2]; uint32_t current_qtd; struct ehci_qtd overlay; -} __attribute__((packed)); +} __attribute__((packed, aligned(128))); + +static_assert(!(sizeof(struct ehci_qh) % 128), + "sizeof(ehci_qh) must be a multiple of 128"); typedef struct ehci_fat_qh ehci_fat_qh_t; typedef struct ehci_fat_qtd ehci_fat_qtd_t; -#define DIFF_TO_MULTIPLE(value, divisor) \ - ((divisor) - ((((value) + (divisor) - 1) % (divisor)) + 1)) - struct ehci_fat_qh { volatile struct ehci_qh qh; - // Align the QH to 128 bytes (something with cache lines?). Otherwise, - // there may be conflicts between data we are writing to our very own - // fields provided by ehci_fat_qh_t and writes done by the HC to this - // structure. - uint8_t alignment[DIFF_TO_MULTIPLE(sizeof(struct ehci_qh), 128)]; - struct cdi_mem_area *cdi_mem_area; uintptr_t paddr; ehci_fat_qh_t *next, *previous; ehci_fat_qtd_t *first_qtd, *last_qtd; -}; +} __attribute__((aligned(64))); + +static_assert(!(sizeof(struct ehci_fat_qh) % 64), + "sizeof(ehci_fat_qh) must be a multiple of 64"); struct ehci_fat_qtd { volatile struct ehci_qtd qtd; - // Align the qTD to a multiple of 128 bytes. - uint8_t alignment[DIFF_TO_MULTIPLE(sizeof(struct ehci_qtd), 128)]; - struct cdi_mem_area *cdi_mem_area; uintptr_t paddr; @@ -111,7 +109,10 @@ struct ehci_fat_qtd { size_t write_back_size; cdi_usb_transmission_result_t *result; -}; +} __attribute__((aligned(64))); + +static_assert(!(sizeof(struct ehci_fat_qtd) % 64), + "sizeof(ehci_fat_qtd) must be a multiple of 64"); struct ehci { struct cdi_usb_hc hc; -- 2.6.4 From max at tyndur.org Tue Dec 29 01:00:49 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 01:00:49 +0100 Subject: [cdi-devel] [PATCH 0/5] usb: HID Message-ID: <1451347254-25755-1-git-send-email-max@tyndur.org> This series adds the CDI.hid interface, specifies an interrupt transfer interface for CDI.usb, implements this interface in ehci and usb, and adds a usb-hid driver for keyboards. Note that the CDI.hid interface does not encompass all kinds of HID devices (yet), but it is intended to be able to represent keyboards, mice and gamepads/joysticks. This series depends on my "usb: Some fixes" series. Max Reitz (5): usb: Extend interface for interrupt transfers ehci: Implement interrupt transfers usb: Implement interrupt transfers hid: Specify interface usb-hid: Add driver ehci/ehci.c | 265 ++++++++++++++++++++++++++++++++++++++++++--- ehci/ehci.h | 20 ++++ ehci/main.c | 11 +- include/cdi-osdep.h | 20 ++++ include/cdi.h | 1 + include/cdi/hid-keycodes.h | 262 ++++++++++++++++++++++++++++++++++++++++++++ include/cdi/hid-ledcodes.h | 85 +++++++++++++++ include/cdi/hid.h | 113 +++++++++++++++++++ include/cdi/usb.h | 57 ++++++++++ include/cdi/usb_hcd.h | 29 ++++- usb-hid/main.c | 74 +++++++++++++ usb-hid/usb-hid.c | 153 ++++++++++++++++++++++++++ usb-hid/usb-hid.h | 54 +++++++++ usb/main.c | 2 + usb/usb.c | 89 +++++++++++++++ usb/usb.h | 13 +++ 16 files changed, 1229 insertions(+), 19 deletions(-) create mode 100644 include/cdi/hid-keycodes.h create mode 100644 include/cdi/hid-ledcodes.h create mode 100644 include/cdi/hid.h create mode 100644 usb-hid/main.c create mode 100644 usb-hid/usb-hid.c create mode 100644 usb-hid/usb-hid.h -- 2.6.4 From max at tyndur.org Tue Dec 29 01:00:50 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 01:00:50 +0100 Subject: [cdi-devel] [PATCH 1/5] usb: Extend interface for interrupt transfers In-Reply-To: <1451347254-25755-1-git-send-email-max@tyndur.org> References: <1451347254-25755-1-git-send-email-max@tyndur.org> Message-ID: <1451347254-25755-2-git-send-email-max@tyndur.org> + Add a way to make the HCD start transactions as interrupt transfers + Add a way to make the bus driver start an interrupt transfer + Add a way to make the bus driver cancel and destroy and asynchronous transmission (such as an interrupt transfer) Signed-off-by: Max Reitz --- include/cdi/usb.h | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++ include/cdi/usb_hcd.h | 29 +++++++++++++++++++++++++- 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/include/cdi/usb.h b/include/cdi/usb.h index c7fa751..894be0d 100644 --- a/include/cdi/usb.h +++ b/include/cdi/usb.h @@ -51,6 +51,21 @@ typedef uint32_t cdi_usb_port_status_t; #define CDI_USB_PORT_SPEED_MASK (0x7) #define CDI_USB_PORT_CONNECTED (1 << 3) +/** + * Callback function pointer type for asynchronous transmissions. + */ +typedef void (*cdi_usb_async_cb_t)(void* opaque); + +/** + * Callback function pointer type for interrupt transfers. + */ +typedef cdi_usb_async_cb_t cdi_usb_interrupt_cb_t; + +/** + * Type of asynchronous transmissions. + */ +typedef void* cdi_usb_async_transmission_t; + struct cdi_usb_hub; /** @@ -158,6 +173,27 @@ struct cdi_usb_driver { cdi_usb_transmission_result_t (*bulk_transfer)(struct cdi_usb_device* dev, int ep, void* data, size_t size); + + /** + * Enqueues an interrupt transfer to endpoint @ep (0 up until + * dev->endpoint_count - 1) of device @dev, trying to transfer @size bytes + * to @data every polling interval as specified by the given endpoint's + * descriptor. Each time a transfer is successful, the @cb is invoked. + * + * This function will return immediately. Use destroy_async_transfer() + * to dequeue and release its resources. + * + * Returns NULL on error. + */ + cdi_usb_async_transmission_t + (*interrupt_transfer)(struct cdi_usb_device* dev, int ep, + void* data, size_t size, + cdi_usb_interrupt_cb_t cb, void* opaque); + + /** + * Cancels the given asynchronous transmission and releases its resources. + */ + void (*destroy_async_transfer)(cdi_usb_async_transmission_t transmission); }; /** @@ -212,6 +248,27 @@ cdi_usb_transmission_result_t cdi_usb_bulk_transfer(struct cdi_usb_device* dev, int ep, void* data, size_t size); +/** + * Enqueues an interrupt transfer to endpoint @ep (0 up until + * dev->endpoint_count - 1) of device @dev, trying to transfer @size bytes to + * @data every polling interval as specified by the given endpoint's descriptor. + * Each time a transfer is successful, the @cb is invoked. + * + * This function will return immediately. Use destroy_async_transfer() to + * dequeue and release its resources. + * + * Returns NULL on error. + */ +cdi_usb_async_transmission_t + cdi_usb_interrupt_transfer(struct cdi_usb_device* dev, int ep, + void* data, size_t size, + cdi_usb_interrupt_cb_t cb, void* opaque); + +/** + * Cancels the given asynchronous transmission and releases its resources. + */ +void cdi_usb_destroy_async_transfer(cdi_usb_async_transmission_t transmission); + #ifdef __cplusplus }; // extern "C" #endif diff --git a/include/cdi/usb_hcd.h b/include/cdi/usb_hcd.h index 842ae73..37f0400 100644 --- a/include/cdi/usb_hcd.h +++ b/include/cdi/usb_hcd.h @@ -20,6 +20,11 @@ */ typedef void* cdi_usb_hc_transaction_t; +/** + * Callback function pointer type for interrupt transactions. + */ +typedef void (*cdi_usb_hc_interrupt_cb_t)(void* opaque); + typedef enum { CDI_USB_IN, CDI_USB_OUT, @@ -139,7 +144,7 @@ struct cdi_usb_hcd { const struct cdi_usb_hc_transmission* trans); /** - * Starts asynchronous execution of a transaction. + * Starts asynchronous execution of a control or bulk transaction. */ void (*start_transaction)(struct cdi_usb_hc* hc, cdi_usb_hc_transaction_t ta); @@ -155,6 +160,28 @@ struct cdi_usb_hcd { cdi_usb_hc_transaction_t ta); /** + * Starts periodic execution of an interrupt transaction. + * + * The unit of @interval depends on the transmission speed. For low and + * full speed devices, it is one frame (= 1 ms); for high speed devices, it + * is one microframe (= 1/8 ms). + * + * @interval must be a positive power of two. Depending on the host + * controller, there may be an upper limit; values greater than that limit + * will be capped accordingly. + * + * Whenever data is received, the @cb is invoked. + * + * All transmissions enqueued in this transaction must be CDI_USB_IN + * transmissions. + */ + void (*start_interrupt_transaction)(struct cdi_usb_hc* hc, + cdi_usb_hc_transaction_t ta, + int interval, + cdi_usb_hc_interrupt_cb_t cb, + void* cb_opaque); + + /** * Destroys a transaction. Transmissions which have not been waited on may * or may not have been executed by the time this function returns. The * values of the variables pointed to by the @result field of unwaited-for -- 2.6.4 From max at tyndur.org Tue Dec 29 01:00:51 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 01:00:51 +0100 Subject: [cdi-devel] [PATCH 2/5] ehci: Implement interrupt transfers In-Reply-To: <1451347254-25755-1-git-send-email-max@tyndur.org> References: <1451347254-25755-1-git-send-email-max@tyndur.org> Message-ID: <1451347254-25755-3-git-send-email-max@tyndur.org> Signed-off-by: Max Reitz --- ehci/ehci.c | 265 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- ehci/ehci.h | 20 +++++ ehci/main.c | 11 +-- 3 files changed, 278 insertions(+), 18 deletions(-) diff --git a/ehci/ehci.c b/ehci/ehci.c index addec00..4b548ae 100644 --- a/ehci/ehci.c +++ b/ehci/ehci.c @@ -40,6 +40,13 @@ static void bios_handoff(struct cdi_pci_device *pci_dev, struct ehci *hc); static void irq_handler(struct cdi_device *dev); +static void init_periodic_pseudo_qhs(struct ehci *hc); + + +static inline bool is_power_of_two(unsigned value) +{ + return !(value & (value - 1)); +} struct cdi_device *ehci_init_device(struct cdi_bus_data *bus_data) @@ -111,6 +118,18 @@ struct cdi_device *ehci_init_device(struct cdi_bus_data *bus_data) } hc->regs->periodiclistbase = hc->periodic_list_mem->paddr.items[0].start; + hc->periodic_qhs = calloc(1024, sizeof(*hc->periodic_qhs)); + // 10 = |0..10| = |ld(1)..ld(1024)| + hc->periodic_pseudo_qhs_mem = + cdi_mem_alloc(11 * sizeof(hc->periodic_pseudo_qhs[0]), + 6 + | CDI_MEM_PHYS_CONTIGUOUS + | CDI_MEM_DMA_4G + | CDI_MEM_NOINIT); + hc->periodic_pseudo_qhs = hc->periodic_pseudo_qhs_mem->vaddr; + + init_periodic_pseudo_qhs(hc); + // Create anchor struct cdi_mem_area *anchor_qh; anchor_qh = cdi_mem_alloc(sizeof(ehci_fat_qh_t), 6 @@ -157,8 +176,8 @@ struct cdi_device *ehci_init_device(struct cdi_bus_data *bus_data) cdi_register_irq(pci_dev->irq, &irq_handler, &hc->hc.dev); - // async advance doorbell - hc->regs->usbintr = EHCI_INT_IAA; + // async advance doorbell, USB interrupt + hc->regs->usbintr = EHCI_INT_IAA | EHCI_INT_USBINT; // Route everything to this HC hc->regs->configflag |= EHCI_CF_CF; @@ -181,6 +200,10 @@ fail: if (hc->periodic_list_mem) { cdi_mem_free(hc->periodic_list_mem); } + free(hc->periodic_qhs); + if (hc->periodic_pseudo_qhs_mem) { + cdi_mem_free(hc->periodic_pseudo_qhs_mem); + } cdi_list_destroy(hc->retired_qhs); free((void *)hc->hc.dev.name); free(hc); @@ -223,6 +246,8 @@ static void bios_handoff(struct cdi_pci_device *pci_dev, struct ehci *hc) } +static void qtd_write_back(ehci_fat_qtd_t *qtd); + static void irq_handler(struct cdi_device *dev) { struct cdi_usb_hc *cdi_hc = CDI_UPCAST(dev, struct cdi_usb_hc, dev); @@ -231,14 +256,108 @@ static void irq_handler(struct cdi_device *dev) uint32_t usbsts = hc->regs->usbsts; hc->regs->usbsts = usbsts; - // async advance doorbell - if (!(usbsts & EHCI_STS_IAA)) { - return; + if (usbsts & EHCI_STS_IAA) { + // async advance doorbell + + ehci_fat_qh_t *rqh; + while ((rqh = cdi_list_pop(hc->retired_qhs))) { + cdi_mem_free(rqh->cdi_mem_area); + } } - ehci_fat_qh_t *rqh; - while ((rqh = cdi_list_pop(hc->retired_qhs))) { - cdi_mem_free(rqh->cdi_mem_area); + if (usbsts & EHCI_STS_USBINT) { + // IOC qTD retired + + for (ehci_fat_qh_t *qh = hc->periodic_functional_qhs; qh; + qh = qh->next_periodic) + { + if (qh->qh.overlay.status & EHCI_QTDS_ACTIVE) { + continue; + } + + bool error = false; + + for (ehci_fat_qtd_t *qtd = qh->first_qtd; qtd; qtd = qtd->next) { + assert((qtd->qtd.status & EHCI_QTDS_PID_MASK) == + EHCI_QTDS_PID_IN); + + error = error || (qtd->qtd.status & EHCI_QTDS_HALTED); + if (!error) { + qtd_write_back(qtd); + } + qtd->qtd.buffers[0] &= ~0xfffu; + qtd->qtd.status &= ~0x7fu; // clear errors + qtd->qtd.status |= EHCI_QTDS_XFLEN(qtd->write_back_size) + | EHCI_QTDS_IOC + | EHCI_QTDS_CP(0) + | EHCI_QTDS_CERR(3) + | EHCI_QTDS_PID_IN + | EHCI_QTDS_ACTIVE; + } + + if (!error) { + qh->cb(qh->cb_opaque); + } + + // Reactivate the QH + qh->qh.overlay.next_qtd = qh->first_qtd->paddr; + qh->qh.overlay.alt_next_qtd = qh->first_qtd->paddr; + qh->qh.overlay.status &= ~0x7fu; // clear errors + } + } +} + + +static void init_periodic_pseudo_qhs(struct ehci *hc) +{ + for (int e = 0; e < 11; e++) { + ehci_fat_qh_t *qh = &hc->periodic_pseudo_qhs[e]; + int interval = 1 << e; + + memset(qh, 0, sizeof(*qh)); + + qh->is_pseudo_qh = true; + + qh->paddr = hc->periodic_pseudo_qhs_mem->paddr.items[0].start + + e * sizeof(*qh); + + qh->qh.ep_state[0] = EHCI_QHES0_RL(0) + | EHCI_QHES0_MPL(0) + | EHCI_QHES0_DTC + | EHCI_QHES0_EP(0) + | EHCI_QHES0_DEV(0) + | EHCI_QHES0_EPS_HS; + qh->qh.ep_state[1] = EHCI_QHES1_MULT(1) + | EHCI_QHES1_PORT(0) + | EHCI_QHES1_HUB(0) + | EHCI_QHES1_SCM(0xff) + | EHCI_QHES1_ISM(0x01); + + qh->qh.overlay.next_qtd = EHCI_T; + qh->qh.overlay.alt_next_qtd = EHCI_T; + qh->qh.overlay.status = EHCI_QTDS_HALTED; + + + // EHCI specification, 4.6: "Interrupt queue heads are linked into the + // frame list ordered by poll rate. Longer poll rates are linked first + // [...]." + // Therefore, link from high exponents (intervals) to lower ones. + + if (e > 0) { + qh->qh.next_qh = hc->periodic_pseudo_qhs[e - 1].paddr | EHCI_QH; + qh->next = &hc->periodic_pseudo_qhs[e - 1]; + } else { + qh->qh.next_qh = EHCI_T; + } + + if (e < 10) { + qh->previous = &hc->periodic_pseudo_qhs[e + 1]; + } + + for (int i = 0; i < 1024; i += interval) { + hc->periodic_list[i] = qh->paddr | EHCI_QH; + hc->periodic_qhs[i] = qh; + } } } @@ -323,7 +442,28 @@ static void enter_async_qh(struct ehci *hc, ehci_fat_qh_t *qh) } -static void retire_qh(struct ehci *hc, ehci_fat_qh_t *qh) +static void enter_interrupt_qh(struct ehci *hc, ehci_fat_qh_t *qh, + int frame_interval_shift) +{ + qh->next = hc->periodic_functional_qhs; + hc->periodic_functional_qhs = qh; + + ehci_fat_qh_t *pseudo_qh = &hc->periodic_pseudo_qhs[frame_interval_shift]; + + qh->next = pseudo_qh->next; + qh->previous = pseudo_qh; + + pseudo_qh->next = qh; + if (qh->next) { + qh->next->previous = qh; + } + + qh->qh.next_qh = pseudo_qh->qh.next_qh; + pseudo_qh->qh.next_qh = qh->paddr | EHCI_QH; +} + + +static void retire_async_qh(struct ehci *hc, ehci_fat_qh_t *qh) { qh->previous->qh.next_qh = qh->qh.next_qh; @@ -336,11 +476,29 @@ static void retire_qh(struct ehci *hc, ehci_fat_qh_t *qh) } -static void retire_first_qtd(ehci_fat_qh_t *qh) +static void retire_periodic_qh(struct ehci *hc, ehci_fat_qh_t *qh) { - ehci_fat_qtd_t *qtd = qh->first_qtd; + qh->previous->qh.next_qh = qh->qh.next_qh; - assert(qtd); + qh->previous->next = qh->next; + if (qh->next) { + qh->next->previous = qh->previous; + } + + ehci_fat_qh_t **func_periodic_ptr = &hc->periodic_functional_qhs; + while (*func_periodic_ptr && *func_periodic_ptr != qh) { + func_periodic_ptr = &(*func_periodic_ptr)->next_periodic; + } + assert(*func_periodic_ptr == qh); + *func_periodic_ptr = qh->next_periodic; + + cdi_list_push(hc->retired_qhs, qh); +} + + +static void qtd_write_back(ehci_fat_qtd_t *qtd) +{ + ehci_fat_qh_t *qh = qtd->qh; uint32_t err_mask = (qh->qh.ep_state[0] & EHCI_QHES0_EPS_MASK) == EHCI_QHES0_EPS_HS @@ -371,6 +529,16 @@ static void retire_first_qtd(ehci_fat_qh_t *qh) } assert(!rem); } +} + + +static void retire_first_qtd(ehci_fat_qh_t *qh) +{ + ehci_fat_qtd_t *qtd = qh->first_qtd; + + assert(qtd); + + qtd_write_back(qtd); qh->first_qtd = qtd->next; if (qh->last_qtd == qtd) { @@ -561,6 +729,73 @@ void ehci_start_transaction(struct cdi_usb_hc *cdi_hc, } +void ehci_start_interrupt_transaction(struct cdi_usb_hc *cdi_hc, + cdi_usb_hc_transaction_t ta, + int interval, + cdi_usb_hc_interrupt_cb_t cb, + void *cb_opaque) +{ + struct ehci *hc = CDI_UPCAST(cdi_hc, struct ehci, hc); + ehci_fat_qh_t *qh = ta; + + // Set IOC for all qTDs + for (ehci_fat_qtd_t *qtd = qh->first_qtd; qtd; qtd = qtd->next) { + qtd->qtd.status |= EHCI_QTDS_IOC; + } + + assert(interval > 0 && is_power_of_two(interval)); + + assert(cb); + qh->cb = cb; + qh->cb_opaque = cb_opaque; + + if (interval > 1024 * 8) { + interval = 1024 * 8; + } + + // Moving the microframe index along looks like an easy way of balancing the + // periodic load a bit. + int start_microframe = hc->periodic_start_microframe; + hc->periodic_start_microframe = (hc->periodic_start_microframe + 1) % 8; + + bool split = + (qh->qh.ep_state[0] & EHCI_QHES0_EPS_MASK) != EHCI_QHES0_EPS_HS; + + if (split) { + // If split transactions start in the latter four microframes of a + // frame, their management is more difficult. Therefore, just limit it + // to the first four microframes. + start_microframe %= 4; + } + + int s_mask = 0; + + for (int microframe = start_microframe; microframe < start_microframe + 8; + microframe += interval) + { + s_mask |= 1 << (microframe % 8); + } + + assert(!(qh->qh.ep_state[1] & EHCI_QHES1_ISM(0xff))); + qh->qh.ep_state[1] |= EHCI_QHES1_ISM(s_mask); + + if (split) { + // Don't just issue complete split requests all over the place, but only + // when we actually should do so (3 requests starting 2 microframes + // after the start split request) + qh->qh.ep_state[1] &= ~EHCI_QHES1_SCM(0xff); + qh->qh.ep_state[1] |= EHCI_QHES1_SCM(7 << (start_microframe + 2)); + } + + int frame_interval_shift = __builtin_ctz(interval) - 3; + if (frame_interval_shift < 0) { + frame_interval_shift = 0; + } + + enter_interrupt_qh(hc, qh, frame_interval_shift); +} + + void ehci_wait_transaction(struct cdi_usb_hc *cdi_hc, cdi_usb_hc_transaction_t ta) { @@ -639,5 +874,9 @@ void ehci_destroy_transaction(struct cdi_usb_hc *cdi_hc, while (qh->first_qtd) { retire_first_qtd(qh); } - retire_qh(hc, qh); + if (qh->cb) { + retire_periodic_qh(hc, qh); + } else { + retire_async_qh(hc, qh); + } } diff --git a/ehci/ehci.h b/ehci/ehci.h index fb8dd9e..4b55391 100644 --- a/ehci/ehci.h +++ b/ehci/ehci.h @@ -87,8 +87,14 @@ struct ehci_fat_qh { struct cdi_mem_area *cdi_mem_area; uintptr_t paddr; + cdi_usb_hc_interrupt_cb_t cb; + void *cb_opaque; + ehci_fat_qh_t *next, *previous; + ehci_fat_qh_t *next_periodic; ehci_fat_qtd_t *first_qtd, *last_qtd; + + bool is_pseudo_qh; } __attribute__((aligned(64))); static_assert(!(sizeof(struct ehci_fat_qh) % 64), @@ -122,9 +128,17 @@ struct ehci { struct cdi_mem_area *periodic_list_mem; volatile uint32_t *periodic_list; + ehci_fat_qh_t **periodic_qhs; + + struct cdi_mem_area *periodic_pseudo_qhs_mem; + ehci_fat_qh_t *periodic_pseudo_qhs; + ehci_fat_qh_t *periodic_functional_qhs; ehci_fat_qh_t *async_start; cdi_list_t retired_qhs; + + // For a bit of load balancing + int periodic_start_microframe; }; #define PCI_CLASS_SERIAL_BUS_CONTROLLER 0x0c @@ -254,6 +268,7 @@ struct ehci { #define EHCI_QTDS_PID_OUT (0 << 8) // PID: OUT #define EHCI_QTDS_PID_IN (1 << 8) // PID: IN #define EHCI_QTDS_PID_SETUP (2 << 8) // PID: SETUP +#define EHCI_QTDS_PID_MASK (3 << 8) // PID mask #define EHCI_QTDS_ACTIVE (1 << 7) // Status: Active #define EHCI_QTDS_HALTED (1 << 6) // Status: Halted #define EHCI_QTDS_BUFERR (1 << 5) // Status: Data Buffer Error @@ -287,6 +302,11 @@ void ehci_enqueue(struct cdi_usb_hc *hc, void ehci_start_transaction(struct cdi_usb_hc *cdi_hc, cdi_usb_hc_transaction_t ta); void ehci_wait_transaction(struct cdi_usb_hc *hc, cdi_usb_hc_transaction_t ta); +void ehci_start_interrupt_transaction(struct cdi_usb_hc *hc, + cdi_usb_hc_transaction_t ta, + int interval, + cdi_usb_hc_interrupt_cb_t cb, + void *cb_opaque); void ehci_destroy_transaction(struct cdi_usb_hc *hc, cdi_usb_hc_transaction_t ta); diff --git a/ehci/main.c b/ehci/main.c index 5623819..97974ac 100644 --- a/ehci/main.c +++ b/ehci/main.c @@ -59,11 +59,12 @@ static struct cdi_usb_hcd ehcd = { .port_status = ehci_rh_port_status, }, - .create_transaction = ehci_create_transaction, - .enqueue = ehci_enqueue, - .start_transaction = ehci_start_transaction, - .wait_transaction = ehci_wait_transaction, - .destroy_transaction = ehci_destroy_transaction, + .create_transaction = ehci_create_transaction, + .enqueue = ehci_enqueue, + .start_transaction = ehci_start_transaction, + .wait_transaction = ehci_wait_transaction, + .start_interrupt_transaction = ehci_start_interrupt_transaction, + .destroy_transaction = ehci_destroy_transaction, }; CDI_DRIVER(DRIVER_NAME, ehcd) -- 2.6.4 From max at tyndur.org Tue Dec 29 01:00:52 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 01:00:52 +0100 Subject: [cdi-devel] [PATCH 3/5] usb: Implement interrupt transfers In-Reply-To: <1451347254-25755-1-git-send-email-max@tyndur.org> References: <1451347254-25755-1-git-send-email-max@tyndur.org> Message-ID: <1451347254-25755-4-git-send-email-max@tyndur.org> Signed-off-by: Max Reitz --- usb/main.c | 2 ++ usb/usb.c | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ usb/usb.h | 13 +++++++++ 3 files changed, 104 insertions(+) diff --git a/usb/main.c b/usb/main.c index 3add372..30d3716 100644 --- a/usb/main.c +++ b/usb/main.c @@ -56,6 +56,8 @@ static struct cdi_usb_driver usbd = { .get_endpoint_descriptor = usb_get_endpoint_descriptor, .control_transfer = usb_control_transfer, .bulk_transfer = usb_bulk_transfer, + .interrupt_transfer = usb_interrupt_transfer, + .destroy_async_transfer = usb_destroy_async_transfer, }; CDI_DRIVER(DRIVER_NAME, usbd) diff --git a/usb/usb.c b/usb/usb.c index 4e1dacc..87db9f9 100644 --- a/usb/usb.c +++ b/usb/usb.c @@ -769,6 +769,95 @@ cdi_usb_transmission_result_t usb_bulk_transfer(struct cdi_usb_device *dev, } +static inline bool is_power_of_two(unsigned value) +{ + return !(value & (value - 1)); +} + +cdi_usb_async_transmission_t usb_interrupt_transfer(struct cdi_usb_device *dev, + int ep, void *data, + size_t size, + cdi_usb_interrupt_cb_t cb, + void *opaque) +{ + usb_logical_device_t *ldev = CDI_UPCAST(dev, usb_logical_device_t, cdi); + + if (ep < 0 || ep >= dev->endpoint_count) { + return NULL; + } + + int ep_idx = ldev->endpoints[ep]; + usb_endpoint_t *ep_info = &ldev->dev->eps[ep_idx >> 4][ep_idx & 0xf]; + + if (ep_info->type != CDI_USB_INTERRUPT || !(ep_idx >> 4)) { + return NULL; + } + + struct cdi_usb_hcd *hcd = CDI_UPCAST(ldev->dev->hc->dev.driver, + struct cdi_usb_hcd, drv); + cdi_usb_hc_transaction_t ta; + + ta = hcd->create_transaction(ldev->dev->hc, &(struct cdi_usb_hc_ep_info){ + .dev = ldev->dev->id, + .ep = ep_info->ep, + .ep_type = ep_info->type, + .speed = ldev->dev->speed, + .mps = ep_info->mps, + .tt_addr = ldev->dev->tt_addr, + .tt_port = ldev->dev->tt_port + }); + + hcd->enqueue(ldev->dev->hc, &(struct cdi_usb_hc_transmission){ + .ta = ta, + .token = CDI_USB_IN, + .buffer = data, + .size = size, + .toggle = ep_info->toggle, + }); + + int interval = 0; + if (ldev->dev->speed == CDI_USB_LOW_SPEED || + ldev->dev->speed == CDI_USB_FULL_SPEED) + { + interval = ep_info->desc->b_interval; + if (!interval) { + interval = 1; + } else if (!is_power_of_two(interval)) { + // Round up + interval = 1 << (sizeof(unsigned) * 8 - __builtin_clz(interval)); + } + } else if (ldev->dev->speed == CDI_USB_HIGH_SPEED) { + if (ep_info->desc->b_interval < 16) { + interval = 1 << ep_info->desc->b_interval; + } else { + interval = 1 << 16; + } + } else { + // TODO + abort(); + } + + struct usb_async_transmission *at = malloc(sizeof(*at)); + at->ta = ta; + at->hc = ldev->dev->hc; + + hcd->start_interrupt_transaction(at->hc, ta, interval, cb, opaque); + + return at; +} + + +void usb_destroy_async_transfer(cdi_usb_async_transmission_t cdi_at) +{ + struct usb_async_transmission *at = cdi_at; + struct cdi_usb_hcd *hcd = CDI_UPCAST(at->hc->dev.driver, + struct cdi_usb_hcd, drv); + + hcd->destroy_transaction(at->hc, at->ta); + free(at); +} + + static struct cdi_usb_hub_driver hub_drv; diff --git a/usb/usb.h b/usb/usb.h index 9f1f4ac..687fec8 100644 --- a/usb/usb.h +++ b/usb/usb.h @@ -71,6 +71,11 @@ struct usb_logical_device { int *endpoints; }; +struct usb_async_transmission { + cdi_usb_hc_transaction_t ta; + struct cdi_usb_hc *hc; +}; + struct cdi_device *usb_init_hc(struct cdi_bus_data *bus_data); @@ -85,4 +90,12 @@ cdi_usb_transmission_result_t usb_bulk_transfer(struct cdi_usb_device *dev, int ep, void *data, size_t size); +cdi_usb_async_transmission_t usb_interrupt_transfer(struct cdi_usb_device *dev, + int ep, void *data, + size_t size, + cdi_usb_interrupt_cb_t cb, + void *opaque); + +void usb_destroy_async_transfer(cdi_usb_async_transmission_t at); + #endif -- 2.6.4 From max at tyndur.org Tue Dec 29 01:00:53 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 01:00:53 +0100 Subject: [cdi-devel] [PATCH 4/5] hid: Specify interface In-Reply-To: <1451347254-25755-1-git-send-email-max@tyndur.org> References: <1451347254-25755-1-git-send-email-max@tyndur.org> Message-ID: <1451347254-25755-5-git-send-email-max@tyndur.org> Signed-off-by: Max Reitz --- include/cdi-osdep.h | 20 ++++ include/cdi.h | 1 + include/cdi/hid-keycodes.h | 262 +++++++++++++++++++++++++++++++++++++++++++++ include/cdi/hid-ledcodes.h | 85 +++++++++++++++ include/cdi/hid.h | 113 +++++++++++++++++++ 5 files changed, 481 insertions(+) create mode 100644 include/cdi/hid-keycodes.h create mode 100644 include/cdi/hid-ledcodes.h create mode 100644 include/cdi/hid.h diff --git a/include/cdi-osdep.h b/include/cdi-osdep.h index 2a80be8..89038c7 100644 --- a/include/cdi-osdep.h +++ b/include/cdi-osdep.h @@ -67,6 +67,26 @@ typedef struct { /** * \german + * OS-spezifische Daten zu HIDs. + * \endgerman + * \english + * OS-specific HID data. + * \endenglish + * \thuringiansaxonian + * Vonn? j?wailschn Bedriebssysd??m abh?ngsche D?hdn, nu f?r so HID-Dingor. + * \endthuringiansaxonian + * \french + * Des donn?es tributaires du syst?me d'exploitation pour des HIDs. + * \endfrench + * \japanese + * HID????????OS???????? + * \endjapanese + */ +typedef struct { +} cdi_hid_osdep; + +/** + * \german * OS-spezifische Daten fuer einen ISA-DMA-Zugriff * \endgerman * \english diff --git a/include/cdi.h b/include/cdi.h index 8ed0738..f90f5ea 100644 --- a/include/cdi.h +++ b/include/cdi.h @@ -119,6 +119,7 @@ typedef enum { CDI_FILESYSTEM = 9, CDI_PCI = 10, CDI_AHCI = 11, + CDI_HID = 12, } cdi_device_type_t; struct cdi_driver; diff --git a/include/cdi/hid-keycodes.h b/include/cdi/hid-keycodes.h new file mode 100644 index 0000000..63f6793 --- /dev/null +++ b/include/cdi/hid-keycodes.h @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2015 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. + */ + +#ifndef _CDI_HID_KEYCODES_H_ +#define _CDI_HID_KEYCODES_H_ + +/** + * These codes are those used by USB HID keyboards + * (see Universal Serial Bus HID Usage Tables, section 10 + * "Keyboard/Keypad Page (0x07)"). + * + * Note that the naming convention follows the US keyboard layout. Non-US keys + * are named after the DE-de keyboard layout (if available). + */ +enum cdi_hid_keycodes { + CDI_HID_KEY_A = 0x04, + CDI_HID_KEY_B, + CDI_HID_KEY_C, + CDI_HID_KEY_D, + CDI_HID_KEY_E, + CDI_HID_KEY_F, + CDI_HID_KEY_G, + CDI_HID_KEY_H, + CDI_HID_KEY_I, + CDI_HID_KEY_J, + CDI_HID_KEY_K, + CDI_HID_KEY_L, + CDI_HID_KEY_M, + CDI_HID_KEY_N, + CDI_HID_KEY_O, + CDI_HID_KEY_P, + CDI_HID_KEY_Q, + CDI_HID_KEY_R, + CDI_HID_KEY_S, + CDI_HID_KEY_T, + CDI_HID_KEY_U, + CDI_HID_KEY_V, + CDI_HID_KEY_W, + CDI_HID_KEY_X, + CDI_HID_KEY_Y, + CDI_HID_KEY_Z, + + CDI_HID_KEY_1 = 0x1e, + CDI_HID_KEY_2, + CDI_HID_KEY_3, + CDI_HID_KEY_4, + CDI_HID_KEY_5, + CDI_HID_KEY_6, + CDI_HID_KEY_7, + CDI_HID_KEY_8, + CDI_HID_KEY_9, + CDI_HID_KEY_0, + + CDI_HID_KEY_RETURN = 0x28, // Defined as "Return (ENTER)" + CDI_HID_KEY_ESCAPE = 0x29, + CDI_HID_KEY_BACKSPACE = 0x2a, + CDI_HID_KEY_TAB = 0x2b, + CDI_HID_KEY_SPACE = 0x2c, + CDI_HID_KEY_MINUS = 0x2d, + CDI_HID_KEY_EQUAL = 0x2e, + CDI_HID_KEY_LBRACKET = 0x2f, + CDI_HID_KEY_RBRACKET = 0x30, + CDI_HID_KEY_BACKSLASH = 0x31, + CDI_HID_KEY_HASH = 0x32, // Non-US keyboards + CDI_HID_KEY_SEMICOLON = 0x33, + CDI_HID_KEY_APOSTROPHE = 0x34, + CDI_HID_KEY_GRAVE_ACCENT = 0x35, + CDI_HID_KEY_COMMA = 0x36, + CDI_HID_KEY_PERIOD = 0x37, + CDI_HID_KEY_SLASH = 0x38, + CDI_HID_KEY_CAPS_LOCK = 0x39, + + CDI_HID_KEY_F1 = 0x3a, + CDI_HID_KEY_F2, + CDI_HID_KEY_F3, + CDI_HID_KEY_F4, + CDI_HID_KEY_F5, + CDI_HID_KEY_F6, + CDI_HID_KEY_F7, + CDI_HID_KEY_F8, + CDI_HID_KEY_F9, + CDI_HID_KEY_F10, + CDI_HID_KEY_F11, + CDI_HID_KEY_F12, + + CDI_HID_KEY_PRINT_SCREEN = 0x46, + CDI_HID_KEY_SCROLL_LOCK = 0x47, + CDI_HID_KEY_PAUSE = 0x48, + CDI_HID_KEY_INSERT = 0x49, + CDI_HID_KEY_HOME = 0x4a, + CDI_HID_KEY_PAGE_UP = 0x4b, + CDI_HID_KEY_DELETE = 0x4c, + CDI_HID_KEY_END = 0x4d, + CDI_HID_KEY_PAGE_DOWN = 0x4e, + CDI_HID_KEY_RIGHT_ARROW = 0x4f, + CDI_HID_KEY_LEFT_ARROW = 0x50, + CDI_HID_KEY_DOWN_ARROW = 0x51, + CDI_HID_KEY_UP_ARROW = 0x52, + CDI_HID_KEY_NUM_LOCK = 0x53, + + CDI_HID_KEY_KEYPAD_SLASH = 0x54, + CDI_HID_KEY_KEYPAD_ASTERISK = 0x55, + CDI_HID_KEY_KEYPAD_MINUS = 0x56, + CDI_HID_KEY_KEYPAD_PLUS = 0x57, + CDI_HID_KEY_KEYPAD_ENTER = 0x58, + + CDI_HID_KEY_KEYPAD_1 = 0x59, + CDI_HID_KEY_KEYPAD_2, + CDI_HID_KEY_KEYPAD_3, + CDI_HID_KEY_KEYPAD_4, + CDI_HID_KEY_KEYPAD_5, + CDI_HID_KEY_KEYPAD_6, + CDI_HID_KEY_KEYPAD_7, + CDI_HID_KEY_KEYPAD_8, + CDI_HID_KEY_KEYPAD_9, + CDI_HID_KEY_KEYPAD_0, + + CDI_HID_KEY_KEYPAD_POINT = 0x63, + + CDI_HID_KEY_CHEVRONS = 0x64, // Non-US keyboards + CDI_HID_KEY_APPLICATION = 0x65, + CDI_HID_KEY_POWER = 0x66, + + CDI_HID_KEY_KEYPAD_EQUAL = 0x67, + + CDI_HID_KEY_F13 = 0x68, + CDI_HID_KEY_F14, + CDI_HID_KEY_F15, + CDI_HID_KEY_F16, + CDI_HID_KEY_F17, + CDI_HID_KEY_F18, + CDI_HID_KEY_F19, + CDI_HID_KEY_F20, + CDI_HID_KEY_F21, + CDI_HID_KEY_F22, + CDI_HID_KEY_F23, + CDI_HID_KEY_F24, + + CDI_HID_KEY_EXECUTE = 0x74, + CDI_HID_KEY_HELP = 0x75, + CDI_HID_KEY_MENU = 0x76, + CDI_HID_KEY_SELECT = 0x77, + CDI_HID_KEY_STOP = 0x78, + CDI_HID_KEY_AGAIN = 0x79, + CDI_HID_KEY_UNDO = 0x7a, + CDI_HID_KEY_CUT = 0x7b, + CDI_HID_KEY_COPY = 0x7c, + CDI_HID_KEY_PASTE = 0x7d, + CDI_HID_KEY_FIND = 0x7e, + CDI_HID_KEY_MUTE = 0x7f, + CDI_HID_KEY_VOLUME_UP = 0x80, + CDI_HID_KEY_VOLUME_DOWN = 0x81, + + CDI_HID_KEY_LOCKING_CAPS_LOCK = 0x82, + CDI_HID_KEY_LOCKING_NUM_LOCK = 0x83, + CDI_HID_KEY_LOCKING_SCROLL_LOCK = 0x84, + + CDI_HID_KEY_KEYPAD_COMMA = 0x85, + CDI_HID_KEY_KEYPAD_EQUAL_AS400 = 0x86, + + CDI_HID_KEY_INTERNATIONAL_1 = 0x87, + CDI_HID_KEY_INTERNATIONAL_2, + CDI_HID_KEY_INTERNATIONAL_3, + CDI_HID_KEY_INTERNATIONAL_4, + CDI_HID_KEY_INTERNATIONAL_5, + CDI_HID_KEY_INTERNATIONAL_6, + CDI_HID_KEY_INTERNATIONAL_7, + CDI_HID_KEY_INTERNATIONAL_8, + CDI_HID_KEY_INTERNATIONAL_9, + + CDI_HID_KEY_LANG_1 = 0x90, // Hangul/English toggle key + CDI_HID_KEY_LANG_2, // Hanja conversion key + CDI_HID_KEY_LANG_3, // Katakana key + CDI_HID_KEY_LANG_4, // Hiragana key + CDI_HID_KEY_LANG_5, // Zenkaku/Hankaku key + CDI_HID_KEY_LANG_6, + CDI_HID_KEY_LANG_7, + CDI_HID_KEY_LANG_8, + CDI_HID_KEY_LANG_9, + + CDI_HID_KEY_ALTERNATE_ERASE = 0x99, + CDI_HID_KEY_SYS_REQ = 0x9a, + CDI_HID_KEY_CANCEL = 0x9b, + CDI_HID_KEY_CLEAR = 0x9c, + CDI_HID_KEY_PRIOR = 0x9d, + CDI_HID_KEY_ALT_RETURN = 0x9e, // Defined as "Return" + // (cf. CDI_KEY_RETURN) + CDI_HID_KEY_SEPARATOR = 0x9f, + CDI_HID_KEY_OUT = 0xa0, + CDI_HID_KEY_OPER = 0xa1, + CDI_HID_KEY_CLEAR_AGAIN = 0xa2, + CDI_HID_KEY_CR_SEL_PROPS = 0xa3, + CDI_HID_KEY_EX_SEL = 0xa4, + + CDI_HID_KEY_KEYPAD_00 = 0xb0, + CDI_HID_KEY_KEYPAD_000 = 0xb1, + CDI_HID_KEY_THOUSANDS_SEPARATOR = 0xb2, + CDI_HID_KEY_DECIMAL_SEPARATOR = 0xb3, + CDI_HID_KEY_CURRENCY_UNIT = 0xb4, + CDI_HID_KEY_CURRENCY_SUB_UNIT = 0xb5, + CDI_HID_KEY_KEYPAD_LPAREN = 0xb6, + CDI_HID_KEY_KEYPAD_RPAREN = 0xb7, + CDI_HID_KEY_KEYPAD_LBRACE = 0xb8, + CDI_HID_KEY_KEYPAD_RBRACE = 0xb9, + CDI_HID_KEY_KEYPAD_TAB = 0xba, + CDI_HID_KEY_KEYPAD_BACKSPACE = 0xbb, + + CDI_HID_KEY_KEYPAD_A = 0xbc, + CDI_HID_KEY_KEYPAD_B, + CDI_HID_KEY_KEYPAD_C, + CDI_HID_KEY_KEYPAD_D, + CDI_HID_KEY_KEYPAD_E, + CDI_HID_KEY_KEYPAD_F, + + CDI_HID_KEY_KEYPAD_XOR = 0xc2, + CDI_HID_KEY_KEYPAD_HAT = 0xc3, + CDI_HID_KEY_KEYPAD_PERCENTAGE = 0xc4, + CDI_HID_KEY_KEYPAD_LESS_THAN = 0xc5, + CDI_HID_KEY_KEYPAD_GREATER_THAN = 0xc6, + CDI_HID_KEY_KEYPAD_AMPERSAND = 0xc7, + CDI_HID_KEY_KEYPAD_2_AMPERSANDS = 0xc8, + CDI_HID_KEY_KEYPAD_PIPE = 0xc9, + CDI_HID_KEY_KEYPAD_2_PIPES = 0xca, + CDI_HID_KEY_KEYPAD_COLON = 0xcb, + CDI_HID_KEY_KEYPAD_HASH = 0xcc, + CDI_HID_KEY_KEYPAD_SPACE = 0xcd, + CDI_HID_KEY_KEYPAD_AT = 0xce, + CDI_HID_KEY_KEYPAD_EXCLAMATION = 0xcf, + CDI_HID_KEY_KEYPAD_MEM_STORE = 0xd0, + CDI_HID_KEY_KEYPAD_MEM_RECALL = 0xd1, + CDI_HID_KEY_KEYPAD_MEM_CLEAR = 0xd2, + CDI_HID_KEY_KEYPAD_MEM_ADD = 0xd3, + CDI_HID_KEY_KEYPAD_MEM_SUBTRACT = 0xd4, + CDI_HID_KEY_KEYPAD_MEM_MULTIPLY = 0xd5, + CDI_HID_KEY_KEYPAD_MEM_DIVIDE = 0xd6, + CDI_HID_KEY_KEYPAD_SIGN = 0xd7, + CDI_HID_KEY_KEYPAD_CLEAR = 0xd8, + CDI_HID_KEY_KEYPAD_CLEAR_ENTRY = 0xd9, + CDI_HID_KEY_KEYPAD_BINARY = 0xda, + CDI_HID_KEY_KEYPAD_OCTAL = 0xdb, + CDI_HID_KEY_KEYPAD_DECIMAL = 0xdc, + CDI_HID_KEY_KEYPAD_HEXADECIMAL = 0xdd, + + CDI_HID_KEY_LCONTROL = 0xe0, + CDI_HID_KEY_LSHIFT = 0xe1, + CDI_HID_KEY_LALT = 0xe2, + CDI_HID_KEY_LMETA = 0xe3, + + CDI_HID_KEY_RCONTROL = 0xe4, + CDI_HID_KEY_RSHIFT = 0xe5, + CDI_HID_KEY_RALT = 0xe6, + CDI_HID_KEY_RMETA = 0xe7, +}; + +#endif diff --git a/include/cdi/hid-ledcodes.h b/include/cdi/hid-ledcodes.h new file mode 100644 index 0000000..a4104ec --- /dev/null +++ b/include/cdi/hid-ledcodes.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2015 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. + */ + +#ifndef _CDI_HID_LEDCODES_H_ +#define _CDI_HID_LEDCODES_H_ + +/** + * These codes are those defined by the USB HID class + * (see Universal Serial Bus HID Usage Tables, section 11 "LED Page (0x08)"). + * + * Only OOC (on/off control) LEDs are defined here. + */ +enum cdi_hid_ledcodes { + CDI_HID_LED_NUM_LOCK = 0x01, + CDI_HID_LED_CAPS_LOCK = 0x02, + CDI_HID_LED_SCROLL_LOCK = 0x03, + CDI_HID_LED_COMPOSE = 0x04, + CDI_HID_LED_KANA = 0x05, + CDI_HID_LED_POWER = 0x06, + CDI_HID_LED_SHIFT = 0x07, + CDI_HID_LED_DO_NOT_DISTURB = 0x08, + CDI_HID_LED_MUTE = 0x09, + CDI_HID_LED_TONE_ENABLE = 0x0a, + CDI_HID_LED_HIGH_CUT_FILTER = 0x0b, + CDI_HID_LED_LOW_CUT_FILTER = 0x0c, + CDI_HID_LED_EQUALIZER_ENABLE = 0x0d, + CDI_HID_LED_SOUND_FIELD_ON = 0x0e, + CDI_HID_LED_SURROUND_ON = 0x0f, + CDI_HID_LED_REPEAT = 0x10, + CDI_HID_LED_STEREO = 0x11, + CDI_HID_LED_SAMPL_RATE_DETECT = 0x12, + CDI_HID_LED_SPINNING = 0x13, + CDI_HID_LED_CAV = 0x14, + CDI_HID_LED_CLV = 0x15, + CDI_HID_LED_REC_FORMAT_DETECT = 0x16, + CDI_HID_LED_OFF_HOOK = 0x17, + CDI_HID_LED_RING = 0x18, + CDI_HID_LED_MESSAGE_WAITING = 0x19, + CDI_HID_LED_DATA_MODE = 0x1a, + CDI_HID_LED_BATTERY_OPERATION = 0x1b, + CDI_HID_LED_BATTERY_OK = 0x1c, + CDI_HID_LED_BATTERY_LOW = 0x1d, + CDI_HID_LED_SPEAKER = 0x1e, + CDI_HID_LED_HEAD_SET = 0x1f, + CDI_HID_LED_HOLD = 0x20, + CDI_HID_LED_MICROPHONE = 0x21, + CDI_HID_LED_COVERAGE = 0x22, + CDI_HID_LED_NIGHT_MODE = 0x23, + CDI_HID_LED_SEND_CALLS = 0x24, + CDI_HID_LED_CALL_PICKUP = 0x25, + CDI_HID_LED_CONFERENCE = 0x26, + CDI_HID_LED_STAND_BY = 0x27, + CDI_HID_LED_CAMERA_ON = 0x28, + CDI_HID_LED_CAMERA_OFF = 0x29, + CDI_HID_LED_ON_LINE = 0x2a, + CDI_HID_LED_OFF_LINE = 0x2b, + CDI_HID_LED_BUSY = 0x2c, + CDI_HID_LED_READY = 0x2d, + CDI_HID_LED_PAPER_OUT = 0x2e, + CDI_HID_LED_PAPER_JAM = 0x2f, + CDI_HID_LED_REMOTE = 0x30, + CDI_HID_LED_FORWARD = 0x31, + CDI_HID_LED_REVERSE = 0x32, + CDI_HID_LED_STOP = 0x33, + CDI_HID_LED_REWIND = 0x34, + CDI_HID_LED_FAST_FORWARD = 0x35, + CDI_HID_LED_PLAY = 0x36, + CDI_HID_LED_PAUSE = 0x37, + CDI_HID_LED_RECORD = 0x38, + CDI_HID_LED_ERROR = 0x39, + + CDI_HID_LED_GENERIC_INDICATOR = 0x4b, + CDI_HID_LED_SYSTEM_SUSPEND = 0x4c, + CDI_HID_LED_EXT_POWER_CONNECTED = 0x4d, +}; + +#endif + diff --git a/include/cdi/hid.h b/include/cdi/hid.h new file mode 100644 index 0000000..0196a62 --- /dev/null +++ b/include/cdi/hid.h @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2015 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. + */ + +#ifndef _CDI_HID_H_ +#define _CDI_HID_H_ + +#include + +#include +#include +#include +#include + + +/** + * Entry of the bitmaps used in this header. In each entry (i.e. each byte), + * the LSb is bit 0 and the MSb is bit 7. + */ +typedef uint8_t cdi_hid_bitmap_t; + +/** + * This array will be extended in the future. The CDI library should ignore + * unknown device types. + */ +enum cdi_hid_type { + CDI_HID_KEYBOARD, + CDI_HID_MOUSE, +}; + +struct cdi_hid { + struct cdi_device dev; + + /** + * Type of the HID. If it is in a meaningful way possible to interpret a + * device as a keyboard or a mouse, this interpretation should be done by + * the HID driver and this field should be set to CDI_HID_KEYBOARD or + * CDI_HID_MOUSE accordingly. The operating system may safely assume that + * any HID that is not reported to be a keyboard or mouse actually to be + * unusable as keyboard or mouse. + * + * Note that a HID driver is free to provide multiple cdi_hid objects with + * differing types for a single physical device. + */ + enum cdi_hid_type type; + + /** + * Number of buttons, axes and LEDs offered by this HID. + */ + size_t button_count, axes_count, led_count; + + /** + * Bitmap representing the state of the buttons the HID provides. It has + * @button_count entries. The interpretation of a set or cleared bit is + * depending on the device (e.g. whether a set bit means a button is down or + * that its state changed). + * + * For keyboards and mice the button order is fixed (see cdi/hid-keycodes.h + * for keyboards), and a set bit indicates the respective button is down. + */ + cdi_hid_bitmap_t* button_states; + + /** + * Array containing the state of the axes the HID provides, with @axes_count + * entries. The interpretation of these values is completely depending on + * the device (e.g. the range of values allowed; whether the value is + * relative or absolute, etc.). + * + * Keyboards do not have any axes. + * + * Mice have two or three axes: + * - Axis 1: Relative X movement, range [-1.0, 1.0] (positive is right) + * - Axis 2: Relative Y movement, range [-1.0, 1.0] (positive is up) + * - Axis 3: Relative wheel movement, 1.0 per tick (positive is forwards) + */ + float* axes_states; + + cdi_hid_osdep meta; +}; + +struct cdi_hid_driver { + struct cdi_driver drv; + + /** + * Sets the state of the LEDs the HID provides. + * + * For the LEDs keyboards can provide (and all USB HIDs can provide), see + * cdi/hid-ledcodes.h. + */ + void (*set_leds)(struct cdi_hid* device, const cdi_hid_bitmap_t* states); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Invoked by a HID driver to report to the CDI library that the device's state + * may have changed (i.e. the values in @button_states and/or @axes_states). + */ +void cdi_hid_state_update(struct cdi_hid* device); + +#ifdef __cplusplus +}; // extern "C" +#endif + +#endif -- 2.6.4 From max at tyndur.org Tue Dec 29 01:00:54 2015 From: max at tyndur.org (Max Reitz) Date: Tue, 29 Dec 2015 01:00:54 +0100 Subject: [cdi-devel] [PATCH 5/5] usb-hid: Add driver In-Reply-To: <1451347254-25755-1-git-send-email-max@tyndur.org> References: <1451347254-25755-1-git-send-email-max@tyndur.org> Message-ID: <1451347254-25755-6-git-send-email-max@tyndur.org> Signed-off-by: Max Reitz --- usb-hid/main.c | 74 ++++++++++++++++++++++++++ usb-hid/usb-hid.c | 153 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ usb-hid/usb-hid.h | 54 +++++++++++++++++++ 3 files changed, 281 insertions(+) create mode 100644 usb-hid/main.c create mode 100644 usb-hid/usb-hid.c create mode 100644 usb-hid/usb-hid.h diff --git a/usb-hid/main.c b/usb-hid/main.c new file mode 100644 index 0000000..4ff637e --- /dev/null +++ b/usb-hid/main.c @@ -0,0 +1,74 @@ +/****************************************************************************** + * Copyright (c) 2015 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 "usb-hid.h" + + +#define DRIVER_NAME "usb-hid" + + +static struct cdi_hid_driver drv; +static struct cdi_usb_bus_device_pattern keyboard_bus_pattern; + +static int drv_init(void) +{ + cdi_driver_init(&drv.drv); + cdi_handle_bus_device(&drv.drv, &keyboard_bus_pattern.pattern); + return 0; +} + +static int drv_destroy(void) +{ + cdi_driver_destroy(&drv.drv); + return 0; +} + + +static struct cdi_hid_driver drv = { + .drv = { + .name = DRIVER_NAME, + .type = CDI_HID, + .bus = CDI_USB, + .init = drv_init, + .destroy = drv_destroy, + .init_device = init_usb_device, + }, +}; + +static struct cdi_usb_bus_device_pattern keyboard_bus_pattern = { + .pattern = { + .bus_type = CDI_USB, + }, + + .vendor_id = -1, + .product_id = -1, + + .class_id = CDI_USB_IFCCLS_HID, + .subclass_id = USBHID_SUBCLS_BOOT, + .protocol_id = USBHID_PROTO_KEYBOARD, +}; + +CDI_DRIVER(DRIVER_NAME, drv) diff --git a/usb-hid/usb-hid.c b/usb-hid/usb-hid.c new file mode 100644 index 0000000..1b2edc9 --- /dev/null +++ b/usb-hid/usb-hid.c @@ -0,0 +1,153 @@ +/****************************************************************************** + * Copyright (c) 2015 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 + +#include "usb-hid.h" + + +typedef struct usb_hid_keyboard { + struct cdi_hid dev; + struct cdi_usb_device usb; + + cdi_usb_async_transmission_t interrupt_trans; + uint8_t interrupt_buffer[8]; + + int interrupt_ep; +} usb_hid_keyboard_t; + + +static void interrupt_cb(void *opaque) +{ + usb_hid_keyboard_t *dev = opaque; + // On rollover, all scancode bytes are set to 0x01 (Keyboard ErrorRollOver) + bool have_rollover = dev->interrupt_buffer[2] == 0x01; + + if (have_rollover) { + // On rollover, we will only update the modifier keys + dev->dev.button_states[USBHID_BOOT_KEYBOARD_MODIFIER_MINIMUM_KEY] = 0; + } else { + // Otherwise, we will update all keys + memset(dev->dev.button_states, 0, 256 / 8); + } + + uint8_t modifier = dev->interrupt_buffer[0]; + for (int mod_key = 0; mod_key < 8; mod_key++) { + if (modifier & (1 << mod_key)) { + int button = mod_key + USBHID_BOOT_KEYBOARD_MODIFIER_MINIMUM_KEY; + dev->dev.button_states[button / 8] |= 1 << (button % 8); + } + } + + if (!have_rollover) { + for (int i = 2; i < 8; i++) { + int button = dev->interrupt_buffer[i]; + if (button) { + dev->dev.button_states[button / 8] |= 1 << (button % 8); + } + } + } + + cdi_hid_state_update(&dev->dev); +} + + +struct cdi_device *init_usb_device(struct cdi_bus_data *bus_data) +{ + static int dev_counter = 0; + usb_hid_keyboard_t *dev = calloc(1, sizeof(*dev)); + dev->usb = *CDI_UPCAST(bus_data, struct cdi_usb_device, bus_data); + + // Switch to boot protocol + cdi_usb_transmission_result_t res; + + res = cdi_usb_control_transfer(&dev->usb, 0, &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_CLASS | CDI_USB_CREQ_INTERFACE + | CDI_USB_CREQ_OUT, + .b_request = USBHID_CREQ_SET_PROTOCOL, + .w_value = 0, // Boot Protocol + .w_index = dev->usb.interface + }, NULL); + + if (res != CDI_USB_OK) { + free(dev); + return NULL; + } + + for (int ep = 1; ep < dev->usb.endpoint_count; ep++) { + struct cdi_usb_endpoint_descriptor ep_desc; + cdi_usb_get_endpoint_descriptor(&dev->usb, ep, &ep_desc); + if ((ep_desc.bm_attributes & CDI_USB_EPDSC_ATTR_XFER_TYPE_MASK) + == CDI_USB_EPDSC_ATTR_INTERRUPT && + ep_desc.b_endpoint_address & CDI_USB_EPDSC_EPADR_DIR) + { + dev->interrupt_ep = ep; + break; + } + } + + if (!dev->interrupt_ep) { + free(dev); + return NULL; + } + + + dev->interrupt_trans = + cdi_usb_interrupt_transfer(&dev->usb, dev->interrupt_ep, + dev->interrupt_buffer, + sizeof(dev->interrupt_buffer), + interrupt_cb, dev); + + dev->dev.button_count = 256; + dev->dev.axes_count = 0; + dev->dev.led_count = 5; + + dev->dev.button_states = calloc(1, 256 / 8); + + asprintf((char **)&dev->dev.dev.name, "hid-kbd%i", dev_counter++); + + return &dev->dev.dev; +} + + +void set_keyboard_leds(struct cdi_hid *device, const cdi_hid_bitmap_t *states) +{ + usb_hid_keyboard_t *dev = CDI_UPCAST(device, usb_hid_keyboard_t, dev); + uint8_t shifted_states = *(uint8_t *)states >> 1; + + cdi_usb_control_transfer(&dev->usb, 0, &(struct cdi_usb_setup_packet){ + .bm_request_type = CDI_USB_CREQ_CLASS | CDI_USB_CREQ_INTERFACE + | CDI_USB_CREQ_OUT, + .b_request = USBHID_CREQ_SET_REPORT, + .w_index = dev->usb.interface, + .w_length = 1 + }, &shifted_states); +} diff --git a/usb-hid/usb-hid.h b/usb-hid/usb-hid.h new file mode 100644 index 0000000..54c63a6 --- /dev/null +++ b/usb-hid/usb-hid.h @@ -0,0 +1,54 @@ +/****************************************************************************** + * Copyright (c) 2015 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_HID_H +#define USB_HID_H + +#include +#include + + +// HID subclass codes +#define USBHID_SUBCLS_NONE 0x00 // No Subclass +#define USBHID_SUBCLS_BOOT 0x01 // Boot Interface Subclass + +// HID protocol codes (only non-zero if the subclass is 0x01) +#define USBHID_PROTO_NONE 0x00 // None +#define USBHID_PROTO_KEYBOARD 0x01 // Keyboard +#define USBHID_PROTO_MOUSE 0x02 // Mouse + +// HID control request codes +#define USBHID_CREQ_GET_REPORT 0x01 +#define USBHID_CREQ_GET_IDLE 0x02 +#define USBHID_CREQ_GET_PROTOCOL 0x03 +#define USBHID_CREQ_SET_REPORT 0x09 +#define USBHID_CREQ_SET_IDLE 0x0a +#define USBHID_CREQ_SET_PROTOCOL 0x0b + +// Usage Minimum of the modifier byte for the keyboard boot protocol +// (see USB HID specification, section B.1) +#define USBHID_BOOT_KEYBOARD_MODIFIER_MINIMUM_KEY 0xe0 + + +struct cdi_device *init_usb_device(struct cdi_bus_data *bus_data); + +#endif -- 2.6.4 From kevin at tyndur.org Tue Dec 29 22:27:17 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Tue, 29 Dec 2015 22:27:17 +0100 Subject: [cdi-devel] [PATCH 00/10] usb: Some fixes In-Reply-To: <1451346799-23335-1-git-send-email-max@tyndur.org> References: <1451346799-23335-1-git-send-email-max@tyndur.org> Message-ID: <20151229212716.GA8240@silvanus> On Tue, Dec 29, 2015 at 12:53:09AM +0100, Max Reitz wrote: > Several generic fixes for the USB bus driver, and one for usb-storage. > > Some usb patches (like the last one) are not strictly fixes, but are > nice to have anyway; the same applies to the ehci patch. > > > Max Reitz (10): > usb: extern "C" {} > usb: Add necessary recovery intervals > usb: Ignore hub power switching errors > usb: Make descriptors inherit from a common base > usb: Store hub and hub_port for each usb_device > usb: Create provide_virtual_devices() > usb: Fix and simplify debugging code > usb: Clear ENDPOINT_HALT on stalling bulk transfer > usb-storage: Drop bulk_only_reset()'s return value > ehci: Use __attribute__((aligned())) Acked-by: Kevin Wolf From kevin at tyndur.org Wed Dec 30 17:27:16 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Wed, 30 Dec 2015 17:27:16 +0100 Subject: [cdi-devel] [PATCH 0/7] e1000: Support the NIC in the T500 Message-ID: <1451492843-6394-1-git-send-email-kevin@tyndur.org> This series fixes a few bugs in the e1000 driver and adds support for the e1000e chip used in the Thinkpad T500. Kevin Wolf (7): e1000: Fix TCTL Pad Short Packets bit e1000: Make descriptors volatile e1000: Fix error path for full TX queue e1000: Introduce e1000_model e1000: Move a few model-specific things to e1000_model e1000: Implement support for 8086:10f5 e1000e chip e1000: Wait for Link Up e1000/device.c | 153 ++++++++++++++++++++++++++++++++++++++++++++++++------- e1000/device.h | 68 ++++++++++++++++++++++--- e1000/e1000_io.h | 29 +++++++++++ 3 files changed, 225 insertions(+), 25 deletions(-) -- 2.1.4 From kevin at tyndur.org Wed Dec 30 17:27:17 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Wed, 30 Dec 2015 17:27:17 +0100 Subject: [cdi-devel] [PATCH 1/7] e1000: Fix TCTL Pad Short Packets bit In-Reply-To: <1451492843-6394-1-git-send-email-kevin@tyndur.org> References: <1451492843-6394-1-git-send-email-kevin@tyndur.org> Message-ID: <1451492843-6394-2-git-send-email-kevin@tyndur.org> It's bit 3, not bit 2. Signed-off-by: Kevin Wolf --- e1000/device.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e1000/device.h b/e1000/device.h index 712cf08..314ba87 100644 --- a/e1000/device.h +++ b/e1000/device.h @@ -88,7 +88,7 @@ enum { enum { TCTL_ENABLE = (1 << 1), - TCTL_PADDING = (1 << 2), + TCTL_PADDING = (1 << 3), TCTL_COLL_TSH = (0x0f << 4), /* CT - Collision Threshold */ TCTL_COLL_DIST = (0x40 << 12), /* COLD - Collision Distance */ }; -- 2.1.4 From kevin at tyndur.org Wed Dec 30 17:27:18 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Wed, 30 Dec 2015 17:27:18 +0100 Subject: [cdi-devel] [PATCH 2/7] e1000: Make descriptors volatile In-Reply-To: <1451492843-6394-1-git-send-email-kevin@tyndur.org> References: <1451492843-6394-1-git-send-email-kevin@tyndur.org> Message-ID: <1451492843-6394-3-git-send-email-kevin@tyndur.org> The hardware is supposed to write to these, so let's make sure that the compiler doesn't cache any values. While at it, assert the right alignment. Signed-off-by: Kevin Wolf --- e1000/device.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/e1000/device.h b/e1000/device.h index 314ba87..7b0ae03 100644 --- a/e1000/device.h +++ b/e1000/device.h @@ -144,6 +144,7 @@ struct e1000_tx_descriptor { uint8_t checksum_start; uint16_t special; } __attribute__((packed)) __attribute__((aligned (4))); +CDI_BUILD_BUG_ON((sizeof(struct e1000_tx_descriptor) * TX_BUFFER_NUM) % 128); enum { TX_CMD_EOP = 0x01, @@ -158,17 +159,18 @@ struct e1000_rx_descriptor { uint8_t error; uint16_t padding2; } __attribute__((packed)) __attribute__((aligned (4))); +CDI_BUILD_BUG_ON((sizeof(struct e1000_rx_descriptor) * RX_BUFFER_NUM) % 128); struct e1000_device { struct cdi_net_device net; uintptr_t phys; - struct e1000_tx_descriptor tx_desc[TX_BUFFER_NUM] __attribute__((aligned(16))); + volatile struct e1000_tx_descriptor tx_desc[TX_BUFFER_NUM] __attribute__((aligned(16))); uint8_t tx_buffer[TX_BUFFER_NUM * TX_BUFFER_SIZE]; uint32_t tx_cur_buffer; - struct e1000_rx_descriptor rx_desc[RX_BUFFER_NUM] __attribute__((aligned(16))); + volatile struct e1000_rx_descriptor rx_desc[RX_BUFFER_NUM] __attribute__((aligned(16))); uint8_t rx_buffer[RX_BUFFER_NUM * RX_BUFFER_SIZE]; uint32_t rx_cur_buffer; -- 2.1.4 From kevin at tyndur.org Wed Dec 30 17:27:19 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Wed, 30 Dec 2015 17:27:19 +0100 Subject: [cdi-devel] [PATCH 3/7] e1000: Fix error path for full TX queue In-Reply-To: <1451492843-6394-1-git-send-email-kevin@tyndur.org> References: <1451492843-6394-1-git-send-email-kevin@tyndur.org> Message-ID: <1451492843-6394-4-git-send-email-kevin@tyndur.org> ! e1000: If we don't queue a new packet, we must not advance the tx_cur_buffer either. Signed-off-by: Kevin Wolf --- e1000/device.c | 1 + 1 file changed, 1 insertion(+) diff --git a/e1000/device.c b/e1000/device.c index c4709ae..ca516cf 100644 --- a/e1000/device.c +++ b/e1000/device.c @@ -447,6 +447,7 @@ void e1000_send_packet(struct cdi_net_device* device, void* data, size_t size) head = reg_inl(netcard, REG_TXDESC_HEAD); if (netcard->tx_cur_buffer == head) { printf("e1000: Kein Platz in der Sendewarteschlange!\n"); + netcard->tx_cur_buffer = cur; return; } -- 2.1.4 From kevin at tyndur.org Wed Dec 30 17:27:20 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Wed, 30 Dec 2015 17:27:20 +0100 Subject: [cdi-devel] [PATCH 4/7] e1000: Introduce e1000_model In-Reply-To: <1451492843-6394-1-git-send-email-kevin@tyndur.org> References: <1451492843-6394-1-git-send-email-kevin@tyndur.org> Message-ID: <1451492843-6394-5-git-send-email-kevin@tyndur.org> This patch converts the existing PCI ID list into a list of model structs, which we will extend to store model-specific options and function pointers. Signed-off-by: Kevin Wolf --- e1000/device.c | 12 +++++------- e1000/device.h | 7 +++++++ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/e1000/device.c b/e1000/device.c index ca516cf..112f44a 100644 --- a/e1000/device.c +++ b/e1000/device.c @@ -345,10 +345,7 @@ static uint64_t get_mac_address(struct e1000_device* device) #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) -static struct { - uint16_t vendor_id; - uint16_t device_id; -} pci_id_list[] = { +static struct e1000_model models[] = { { 0x8086, 0x1004 }, { 0x8086, 0x100f }, { 0x8086, 0x100e }, @@ -361,9 +358,9 @@ struct cdi_device* e1000_init_device(struct cdi_bus_data* bus_data) struct cdi_mem_area* buf; int i; - for (i = 0; i < ARRAY_SIZE(pci_id_list); i++) { - if (pci->vendor_id == pci_id_list[i].vendor_id - && pci->device_id == pci_id_list[i].device_id) + for (i = 0; i < ARRAY_SIZE(models); i++) { + if (pci->vendor_id == models[i].vendor_id + && pci->device_id == models[i].device_id) { goto found; } @@ -380,6 +377,7 @@ found: netcard = buf->vaddr; memset(netcard, 0, sizeof(*netcard)); + netcard->model = &models[i]; netcard->phys = buf->paddr.items[0].start; netcard->net.dev.bus_data = (struct cdi_bus_data*) pci; diff --git a/e1000/device.h b/e1000/device.h index 7b0ae03..d424f19 100644 --- a/e1000/device.h +++ b/e1000/device.h @@ -161,6 +161,11 @@ struct e1000_rx_descriptor { } __attribute__((packed)) __attribute__((aligned (4))); CDI_BUILD_BUG_ON((sizeof(struct e1000_rx_descriptor) * RX_BUFFER_NUM) % 128); +struct e1000_model { + uint16_t vendor_id; + uint16_t device_id; +}; + struct e1000_device { struct cdi_net_device net; @@ -176,6 +181,8 @@ struct e1000_device { void* mem_base; uint8_t revision; + + struct e1000_model* model; }; struct cdi_device* e1000_init_device(struct cdi_bus_data* bus_data); -- 2.1.4 From kevin at tyndur.org Wed Dec 30 17:27:21 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Wed, 30 Dec 2015 17:27:21 +0100 Subject: [cdi-devel] [PATCH 5/7] e1000: Move a few model-specific things to e1000_model In-Reply-To: <1451492843-6394-1-git-send-email-kevin@tyndur.org> References: <1451492843-6394-1-git-send-email-kevin@tyndur.org> Message-ID: <1451492843-6394-6-git-send-email-kevin@tyndur.org> Before we can add another model that works differently, let's move a few model-specific things to e1000_model. This patch merely introduces some indirection, no semantic change is intended. It also adds a (commented out) function for e1000e EERD use, which is the same as for the previously supported e1000 models except that some flags are in different bit positions. Signed-off-by: Kevin Wolf --- e1000/device.c | 51 ++++++++++++++++++++++++++++++++++++++++----------- e1000/device.h | 16 +++++++++++++--- 2 files changed, 53 insertions(+), 14 deletions(-) diff --git a/e1000/device.c b/e1000/device.c index 112f44a..6356721 100644 --- a/e1000/device.c +++ b/e1000/device.c @@ -213,32 +213,48 @@ static uint32_t e1000_read_uwire(struct e1000_device *device, uint16_t offset) return data; } -static uint32_t e1000_read_eerd(struct e1000_device *device, uint16_t offset) +static uint32_t do_read_eerd(struct e1000_device *device, uint16_t offset, + uint32_t start_flag, uint32_t done_flag) { uint32_t eerd, i; - reg_outl(device, REG_EEPROM_READ, (offset << 8) | EERD_START); + reg_outl(device, REG_EEPROM_READ, (offset << 8) | start_flag); for(i = 0; i < 100; i++) { eerd = reg_inl(device, REG_EEPROM_READ); - if(eerd & EERD_DONE) + if (eerd & done_flag) { break; + } cdi_sleep_ms(1); } - if(eerd & EERD_DONE) + if (eerd & done_flag) { return (eerd >> 16) & 0xFFFF; - else + } else { return (uint32_t) -1; + } +} + +static uint32_t e1000_read_eerd(struct e1000_device *device, uint16_t offset) +{ + return do_read_eerd(device, offset, EERD_E1000_START, EERD_E1000_DONE); +} + +#if 0 +static uint32_t e1000e_read_eerd(struct e1000_device *device, uint16_t offset) +{ + return do_read_eerd(device, offset, EERD_E1000E_START, EERD_E1000E_DONE); } +#endif static uint16_t e1000_eeprom_read(struct e1000_device* device, uint16_t offset) { static int eerd_safe = 1; uint32_t data = 0; - if(eerd_safe) - data = e1000_read_eerd(device, offset); + if (eerd_safe) { + data = device->model->eeprom_read(device, offset); + } if(!eerd_safe || (data == ((uint32_t) -1))) { eerd_safe = 0; @@ -326,7 +342,7 @@ static void reset_nic(struct e1000_device* netcard) reg_outl(netcard, REG_RX_CTL, RCTL_ENABLE | RCTL_BROADCAST | RCTL_2K_BUFSIZE); reg_outl(netcard, REG_TX_CTL, TCTL_ENABLE | TCTL_PADDING - | TCTL_COLL_TSH | TCTL_COLL_DIST); + | TCTL_COLL_TSH | netcard->model->tctl_flags); } @@ -346,9 +362,22 @@ static uint64_t get_mac_address(struct e1000_device* device) #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) static struct e1000_model models[] = { - { 0x8086, 0x1004 }, - { 0x8086, 0x100f }, - { 0x8086, 0x100e }, + { + .vendor_id = 0x8086, + .device_id = 0x1004, + .tctl_flags = TCTL_COLL_DIST_E1000, + .eeprom_read = e1000_read_eerd, + }, { + .vendor_id = 0x8086, + .device_id = 0x100e, + .tctl_flags = TCTL_COLL_DIST_E1000, + .eeprom_read = e1000_read_eerd, + }, { + .vendor_id = 0x8086, + .device_id = 0x100f, + .tctl_flags = TCTL_COLL_DIST_E1000, + .eeprom_read = e1000_read_eerd, + } }; struct cdi_device* e1000_init_device(struct cdi_bus_data* bus_data) diff --git a/e1000/device.h b/e1000/device.h index d424f19..2eebf8a 100644 --- a/e1000/device.h +++ b/e1000/device.h @@ -90,7 +90,9 @@ enum { TCTL_ENABLE = (1 << 1), TCTL_PADDING = (1 << 3), TCTL_COLL_TSH = (0x0f << 4), /* CT - Collision Threshold */ - TCTL_COLL_DIST = (0x40 << 12), /* COLD - Collision Distance */ + + /* e1000 specific values */ + TCTL_COLL_DIST_E1000 = (0x40 << 12), /* COLD - Collision Distance */ }; enum { @@ -104,8 +106,11 @@ enum { #define RAH_VALID (1 << 31) /* AV */ -#define EERD_START (1 << 0) -#define EERD_DONE (1 << 4) +#define EERD_E1000_START (1 << 0) +#define EERD_E1000_DONE (1 << 4) + +#define EERD_E1000E_START (1 << 0) +#define EERD_E1000E_DONE (1 << 1) /* EEPROM/Flash Control */ #define E1000_EECD_SK 0x00000001 /* EEPROM Clock */ @@ -161,9 +166,14 @@ struct e1000_rx_descriptor { } __attribute__((packed)) __attribute__((aligned (4))); CDI_BUILD_BUG_ON((sizeof(struct e1000_rx_descriptor) * RX_BUFFER_NUM) % 128); +struct e1000_device; + struct e1000_model { uint16_t vendor_id; uint16_t device_id; + + uint32_t tctl_flags; + uint32_t (*eeprom_read)(struct e1000_device *device, uint16_t offset); }; struct e1000_device { -- 2.1.4 From kevin at tyndur.org Wed Dec 30 17:27:22 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Wed, 30 Dec 2015 17:27:22 +0100 Subject: [cdi-devel] [PATCH 6/7] e1000: Implement support for 8086:10f5 e1000e chip In-Reply-To: <1451492843-6394-1-git-send-email-kevin@tyndur.org> References: <1451492843-6394-1-git-send-email-kevin@tyndur.org> Message-ID: <1451492843-6394-7-git-send-email-kevin@tyndur.org> This adds support for the e1000e in my Thinkpad T500. The main difference between the already supported e1000 cards and the 8086:10f5 is that the EEPROM can't be accessed using EERD, but must use the flash interface. Apart from that, only the settings in TCTL differ. Signed-off-by: Kevin Wolf --- e1000/device.c | 79 +++++++++++++++++++++++++++++++++++++++++++++++++++++++- e1000/device.h | 32 +++++++++++++++++++++++ e1000/e1000_io.h | 29 +++++++++++++++++++++ 3 files changed, 139 insertions(+), 1 deletion(-) diff --git a/e1000/device.c b/e1000/device.c index 6356721..d9e65c5 100644 --- a/e1000/device.c +++ b/e1000/device.c @@ -247,6 +247,63 @@ static uint32_t e1000e_read_eerd(struct e1000_device *device, uint16_t offset) } #endif +static uint32_t e1000e_read_flash(struct e1000_device *device, uint16_t offset) +{ + uint16_t hsfsts; + uint32_t linear_address; + + /* Convert from words to bytes */ + offset *= 2; + + if (device->flash_base == NULL) { + printf("e1000: Cannot read from flash without flash BAR\n"); + return (uint32_t) -1; + } + + if (offset + 2 > device->flash_size) { + printf("e1000: Cannot read from flash offset %d (size %d)\n", + offset, device->flash_size); + return (uint32_t) -1; + } + + /* Check that hardware sequencing is supported */ + hsfsts = flash_reg_inw(device, FLASH_REG_HSFSTS); + if ((hsfsts & HSFSTS_FDV) == 0) { + /* TODO Implement access using Software Sequencing registers */ + printf("e1000: Cannot read from flash without hardware sequencing\n"); + return (uint32_t) -1; + } + + /* Check that no SPI cycle is in progress */ + if (hsfsts & HSFSTS_SCIP) { + printf("e1000: Cannot read from flash while SPI cycle in progress\n"); + return (uint32_t) -1; + } + + /* Start a new cycle */ + linear_address = device->flash_base_offset + offset; + flash_reg_outl(device, FLASH_REG_FADDR, linear_address); + + flash_reg_outw(device, FLASH_REG_HSFSTS, + HSFSTS_FDONE | HSFSTS_FCERR | HSFSTS_AEL); + flash_reg_outw(device, FLASH_REG_HSFCTL, + HSFCTL_FGO | HSFCTL_FCYCLE_READ | HSFCTL_FDBC_WORD); + + CDI_CONDITION_WAIT_SLEEP( + flash_reg_inw(device, FLASH_REG_HSFSTS) & HSFSTS_FDONE, 100, 1); + + hsfsts = flash_reg_inw(device, FLASH_REG_HSFSTS); + if ((hsfsts & (HSFSTS_FDONE | HSFSTS_FCERR)) == HSFSTS_FDONE) { + return flash_reg_inl(device, FLASH_REG_FDATA0); + } else if ((hsfsts & HSFSTS_FDONE) == 0){ + printf("e1000: Timeout while reading from flash\n"); + } else { + printf("e1000: Error while reading from flash\n"); + } + + return (uint32_t) -1; +} + static uint16_t e1000_eeprom_read(struct e1000_device* device, uint16_t offset) { static int eerd_safe = 1; @@ -287,6 +344,18 @@ static void reset_nic(struct e1000_device* netcard) cdi_sleep_ms(10); while (reg_inl(netcard, REG_CTL) & CTL_RESET); + // Flash-Basisadresse + if (netcard->flash_base) { + uint32_t glfpr = flash_reg_inl(netcard, FLASH_REG_GLFPR); + uint32_t base = (glfpr & 0x1fff) << 12; + uint32_t limit = ((glfpr >> 16) & 0x1fff) << 12; + + netcard->flash_base_offset = base; + netcard->flash_size = limit - base; + + printf("e1000: Flash base offset %x; size %x\n", base, limit - base); + } + // Kontrollregister initialisieren reg_outl(netcard, REG_CTL, CTL_AUTO_SPEED | CTL_LINK_UP); @@ -377,6 +446,11 @@ static struct e1000_model models[] = { .device_id = 0x100f, .tctl_flags = TCTL_COLL_DIST_E1000, .eeprom_read = e1000_read_eerd, + }, { + .vendor_id = 0x8086, + .device_id = 0x10f5, + .tctl_flags = TCTL_COLL_DIST_E1000E | TCTL_RRTHRESH, + .eeprom_read = e1000e_read_flash, } }; @@ -418,9 +492,12 @@ found: cdi_list_t reslist = pci->resources; struct cdi_pci_resource* res; for (i = 0; (res = cdi_list_get(reslist, i)); i++) { - if (res->type == CDI_PCI_MEMORY) { + if (res->type == CDI_PCI_MEMORY && res->index == 0) { struct cdi_mem_area* mmio = cdi_mem_map(res->start, res->length); netcard->mem_base = mmio->vaddr; + } else if (res->type == CDI_PCI_MEMORY && res->index == 1) { + struct cdi_mem_area* mmio = cdi_mem_map(res->start, res->length); + netcard->flash_base = mmio->vaddr; } } diff --git a/e1000/device.h b/e1000/device.h index 2eebf8a..638e6f9 100644 --- a/e1000/device.h +++ b/e1000/device.h @@ -93,6 +93,10 @@ enum { /* e1000 specific values */ TCTL_COLL_DIST_E1000 = (0x40 << 12), /* COLD - Collision Distance */ + + /* e1000e specific values */ + TCTL_COLL_DIST_E1000E = (0x3f << 12), /* COLD - Collision Distance */ + TCTL_RRTHRESH = (0x03 << 28), /* Read Request Threshold */ }; enum { @@ -101,6 +105,31 @@ enum { }; enum { + FLASH_REG_GLFPR = 0x0, /* Gigabit LAN Flash Primary Region */ + FLASH_REG_HSFSTS = 0x4, /* Hardware Sequencing Flash Status */ + FLASH_REG_HSFCTL = 0x6, /* Hardware Sequencing Flash Control */ + FLASH_REG_FADDR = 0x8, /* Flash Address Register */ + FLASH_REG_FDATA0 = 0x10, /* Flash Data 0 Register */ +}; + +enum { + HSFSTS_FDONE = (1 << 0), + HSFSTS_FCERR = (1 << 1), + HSFSTS_AEL = (1 << 2), + HSFSTS_SCIP = (1 << 5), + HSFSTS_FDV = (1 << 14), +}; + +enum { + HSFCTL_FGO = (1 << 0), + HSFCTL_FCYCLE_READ = (0 << 1), + /*HSFCTL_FCYCLE_WRITE = (2 << 1),*/ + HSFCTL_FDBC_BYTE = (0 << 8), + HSFCTL_FDBC_WORD = (1 << 8), + HSFCTL_FDBC_DWORD = (3 << 8), +}; + +enum { EEPROM_OFS_MAC = 0x0, }; @@ -190,6 +219,9 @@ struct e1000_device { uint32_t rx_cur_buffer; void* mem_base; + void* flash_base; + uint32_t flash_base_offset; + uint32_t flash_size; uint8_t revision; struct e1000_model* model; diff --git a/e1000/e1000_io.h b/e1000/e1000_io.h index 68937a9..2432b1c 100644 --- a/e1000/e1000_io.h +++ b/e1000/e1000_io.h @@ -74,4 +74,33 @@ static inline uint32_t reg_inl(struct e1000_device* netcard, uint16_t reg) return *mmio; } + +/* Flash register access */ + +static inline void flash_reg_outw + (struct e1000_device* netcard, uint16_t reg, uint16_t value) +{ + volatile uint16_t* mmio = (uint16_t*) (((char*)netcard->flash_base) + reg); + *mmio = value; +} + +static inline void flash_reg_outl + (struct e1000_device* netcard, uint16_t reg, uint32_t value) +{ + volatile uint32_t* mmio = (uint32_t*) (((char*)netcard->flash_base) + reg); + *mmio = value; +} + +static inline uint16_t flash_reg_inw(struct e1000_device* netcard, uint16_t reg) +{ + volatile uint16_t* mmio = (uint16_t*) (((char*)netcard->flash_base) + reg); + return *mmio; +} + +static inline uint32_t flash_reg_inl(struct e1000_device* netcard, uint16_t reg) +{ + volatile uint32_t* mmio = (uint32_t*) (((char*)netcard->flash_base) + reg); + return *mmio; +} + #endif -- 2.1.4 From kevin at tyndur.org Wed Dec 30 17:27:23 2015 From: kevin at tyndur.org (Kevin Wolf) Date: Wed, 30 Dec 2015 17:27:23 +0100 Subject: [cdi-devel] [PATCH 7/7] e1000: Wait for Link Up In-Reply-To: <1451492843-6394-1-git-send-email-kevin@tyndur.org> References: <1451492843-6394-1-git-send-email-kevin@tyndur.org> Message-ID: <1451492843-6394-8-git-send-email-kevin@tyndur.org> As we currently don't forward any link changes to the OS, the most reasonable thing to do is to wait a bit during device initialisation to give it a chance to have the link set up before the OS tries to make a DHCP request. Signed-off-by: Kevin Wolf --- e1000/device.c | 10 ++++++++++ e1000/device.h | 5 +++++ 2 files changed, 15 insertions(+) diff --git a/e1000/device.c b/e1000/device.c index d9e65c5..95ca731 100644 --- a/e1000/device.c +++ b/e1000/device.c @@ -508,6 +508,13 @@ found: printf("e1000: Fuehre Reset der Karte durch\n"); reset_nic(netcard); + printf("e1000: Warte auf Link\n"); + CDI_CONDITION_WAIT_SLEEP(reg_inl(netcard, REG_STATUS) & STATUS_LINK_UP, + 3000, 10); + if ((reg_inl(netcard, REG_STATUS) & STATUS_LINK_UP) == 0) { + printf("e1000: Kein Link\n"); + } + cdi_net_device_init(&netcard->net); // Interrupts aktivieren @@ -634,6 +641,9 @@ static void e1000_handle_interrupt(struct cdi_device* device) } else if (icr & ICR_TRANSMIT) { // Nichts zu tun + } else if (icr & ICR_LINK_CHANGE) { + printf("e1000: Link %s\n", + reg_inl(netcard, REG_STATUS) & STATUS_LINK_UP ? "up" : "down"); } else { #ifdef DEBUG printf("e1000: Unerwarteter Interrupt.\n"); diff --git a/e1000/device.h b/e1000/device.h index 638e6f9..85bca25 100644 --- a/e1000/device.h +++ b/e1000/device.h @@ -81,6 +81,10 @@ enum { }; enum { + STATUS_LINK_UP = (1 << 1), /* LU */ +}; + +enum { RCTL_ENABLE = (1 << 1), RCTL_BROADCAST = (1 << 15), /* BAM */ RCTL_2K_BUFSIZE = (0 << 16), /* BSIZE */ @@ -101,6 +105,7 @@ enum { enum { ICR_TRANSMIT = (1 << 0), + ICR_LINK_CHANGE = (1 << 2), ICR_RECEIVE = (1 << 7), }; -- 2.1.4