1/*
2 * Copyright (c) 2007-2013 ETH Zurich.
3 * All rights reserved.
4 *
5 * This file is distributed under the terms in the attached LICENSE file.
6 * If you do not find this file, copies can be found by writing to:
7 * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
8 */
9
10#include <stdlib.h>
11#include <stdio.h>
12#include <string.h>
13#include <barrelfish/barrelfish.h>
14
15#include <usb/usb.h>
16#include <usb/usb_parse.h>
17
18#include <if/usb_driver_defs.h>
19
20#include <usb_controller.h>
21#include <usb_device.h>
22#include <usb_request.h>
23#include <usb_pipe.h>
24#include <usb_interface.h>
25#include <usb_hub.h>
26#include <usb_transfer.h>
27#include <usb_endpoint.h>
28
29/**
30 * \brief frees up the allocated interface and enpoint structures for the
31 *        current configuration
32 *
33 * \param dev the usb device to free the structures
34 *
35 * NOTE: changing the configuration usually involves freeing up the old dat
36 */
37static void usb_device_free_config(struct usb_device *device)
38{
39    USB_DEBUG_TR_ENTER;
40
41    /* free the allocated array structures, if set */
42    if (device->ifaces != NULL) {
43        free(device->ifaces);
44    }
45
46    if (device->endpoints != NULL) {
47        free(device->endpoints);
48    }
49
50    /* update the pointers */
51    device->ep_clear_stall = NULL;
52    device->ifaces = NULL;
53    device->iface_max = 0;
54    device->endpoints = NULL;
55    device->ep_max = 0;
56}
57
58/**
59 * \brief this functions parses the configuration descriptor and allocates
60 *        the interface and endpoint structures for this configuration
61 *
62 * \param device the device to process the configuraiton
63 * \param iface the interface to initialze mostly USB_INTERFACE_ANY
64 * \��aram init  0=do allocation, 1=do initialization
65 *
66 * NOTE: usually you have to call first with init=0 to allocate the structures
67 *       then call with init=1 to initialize the allocated structures
68 */
69static usb_error_t usb_device_parse_config(struct usb_device *device,
70        uint8_t iface, uint8_t init)
71{
72    USB_DEBUG_TR_ENTER;
73
74    struct usb_iface_parse_state iface_ps;
75
76    /* variabels for tracking the endpoints */
77    struct usb_endpoint *ep;
78    uint8_t ep_max, ep_current;
79
80    /* the alternative interface index */
81    uint8_t alt_index = 0;
82
83    usb_error_t err = USB_ERR_OK;
84
85    if (iface != USB_INTERFACE_INDEX_ANY) {
86        /*
87         * this is some kind of parameter overloading, if we set the alternate
88         * index to a specific value
89         */
90        alt_index = init;
91        init = 2;
92    }
93
94    if (init) {
95        /*
96         * performa a reset on the allocated endpoints and check if they are
97         * still used or not.
98         */
99        ep = device->endpoints;
100        ep_max = device->ep_max;
101
102        while (ep_max--) {
103            if ((iface == USB_INTERFACE_INDEX_ANY)
104                    || (iface == ep->iface_index)) {
105                /* just check if the iface_index matches */
106                if (ep->ref_allocation != 0) {
107                    err = USB_ERR_IN_USE;
108                } else {
109                    /* perform the actual resetting */
110                    memset(ep, 0, sizeof(*ep));
111                    ep->iface_index = USB_INTERFACE_INDEX_ANY;
112                }
113            }
114            ep++;
115        }
116        if (err != USB_ERR_OK) {
117            return (err);
118        }
119    }
120
121    /* reset the interface parsing state */
122    memset(&iface_ps, 0, sizeof(iface_ps));
123
124    ep_current = 0;
125    ep_max = 0;
126    uint8_t ep_tmp = 0;
127
128    struct usb_interface_descriptor *idesc;
129    struct usb_interface *interface;
130    struct usb_endpoint_descriptor *edesc;
131    uint8_t iface_index = 0;
132
133    /*
134     * The config descriptor has the following structure
135     *    + interface descriptor 1
136     *      + endpoint descriptor 1
137     *      + endpoint descriptor 2
138     *    + interface descriptor 2
139     *      + endpoint descriptor 1
140     *      + endpoint descriptor 2
141     *
142     * we first have to get the next interface and then all the belonging
143     * endpoints
144     */
145    while ((idesc = usb_parse_next_iface(device->config_desc, &iface_ps))) {
146
147        if (iface_ps.iface_index == 32) {
148            /*
149             * there is a maximum of 32 interfaces, since the interface number
150             * is just 4 bits.
151             */
152            break;
153        }
154
155        /* get next interface location */
156        interface = device->ifaces + iface_ps.iface_index;
157
158        uint8_t do_init = 0;
159
160        if (init) {
161            /*
162             * if a specific interface other than USB_INTERFACE_INDEX_ANY is
163             * given, then we just want to initialize this given interface
164             */
165            if ((iface_index != USB_INTERFACE_INDEX_ANY)
166                    && (iface_index != iface_ps.iface_index)) {
167                do_init = 0;
168            } else if (alt_index != iface_ps.iface_index_alt) {
169                do_init = 0;
170            } else {
171                do_init = 1;
172            }
173        }
174
175        /* update the current endpoint count in case of an alternative iface*/
176        if (iface_ps.iface_index_alt == 0) {
177            ep_current = ep_max;
178        }
179
180        /* perform the initialization of the interface structure */
181        if (do_init) {
182            assert(interface != NULL);
183
184            interface->descriptor = idesc;
185            interface->parent_iface_index = USB_INTERFACE_INDEX_ANY;
186            interface->alt_setting = alt_index;
187        }
188
189        /*
190         * the endpoint descriptors are located in the configuration descriptor
191         * right after the interface descriptor. so we can use the address
192         * of the current interface descriptor as the starting point for
193         * looking for the first endpoint descriptor of this interface
194         */
195        edesc = (struct usb_endpoint_descriptor *) idesc;
196
197        ep_tmp = ep_current;
198
199        while ((edesc = usb_parse_next_edesc(device->config_desc, edesc))) {
200
201            if (ep_tmp == 32) {
202                /*
203                 * there are maximum 32 endpoints within an interface since the
204                 * endpoint number is just 4 bits long
205                 */
206                break;
207            }
208
209            /* get the location of the next endpoint */
210            ep = device->endpoints + ep_tmp;
211
212            if (do_init) {
213                /* initialize it if the memory is allocated */
214                usb_endpoint_init(device, iface_ps.iface_index, edesc, ep);
215            }
216
217            ep_tmp++;
218
219            if (ep_max < ep_tmp) {
220                /* update the current maximum found endpoints */
221                ep_max = ep_tmp;
222            }
223
224            /*
225             * update the interface descriptor pointer.
226             * NOTE: usb_parse_next_edesc returns null if there is no more
227             *       endpoint descriptor, so we have to do the update
228             *       within the loop to avoid null pointers
229             */
230            idesc = (struct usb_interface_descriptor *) edesc;
231        } /* parse next ep descriptor */
232    } /* parse next iface descriptor */
233
234    if (!init) {
235        /*
236         * allocate memory for the interface and endpoint structures according
237         * to the values of the number of found endpoints / interfaces
238         * in the code above.
239         */
240        device->iface_max = iface_ps.iface_index;
241        device->ifaces = NULL;
242        if (device->iface_max != 0) {
243            device->ifaces = malloc(sizeof(*interface) * device->iface_max);
244            if (device->ifaces == NULL) {
245                usb_device_free_config(device);
246                return (USB_ERR_NOMEM);
247            }
248        }
249
250        if (ep_max != 0) {
251            device->endpoints = malloc(sizeof(*ep) * ep_max);
252            if (device->endpoints == NULL) {
253                usb_device_free_config(device);
254                return (USB_ERR_NOMEM);
255            }
256            device->ep_max = ep_max;
257            /* XXX: clearing stall currently not supported */
258            device->ep_clear_stall = NULL;
259        }
260    }
261
262    return (USB_ERR_OK);
263}
264
265/**
266 * \brief initializes the device descriptor by executing the request on the
267 *        usb device
268 *
269 * \param device the device to initialize the device descriptor
270 */
271static usb_error_t usb_device_initialize_descriptor(struct usb_device *device)
272{
273    USB_DEBUG_TR_ENTER;
274
275    usb_error_t err;
276
277    switch (device->speed) {
278        case USB_SPEED_LOW:
279        case USB_SPEED_FULL:
280            /*
281             * full and low speed device have a maximum packet size of 8 bytes
282             * so we have to treat them a little bit special here
283             */
284            err = usb_req_get_descriptor(device, NULL, &device->device_desc, 8,
285                    8, 0, USB_DESCRIPTOR_TYPE_DEVICE, 0, 0);
286
287            if (err != USB_ERR_OK) {
288                USB_DEBUG("ERROR: Failed to get device descriptor\n");
289                USB_DEBUG_TR_RETURN;
290                return (err);
291            }
292            break;
293        default:
294            /*
295             * for high and super speed devices we have a maximum packet size
296             * of at least 64 bytes
297             */
298            break;
299    }
300
301    err = usb_req_get_device_descriptor(device, &device->device_desc);
302
303    if (err != USB_ERR_OK) {
304        /* retry once more */
305        USB_DEBUG("NOTICE: getting descriptor failed. retry.\n");
306        err = usb_req_get_device_descriptor(device, &device->device_desc);
307    }
308
309    return (err);
310}
311
312/**
313 * \brief changes the current configuration of the device
314 *
315 * \param device the device to update the configuration
316 * \param config the configuration value to set
317 *
318 * NOTE: This updates also the configuration descriptor and parses it
319 */
320usb_error_t usb_device_set_configuration(struct usb_device *device,
321        uint8_t config)
322{
323    USB_DEBUG_TR_ENTER;
324
325    if (config > device->device_desc.bNumConfigurations) {
326        USB_DEBUG("WARNING: setting configuration bigger than num config\n");
327        return (USB_ERR_INVAL);
328    }
329
330    /* free the old parsed configuration first i.e. the endpoints and ifaces */
331    usb_device_free_config(device);
332
333    /* free old config descriptor */
334    if (device->config_desc) {
335        free(device->config_desc);
336        device->config_desc = NULL;
337    }
338
339    /*
340     * if the configuration to be set is USB_CONFIGURATION_UNCONFIGURED
341     * then we don't process further and change the device state to
342     * ADDRESSED.
343     */
344    if (config == USB_CONFIGURATION_UNCONFIGURED) {
345        device->config_index = USB_CONFIGURATION_UNCONFIGURED;
346        device->config_number = 0;
347        if (device->state == USB_DEVICE_STATE_CONFIGURED) {
348            device->state = USB_DEVICE_STATE_ADDRESSED;
349        }
350        return (USB_ERR_OK);
351    }
352
353    usb_error_t err;
354    struct usb_config_descriptor *cdesc;
355
356    /* get the new configuration descriptor belonging to configuration config */
357    err = usb_req_get_config_descriptor(device, &cdesc, config);
358
359    if (err) {
360        USB_DEBUG("ERROR: getting configuration failed.\n");
361        USB_DEBUG_TR_RETURN;
362        return (err);
363    }
364
365    assert(cdesc != NULL);
366
367    /* update the configuration descriptor of the device */
368    device->config_desc = cdesc;
369
370    /*
371     * TODO: Check if the devices has its own power source or if it takes
372     * the power from the bus. This is important for attached hubs since
373     * it its not allowed to attach multiple bus powered hubs in series
374     */
375    device->flags.self_powered = 1;
376
377    /* update the device state and set the configuration values */
378    device->config_index = config;
379    device->config_number = cdesc->bConfigurationValue;
380    device->state = USB_DEVICE_STATE_CONFIGURED;
381
382    /* set the actual configuration value */
383    err = usb_req_set_config(device, cdesc->bConfigurationValue);
384
385    if (err != USB_ERR_OK) {
386        USB_DEBUG("ERROR: usb_req_set_config failed.\n");
387        USB_DEBUG_TR_RETURN;
388        return (err);
389    }
390
391    /* parse the configuration to allocate new interfaces and endpoints for
392     * this device and initialize them
393     */
394    err = usb_device_parse_config(device, USB_INTERFACE_INDEX_ANY, 0);
395    if (err) {
396        usb_device_free_config(device);
397        USB_DEBUG("WARNING: allocating ifaces and endpoints failed\n");
398        return (err);
399    }
400
401    err = usb_device_parse_config(device, USB_INTERFACE_INDEX_ANY, 1);
402    if (err) {
403        usb_device_free_config(device);
404        USB_DEBUG("WARNING: initialization of ifaces and endpoints failed\n");
405        return (err);
406    }
407
408    USB_DEBUG_TR_RETURN;
409
410    return (USB_ERR_OK);
411}
412
413static void usb_device_setup_strings(struct usb_device *device)
414{
415    char buf[255];
416
417    usb_req_get_string(device, buf, 255, device->device_desc.iSerialNumber);
418    device->serial_number = strdup(buf);
419
420    usb_req_get_string(device, buf, 255, device->device_desc.iManufacturer);
421    if (buf[0] == 0) {
422        snprintf(buf, 255, "vendor 0x%04x", device->device_desc.idVendor);
423    }
424    device->manifacturer = strdup(buf);
425
426    usb_req_get_string(device, buf, 255, device->device_desc.iProduct);
427    if (buf[0] == 0) {
428        snprintf(buf, 255, "product 0x%04x", device->device_desc.idProduct);
429        device->product = strdup(buf);
430    }
431    device->product = strdup(buf);
432
433}
434
435/**
436 * \brief allocates a newly discovered device and initializes it
437 *
438 * \param hc the host controller of the newly discovered device
439 * \param parent_hub the parent hub of the device
440 * \parem depth the depth of the device in the usb topology
441 * \param portindex the port index of the parent hub
442 * \param portno the port number the device is connected to
443 * \param speed speed information
444 * \��aram mode the mode of the device. Currently just USB_MODE_HOST
445 *
446 * \return pointer to a usb device on success
447 *         NULL on failure
448 */
449struct usb_device *usb_device_alloc(struct usb_host_controller *hc,
450        struct usb_device *parent_hub, uint8_t depth, uint8_t portindex,
451        uint8_t portno, usb_speed_t speed, usb_mode_t mode)
452{
453    USB_DEBUG_TR_ENTER;
454    usb_error_t err;
455
456    /*
457     * find and empty device index / address we can use, starting at the
458     * root hub device address which is 1 per default.
459     */
460    uint8_t device_index = USB_ROOTHUB_ADDRESS;
461    while (device_index < hc->devices_max) {
462        if (hc->devices[device_index] == NULL) {
463            break;
464        }
465        device_index++;
466    }
467
468    if (device_index == hc->devices_max) {
469        /* no free space on the bus */
470        USB_DEBUG("WARNING: No free device index!\n");
471        return (NULL);
472    }
473
474    /* the depth of the usb devices must not exceed 7 */
475    if (depth > 7) {
476        USB_DEBUG("ERROR: Invalid device depth.\n");
477        return (NULL);
478    }
479
480    struct usb_device *device = malloc(sizeof(struct usb_device));
481    if (device == NULL) {
482        USB_DEBUG("ERROR: no free mem.\n");
483        return (NULL);
484    }
485
486    /* make sure that everything has an expected value */
487    memset(device, 0, sizeof(struct usb_device));
488
489    /* counter for xfer IDs belonging to this device */
490    device->xfer_id = 1;
491
492    /* initialize the device with the supplied values */
493    device->parent_hub = parent_hub;
494    device->hub_port_index = portindex;
495    device->hub_port_number = portno;
496    device->depth = depth;
497    device->controller = hc;
498
499    /* all new devices have 0 als default start address */
500    device->device_address = 0;
501
502    /* setup default endpoint descriptor */
503    device->ctrl_ep_desc.bLength = sizeof(device->ctrl_ep_desc);
504    device->ctrl_ep_desc.bDescriptorType = USB_DESCRIPTOR_TYPE_ENDPOINT;
505
506    /*
507     * by setting the maximum packet size of the control endpoint to 8 bytes
508     * we ensure that the initial transactions can be executed by any device
509     */
510    device->ctrl_ep_desc.wMaxPacketSize = 8;
511    device->device_desc.bMaxPacketSize0 = 8;
512
513    device->speed = speed;
514    device->flags.usb_mode = mode;
515
516    /*
517     * find the parent high speed hub. This is needed for the transaction
518     * translator of the high speed hub. This may not always succeed, since
519     * the root hub has no parent hub and OHCI/UHCI only supportes FULL/LOW
520     * speed devices.
521     */
522    struct usb_device *hub = device->parent_hub;
523    struct usb_device *adev = device;
524
525    while (hub) {
526        if (hub->speed == USB_SPEED_HIGH) {
527            device->hs_hub_address = hub->device_address;
528            device->parent_hs_hub = hub;
529            device->hs_hub_port_number = adev->hub_port_number;
530            break;
531        }
532        adev = hub;
533        hub = hub->parent_hub;
534    }
535
536    /* initialize the control endpoint */
537    usb_endpoint_init(device, 0, &device->ctrl_ep_desc, &device->ctrl_ep);
538
539    device->device_index = device_index;
540
541    /* the devices is now attached and thus in the powered state */
542    device->state = USB_DEVICE_STATE_POWERED;
543
544    /* set the device address */
545    err = usb_req_set_address(device, device_index);
546
547    if (err) {
548        debug_printf("set address failed (ignored)\n");
549        return (NULL);
550    }
551
552    /* wait till the address has settled */
553    lib_usb_wait(USB_DELAY_SET_ADDRESS);
554
555    /*
556     * this check has to be done, since there may be a controller specific
557     * set address function that does this already for us, however this may
558     * not be the case, thus we have to check and do it ourself.
559     */
560    if (device->device_address == 0) {
561        USB_DEBUG_DEV("setting device address to %i\n", device_index);
562        device->device_address = device_index;
563    }
564
565    /* update the devices state to addressed */
566    device->state = USB_DEVICE_STATE_ADDRESSED;
567
568    /* initialize the device descriptor */
569    err = usb_device_initialize_descriptor(device);
570
571    assert(device->device_desc.bDescriptorType == USB_DESCRIPTOR_TYPE_DEVICE);
572
573    char buf[255];
574    memset(buf, 0, sizeof(buf));
575
576    /* try to read the string descriptors if any */
577    if (device->device_desc.iManufacturer || device->device_desc.iProduct
578            || device->device_desc.iSerialNumber) {
579        err = usb_req_get_string_desc(device, buf, 4, 0, 0);
580    } else {
581        /* there are no string descriptors.. setting to invalid */
582        err = USB_ERR_INVAL;
583    }
584
585    /* if there are any string descriptors try to get the language id */
586    if (err != USB_ERR_OK || buf[0] < 4) {
587        device->flags.no_strings = 1;
588    } else {
589        uint16_t langid = 0;
590
591        buf[0] &= ~1;
592        uint32_t i;
593        for (i = 2; i < buf[0]; i += 2) {
594            langid = (uint16_t) *(buf + i);
595            if ((langid & 0x00FF) == 0x0009) {
596                break;
597            }
598        }
599        if (i >= buf[0]) {
600            langid = (uint16_t) *(buf + 2);
601        }
602        device->language_id = langid;
603    }
604
605    /* setup the string descriptors by reading out the string descriptors */
606    usb_device_setup_strings(device);
607
608    /* TODO: check for the real power needs */
609    device->power_needed = USB_POWER_MIN;
610
611    /* finally set the configuration */
612    err = usb_device_set_configuration(device, 0);
613
614    if (err != USB_ERR_OK) {
615        if (device->device_desc.bNumConfigurations != 0) {
616            debug_printf("WARNING: Set configuration failed.\n");
617
618            USB_DEBUG("WARNING: getting descriptor failed. "
619            "Try to re-enumerate\n");
620            /* TODO: err = usb_req_re_enumerate(dev, NULL); */
621            assert(!"NYI: re-enumeration\n");
622            err = usb_device_set_configuration(device, 0);
623        }
624    }
625
626    if (err != USB_ERR_OK) {
627        usb_device_free(device, 0);
628        return (NULL);
629    }
630
631    /* set the device index on the port of the parent hub */
632    if (parent_hub) {
633        (parent_hub->hub->ports + portindex)->device_index = device_index;
634    }
635
636    if (device_index != 0) {
637        hc->devices[device_index] = device;
638    }
639
640    USB_DEBUG_TR_RETURN;
641
642    return (device);
643}
644
645/// state variable for the device detached
646static volatile uint8_t usb_device_detached = 0;
647
648/**
649 * \brief call back function when the detach notification is sent sucessfully
650 *
651 * \brief a pointer to the detached devices
652 */
653static void usb_device_detach_cb(void *a)
654{
655    struct usb_device *st = a;
656    free(st->usb_driver_binding);
657    free(st->usb_manager_binding);
658    st->usb_driver_binding = NULL;
659    st->usb_manager_binding = NULL;
660    usb_device_detached = 1;
661}
662
663/**
664 * \brief sends the detach notification
665 *
666 * \param a pointer to the detached device
667 */
668static void usb_device_detach_notify(void *a)
669{
670
671    struct usb_device *st = a;
672    errval_t err;
673
674    struct event_closure txcont = MKCONT(usb_device_detach_cb, st);
675
676    err = usb_driver_device_detach_notify__tx(st->usb_driver_binding, txcont);
677
678    if (err_is_fail(err)) {
679        if (err_no(err) == FLOUNDER_ERR_TX_BUSY) {
680            txcont = MKCONT(usb_device_detach_notify, st);
681            struct waitset *ws = get_default_waitset();
682            err = st->usb_driver_binding->register_send(st->usb_driver_binding,
683                    ws, txcont);
684            if (err_is_fail(err)) {
685                DEBUG_ERR(err, "error register_send on binding failed!\n");
686            }
687        } else {
688            DEBUG_ERR(err, "error _retry(): sending response!\n");\
689            free(st->usb_driver_binding);
690            free(st->usb_manager_binding);
691            st->usb_driver_binding = NULL;
692            st->usb_manager_binding = NULL;
693        }
694    }
695}
696
697/**
698 * \brief this function frees the allocated memory for a device
699 */
700void usb_device_free(struct usb_device * device, uint8_t flag)
701{
702    usb_device_detached = 1;
703    if (device->hub != NULL) {
704        debug_printf("Device was a hub device: TODO: recurse on other..");
705
706    } else {
707        if (device->usb_driver_binding != NULL) {
708            usb_device_detached = 0;
709            usb_device_detach_notify(device);
710        }
711    }
712
713    uint8_t timeout = 0;
714    while (!usb_device_detached) {
715        lib_usb_wait(10);
716        if (timeout > 5) {
717            break;
718        }
719        timeout++;
720    }
721
722    struct usb_xfer *xfer = device->xfers;
723    struct usb_xfer *xfer_next;
724
725    while (xfer != NULL) {
726        xfer_next = xfer->device_xfers_next;
727        usb_transfer_unsetup(&xfer, 1);
728        xfer = xfer_next;
729    }
730
731    device->controller->devices[device->device_index] = NULL;
732
733    if (device->config_desc)
734        free(device->config_desc);
735    if (device->ifaces)
736        free(device->ifaces);
737    if (device->endpoints)
738        free(device->endpoints);
739    if (device->serial_number)
740        free(device->serial_number);
741    if (device->manifacturer)
742        free(device->manifacturer);
743    if (device->product)
744        free(device->product);
745    if (device->ep_clear_stall)
746        free(device->ep_clear_stall);
747    free(device);
748}
749