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