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