xref: /openbmc/qemu/hw/usb/bus.c (revision 1dde0f48d53ad39401ec5064a61162d6784aad44)
1 #include "hw/hw.h"
2 #include "hw/usb.h"
3 #include "hw/qdev.h"
4 #include "sysemu/sysemu.h"
5 #include "monitor/monitor.h"
6 #include "trace.h"
7 
8 static void usb_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent);
9 
10 static char *usb_get_dev_path(DeviceState *dev);
11 static char *usb_get_fw_dev_path(DeviceState *qdev);
12 static void usb_qdev_unrealize(DeviceState *qdev, Error **errp);
13 
14 static Property usb_props[] = {
15     DEFINE_PROP_STRING("port", USBDevice, port_path),
16     DEFINE_PROP_STRING("serial", USBDevice, serial),
17     DEFINE_PROP_BIT("full-path", USBDevice, flags,
18                     USB_DEV_FLAG_FULL_PATH, true),
19     DEFINE_PROP_BIT("msos-desc", USBDevice, flags,
20                     USB_DEV_FLAG_MSOS_DESC_ENABLE, true),
21     DEFINE_PROP_END_OF_LIST()
22 };
23 
24 static void usb_bus_class_init(ObjectClass *klass, void *data)
25 {
26     BusClass *k = BUS_CLASS(klass);
27 
28     k->print_dev = usb_bus_dev_print;
29     k->get_dev_path = usb_get_dev_path;
30     k->get_fw_dev_path = usb_get_fw_dev_path;
31 }
32 
33 static const TypeInfo usb_bus_info = {
34     .name = TYPE_USB_BUS,
35     .parent = TYPE_BUS,
36     .instance_size = sizeof(USBBus),
37     .class_init = usb_bus_class_init,
38 };
39 
40 static int next_usb_bus = 0;
41 static QTAILQ_HEAD(, USBBus) busses = QTAILQ_HEAD_INITIALIZER(busses);
42 
43 static int usb_device_post_load(void *opaque, int version_id)
44 {
45     USBDevice *dev = opaque;
46 
47     if (dev->state == USB_STATE_NOTATTACHED) {
48         dev->attached = 0;
49     } else {
50         dev->attached = 1;
51     }
52     if (dev->setup_index < 0 ||
53         dev->setup_len < 0 ||
54         dev->setup_index > dev->setup_len ||
55         dev->setup_len > sizeof(dev->data_buf)) {
56         return -EINVAL;
57     }
58     return 0;
59 }
60 
61 const VMStateDescription vmstate_usb_device = {
62     .name = "USBDevice",
63     .version_id = 1,
64     .minimum_version_id = 1,
65     .post_load = usb_device_post_load,
66     .fields = (VMStateField[]) {
67         VMSTATE_UINT8(addr, USBDevice),
68         VMSTATE_INT32(state, USBDevice),
69         VMSTATE_INT32(remote_wakeup, USBDevice),
70         VMSTATE_INT32(setup_state, USBDevice),
71         VMSTATE_INT32(setup_len, USBDevice),
72         VMSTATE_INT32(setup_index, USBDevice),
73         VMSTATE_UINT8_ARRAY(setup_buf, USBDevice, 8),
74         VMSTATE_END_OF_LIST(),
75     }
76 };
77 
78 void usb_bus_new(USBBus *bus, size_t bus_size,
79                  USBBusOps *ops, DeviceState *host)
80 {
81     qbus_create_inplace(bus, bus_size, TYPE_USB_BUS, host, NULL);
82     bus->ops = ops;
83     bus->busnr = next_usb_bus++;
84     bus->qbus.allow_hotplug = 1; /* Yes, we can */
85     QTAILQ_INIT(&bus->free);
86     QTAILQ_INIT(&bus->used);
87     QTAILQ_INSERT_TAIL(&busses, bus, next);
88 }
89 
90 void usb_bus_release(USBBus *bus)
91 {
92     assert(next_usb_bus > 0);
93 
94     QTAILQ_REMOVE(&busses, bus, next);
95 }
96 
97 USBBus *usb_bus_find(int busnr)
98 {
99     USBBus *bus;
100 
101     if (-1 == busnr)
102         return QTAILQ_FIRST(&busses);
103     QTAILQ_FOREACH(bus, &busses, next) {
104         if (bus->busnr == busnr)
105             return bus;
106     }
107     return NULL;
108 }
109 
110 static void usb_device_realize(USBDevice *dev, Error **errp)
111 {
112     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
113 
114     if (klass->realize) {
115         klass->realize(dev, errp);
116     }
117 }
118 
119 USBDevice *usb_device_find_device(USBDevice *dev, uint8_t addr)
120 {
121     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
122     if (klass->find_device) {
123         return klass->find_device(dev, addr);
124     }
125     return NULL;
126 }
127 
128 static void usb_device_handle_destroy(USBDevice *dev)
129 {
130     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
131     if (klass->handle_destroy) {
132         klass->handle_destroy(dev);
133     }
134 }
135 
136 void usb_device_cancel_packet(USBDevice *dev, USBPacket *p)
137 {
138     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
139     if (klass->cancel_packet) {
140         klass->cancel_packet(dev, p);
141     }
142 }
143 
144 void usb_device_handle_attach(USBDevice *dev)
145 {
146     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
147     if (klass->handle_attach) {
148         klass->handle_attach(dev);
149     }
150 }
151 
152 void usb_device_handle_reset(USBDevice *dev)
153 {
154     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
155     if (klass->handle_reset) {
156         klass->handle_reset(dev);
157     }
158 }
159 
160 void usb_device_handle_control(USBDevice *dev, USBPacket *p, int request,
161                                int value, int index, int length, uint8_t *data)
162 {
163     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
164     if (klass->handle_control) {
165         klass->handle_control(dev, p, request, value, index, length, data);
166     }
167 }
168 
169 void usb_device_handle_data(USBDevice *dev, USBPacket *p)
170 {
171     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
172     if (klass->handle_data) {
173         klass->handle_data(dev, p);
174     }
175 }
176 
177 const char *usb_device_get_product_desc(USBDevice *dev)
178 {
179     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
180     return klass->product_desc;
181 }
182 
183 const USBDesc *usb_device_get_usb_desc(USBDevice *dev)
184 {
185     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
186     if (dev->usb_desc) {
187         return dev->usb_desc;
188     }
189     return klass->usb_desc;
190 }
191 
192 void usb_device_set_interface(USBDevice *dev, int interface,
193                               int alt_old, int alt_new)
194 {
195     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
196     if (klass->set_interface) {
197         klass->set_interface(dev, interface, alt_old, alt_new);
198     }
199 }
200 
201 void usb_device_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
202 {
203     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
204     if (klass->flush_ep_queue) {
205         klass->flush_ep_queue(dev, ep);
206     }
207 }
208 
209 void usb_device_ep_stopped(USBDevice *dev, USBEndpoint *ep)
210 {
211     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
212     if (klass->ep_stopped) {
213         klass->ep_stopped(dev, ep);
214     }
215 }
216 
217 int usb_device_alloc_streams(USBDevice *dev, USBEndpoint **eps, int nr_eps,
218                              int streams)
219 {
220     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
221     if (klass->alloc_streams) {
222         return klass->alloc_streams(dev, eps, nr_eps, streams);
223     }
224     return 0;
225 }
226 
227 void usb_device_free_streams(USBDevice *dev, USBEndpoint **eps, int nr_eps)
228 {
229     USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
230     if (klass->free_streams) {
231         klass->free_streams(dev, eps, nr_eps);
232     }
233 }
234 
235 static void usb_qdev_realize(DeviceState *qdev, Error **errp)
236 {
237     USBDevice *dev = USB_DEVICE(qdev);
238     Error *local_err = NULL;
239 
240     pstrcpy(dev->product_desc, sizeof(dev->product_desc),
241             usb_device_get_product_desc(dev));
242     dev->auto_attach = 1;
243     QLIST_INIT(&dev->strings);
244     usb_ep_init(dev);
245 
246     usb_claim_port(dev, &local_err);
247     if (local_err) {
248         error_propagate(errp, local_err);
249         return;
250     }
251 
252     usb_device_realize(dev, &local_err);
253     if (local_err) {
254         usb_release_port(dev);
255         error_propagate(errp, local_err);
256         return;
257     }
258 
259     if (dev->auto_attach) {
260         usb_device_attach(dev, &local_err);
261         if (local_err) {
262             usb_qdev_unrealize(qdev, NULL);
263             error_propagate(errp, local_err);
264             return;
265         }
266     }
267 }
268 
269 static void usb_qdev_unrealize(DeviceState *qdev, Error **errp)
270 {
271     USBDevice *dev = USB_DEVICE(qdev);
272 
273     if (dev->attached) {
274         usb_device_detach(dev);
275     }
276     usb_device_handle_destroy(dev);
277     if (dev->port) {
278         usb_release_port(dev);
279     }
280 }
281 
282 typedef struct LegacyUSBFactory
283 {
284     const char *name;
285     const char *usbdevice_name;
286     USBDevice *(*usbdevice_init)(USBBus *bus, const char *params);
287 } LegacyUSBFactory;
288 
289 static GSList *legacy_usb_factory;
290 
291 void usb_legacy_register(const char *typename, const char *usbdevice_name,
292                          USBDevice *(*usbdevice_init)(USBBus *bus,
293                                                       const char *params))
294 {
295     if (usbdevice_name) {
296         LegacyUSBFactory *f = g_malloc0(sizeof(*f));
297         f->name = typename;
298         f->usbdevice_name = usbdevice_name;
299         f->usbdevice_init = usbdevice_init;
300         legacy_usb_factory = g_slist_append(legacy_usb_factory, f);
301     }
302 }
303 
304 USBDevice *usb_create(USBBus *bus, const char *name)
305 {
306     DeviceState *dev;
307 
308     dev = qdev_create(&bus->qbus, name);
309     return USB_DEVICE(dev);
310 }
311 
312 USBDevice *usb_create_simple(USBBus *bus, const char *name)
313 {
314     USBDevice *dev = usb_create(bus, name);
315     int rc;
316 
317     if (!dev) {
318         error_report("Failed to create USB device '%s'", name);
319         return NULL;
320     }
321     rc = qdev_init(&dev->qdev);
322     if (rc < 0) {
323         error_report("Failed to initialize USB device '%s'", name);
324         return NULL;
325     }
326     return dev;
327 }
328 
329 static void usb_fill_port(USBPort *port, void *opaque, int index,
330                           USBPortOps *ops, int speedmask)
331 {
332     port->opaque = opaque;
333     port->index = index;
334     port->ops = ops;
335     port->speedmask = speedmask;
336     usb_port_location(port, NULL, index + 1);
337 }
338 
339 void usb_register_port(USBBus *bus, USBPort *port, void *opaque, int index,
340                        USBPortOps *ops, int speedmask)
341 {
342     usb_fill_port(port, opaque, index, ops, speedmask);
343     QTAILQ_INSERT_TAIL(&bus->free, port, next);
344     bus->nfree++;
345 }
346 
347 int usb_register_companion(const char *masterbus, USBPort *ports[],
348                            uint32_t portcount, uint32_t firstport,
349                            void *opaque, USBPortOps *ops, int speedmask)
350 {
351     USBBus *bus;
352     int i;
353 
354     QTAILQ_FOREACH(bus, &busses, next) {
355         if (strcmp(bus->qbus.name, masterbus) == 0) {
356             break;
357         }
358     }
359 
360     if (!bus || !bus->ops->register_companion) {
361         qerror_report(QERR_INVALID_PARAMETER_VALUE, "masterbus",
362                       "an USB masterbus");
363         if (bus) {
364             error_printf_unless_qmp(
365                 "USB bus '%s' does not allow companion controllers\n",
366                 masterbus);
367         }
368         return -1;
369     }
370 
371     for (i = 0; i < portcount; i++) {
372         usb_fill_port(ports[i], opaque, i, ops, speedmask);
373     }
374 
375     return bus->ops->register_companion(bus, ports, portcount, firstport);
376 }
377 
378 void usb_port_location(USBPort *downstream, USBPort *upstream, int portnr)
379 {
380     if (upstream) {
381         snprintf(downstream->path, sizeof(downstream->path), "%s.%d",
382                  upstream->path, portnr);
383         downstream->hubcount = upstream->hubcount + 1;
384     } else {
385         snprintf(downstream->path, sizeof(downstream->path), "%d", portnr);
386         downstream->hubcount = 0;
387     }
388 }
389 
390 void usb_unregister_port(USBBus *bus, USBPort *port)
391 {
392     if (port->dev) {
393         object_unparent(OBJECT(port->dev));
394     }
395     QTAILQ_REMOVE(&bus->free, port, next);
396     bus->nfree--;
397 }
398 
399 void usb_claim_port(USBDevice *dev, Error **errp)
400 {
401     USBBus *bus = usb_bus_from_device(dev);
402     USBPort *port;
403 
404     assert(dev->port == NULL);
405 
406     if (dev->port_path) {
407         QTAILQ_FOREACH(port, &bus->free, next) {
408             if (strcmp(port->path, dev->port_path) == 0) {
409                 break;
410             }
411         }
412         if (port == NULL) {
413             error_setg(errp, "Error: usb port %s (bus %s) not found (in use?)",
414                        dev->port_path, bus->qbus.name);
415             return;
416         }
417     } else {
418         if (bus->nfree == 1 && strcmp(object_get_typename(OBJECT(dev)), "usb-hub") != 0) {
419             /* Create a new hub and chain it on */
420             usb_create_simple(bus, "usb-hub");
421         }
422         if (bus->nfree == 0) {
423             error_setg(errp, "Error: tried to attach usb device %s to a bus "
424                        "with no free ports", dev->product_desc);
425             return;
426         }
427         port = QTAILQ_FIRST(&bus->free);
428     }
429     trace_usb_port_claim(bus->busnr, port->path);
430 
431     QTAILQ_REMOVE(&bus->free, port, next);
432     bus->nfree--;
433 
434     dev->port = port;
435     port->dev = dev;
436 
437     QTAILQ_INSERT_TAIL(&bus->used, port, next);
438     bus->nused++;
439 }
440 
441 void usb_release_port(USBDevice *dev)
442 {
443     USBBus *bus = usb_bus_from_device(dev);
444     USBPort *port = dev->port;
445 
446     assert(port != NULL);
447     trace_usb_port_release(bus->busnr, port->path);
448 
449     QTAILQ_REMOVE(&bus->used, port, next);
450     bus->nused--;
451 
452     dev->port = NULL;
453     port->dev = NULL;
454 
455     QTAILQ_INSERT_TAIL(&bus->free, port, next);
456     bus->nfree++;
457 }
458 
459 static void usb_mask_to_str(char *dest, size_t size,
460                             unsigned int speedmask)
461 {
462     static const struct {
463         unsigned int mask;
464         const char *name;
465     } speeds[] = {
466         { .mask = USB_SPEED_MASK_FULL,  .name = "full"  },
467         { .mask = USB_SPEED_MASK_HIGH,  .name = "high"  },
468         { .mask = USB_SPEED_MASK_SUPER, .name = "super" },
469     };
470     int i, pos = 0;
471 
472     for (i = 0; i < ARRAY_SIZE(speeds); i++) {
473         if (speeds[i].mask & speedmask) {
474             pos += snprintf(dest + pos, size - pos, "%s%s",
475                             pos ? "+" : "",
476                             speeds[i].name);
477         }
478     }
479 }
480 
481 void usb_check_attach(USBDevice *dev, Error **errp)
482 {
483     USBBus *bus = usb_bus_from_device(dev);
484     USBPort *port = dev->port;
485     char devspeed[32], portspeed[32];
486 
487     assert(port != NULL);
488     assert(!dev->attached);
489     usb_mask_to_str(devspeed, sizeof(devspeed), dev->speedmask);
490     usb_mask_to_str(portspeed, sizeof(portspeed), port->speedmask);
491     trace_usb_port_attach(bus->busnr, port->path,
492                           devspeed, portspeed);
493 
494     if (!(port->speedmask & dev->speedmask)) {
495         error_setg(errp, "Warning: speed mismatch trying to attach"
496                    " usb device \"%s\" (%s speed)"
497                    " to bus \"%s\", port \"%s\" (%s speed)",
498                    dev->product_desc, devspeed,
499                    bus->qbus.name, port->path, portspeed);
500         return;
501     }
502 }
503 
504 void usb_device_attach(USBDevice *dev, Error **errp)
505 {
506     USBPort *port = dev->port;
507     Error *local_err = NULL;
508 
509     usb_check_attach(dev, &local_err);
510     if (local_err) {
511         error_propagate(errp, local_err);
512         return;
513     }
514 
515     dev->attached++;
516     usb_attach(port);
517 }
518 
519 int usb_device_detach(USBDevice *dev)
520 {
521     USBBus *bus = usb_bus_from_device(dev);
522     USBPort *port = dev->port;
523 
524     assert(port != NULL);
525     assert(dev->attached);
526     trace_usb_port_detach(bus->busnr, port->path);
527 
528     usb_detach(port);
529     dev->attached--;
530     return 0;
531 }
532 
533 int usb_device_delete_addr(int busnr, int addr)
534 {
535     USBBus *bus;
536     USBPort *port;
537     USBDevice *dev;
538 
539     bus = usb_bus_find(busnr);
540     if (!bus)
541         return -1;
542 
543     QTAILQ_FOREACH(port, &bus->used, next) {
544         if (port->dev->addr == addr)
545             break;
546     }
547     if (!port)
548         return -1;
549     dev = port->dev;
550 
551     object_unparent(OBJECT(dev));
552     return 0;
553 }
554 
555 static const char *usb_speed(unsigned int speed)
556 {
557     static const char *txt[] = {
558         [ USB_SPEED_LOW  ] = "1.5",
559         [ USB_SPEED_FULL ] = "12",
560         [ USB_SPEED_HIGH ] = "480",
561         [ USB_SPEED_SUPER ] = "5000",
562     };
563     if (speed >= ARRAY_SIZE(txt))
564         return "?";
565     return txt[speed];
566 }
567 
568 static void usb_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent)
569 {
570     USBDevice *dev = USB_DEVICE(qdev);
571     USBBus *bus = usb_bus_from_device(dev);
572 
573     monitor_printf(mon, "%*saddr %d.%d, port %s, speed %s, name %s%s\n",
574                    indent, "", bus->busnr, dev->addr,
575                    dev->port ? dev->port->path : "-",
576                    usb_speed(dev->speed), dev->product_desc,
577                    dev->attached ? ", attached" : "");
578 }
579 
580 static char *usb_get_dev_path(DeviceState *qdev)
581 {
582     USBDevice *dev = USB_DEVICE(qdev);
583     DeviceState *hcd = qdev->parent_bus->parent;
584     char *id = NULL;
585 
586     if (dev->flags & (1 << USB_DEV_FLAG_FULL_PATH)) {
587         id = qdev_get_dev_path(hcd);
588     }
589     if (id) {
590         char *ret = g_strdup_printf("%s/%s", id, dev->port->path);
591         g_free(id);
592         return ret;
593     } else {
594         return g_strdup(dev->port->path);
595     }
596 }
597 
598 static char *usb_get_fw_dev_path(DeviceState *qdev)
599 {
600     USBDevice *dev = USB_DEVICE(qdev);
601     char *fw_path, *in;
602     ssize_t pos = 0, fw_len;
603     long nr;
604 
605     fw_len = 32 + strlen(dev->port->path) * 6;
606     fw_path = g_malloc(fw_len);
607     in = dev->port->path;
608     while (fw_len - pos > 0) {
609         nr = strtol(in, &in, 10);
610         if (in[0] == '.') {
611             /* some hub between root port and device */
612             pos += snprintf(fw_path + pos, fw_len - pos, "hub@%lx/", nr);
613             in++;
614         } else {
615             /* the device itself */
616             pos += snprintf(fw_path + pos, fw_len - pos, "%s@%lx",
617                             qdev_fw_name(qdev), nr);
618             break;
619         }
620     }
621     return fw_path;
622 }
623 
624 void usb_info(Monitor *mon, const QDict *qdict)
625 {
626     USBBus *bus;
627     USBDevice *dev;
628     USBPort *port;
629 
630     if (QTAILQ_EMPTY(&busses)) {
631         monitor_printf(mon, "USB support not enabled\n");
632         return;
633     }
634 
635     QTAILQ_FOREACH(bus, &busses, next) {
636         QTAILQ_FOREACH(port, &bus->used, next) {
637             dev = port->dev;
638             if (!dev)
639                 continue;
640             monitor_printf(mon, "  Device %d.%d, Port %s, Speed %s Mb/s, Product %s\n",
641                            bus->busnr, dev->addr, port->path, usb_speed(dev->speed),
642                            dev->product_desc);
643         }
644     }
645 }
646 
647 /* handle legacy -usbdevice cmd line option */
648 USBDevice *usbdevice_create(const char *cmdline)
649 {
650     USBBus *bus = usb_bus_find(-1 /* any */);
651     LegacyUSBFactory *f = NULL;
652     GSList *i;
653     char driver[32];
654     const char *params;
655     int len;
656 
657     params = strchr(cmdline,':');
658     if (params) {
659         params++;
660         len = params - cmdline;
661         if (len > sizeof(driver))
662             len = sizeof(driver);
663         pstrcpy(driver, len, cmdline);
664     } else {
665         params = "";
666         pstrcpy(driver, sizeof(driver), cmdline);
667     }
668 
669     for (i = legacy_usb_factory; i; i = i->next) {
670         f = i->data;
671         if (strcmp(f->usbdevice_name, driver) == 0) {
672             break;
673         }
674     }
675     if (i == NULL) {
676 #if 0
677         /* no error because some drivers are not converted (yet) */
678         error_report("usbdevice %s not found", driver);
679 #endif
680         return NULL;
681     }
682 
683     if (!bus) {
684         error_report("Error: no usb bus to attach usbdevice %s, "
685                      "please try -machine usb=on and check that "
686                      "the machine model supports USB", driver);
687         return NULL;
688     }
689 
690     if (!f->usbdevice_init) {
691         if (*params) {
692             error_report("usbdevice %s accepts no params", driver);
693             return NULL;
694         }
695         return usb_create_simple(bus, f->name);
696     }
697     return f->usbdevice_init(bus, params);
698 }
699 
700 static void usb_device_class_init(ObjectClass *klass, void *data)
701 {
702     DeviceClass *k = DEVICE_CLASS(klass);
703     k->bus_type = TYPE_USB_BUS;
704     k->unplug   = qdev_simple_unplug_cb;
705     k->realize  = usb_qdev_realize;
706     k->unrealize = usb_qdev_unrealize;
707     k->props    = usb_props;
708 }
709 
710 static const TypeInfo usb_device_type_info = {
711     .name = TYPE_USB_DEVICE,
712     .parent = TYPE_DEVICE,
713     .instance_size = sizeof(USBDevice),
714     .abstract = true,
715     .class_size = sizeof(USBDeviceClass),
716     .class_init = usb_device_class_init,
717 };
718 
719 static void usb_register_types(void)
720 {
721     type_register_static(&usb_bus_info);
722     type_register_static(&usb_device_type_info);
723 }
724 
725 type_init(usb_register_types)
726