xref: /openbmc/qemu/hw/usb/dev-hub.c (revision 520e210c)
1 /*
2  * QEMU USB HUB emulation
3  *
4  * Copyright (c) 2005 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "qemu/osdep.h"
25 #include "qapi/error.h"
26 #include "qemu-common.h"
27 #include "trace.h"
28 #include "hw/usb.h"
29 #include "desc.h"
30 #include "qemu/error-report.h"
31 
32 #define NUM_PORTS 8
33 
34 typedef struct USBHubPort {
35     USBPort port;
36     uint16_t wPortStatus;
37     uint16_t wPortChange;
38 } USBHubPort;
39 
40 typedef struct USBHubState {
41     USBDevice dev;
42     USBEndpoint *intr;
43     USBHubPort ports[NUM_PORTS];
44 } USBHubState;
45 
46 #define TYPE_USB_HUB "usb-hub"
47 #define USB_HUB(obj) OBJECT_CHECK(USBHubState, (obj), TYPE_USB_HUB)
48 
49 #define ClearHubFeature		(0x2000 | USB_REQ_CLEAR_FEATURE)
50 #define ClearPortFeature	(0x2300 | USB_REQ_CLEAR_FEATURE)
51 #define GetHubDescriptor	(0xa000 | USB_REQ_GET_DESCRIPTOR)
52 #define GetHubStatus		(0xa000 | USB_REQ_GET_STATUS)
53 #define GetPortStatus		(0xa300 | USB_REQ_GET_STATUS)
54 #define SetHubFeature		(0x2000 | USB_REQ_SET_FEATURE)
55 #define SetPortFeature		(0x2300 | USB_REQ_SET_FEATURE)
56 
57 #define PORT_STAT_CONNECTION	0x0001
58 #define PORT_STAT_ENABLE	0x0002
59 #define PORT_STAT_SUSPEND	0x0004
60 #define PORT_STAT_OVERCURRENT	0x0008
61 #define PORT_STAT_RESET		0x0010
62 #define PORT_STAT_POWER		0x0100
63 #define PORT_STAT_LOW_SPEED	0x0200
64 #define PORT_STAT_HIGH_SPEED    0x0400
65 #define PORT_STAT_TEST          0x0800
66 #define PORT_STAT_INDICATOR     0x1000
67 
68 #define PORT_STAT_C_CONNECTION	0x0001
69 #define PORT_STAT_C_ENABLE	0x0002
70 #define PORT_STAT_C_SUSPEND	0x0004
71 #define PORT_STAT_C_OVERCURRENT	0x0008
72 #define PORT_STAT_C_RESET	0x0010
73 
74 #define PORT_CONNECTION	        0
75 #define PORT_ENABLE		1
76 #define PORT_SUSPEND		2
77 #define PORT_OVERCURRENT	3
78 #define PORT_RESET		4
79 #define PORT_POWER		8
80 #define PORT_LOWSPEED		9
81 #define PORT_HIGHSPEED		10
82 #define PORT_C_CONNECTION	16
83 #define PORT_C_ENABLE		17
84 #define PORT_C_SUSPEND		18
85 #define PORT_C_OVERCURRENT	19
86 #define PORT_C_RESET		20
87 #define PORT_TEST               21
88 #define PORT_INDICATOR          22
89 
90 /* same as Linux kernel root hubs */
91 
92 enum {
93     STR_MANUFACTURER = 1,
94     STR_PRODUCT,
95     STR_SERIALNUMBER,
96 };
97 
98 static const USBDescStrings desc_strings = {
99     [STR_MANUFACTURER] = "QEMU",
100     [STR_PRODUCT]      = "QEMU USB Hub",
101     [STR_SERIALNUMBER] = "314159",
102 };
103 
104 static const USBDescIface desc_iface_hub = {
105     .bInterfaceNumber              = 0,
106     .bNumEndpoints                 = 1,
107     .bInterfaceClass               = USB_CLASS_HUB,
108     .eps = (USBDescEndpoint[]) {
109         {
110             .bEndpointAddress      = USB_DIR_IN | 0x01,
111             .bmAttributes          = USB_ENDPOINT_XFER_INT,
112             .wMaxPacketSize        = 1 + DIV_ROUND_UP(NUM_PORTS, 8),
113             .bInterval             = 0xff,
114         },
115     }
116 };
117 
118 static const USBDescDevice desc_device_hub = {
119     .bcdUSB                        = 0x0110,
120     .bDeviceClass                  = USB_CLASS_HUB,
121     .bMaxPacketSize0               = 8,
122     .bNumConfigurations            = 1,
123     .confs = (USBDescConfig[]) {
124         {
125             .bNumInterfaces        = 1,
126             .bConfigurationValue   = 1,
127             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_SELFPOWER |
128                                      USB_CFG_ATT_WAKEUP,
129             .nif = 1,
130             .ifs = &desc_iface_hub,
131         },
132     },
133 };
134 
135 static const USBDesc desc_hub = {
136     .id = {
137         .idVendor          = 0x0409,
138         .idProduct         = 0x55aa,
139         .bcdDevice         = 0x0101,
140         .iManufacturer     = STR_MANUFACTURER,
141         .iProduct          = STR_PRODUCT,
142         .iSerialNumber     = STR_SERIALNUMBER,
143     },
144     .full = &desc_device_hub,
145     .str  = desc_strings,
146 };
147 
148 static const uint8_t qemu_hub_hub_descriptor[] =
149 {
150         0x00,			/*  u8  bLength; patched in later */
151         0x29,			/*  u8  bDescriptorType; Hub-descriptor */
152         0x00,			/*  u8  bNbrPorts; (patched later) */
153         0x0a,			/* u16  wHubCharacteristics; */
154         0x00,			/*   (per-port OC, no power switching) */
155         0x01,			/*  u8  bPwrOn2pwrGood; 2ms */
156         0x00			/*  u8  bHubContrCurrent; 0 mA */
157 
158         /* DeviceRemovable and PortPwrCtrlMask patched in later */
159 };
160 
161 static void usb_hub_attach(USBPort *port1)
162 {
163     USBHubState *s = port1->opaque;
164     USBHubPort *port = &s->ports[port1->index];
165 
166     trace_usb_hub_attach(s->dev.addr, port1->index + 1);
167     port->wPortStatus |= PORT_STAT_CONNECTION;
168     port->wPortChange |= PORT_STAT_C_CONNECTION;
169     if (port->port.dev->speed == USB_SPEED_LOW) {
170         port->wPortStatus |= PORT_STAT_LOW_SPEED;
171     } else {
172         port->wPortStatus &= ~PORT_STAT_LOW_SPEED;
173     }
174     usb_wakeup(s->intr, 0);
175 }
176 
177 static void usb_hub_detach(USBPort *port1)
178 {
179     USBHubState *s = port1->opaque;
180     USBHubPort *port = &s->ports[port1->index];
181 
182     trace_usb_hub_detach(s->dev.addr, port1->index + 1);
183     usb_wakeup(s->intr, 0);
184 
185     /* Let upstream know the device on this port is gone */
186     s->dev.port->ops->child_detach(s->dev.port, port1->dev);
187 
188     port->wPortStatus &= ~PORT_STAT_CONNECTION;
189     port->wPortChange |= PORT_STAT_C_CONNECTION;
190     if (port->wPortStatus & PORT_STAT_ENABLE) {
191         port->wPortStatus &= ~PORT_STAT_ENABLE;
192         port->wPortChange |= PORT_STAT_C_ENABLE;
193     }
194     if (port->wPortStatus & PORT_STAT_SUSPEND) {
195         port->wPortStatus &= ~PORT_STAT_SUSPEND;
196         port->wPortChange |= PORT_STAT_C_SUSPEND;
197     }
198     usb_wakeup(s->intr, 0);
199 }
200 
201 static void usb_hub_child_detach(USBPort *port1, USBDevice *child)
202 {
203     USBHubState *s = port1->opaque;
204 
205     /* Pass along upstream */
206     s->dev.port->ops->child_detach(s->dev.port, child);
207 }
208 
209 static void usb_hub_wakeup(USBPort *port1)
210 {
211     USBHubState *s = port1->opaque;
212     USBHubPort *port = &s->ports[port1->index];
213 
214     if (port->wPortStatus & PORT_STAT_SUSPEND) {
215         port->wPortStatus &= ~PORT_STAT_SUSPEND;
216         port->wPortChange |= PORT_STAT_C_SUSPEND;
217         usb_wakeup(s->intr, 0);
218     }
219 }
220 
221 static void usb_hub_complete(USBPort *port, USBPacket *packet)
222 {
223     USBHubState *s = port->opaque;
224 
225     /*
226      * Just pass it along upstream for now.
227      *
228      * If we ever implement usb 2.0 split transactions this will
229      * become a little more complicated ...
230      *
231      * Can't use usb_packet_complete() here because packet->owner is
232      * cleared already, go call the ->complete() callback directly
233      * instead.
234      */
235     s->dev.port->ops->complete(s->dev.port, packet);
236 }
237 
238 static USBDevice *usb_hub_find_device(USBDevice *dev, uint8_t addr)
239 {
240     USBHubState *s = USB_HUB(dev);
241     USBHubPort *port;
242     USBDevice *downstream;
243     int i;
244 
245     for (i = 0; i < NUM_PORTS; i++) {
246         port = &s->ports[i];
247         if (!(port->wPortStatus & PORT_STAT_ENABLE)) {
248             continue;
249         }
250         downstream = usb_find_device(&port->port, addr);
251         if (downstream != NULL) {
252             return downstream;
253         }
254     }
255     return NULL;
256 }
257 
258 static void usb_hub_handle_reset(USBDevice *dev)
259 {
260     USBHubState *s = USB_HUB(dev);
261     USBHubPort *port;
262     int i;
263 
264     trace_usb_hub_reset(s->dev.addr);
265     for (i = 0; i < NUM_PORTS; i++) {
266         port = s->ports + i;
267         port->wPortStatus = PORT_STAT_POWER;
268         port->wPortChange = 0;
269         if (port->port.dev && port->port.dev->attached) {
270             port->wPortStatus |= PORT_STAT_CONNECTION;
271             port->wPortChange |= PORT_STAT_C_CONNECTION;
272             if (port->port.dev->speed == USB_SPEED_LOW) {
273                 port->wPortStatus |= PORT_STAT_LOW_SPEED;
274             }
275         }
276     }
277 }
278 
279 static const char *feature_name(int feature)
280 {
281     static const char *name[] = {
282         [PORT_CONNECTION]    = "connection",
283         [PORT_ENABLE]        = "enable",
284         [PORT_SUSPEND]       = "suspend",
285         [PORT_OVERCURRENT]   = "overcurrent",
286         [PORT_RESET]         = "reset",
287         [PORT_POWER]         = "power",
288         [PORT_LOWSPEED]      = "lowspeed",
289         [PORT_HIGHSPEED]     = "highspeed",
290         [PORT_C_CONNECTION]  = "change connection",
291         [PORT_C_ENABLE]      = "change enable",
292         [PORT_C_SUSPEND]     = "change suspend",
293         [PORT_C_OVERCURRENT] = "change overcurrent",
294         [PORT_C_RESET]       = "change reset",
295         [PORT_TEST]          = "test",
296         [PORT_INDICATOR]     = "indicator",
297     };
298     if (feature < 0 || feature >= ARRAY_SIZE(name)) {
299         return "?";
300     }
301     return name[feature] ?: "?";
302 }
303 
304 static void usb_hub_handle_control(USBDevice *dev, USBPacket *p,
305                int request, int value, int index, int length, uint8_t *data)
306 {
307     USBHubState *s = (USBHubState *)dev;
308     int ret;
309 
310     trace_usb_hub_control(s->dev.addr, request, value, index, length);
311 
312     ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
313     if (ret >= 0) {
314         return;
315     }
316 
317     switch(request) {
318     case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
319         if (value == 0 && index != 0x81) { /* clear ep halt */
320             goto fail;
321         }
322         break;
323         /* usb specific requests */
324     case GetHubStatus:
325         data[0] = 0;
326         data[1] = 0;
327         data[2] = 0;
328         data[3] = 0;
329         p->actual_length = 4;
330         break;
331     case GetPortStatus:
332         {
333             unsigned int n = index - 1;
334             USBHubPort *port;
335             if (n >= NUM_PORTS) {
336                 goto fail;
337             }
338             port = &s->ports[n];
339             trace_usb_hub_get_port_status(s->dev.addr, index,
340                                           port->wPortStatus,
341                                           port->wPortChange);
342             data[0] = port->wPortStatus;
343             data[1] = port->wPortStatus >> 8;
344             data[2] = port->wPortChange;
345             data[3] = port->wPortChange >> 8;
346             p->actual_length = 4;
347         }
348         break;
349     case SetHubFeature:
350     case ClearHubFeature:
351         if (value != 0 && value != 1) {
352             goto fail;
353         }
354         break;
355     case SetPortFeature:
356         {
357             unsigned int n = index - 1;
358             USBHubPort *port;
359             USBDevice *dev;
360 
361             trace_usb_hub_set_port_feature(s->dev.addr, index,
362                                            feature_name(value));
363 
364             if (n >= NUM_PORTS) {
365                 goto fail;
366             }
367             port = &s->ports[n];
368             dev = port->port.dev;
369             switch(value) {
370             case PORT_SUSPEND:
371                 port->wPortStatus |= PORT_STAT_SUSPEND;
372                 break;
373             case PORT_RESET:
374                 if (dev && dev->attached) {
375                     usb_device_reset(dev);
376                     port->wPortChange |= PORT_STAT_C_RESET;
377                     /* set enable bit */
378                     port->wPortStatus |= PORT_STAT_ENABLE;
379                     usb_wakeup(s->intr, 0);
380                 }
381                 break;
382             case PORT_POWER:
383                 break;
384             default:
385                 goto fail;
386             }
387         }
388         break;
389     case ClearPortFeature:
390         {
391             unsigned int n = index - 1;
392             USBHubPort *port;
393 
394             trace_usb_hub_clear_port_feature(s->dev.addr, index,
395                                              feature_name(value));
396 
397             if (n >= NUM_PORTS) {
398                 goto fail;
399             }
400             port = &s->ports[n];
401             switch(value) {
402             case PORT_ENABLE:
403                 port->wPortStatus &= ~PORT_STAT_ENABLE;
404                 break;
405             case PORT_C_ENABLE:
406                 port->wPortChange &= ~PORT_STAT_C_ENABLE;
407                 break;
408             case PORT_SUSPEND:
409                 if (port->wPortStatus & PORT_STAT_SUSPEND) {
410                     port->wPortStatus &= ~PORT_STAT_SUSPEND;
411 
412                     /*
413                      * USB Spec rev2.0 11.24.2.7.2.3 C_PORT_SUSPEND
414                      * "This bit is set on the following transitions:
415                      *  - On transition from the Resuming state to the
416                      *    SendEOP [sic] state"
417                      *
418                      * Note that this includes both remote wake-up and
419                      * explicit ClearPortFeature(PORT_SUSPEND).
420                      */
421                     port->wPortChange |= PORT_STAT_C_SUSPEND;
422                 }
423                 break;
424             case PORT_C_SUSPEND:
425                 port->wPortChange &= ~PORT_STAT_C_SUSPEND;
426                 break;
427             case PORT_C_CONNECTION:
428                 port->wPortChange &= ~PORT_STAT_C_CONNECTION;
429                 break;
430             case PORT_C_OVERCURRENT:
431                 port->wPortChange &= ~PORT_STAT_C_OVERCURRENT;
432                 break;
433             case PORT_C_RESET:
434                 port->wPortChange &= ~PORT_STAT_C_RESET;
435                 break;
436             default:
437                 goto fail;
438             }
439         }
440         break;
441     case GetHubDescriptor:
442         {
443             unsigned int n, limit, var_hub_size = 0;
444             memcpy(data, qemu_hub_hub_descriptor,
445                    sizeof(qemu_hub_hub_descriptor));
446             data[2] = NUM_PORTS;
447 
448             /* fill DeviceRemovable bits */
449             limit = DIV_ROUND_UP(NUM_PORTS + 1, 8) + 7;
450             for (n = 7; n < limit; n++) {
451                 data[n] = 0x00;
452                 var_hub_size++;
453             }
454 
455             /* fill PortPwrCtrlMask bits */
456             limit = limit + DIV_ROUND_UP(NUM_PORTS, 8);
457             for (;n < limit; n++) {
458                 data[n] = 0xff;
459                 var_hub_size++;
460             }
461 
462             p->actual_length = sizeof(qemu_hub_hub_descriptor) + var_hub_size;
463             data[0] = p->actual_length;
464             break;
465         }
466     default:
467     fail:
468         p->status = USB_RET_STALL;
469         break;
470     }
471 }
472 
473 static void usb_hub_handle_data(USBDevice *dev, USBPacket *p)
474 {
475     USBHubState *s = (USBHubState *)dev;
476 
477     switch(p->pid) {
478     case USB_TOKEN_IN:
479         if (p->ep->nr == 1) {
480             USBHubPort *port;
481             unsigned int status;
482             uint8_t buf[4];
483             int i, n;
484             n = DIV_ROUND_UP(NUM_PORTS + 1, 8);
485             if (p->iov.size == 1) { /* FreeBSD workaround */
486                 n = 1;
487             } else if (n > p->iov.size) {
488                 p->status = USB_RET_BABBLE;
489                 return;
490             }
491             status = 0;
492             for(i = 0; i < NUM_PORTS; i++) {
493                 port = &s->ports[i];
494                 if (port->wPortChange)
495                     status |= (1 << (i + 1));
496             }
497             if (status != 0) {
498                 trace_usb_hub_status_report(s->dev.addr, status);
499                 for(i = 0; i < n; i++) {
500                     buf[i] = status >> (8 * i);
501                 }
502                 usb_packet_copy(p, buf, n);
503             } else {
504                 p->status = USB_RET_NAK; /* usb11 11.13.1 */
505             }
506         } else {
507             goto fail;
508         }
509         break;
510     case USB_TOKEN_OUT:
511     default:
512     fail:
513         p->status = USB_RET_STALL;
514         break;
515     }
516 }
517 
518 static void usb_hub_unrealize(USBDevice *dev, Error **errp)
519 {
520     USBHubState *s = (USBHubState *)dev;
521     int i;
522 
523     for (i = 0; i < NUM_PORTS; i++) {
524         usb_unregister_port(usb_bus_from_device(dev),
525                             &s->ports[i].port);
526     }
527 }
528 
529 static USBPortOps usb_hub_port_ops = {
530     .attach = usb_hub_attach,
531     .detach = usb_hub_detach,
532     .child_detach = usb_hub_child_detach,
533     .wakeup = usb_hub_wakeup,
534     .complete = usb_hub_complete,
535 };
536 
537 static void usb_hub_realize(USBDevice *dev, Error **errp)
538 {
539     USBHubState *s = USB_HUB(dev);
540     USBHubPort *port;
541     int i;
542 
543     if (dev->port->hubcount == 5) {
544         error_setg(errp, "usb hub chain too deep");
545         return;
546     }
547 
548     usb_desc_create_serial(dev);
549     usb_desc_init(dev);
550     s->intr = usb_ep_get(dev, USB_TOKEN_IN, 1);
551     for (i = 0; i < NUM_PORTS; i++) {
552         port = &s->ports[i];
553         usb_register_port(usb_bus_from_device(dev),
554                           &port->port, s, i, &usb_hub_port_ops,
555                           USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL);
556         usb_port_location(&port->port, dev->port, i+1);
557     }
558     usb_hub_handle_reset(dev);
559 }
560 
561 static const VMStateDescription vmstate_usb_hub_port = {
562     .name = "usb-hub-port",
563     .version_id = 1,
564     .minimum_version_id = 1,
565     .fields = (VMStateField[]) {
566         VMSTATE_UINT16(wPortStatus, USBHubPort),
567         VMSTATE_UINT16(wPortChange, USBHubPort),
568         VMSTATE_END_OF_LIST()
569     }
570 };
571 
572 static const VMStateDescription vmstate_usb_hub = {
573     .name = "usb-hub",
574     .version_id = 1,
575     .minimum_version_id = 1,
576     .fields = (VMStateField[]) {
577         VMSTATE_USB_DEVICE(dev, USBHubState),
578         VMSTATE_STRUCT_ARRAY(ports, USBHubState, NUM_PORTS, 0,
579                              vmstate_usb_hub_port, USBHubPort),
580         VMSTATE_END_OF_LIST()
581     }
582 };
583 
584 static void usb_hub_class_initfn(ObjectClass *klass, void *data)
585 {
586     DeviceClass *dc = DEVICE_CLASS(klass);
587     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
588 
589     uc->realize        = usb_hub_realize;
590     uc->product_desc   = "QEMU USB Hub";
591     uc->usb_desc       = &desc_hub;
592     uc->find_device    = usb_hub_find_device;
593     uc->handle_reset   = usb_hub_handle_reset;
594     uc->handle_control = usb_hub_handle_control;
595     uc->handle_data    = usb_hub_handle_data;
596     uc->unrealize      = usb_hub_unrealize;
597     set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
598     dc->fw_name = "hub";
599     dc->vmsd = &vmstate_usb_hub;
600 }
601 
602 static const TypeInfo hub_info = {
603     .name          = TYPE_USB_HUB,
604     .parent        = TYPE_USB_DEVICE,
605     .instance_size = sizeof(USBHubState),
606     .class_init    = usb_hub_class_initfn,
607 };
608 
609 static void usb_hub_register_types(void)
610 {
611     type_register_static(&hub_info);
612 }
613 
614 type_init(usb_hub_register_types)
615