1 // Main code for handling USB controllers and devices.
2 //
3 // Copyright (C) 2009-2013  Kevin O'Connor <kevin@koconnor.net>
4 //
5 // This file may be distributed under the terms of the GNU LGPLv3 license.
6 
7 #include "biosvar.h" // GET_GLOBAL
8 #include "config.h" // CONFIG_*
9 #include "malloc.h" // free
10 #include "output.h" // dprintf
11 #include "romfile.h" // romfile_loadint
12 #include "string.h" // memset
13 #include "usb.h" // struct usb_s
14 #include "usb-ehci.h" // ehci_setup
15 #include "usb-xhci.h" // xhci_setup
16 #include "usb-hid.h" // usb_keyboard_setup
17 #include "usb-hub.h" // usb_hub_setup
18 #include "usb-msc.h" // usb_msc_setup
19 #include "usb-ohci.h" // ohci_setup
20 #include "usb-uas.h" // usb_uas_setup
21 #include "usb-uhci.h" // uhci_setup
22 #include "util.h" // msleep
23 #include "x86.h" // __fls
24 
25 
26 /****************************************************************
27  * Controller function wrappers
28  ****************************************************************/
29 
30 // Allocate, update, or free a usb pipe.
31 static struct usb_pipe *
usb_realloc_pipe(struct usbdevice_s * usbdev,struct usb_pipe * pipe,struct usb_endpoint_descriptor * epdesc)32 usb_realloc_pipe(struct usbdevice_s *usbdev, struct usb_pipe *pipe
33                  , struct usb_endpoint_descriptor *epdesc)
34 {
35     switch (usbdev->hub->cntl->type) {
36     default:
37     case USB_TYPE_UHCI:
38         return uhci_realloc_pipe(usbdev, pipe, epdesc);
39     case USB_TYPE_OHCI:
40         return ohci_realloc_pipe(usbdev, pipe, epdesc);
41     case USB_TYPE_EHCI:
42         return ehci_realloc_pipe(usbdev, pipe, epdesc);
43     case USB_TYPE_XHCI:
44         return xhci_realloc_pipe(usbdev, pipe, epdesc);
45     }
46 }
47 
48 // Send a message on a control pipe using the default control descriptor.
49 static int
usb_send_pipe(struct usb_pipe * pipe_fl,int dir,const void * cmd,void * data,int datasize)50 usb_send_pipe(struct usb_pipe *pipe_fl, int dir, const void *cmd
51               , void *data, int datasize)
52 {
53     switch (GET_LOWFLAT(pipe_fl->type)) {
54     default:
55     case USB_TYPE_UHCI:
56         return uhci_send_pipe(pipe_fl, dir, cmd, data, datasize);
57     case USB_TYPE_OHCI:
58         if (MODESEGMENT)
59             return -1;
60         return ohci_send_pipe(pipe_fl, dir, cmd, data, datasize);
61     case USB_TYPE_EHCI:
62         return ehci_send_pipe(pipe_fl, dir, cmd, data, datasize);
63     case USB_TYPE_XHCI:
64         if (MODESEGMENT)
65             return -1;
66         return xhci_send_pipe(pipe_fl, dir, cmd, data, datasize);
67     }
68 }
69 
70 int
usb_poll_intr(struct usb_pipe * pipe_fl,void * data)71 usb_poll_intr(struct usb_pipe *pipe_fl, void *data)
72 {
73     ASSERT16();
74     switch (GET_LOWFLAT(pipe_fl->type)) {
75     default:
76     case USB_TYPE_UHCI:
77         return uhci_poll_intr(pipe_fl, data);
78     case USB_TYPE_OHCI:
79         return ohci_poll_intr(pipe_fl, data);
80     case USB_TYPE_EHCI:
81         return ehci_poll_intr(pipe_fl, data);
82     case USB_TYPE_XHCI: ;
83         return call32_params(xhci_poll_intr, pipe_fl
84                              , MAKE_FLATPTR(GET_SEG(SS), data), 0, -1);
85     }
86 }
87 
usb_32bit_pipe(struct usb_pipe * pipe_fl)88 int usb_32bit_pipe(struct usb_pipe *pipe_fl)
89 {
90     return (CONFIG_USB_XHCI && GET_LOWFLAT(pipe_fl->type) == USB_TYPE_XHCI)
91         || (CONFIG_USB_OHCI && GET_LOWFLAT(pipe_fl->type) == USB_TYPE_OHCI);
92 }
93 
94 
95 /****************************************************************
96  * Helper functions
97  ****************************************************************/
98 
99 // Allocate a usb pipe.
100 struct usb_pipe *
usb_alloc_pipe(struct usbdevice_s * usbdev,struct usb_endpoint_descriptor * epdesc)101 usb_alloc_pipe(struct usbdevice_s *usbdev
102                , struct usb_endpoint_descriptor *epdesc)
103 {
104     return usb_realloc_pipe(usbdev, NULL, epdesc);
105 }
106 
107 // Free an allocated control or bulk pipe.
108 void
usb_free_pipe(struct usbdevice_s * usbdev,struct usb_pipe * pipe)109 usb_free_pipe(struct usbdevice_s *usbdev, struct usb_pipe *pipe)
110 {
111     if (!pipe)
112         return;
113     usb_realloc_pipe(usbdev, pipe, NULL);
114 }
115 
116 // Send a message to the default control pipe of a device.
117 int
usb_send_default_control(struct usb_pipe * pipe,const struct usb_ctrlrequest * req,void * data)118 usb_send_default_control(struct usb_pipe *pipe, const struct usb_ctrlrequest *req
119                          , void *data)
120 {
121     return usb_send_pipe(pipe, req->bRequestType & USB_DIR_IN, req
122                          , data, req->wLength);
123 }
124 
125 // Send a message to a bulk endpoint
126 int
usb_send_bulk(struct usb_pipe * pipe_fl,int dir,void * data,int datasize)127 usb_send_bulk(struct usb_pipe *pipe_fl, int dir, void *data, int datasize)
128 {
129     return usb_send_pipe(pipe_fl, dir, NULL, data, datasize);
130 }
131 
132 // Check if a pipe for a given controller is on the freelist
133 int
usb_is_freelist(struct usb_s * cntl,struct usb_pipe * pipe)134 usb_is_freelist(struct usb_s *cntl, struct usb_pipe *pipe)
135 {
136     return pipe->cntl != cntl;
137 }
138 
139 // Add a pipe to the controller's freelist
140 void
usb_add_freelist(struct usb_pipe * pipe)141 usb_add_freelist(struct usb_pipe *pipe)
142 {
143     if (!pipe)
144         return;
145     struct usb_s *cntl = pipe->cntl;
146     pipe->freenext = cntl->freelist;
147     cntl->freelist = pipe;
148 }
149 
150 // Check for an available pipe on the freelist.
151 struct usb_pipe *
usb_get_freelist(struct usb_s * cntl,u8 eptype)152 usb_get_freelist(struct usb_s *cntl, u8 eptype)
153 {
154     struct usb_pipe **pfree = &cntl->freelist;
155     for (;;) {
156         struct usb_pipe *pipe = *pfree;
157         if (!pipe)
158             return NULL;
159         if (pipe->eptype == eptype) {
160             *pfree = pipe->freenext;
161             return pipe;
162         }
163         pfree = &pipe->freenext;
164     }
165 }
166 
167 // Fill "pipe" endpoint info from an endpoint descriptor.
168 void
usb_desc2pipe(struct usb_pipe * pipe,struct usbdevice_s * usbdev,struct usb_endpoint_descriptor * epdesc)169 usb_desc2pipe(struct usb_pipe *pipe, struct usbdevice_s *usbdev
170               , struct usb_endpoint_descriptor *epdesc)
171 {
172     pipe->cntl = usbdev->hub->cntl;
173     pipe->type = usbdev->hub->cntl->type;
174     pipe->ep = epdesc->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
175     pipe->devaddr = usbdev->devaddr;
176     pipe->speed = usbdev->speed;
177     pipe->maxpacket = epdesc->wMaxPacketSize;
178     pipe->eptype = epdesc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
179 }
180 
181 // Find the exponential period of the requested interrupt end point.
182 int
usb_get_period(struct usbdevice_s * usbdev,struct usb_endpoint_descriptor * epdesc)183 usb_get_period(struct usbdevice_s *usbdev
184                , struct usb_endpoint_descriptor *epdesc)
185 {
186     int period = epdesc->bInterval;
187     if (usbdev->speed != USB_HIGHSPEED)
188         return (period <= 0) ? 0 : __fls(period);
189     return (period <= 4) ? 0 : period - 4;
190 }
191 
192 // Maximum time (in ms) a data transfer should take
193 int
usb_xfer_time(struct usb_pipe * pipe,int datalen)194 usb_xfer_time(struct usb_pipe *pipe, int datalen)
195 {
196     // Use the maximum command time (5 seconds), except for
197     // set_address commands where we don't want to stall the boot if
198     // the device doesn't actually exist.  Add 100ms to account for
199     // any controller delays.
200     if (!GET_LOWFLAT(pipe->devaddr))
201         return USB_TIME_STATUS + 100;
202     return USB_TIME_COMMAND + 100;
203 }
204 
205 // Find the first endpoint of a given type in an interface description.
206 struct usb_endpoint_descriptor *
usb_find_desc(struct usbdevice_s * usbdev,int type,int dir)207 usb_find_desc(struct usbdevice_s *usbdev, int type, int dir)
208 {
209     struct usb_endpoint_descriptor *epdesc = (void*)&usbdev->iface[1];
210     for (;;) {
211         if ((void*)epdesc >= (void*)usbdev->iface + usbdev->imax
212             || epdesc->bDescriptorType == USB_DT_INTERFACE) {
213             return NULL;
214         }
215         if (epdesc->bDescriptorType == USB_DT_ENDPOINT
216             && (epdesc->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == dir
217             && (epdesc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == type)
218             return epdesc;
219         epdesc = (void*)epdesc + epdesc->bLength;
220     }
221 }
222 
223 // Get the first 8 bytes of the device descriptor.
224 static int
get_device_info8(struct usb_pipe * pipe,struct usb_device_descriptor * dinfo)225 get_device_info8(struct usb_pipe *pipe, struct usb_device_descriptor *dinfo)
226 {
227     struct usb_ctrlrequest req;
228     req.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
229     req.bRequest = USB_REQ_GET_DESCRIPTOR;
230     req.wValue = USB_DT_DEVICE<<8;
231     req.wIndex = 0;
232     req.wLength = 8;
233     return usb_send_default_control(pipe, &req, dinfo);
234 }
235 
236 static struct usb_config_descriptor *
get_device_config(struct usb_pipe * pipe)237 get_device_config(struct usb_pipe *pipe)
238 {
239     struct usb_config_descriptor cfg;
240 
241     struct usb_ctrlrequest req;
242     req.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
243     req.bRequest = USB_REQ_GET_DESCRIPTOR;
244     req.wValue = USB_DT_CONFIG<<8;
245     req.wIndex = 0;
246     req.wLength = sizeof(cfg);
247     int ret = usb_send_default_control(pipe, &req, &cfg);
248     if (ret)
249         return NULL;
250 
251     void *config = malloc_tmphigh(cfg.wTotalLength);
252     if (!config) {
253         warn_noalloc();
254         return NULL;
255     }
256     req.wLength = cfg.wTotalLength;
257     ret = usb_send_default_control(pipe, &req, config);
258     if (ret) {
259         free(config);
260         return NULL;
261     }
262     //hexdump(config, cfg.wTotalLength);
263     return config;
264 }
265 
266 static int
set_configuration(struct usb_pipe * pipe,u16 val)267 set_configuration(struct usb_pipe *pipe, u16 val)
268 {
269     struct usb_ctrlrequest req;
270     req.bRequestType = USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
271     req.bRequest = USB_REQ_SET_CONFIGURATION;
272     req.wValue = val;
273     req.wIndex = 0;
274     req.wLength = 0;
275     return usb_send_default_control(pipe, &req, NULL);
276 }
277 
278 
279 /****************************************************************
280  * Initialization and enumeration
281  ****************************************************************/
282 
283 static const int speed_to_ctlsize[] = {
284     [ USB_FULLSPEED  ] = 8,
285     [ USB_LOWSPEED   ] = 8,
286     [ USB_HIGHSPEED  ] = 64,
287     [ USB_SUPERSPEED ] = 512,
288 };
289 
290 // Assign an address to a device in the default state on the given
291 // controller.
292 static int
usb_set_address(struct usbdevice_s * usbdev)293 usb_set_address(struct usbdevice_s *usbdev)
294 {
295     ASSERT32FLAT();
296     struct usb_s *cntl = usbdev->hub->cntl;
297     dprintf(3, "set_address %p\n", cntl);
298     if (cntl->maxaddr >= USB_MAXADDR)
299         return -1;
300 
301     msleep(USB_TIME_RSTRCY);
302 
303     // Create a pipe for the default address.
304     struct usb_endpoint_descriptor epdesc = {
305         .wMaxPacketSize = speed_to_ctlsize[usbdev->speed],
306         .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
307     };
308     usbdev->defpipe = usb_alloc_pipe(usbdev, &epdesc);
309     if (!usbdev->defpipe)
310         return -1;
311 
312     // Send set_address command.
313     struct usb_ctrlrequest req;
314     req.bRequestType = USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
315     req.bRequest = USB_REQ_SET_ADDRESS;
316     req.wValue = cntl->maxaddr + 1;
317     req.wIndex = 0;
318     req.wLength = 0;
319     int ret = usb_send_default_control(usbdev->defpipe, &req, NULL);
320     if (ret) {
321         usb_free_pipe(usbdev, usbdev->defpipe);
322         return -1;
323     }
324 
325     msleep(USB_TIME_SETADDR_RECOVERY);
326 
327     cntl->maxaddr++;
328     usbdev->devaddr = cntl->maxaddr;
329     usbdev->defpipe = usb_realloc_pipe(usbdev, usbdev->defpipe, &epdesc);
330     if (!usbdev->defpipe)
331         return -1;
332     return 0;
333 }
334 
335 // Called for every found device - see if a driver is available for
336 // this device and do setup if so.
337 static int
configure_usb_device(struct usbdevice_s * usbdev)338 configure_usb_device(struct usbdevice_s *usbdev)
339 {
340     ASSERT32FLAT();
341     dprintf(3, "config_usb: %p\n", usbdev->defpipe);
342 
343     // Set the max packet size for endpoint 0 of this device.
344     struct usb_device_descriptor dinfo;
345     int ret = get_device_info8(usbdev->defpipe, &dinfo);
346     if (ret)
347         return 0;
348     u16 maxpacket = dinfo.bMaxPacketSize0;
349     if (dinfo.bcdUSB >= 0x0300)
350         maxpacket = 1 << dinfo.bMaxPacketSize0;
351     dprintf(3, "device rev=%04x cls=%02x sub=%02x proto=%02x size=%d\n"
352             , dinfo.bcdUSB, dinfo.bDeviceClass, dinfo.bDeviceSubClass
353             , dinfo.bDeviceProtocol, maxpacket);
354     if (maxpacket < 8)
355         return 0;
356     struct usb_endpoint_descriptor epdesc = {
357         .wMaxPacketSize = maxpacket,
358         .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
359     };
360     usbdev->defpipe = usb_realloc_pipe(usbdev, usbdev->defpipe, &epdesc);
361     if (!usbdev->defpipe)
362         return -1;
363 
364     // Get configuration
365     struct usb_config_descriptor *config = get_device_config(usbdev->defpipe);
366     if (!config)
367         return 0;
368 
369     // Determine if a driver exists for this device - only look at the
370     // first interface of the first configuration.
371     struct usb_interface_descriptor *iface = (void*)(&config[1]);
372     if (iface->bInterfaceClass != USB_CLASS_HID
373         && iface->bInterfaceClass != USB_CLASS_MASS_STORAGE
374         && iface->bInterfaceClass != USB_CLASS_HUB)
375         // Not a supported device.
376         goto fail;
377 
378     // Set the configuration.
379     ret = set_configuration(usbdev->defpipe, config->bConfigurationValue);
380     if (ret)
381         goto fail;
382 
383     // Configure driver.
384     usbdev->config = config;
385     usbdev->iface = iface;
386     usbdev->imax = (void*)config + config->wTotalLength - (void*)iface;
387     if (iface->bInterfaceClass == USB_CLASS_HUB)
388         ret = usb_hub_setup(usbdev);
389     else if (iface->bInterfaceClass == USB_CLASS_MASS_STORAGE) {
390         if (iface->bInterfaceProtocol == US_PR_BULK)
391             ret = usb_msc_setup(usbdev);
392         if (iface->bInterfaceProtocol == US_PR_UAS)
393             ret = usb_uas_setup(usbdev);
394     } else
395         ret = usb_hid_setup(usbdev);
396     if (ret)
397         goto fail;
398 
399     free(config);
400     return 1;
401 fail:
402     free(config);
403     return 0;
404 }
405 
406 static void
usb_hub_port_setup(void * data)407 usb_hub_port_setup(void *data)
408 {
409     struct usbdevice_s *usbdev = data;
410     struct usbhub_s *hub = usbdev->hub;
411     u32 port = usbdev->port;
412 
413     for (;;) {
414         // Detect if device present (and possibly start reset)
415         int ret = hub->op->detect(hub, port);
416         if (ret > 0)
417             // Device connected.
418             break;
419         if (ret < 0 || timer_check(hub->detectend))
420             // No device found.
421             goto done;
422         msleep(5);
423     }
424 
425     // XXX - wait USB_TIME_ATTDB time?
426 
427     // Reset port and determine device speed
428     mutex_lock(&hub->cntl->resetlock);
429     int ret = hub->op->reset(hub, port);
430     if (ret < 0)
431         // Reset failed
432         goto resetfail;
433     usbdev->speed = ret;
434 
435     // Set address of port
436     ret = usb_set_address(usbdev);
437     if (ret) {
438         hub->op->disconnect(hub, port);
439         goto resetfail;
440     }
441     mutex_unlock(&hub->cntl->resetlock);
442 
443     // Configure the device
444     int count = configure_usb_device(usbdev);
445     usb_free_pipe(usbdev, usbdev->defpipe);
446     if (!count)
447         hub->op->disconnect(hub, port);
448     hub->devcount += count;
449 done:
450     hub->threads--;
451     free(usbdev);
452     return;
453 
454 resetfail:
455     mutex_unlock(&hub->cntl->resetlock);
456     goto done;
457 }
458 
459 static u32 usb_time_sigatt;
460 
461 void
usb_enumerate(struct usbhub_s * hub)462 usb_enumerate(struct usbhub_s *hub)
463 {
464     u32 portcount = hub->portcount;
465     hub->threads = portcount;
466     hub->detectend = timer_calc(usb_time_sigatt);
467 
468     // Launch a thread for every port.
469     int i;
470     for (i=0; i<portcount; i++) {
471         struct usbdevice_s *usbdev = malloc_tmphigh(sizeof(*usbdev));
472         if (!usbdev) {
473             warn_noalloc();
474             continue;
475         }
476         memset(usbdev, 0, sizeof(*usbdev));
477         usbdev->hub = hub;
478         usbdev->port = i;
479         run_thread(usb_hub_port_setup, usbdev);
480     }
481 
482     // Wait for threads to complete.
483     while (hub->threads)
484         yield();
485 }
486 
487 void
usb_setup(void)488 usb_setup(void)
489 {
490     ASSERT32FLAT();
491     if (! CONFIG_USB)
492         return;
493     dprintf(3, "init usb\n");
494     usb_time_sigatt = romfile_loadint("etc/usb-time-sigatt", USB_TIME_SIGATT);
495     xhci_setup();
496     ehci_setup();
497     uhci_setup();
498     ohci_setup();
499 }
500