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