xref: /openbmc/qemu/hw/usb/xen-usb.c (revision 2df9f571)
1 /*
2  *  xen paravirt usb device backend
3  *
4  *  (c) Juergen Gross <jgross@suse.com>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; under version 2 of the License.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License along
16  *  with this program; if not, see <http://www.gnu.org/licenses/>.
17  *
18  *  Contributions after 2012-01-13 are licensed under the terms of the
19  *  GNU GPL, version 2 or (at your option) any later version.
20  */
21 
22 #include "qemu/osdep.h"
23 #include <libusb.h>
24 #include <sys/user.h>
25 
26 #include "qemu/config-file.h"
27 #include "qemu/main-loop.h"
28 #include "qemu/option.h"
29 #include "hw/sysbus.h"
30 #include "hw/usb.h"
31 #include "hw/xen/xen-legacy-backend.h"
32 #include "monitor/qdev.h"
33 #include "qapi/qmp/qdict.h"
34 #include "qapi/qmp/qstring.h"
35 
36 #include "hw/xen/interface/io/usbif.h"
37 
38 /*
39  * Check for required support of usbif.h: USBIF_SHORT_NOT_OK was the last
40  * macro added we rely on.
41  */
42 #ifdef USBIF_SHORT_NOT_OK
43 
44 #define TR(xendev, lvl, fmt, args...)                               \
45     {                                                               \
46         struct timeval tv;                                          \
47                                                                     \
48         gettimeofday(&tv, NULL);                                    \
49         xen_pv_printf(xendev, lvl, "%8ld.%06ld xen-usb(%s):" fmt,   \
50                       tv.tv_sec, tv.tv_usec, __func__, ##args);     \
51     }
52 #define TR_BUS(xendev, fmt, args...) TR(xendev, 2, fmt, ##args)
53 #define TR_REQ(xendev, fmt, args...) TR(xendev, 3, fmt, ##args)
54 
55 #define USBBACK_MAXPORTS        USBIF_PIPE_PORT_MASK
56 #define USB_DEV_ADDR_SIZE       (USBIF_PIPE_DEV_MASK + 1)
57 
58 /* USB wire protocol: structure describing control request parameter. */
59 struct usbif_ctrlrequest {
60     uint8_t    bRequestType;
61     uint8_t    bRequest;
62     uint16_t   wValue;
63     uint16_t   wIndex;
64     uint16_t   wLength;
65 };
66 
67 struct usbback_info;
68 struct usbback_req;
69 
70 struct usbback_stub {
71     USBDevice     *dev;
72     USBPort       port;
73     unsigned int  speed;
74     bool          attached;
75     QTAILQ_HEAD(, usbback_req) submit_q;
76 };
77 
78 struct usbback_req {
79     struct usbback_info      *usbif;
80     struct usbback_stub      *stub;
81     struct usbif_urb_request req;
82     USBPacket                packet;
83 
84     unsigned int             nr_buffer_segs; /* # of transfer_buffer segments */
85     unsigned int             nr_extra_segs;  /* # of iso_frame_desc segments  */
86 
87     QTAILQ_ENTRY(usbback_req) q;
88 
89     void                     *buffer;
90     void                     *isoc_buffer;
91     struct libusb_transfer   *xfer;
92 
93     bool                     cancelled;
94 };
95 
96 struct usbback_hotplug {
97     QSIMPLEQ_ENTRY(usbback_hotplug) q;
98     unsigned                 port;
99 };
100 
101 struct usbback_info {
102     struct XenLegacyDevice         xendev;  /* must be first */
103     USBBus                   bus;
104     void                     *urb_sring;
105     void                     *conn_sring;
106     struct usbif_urb_back_ring urb_ring;
107     struct usbif_conn_back_ring conn_ring;
108     int                      num_ports;
109     int                      usb_ver;
110     bool                     ring_error;
111     QTAILQ_HEAD(, usbback_req) req_free_q;
112     QSIMPLEQ_HEAD(, usbback_hotplug) hotplug_q;
113     struct usbback_stub      ports[USBBACK_MAXPORTS];
114     struct usbback_stub      *addr_table[USB_DEV_ADDR_SIZE];
115     QEMUBH                   *bh;
116 };
117 
118 static struct usbback_req *usbback_get_req(struct usbback_info *usbif)
119 {
120     struct usbback_req *usbback_req;
121 
122     if (QTAILQ_EMPTY(&usbif->req_free_q)) {
123         usbback_req = g_new0(struct usbback_req, 1);
124     } else {
125         usbback_req = QTAILQ_FIRST(&usbif->req_free_q);
126         QTAILQ_REMOVE(&usbif->req_free_q, usbback_req, q);
127     }
128     return usbback_req;
129 }
130 
131 static void usbback_put_req(struct usbback_req *usbback_req)
132 {
133     struct usbback_info *usbif;
134 
135     usbif = usbback_req->usbif;
136     memset(usbback_req, 0, sizeof(*usbback_req));
137     QTAILQ_INSERT_HEAD(&usbif->req_free_q, usbback_req, q);
138 }
139 
140 static int usbback_gnttab_map(struct usbback_req *usbback_req)
141 {
142     unsigned int nr_segs, i, prot;
143     uint32_t ref[USBIF_MAX_SEGMENTS_PER_REQUEST];
144     struct usbback_info *usbif = usbback_req->usbif;
145     struct XenLegacyDevice *xendev = &usbif->xendev;
146     struct usbif_request_segment *seg;
147     void *addr;
148 
149     nr_segs = usbback_req->nr_buffer_segs + usbback_req->nr_extra_segs;
150     if (!nr_segs) {
151         return 0;
152     }
153 
154     if (nr_segs > USBIF_MAX_SEGMENTS_PER_REQUEST) {
155         xen_pv_printf(xendev, 0, "bad number of segments in request (%d)\n",
156                       nr_segs);
157         return -EINVAL;
158     }
159 
160     for (i = 0; i < nr_segs; i++) {
161         if ((unsigned)usbback_req->req.seg[i].offset +
162             (unsigned)usbback_req->req.seg[i].length > XC_PAGE_SIZE) {
163             xen_pv_printf(xendev, 0, "segment crosses page boundary\n");
164             return -EINVAL;
165         }
166     }
167 
168     if (usbback_req->nr_buffer_segs) {
169         prot = PROT_READ;
170         if (usbif_pipein(usbback_req->req.pipe)) {
171                 prot |= PROT_WRITE;
172         }
173         for (i = 0; i < usbback_req->nr_buffer_segs; i++) {
174             ref[i] = usbback_req->req.seg[i].gref;
175         }
176         usbback_req->buffer =
177             xen_be_map_grant_refs(xendev, ref, usbback_req->nr_buffer_segs,
178                                   prot);
179 
180         if (!usbback_req->buffer) {
181             return -ENOMEM;
182         }
183 
184         for (i = 0; i < usbback_req->nr_buffer_segs; i++) {
185             seg = usbback_req->req.seg + i;
186             addr = usbback_req->buffer + i * XC_PAGE_SIZE + seg->offset;
187             qemu_iovec_add(&usbback_req->packet.iov, addr, seg->length);
188         }
189     }
190 
191     if (!usbif_pipeisoc(usbback_req->req.pipe)) {
192         return 0;
193     }
194 
195     /*
196      * Right now isoc requests are not supported.
197      * Prepare supporting those by doing the work needed on the guest
198      * interface side.
199      */
200 
201     if (!usbback_req->nr_extra_segs) {
202         xen_pv_printf(xendev, 0, "iso request without descriptor segments\n");
203         return -EINVAL;
204     }
205 
206     prot = PROT_READ | PROT_WRITE;
207     for (i = 0; i < usbback_req->nr_extra_segs; i++) {
208         ref[i] = usbback_req->req.seg[i + usbback_req->req.nr_buffer_segs].gref;
209     }
210     usbback_req->isoc_buffer =
211         xen_be_map_grant_refs(xendev, ref, usbback_req->nr_extra_segs,
212                               prot);
213 
214     if (!usbback_req->isoc_buffer) {
215         return -ENOMEM;
216     }
217 
218     return 0;
219 }
220 
221 static int usbback_init_packet(struct usbback_req *usbback_req)
222 {
223     struct XenLegacyDevice *xendev = &usbback_req->usbif->xendev;
224     USBPacket *packet = &usbback_req->packet;
225     USBDevice *dev = usbback_req->stub->dev;
226     USBEndpoint *ep;
227     unsigned int pid, ep_nr;
228     bool sok;
229     int ret = 0;
230 
231     qemu_iovec_init(&packet->iov, USBIF_MAX_SEGMENTS_PER_REQUEST);
232     pid = usbif_pipein(usbback_req->req.pipe) ? USB_TOKEN_IN : USB_TOKEN_OUT;
233     ep_nr = usbif_pipeendpoint(usbback_req->req.pipe);
234     sok = !!(usbback_req->req.transfer_flags & USBIF_SHORT_NOT_OK);
235     if (usbif_pipectrl(usbback_req->req.pipe)) {
236         ep_nr = 0;
237         sok = false;
238     }
239     ep = usb_ep_get(dev, pid, ep_nr);
240     usb_packet_setup(packet, pid, ep, 0, 1, sok, true);
241 
242     switch (usbif_pipetype(usbback_req->req.pipe)) {
243     case USBIF_PIPE_TYPE_ISOC:
244         TR_REQ(xendev, "iso transfer %s: buflen: %x, %d frames\n",
245                (pid == USB_TOKEN_IN) ? "in" : "out",
246                usbback_req->req.buffer_length,
247                usbback_req->req.u.isoc.nr_frame_desc_segs);
248         ret = -EINVAL;  /* isoc not implemented yet */
249         break;
250 
251     case USBIF_PIPE_TYPE_INT:
252         TR_REQ(xendev, "int transfer %s: buflen: %x\n",
253                (pid == USB_TOKEN_IN) ? "in" : "out",
254                usbback_req->req.buffer_length);
255         break;
256 
257     case USBIF_PIPE_TYPE_CTRL:
258         packet->parameter = *(uint64_t *)usbback_req->req.u.ctrl;
259         TR_REQ(xendev, "ctrl parameter: %"PRIx64", buflen: %x\n",
260                packet->parameter,
261                usbback_req->req.buffer_length);
262         break;
263 
264     case USBIF_PIPE_TYPE_BULK:
265         TR_REQ(xendev, "bulk transfer %s: buflen: %x\n",
266                (pid == USB_TOKEN_IN) ? "in" : "out",
267                usbback_req->req.buffer_length);
268         break;
269     default:
270         ret = -EINVAL;
271         break;
272     }
273 
274     return ret;
275 }
276 
277 static void usbback_do_response(struct usbback_req *usbback_req, int32_t status,
278                                 int32_t actual_length, int32_t error_count)
279 {
280     struct usbback_info *usbif;
281     struct usbif_urb_response *res;
282     struct XenLegacyDevice *xendev;
283     unsigned int notify;
284 
285     usbif = usbback_req->usbif;
286     xendev = &usbif->xendev;
287 
288     TR_REQ(xendev, "id %d, status %d, length %d, errcnt %d\n",
289            usbback_req->req.id, status, actual_length, error_count);
290 
291     if (usbback_req->packet.iov.iov) {
292         qemu_iovec_destroy(&usbback_req->packet.iov);
293     }
294 
295     if (usbback_req->buffer) {
296         xen_be_unmap_grant_refs(xendev, usbback_req->buffer,
297                                 usbback_req->nr_buffer_segs);
298         usbback_req->buffer = NULL;
299     }
300 
301     if (usbback_req->isoc_buffer) {
302         xen_be_unmap_grant_refs(xendev, usbback_req->isoc_buffer,
303                                 usbback_req->nr_extra_segs);
304         usbback_req->isoc_buffer = NULL;
305     }
306 
307     if (usbif->urb_sring) {
308         res = RING_GET_RESPONSE(&usbif->urb_ring, usbif->urb_ring.rsp_prod_pvt);
309         res->id = usbback_req->req.id;
310         res->status = status;
311         res->actual_length = actual_length;
312         res->error_count = error_count;
313         res->start_frame = 0;
314         usbif->urb_ring.rsp_prod_pvt++;
315         RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&usbif->urb_ring, notify);
316 
317         if (notify) {
318             xen_pv_send_notify(xendev);
319         }
320     }
321 
322     if (!usbback_req->cancelled)
323         usbback_put_req(usbback_req);
324 }
325 
326 static void usbback_do_response_ret(struct usbback_req *usbback_req,
327                                     int32_t status)
328 {
329     usbback_do_response(usbback_req, status, 0, 0);
330 }
331 
332 static int32_t usbback_xlat_status(int status)
333 {
334     switch (status) {
335     case USB_RET_SUCCESS:
336         return 0;
337     case USB_RET_NODEV:
338         return -ENODEV;
339     case USB_RET_STALL:
340         return -EPIPE;
341     case USB_RET_BABBLE:
342         return -EOVERFLOW;
343     case USB_RET_IOERROR:
344         return -EPROTO;
345     }
346 
347     return -ESHUTDOWN;
348 }
349 
350 static void usbback_packet_complete(struct usbback_req *usbback_req)
351 {
352     USBPacket *packet = &usbback_req->packet;
353     int32_t status;
354 
355     QTAILQ_REMOVE(&usbback_req->stub->submit_q, usbback_req, q);
356 
357     status = usbback_xlat_status(packet->status);
358     usbback_do_response(usbback_req, status, packet->actual_length, 0);
359 }
360 
361 static void usbback_set_address(struct usbback_info *usbif,
362                                 struct usbback_stub *stub,
363                                 unsigned int cur_addr, unsigned int new_addr)
364 {
365     if (cur_addr) {
366         usbif->addr_table[cur_addr] = NULL;
367     }
368     if (new_addr) {
369         usbif->addr_table[new_addr] = stub;
370     }
371 }
372 
373 static void usbback_cancel_req(struct usbback_req *usbback_req)
374 {
375     if (usb_packet_is_inflight(&usbback_req->packet)) {
376         usb_cancel_packet(&usbback_req->packet);
377         QTAILQ_REMOVE(&usbback_req->stub->submit_q, usbback_req, q);
378         usbback_req->cancelled = true;
379         usbback_do_response_ret(usbback_req, -EPROTO);
380     }
381 }
382 
383 static void usbback_process_unlink_req(struct usbback_req *usbback_req)
384 {
385     struct usbback_info *usbif;
386     struct usbback_req *unlink_req;
387     unsigned int id, devnum;
388     int ret;
389 
390     usbif = usbback_req->usbif;
391     ret = 0;
392     id = usbback_req->req.u.unlink.unlink_id;
393     TR_REQ(&usbif->xendev, "unlink id %d\n", id);
394     devnum = usbif_pipedevice(usbback_req->req.pipe);
395     if (unlikely(devnum == 0)) {
396         usbback_req->stub = usbif->ports +
397                             usbif_pipeportnum(usbback_req->req.pipe) - 1;
398         if (unlikely(!usbback_req->stub)) {
399             ret = -ENODEV;
400             goto fail_response;
401         }
402     } else {
403         if (unlikely(!usbif->addr_table[devnum])) {
404             ret = -ENODEV;
405             goto fail_response;
406         }
407         usbback_req->stub = usbif->addr_table[devnum];
408     }
409 
410     QTAILQ_FOREACH(unlink_req, &usbback_req->stub->submit_q, q) {
411         if (unlink_req->req.id == id) {
412             usbback_cancel_req(unlink_req);
413             break;
414         }
415     }
416 
417 fail_response:
418     usbback_do_response_ret(usbback_req, ret);
419 }
420 
421 /*
422  * Checks whether a request can be handled at once or should be forwarded
423  * to the usb framework.
424  * Return value is:
425  * 0 in case of usb framework is needed
426  * 1 in case of local handling (no error)
427  * The request response has been queued already if return value not 0.
428  */
429 static int usbback_check_and_submit(struct usbback_req *usbback_req)
430 {
431     struct usbback_info *usbif;
432     unsigned int devnum;
433     struct usbback_stub *stub;
434     struct usbif_ctrlrequest *ctrl;
435     int ret;
436     uint16_t wValue;
437 
438     usbif = usbback_req->usbif;
439     stub = NULL;
440     devnum = usbif_pipedevice(usbback_req->req.pipe);
441     ctrl = (struct usbif_ctrlrequest *)usbback_req->req.u.ctrl;
442     wValue = le16_to_cpu(ctrl->wValue);
443 
444     /*
445      * When the device is first connected or resetted, USB device has no
446      * address. In this initial state, following requests are sent to device
447      * address (#0),
448      *
449      *  1. GET_DESCRIPTOR (with Descriptor Type is "DEVICE") is sent,
450      *     and OS knows what device is connected to.
451      *
452      *  2. SET_ADDRESS is sent, and then device has its address.
453      *
454      * In the next step, SET_CONFIGURATION is sent to addressed device, and
455      * then the device is finally ready to use.
456      */
457     if (unlikely(devnum == 0)) {
458         stub = usbif->ports + usbif_pipeportnum(usbback_req->req.pipe) - 1;
459         if (!stub->dev || !stub->attached) {
460             ret = -ENODEV;
461             goto do_response;
462         }
463 
464         switch (ctrl->bRequest) {
465         case USB_REQ_GET_DESCRIPTOR:
466             /*
467              * GET_DESCRIPTOR request to device #0.
468              * through normal transfer.
469              */
470             TR_REQ(&usbif->xendev, "devnum 0 GET_DESCRIPTOR\n");
471             usbback_req->stub = stub;
472             return 0;
473         case USB_REQ_SET_ADDRESS:
474             /*
475              * SET_ADDRESS request to device #0.
476              * add attached device to addr_table.
477              */
478             TR_REQ(&usbif->xendev, "devnum 0 SET_ADDRESS\n");
479             usbback_set_address(usbif, stub, 0, wValue);
480             ret = 0;
481             break;
482         default:
483             ret = -EINVAL;
484             break;
485         }
486         goto do_response;
487     }
488 
489     if (unlikely(!usbif->addr_table[devnum])) {
490             ret = -ENODEV;
491             goto do_response;
492     }
493     usbback_req->stub = usbif->addr_table[devnum];
494 
495     /*
496      * Check special request
497      */
498     if (ctrl->bRequest != USB_REQ_SET_ADDRESS) {
499         return 0;
500     }
501 
502     /*
503      * SET_ADDRESS request to addressed device.
504      * change addr or remove from addr_table.
505      */
506     usbback_set_address(usbif, usbback_req->stub, devnum, wValue);
507     ret = 0;
508 
509 do_response:
510     usbback_do_response_ret(usbback_req, ret);
511     return 1;
512 }
513 
514 static void usbback_dispatch(struct usbback_req *usbback_req)
515 {
516     int ret;
517     unsigned int devnum;
518     struct usbback_info *usbif;
519 
520     usbif = usbback_req->usbif;
521 
522     TR_REQ(&usbif->xendev, "start req_id %d pipe %08x\n", usbback_req->req.id,
523            usbback_req->req.pipe);
524 
525     /* unlink request */
526     if (unlikely(usbif_pipeunlink(usbback_req->req.pipe))) {
527         usbback_process_unlink_req(usbback_req);
528         return;
529     }
530 
531     if (usbif_pipectrl(usbback_req->req.pipe)) {
532         if (usbback_check_and_submit(usbback_req)) {
533             return;
534         }
535     } else {
536         devnum = usbif_pipedevice(usbback_req->req.pipe);
537         usbback_req->stub = usbif->addr_table[devnum];
538 
539         if (!usbback_req->stub || !usbback_req->stub->attached) {
540             ret = -ENODEV;
541             goto fail_response;
542         }
543     }
544 
545     QTAILQ_INSERT_TAIL(&usbback_req->stub->submit_q, usbback_req, q);
546 
547     usbback_req->nr_buffer_segs = usbback_req->req.nr_buffer_segs;
548     usbback_req->nr_extra_segs = usbif_pipeisoc(usbback_req->req.pipe) ?
549                                  usbback_req->req.u.isoc.nr_frame_desc_segs : 0;
550 
551     ret = usbback_init_packet(usbback_req);
552     if (ret) {
553         xen_pv_printf(&usbif->xendev, 0, "invalid request\n");
554         ret = -ESHUTDOWN;
555         goto fail_free_urb;
556     }
557 
558     ret = usbback_gnttab_map(usbback_req);
559     if (ret) {
560         xen_pv_printf(&usbif->xendev, 0, "invalid buffer, ret=%d\n", ret);
561         ret = -ESHUTDOWN;
562         goto fail_free_urb;
563     }
564 
565     usb_handle_packet(usbback_req->stub->dev, &usbback_req->packet);
566     if (usbback_req->packet.status != USB_RET_ASYNC) {
567         usbback_packet_complete(usbback_req);
568     }
569     return;
570 
571 fail_free_urb:
572     QTAILQ_REMOVE(&usbback_req->stub->submit_q, usbback_req, q);
573 
574 fail_response:
575     usbback_do_response_ret(usbback_req, ret);
576 }
577 
578 static void usbback_hotplug_notify(struct usbback_info *usbif)
579 {
580     struct usbif_conn_back_ring *ring = &usbif->conn_ring;
581     struct usbif_conn_request req;
582     struct usbif_conn_response *res;
583     struct usbback_hotplug *usb_hp;
584     unsigned int notify;
585 
586     if (!usbif->conn_sring) {
587         return;
588     }
589 
590     /* Check for full ring. */
591     if ((RING_SIZE(ring) - ring->rsp_prod_pvt - ring->req_cons) == 0) {
592         xen_pv_send_notify(&usbif->xendev);
593         return;
594     }
595 
596     usb_hp = QSIMPLEQ_FIRST(&usbif->hotplug_q);
597     QSIMPLEQ_REMOVE_HEAD(&usbif->hotplug_q, q);
598 
599     RING_COPY_REQUEST(ring, ring->req_cons, &req);
600     ring->req_cons++;
601     ring->sring->req_event = ring->req_cons + 1;
602 
603     res = RING_GET_RESPONSE(ring, ring->rsp_prod_pvt);
604     res->id = req.id;
605     res->portnum = usb_hp->port;
606     res->speed = usbif->ports[usb_hp->port - 1].speed;
607     ring->rsp_prod_pvt++;
608     RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(ring, notify);
609 
610     if (notify) {
611         xen_pv_send_notify(&usbif->xendev);
612     }
613 
614     TR_BUS(&usbif->xendev, "hotplug port %d speed %d\n", usb_hp->port,
615            res->speed);
616 
617     g_free(usb_hp);
618 
619     if (!QSIMPLEQ_EMPTY(&usbif->hotplug_q)) {
620         qemu_bh_schedule(usbif->bh);
621     }
622 }
623 
624 static void usbback_bh(void *opaque)
625 {
626     struct usbback_info *usbif;
627     struct usbif_urb_back_ring *urb_ring;
628     struct usbback_req *usbback_req;
629     RING_IDX rc, rp;
630     unsigned int more_to_do;
631 
632     usbif = opaque;
633     if (usbif->ring_error) {
634         return;
635     }
636 
637     if (!QSIMPLEQ_EMPTY(&usbif->hotplug_q)) {
638         usbback_hotplug_notify(usbif);
639     }
640 
641     urb_ring = &usbif->urb_ring;
642     rc = urb_ring->req_cons;
643     rp = urb_ring->sring->req_prod;
644     xen_rmb(); /* Ensure we see queued requests up to 'rp'. */
645 
646     if (RING_REQUEST_PROD_OVERFLOW(urb_ring, rp)) {
647         rc = urb_ring->rsp_prod_pvt;
648         xen_pv_printf(&usbif->xendev, 0, "domU provided bogus ring requests "
649                       "(%#x - %#x = %u). Halting ring processing.\n",
650                       rp, rc, rp - rc);
651         usbif->ring_error = true;
652         return;
653     }
654 
655     while (rc != rp) {
656         if (RING_REQUEST_CONS_OVERFLOW(urb_ring, rc)) {
657             break;
658         }
659         usbback_req = usbback_get_req(usbif);
660 
661         RING_COPY_REQUEST(urb_ring, rc, &usbback_req->req);
662         usbback_req->usbif = usbif;
663 
664         usbback_dispatch(usbback_req);
665 
666         urb_ring->req_cons = ++rc;
667     }
668 
669     RING_FINAL_CHECK_FOR_REQUESTS(urb_ring, more_to_do);
670     if (more_to_do) {
671         qemu_bh_schedule(usbif->bh);
672     }
673 }
674 
675 static void usbback_hotplug_enq(struct usbback_info *usbif, unsigned port)
676 {
677     struct usbback_hotplug *usb_hp;
678 
679     usb_hp = g_new0(struct usbback_hotplug, 1);
680     usb_hp->port = port;
681     QSIMPLEQ_INSERT_TAIL(&usbif->hotplug_q, usb_hp, q);
682     usbback_hotplug_notify(usbif);
683 }
684 
685 static void usbback_portid_drain(struct usbback_info *usbif, unsigned port)
686 {
687     struct usbback_req *req, *tmp;
688     bool sched = false;
689 
690     QTAILQ_FOREACH_SAFE(req, &usbif->ports[port - 1].submit_q, q, tmp) {
691         usbback_cancel_req(req);
692         sched = true;
693     }
694 
695     if (sched) {
696         qemu_bh_schedule(usbif->bh);
697     }
698 }
699 
700 static void usbback_portid_detach(struct usbback_info *usbif, unsigned port)
701 {
702     if (!usbif->ports[port - 1].attached) {
703         return;
704     }
705 
706     usbif->ports[port - 1].speed = USBIF_SPEED_NONE;
707     usbif->ports[port - 1].attached = false;
708     usbback_portid_drain(usbif, port);
709     usbback_hotplug_enq(usbif, port);
710 }
711 
712 static void usbback_portid_remove(struct usbback_info *usbif, unsigned port)
713 {
714     if (!usbif->ports[port - 1].dev) {
715         return;
716     }
717 
718     object_unparent(OBJECT(usbif->ports[port - 1].dev));
719     usbif->ports[port - 1].dev = NULL;
720     usbback_portid_detach(usbif, port);
721 
722     TR_BUS(&usbif->xendev, "port %d removed\n", port);
723 }
724 
725 static void usbback_portid_add(struct usbback_info *usbif, unsigned port,
726                                char *busid)
727 {
728     unsigned speed;
729     char *portname;
730     Error *local_err = NULL;
731     QDict *qdict;
732     QemuOpts *opts;
733     char *tmp;
734 
735     if (usbif->ports[port - 1].dev) {
736         return;
737     }
738 
739     portname = strchr(busid, '-');
740     if (!portname) {
741         xen_pv_printf(&usbif->xendev, 0, "device %s illegal specification\n",
742                       busid);
743         return;
744     }
745     portname++;
746 
747     qdict = qdict_new();
748     qdict_put_str(qdict, "driver", "usb-host");
749     tmp = g_strdup_printf("%s.0", usbif->xendev.qdev.id);
750     qdict_put_str(qdict, "bus", tmp);
751     g_free(tmp);
752     tmp = g_strdup_printf("%s-%u", usbif->xendev.qdev.id, port);
753     qdict_put_str(qdict, "id", tmp);
754     g_free(tmp);
755     qdict_put_int(qdict, "port", port);
756     qdict_put_int(qdict, "hostbus", atoi(busid));
757     qdict_put_str(qdict, "hostport", portname);
758     opts = qemu_opts_from_qdict(qemu_find_opts("device"), qdict, &local_err);
759     if (local_err) {
760         goto err;
761     }
762     usbif->ports[port - 1].dev = USB_DEVICE(qdev_device_add(opts, &local_err));
763     if (!usbif->ports[port - 1].dev) {
764         goto err;
765     }
766     qobject_unref(qdict);
767     speed = usbif->ports[port - 1].dev->speed;
768     switch (speed) {
769     case USB_SPEED_LOW:
770         speed = USBIF_SPEED_LOW;
771         break;
772     case USB_SPEED_FULL:
773         speed = USBIF_SPEED_FULL;
774         break;
775     case USB_SPEED_HIGH:
776         speed = (usbif->usb_ver < USB_VER_USB20) ?
777                 USBIF_SPEED_NONE : USBIF_SPEED_HIGH;
778         break;
779     default:
780         speed = USBIF_SPEED_NONE;
781         break;
782     }
783     if (speed == USBIF_SPEED_NONE) {
784         xen_pv_printf(&usbif->xendev, 0, "device %s wrong speed\n", busid);
785         object_unparent(OBJECT(usbif->ports[port - 1].dev));
786         usbif->ports[port - 1].dev = NULL;
787         return;
788     }
789     usb_device_reset(usbif->ports[port - 1].dev);
790     usbif->ports[port - 1].speed = speed;
791     usbif->ports[port - 1].attached = true;
792     QTAILQ_INIT(&usbif->ports[port - 1].submit_q);
793     usbback_hotplug_enq(usbif, port);
794 
795     TR_BUS(&usbif->xendev, "port %d attached\n", port);
796     return;
797 
798 err:
799     qobject_unref(qdict);
800     xen_pv_printf(&usbif->xendev, 0, "device %s could not be opened\n", busid);
801 }
802 
803 static void usbback_process_port(struct usbback_info *usbif, unsigned port)
804 {
805     char node[8];
806     char *busid;
807 
808     snprintf(node, sizeof(node), "port/%d", port);
809     busid = xenstore_read_be_str(&usbif->xendev, node);
810     if (busid == NULL) {
811         xen_pv_printf(&usbif->xendev, 0, "xenstore_read %s failed\n", node);
812         return;
813     }
814 
815     /* Remove portid, if the port is not connected.  */
816     if (strlen(busid) == 0) {
817         usbback_portid_remove(usbif, port);
818     } else {
819         usbback_portid_add(usbif, port, busid);
820     }
821 
822     g_free(busid);
823 }
824 
825 static void usbback_disconnect(struct XenLegacyDevice *xendev)
826 {
827     struct usbback_info *usbif;
828     unsigned int i;
829 
830     TR_BUS(xendev, "start\n");
831 
832     usbif = container_of(xendev, struct usbback_info, xendev);
833 
834     xen_pv_unbind_evtchn(xendev);
835 
836     if (usbif->urb_sring) {
837         xen_be_unmap_grant_ref(xendev, usbif->urb_sring);
838         usbif->urb_sring = NULL;
839     }
840     if (usbif->conn_sring) {
841         xen_be_unmap_grant_ref(xendev, usbif->conn_sring);
842         usbif->conn_sring = NULL;
843     }
844 
845     for (i = 0; i < usbif->num_ports; i++) {
846         if (usbif->ports[i].dev) {
847             usbback_portid_drain(usbif, i + 1);
848         }
849     }
850 
851     TR_BUS(xendev, "finished\n");
852 }
853 
854 static int usbback_connect(struct XenLegacyDevice *xendev)
855 {
856     struct usbback_info *usbif;
857     struct usbif_urb_sring *urb_sring;
858     struct usbif_conn_sring *conn_sring;
859     int urb_ring_ref;
860     int conn_ring_ref;
861     unsigned int i, max_grants;
862 
863     TR_BUS(xendev, "start\n");
864 
865     /* max_grants: for each request and for the rings (request and connect). */
866     max_grants = USBIF_MAX_SEGMENTS_PER_REQUEST * USB_URB_RING_SIZE + 2;
867     xen_be_set_max_grant_refs(xendev, max_grants);
868 
869     usbif = container_of(xendev, struct usbback_info, xendev);
870 
871     if (xenstore_read_fe_int(xendev, "urb-ring-ref", &urb_ring_ref)) {
872         xen_pv_printf(xendev, 0, "error reading urb-ring-ref\n");
873         return -1;
874     }
875     if (xenstore_read_fe_int(xendev, "conn-ring-ref", &conn_ring_ref)) {
876         xen_pv_printf(xendev, 0, "error reading conn-ring-ref\n");
877         return -1;
878     }
879     if (xenstore_read_fe_int(xendev, "event-channel", &xendev->remote_port)) {
880         xen_pv_printf(xendev, 0, "error reading event-channel\n");
881         return -1;
882     }
883 
884     usbif->urb_sring = xen_be_map_grant_ref(xendev, urb_ring_ref,
885                                             PROT_READ | PROT_WRITE);
886     usbif->conn_sring = xen_be_map_grant_ref(xendev, conn_ring_ref,
887                                              PROT_READ | PROT_WRITE);
888     if (!usbif->urb_sring || !usbif->conn_sring) {
889         xen_pv_printf(xendev, 0, "error mapping rings\n");
890         usbback_disconnect(xendev);
891         return -1;
892     }
893 
894     urb_sring = usbif->urb_sring;
895     conn_sring = usbif->conn_sring;
896     BACK_RING_INIT(&usbif->urb_ring, urb_sring, XC_PAGE_SIZE);
897     BACK_RING_INIT(&usbif->conn_ring, conn_sring, XC_PAGE_SIZE);
898 
899     xen_be_bind_evtchn(xendev);
900 
901     xen_pv_printf(xendev, 1, "urb-ring-ref %d, conn-ring-ref %d, "
902                   "remote port %d, local port %d\n", urb_ring_ref,
903                   conn_ring_ref, xendev->remote_port, xendev->local_port);
904 
905     for (i = 1; i <= usbif->num_ports; i++) {
906         if (usbif->ports[i - 1].dev) {
907             usbback_hotplug_enq(usbif, i);
908         }
909     }
910 
911     return 0;
912 }
913 
914 static void usbback_backend_changed(struct XenLegacyDevice *xendev,
915                                     const char *node)
916 {
917     struct usbback_info *usbif;
918     unsigned int i;
919 
920     TR_BUS(xendev, "path %s\n", node);
921 
922     usbif = container_of(xendev, struct usbback_info, xendev);
923     for (i = 1; i <= usbif->num_ports; i++) {
924         usbback_process_port(usbif, i);
925     }
926 }
927 
928 static int usbback_init(struct XenLegacyDevice *xendev)
929 {
930     struct usbback_info *usbif;
931 
932     TR_BUS(xendev, "start\n");
933 
934     usbif = container_of(xendev, struct usbback_info, xendev);
935 
936     if (xenstore_read_be_int(xendev, "num-ports", &usbif->num_ports) ||
937         usbif->num_ports < 1 || usbif->num_ports > USBBACK_MAXPORTS) {
938         xen_pv_printf(xendev, 0, "num-ports not readable or out of bounds\n");
939         return -1;
940     }
941     if (xenstore_read_be_int(xendev, "usb-ver", &usbif->usb_ver) ||
942         (usbif->usb_ver != USB_VER_USB11 && usbif->usb_ver != USB_VER_USB20)) {
943         xen_pv_printf(xendev, 0, "usb-ver not readable or out of bounds\n");
944         return -1;
945     }
946 
947     usbback_backend_changed(xendev, "port");
948 
949     TR_BUS(xendev, "finished\n");
950 
951     return 0;
952 }
953 
954 static void xen_bus_attach(USBPort *port)
955 {
956     struct usbback_info *usbif;
957 
958     usbif = port->opaque;
959     TR_BUS(&usbif->xendev, "\n");
960     usbif->ports[port->index].attached = true;
961     usbback_hotplug_enq(usbif, port->index + 1);
962 }
963 
964 static void xen_bus_detach(USBPort *port)
965 {
966     struct usbback_info *usbif;
967 
968     usbif = port->opaque;
969     TR_BUS(&usbif->xendev, "\n");
970     usbback_portid_detach(usbif, port->index + 1);
971 }
972 
973 static void xen_bus_child_detach(USBPort *port, USBDevice *child)
974 {
975     struct usbback_info *usbif;
976 
977     usbif = port->opaque;
978     TR_BUS(&usbif->xendev, "\n");
979 }
980 
981 static void xen_bus_complete(USBPort *port, USBPacket *packet)
982 {
983     struct usbback_req *usbback_req;
984     struct usbback_info *usbif;
985 
986     usbback_req = container_of(packet, struct usbback_req, packet);
987     if (usbback_req->cancelled) {
988         g_free(usbback_req);
989         return;
990     }
991 
992     usbif = usbback_req->usbif;
993     TR_REQ(&usbif->xendev, "\n");
994     usbback_packet_complete(usbback_req);
995 }
996 
997 static USBPortOps xen_usb_port_ops = {
998     .attach = xen_bus_attach,
999     .detach = xen_bus_detach,
1000     .child_detach = xen_bus_child_detach,
1001     .complete = xen_bus_complete,
1002 };
1003 
1004 static USBBusOps xen_usb_bus_ops = {
1005 };
1006 
1007 static void usbback_alloc(struct XenLegacyDevice *xendev)
1008 {
1009     struct usbback_info *usbif;
1010     USBPort *p;
1011     unsigned int i;
1012 
1013     usbif = container_of(xendev, struct usbback_info, xendev);
1014 
1015     usb_bus_new(&usbif->bus, sizeof(usbif->bus), &xen_usb_bus_ops,
1016                 DEVICE(&xendev->qdev));
1017     for (i = 0; i < USBBACK_MAXPORTS; i++) {
1018         p = &(usbif->ports[i].port);
1019         usb_register_port(&usbif->bus, p, usbif, i, &xen_usb_port_ops,
1020                           USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL |
1021                           USB_SPEED_MASK_HIGH);
1022     }
1023 
1024     QTAILQ_INIT(&usbif->req_free_q);
1025     QSIMPLEQ_INIT(&usbif->hotplug_q);
1026     usbif->bh = qemu_bh_new(usbback_bh, usbif);
1027 }
1028 
1029 static int usbback_free(struct XenLegacyDevice *xendev)
1030 {
1031     struct usbback_info *usbif;
1032     struct usbback_req *usbback_req;
1033     struct usbback_hotplug *usb_hp;
1034     unsigned int i;
1035 
1036     TR_BUS(xendev, "start\n");
1037 
1038     usbback_disconnect(xendev);
1039     usbif = container_of(xendev, struct usbback_info, xendev);
1040     for (i = 1; i <= usbif->num_ports; i++) {
1041         usbback_portid_remove(usbif, i);
1042     }
1043 
1044     while (!QTAILQ_EMPTY(&usbif->req_free_q)) {
1045         usbback_req = QTAILQ_FIRST(&usbif->req_free_q);
1046         QTAILQ_REMOVE(&usbif->req_free_q, usbback_req, q);
1047         g_free(usbback_req);
1048     }
1049     while (!QSIMPLEQ_EMPTY(&usbif->hotplug_q)) {
1050         usb_hp = QSIMPLEQ_FIRST(&usbif->hotplug_q);
1051         QSIMPLEQ_REMOVE_HEAD(&usbif->hotplug_q, q);
1052         g_free(usb_hp);
1053     }
1054 
1055     qemu_bh_delete(usbif->bh);
1056 
1057     for (i = 0; i < USBBACK_MAXPORTS; i++) {
1058         usb_unregister_port(&usbif->bus, &(usbif->ports[i].port));
1059     }
1060 
1061     usb_bus_release(&usbif->bus);
1062 
1063     TR_BUS(xendev, "finished\n");
1064 
1065     return 0;
1066 }
1067 
1068 static void usbback_event(struct XenLegacyDevice *xendev)
1069 {
1070     struct usbback_info *usbif;
1071 
1072     usbif = container_of(xendev, struct usbback_info, xendev);
1073     qemu_bh_schedule(usbif->bh);
1074 }
1075 
1076 struct XenDevOps xen_usb_ops = {
1077     .size            = sizeof(struct usbback_info),
1078     .flags           = DEVOPS_FLAG_NEED_GNTDEV,
1079     .init            = usbback_init,
1080     .alloc           = usbback_alloc,
1081     .free            = usbback_free,
1082     .backend_changed = usbback_backend_changed,
1083     .initialise      = usbback_connect,
1084     .disconnect      = usbback_disconnect,
1085     .event           = usbback_event,
1086 };
1087 
1088 #else /* USBIF_SHORT_NOT_OK */
1089 
1090 static int usbback_not_supported(void)
1091 {
1092     return -EINVAL;
1093 }
1094 
1095 struct XenDevOps xen_usb_ops = {
1096     .backend_register = usbback_not_supported,
1097 };
1098 
1099 #endif
1100