xref: /qemu/hw/usb/xen-usb.c (revision 727385c4)
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     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,
759                                 &error_abort);
760     usbif->ports[port - 1].dev = USB_DEVICE(qdev_device_add(opts, &local_err));
761     if (!usbif->ports[port - 1].dev) {
762         qobject_unref(qdict);
763         xen_pv_printf(&usbif->xendev, 0,
764                       "device %s could not be opened: %s\n",
765                       busid, error_get_pretty(local_err));
766         error_free(local_err);
767         return;
768     }
769     qobject_unref(qdict);
770     speed = usbif->ports[port - 1].dev->speed;
771     switch (speed) {
772     case USB_SPEED_LOW:
773         speed = USBIF_SPEED_LOW;
774         break;
775     case USB_SPEED_FULL:
776         speed = USBIF_SPEED_FULL;
777         break;
778     case USB_SPEED_HIGH:
779         speed = (usbif->usb_ver < USB_VER_USB20) ?
780                 USBIF_SPEED_NONE : USBIF_SPEED_HIGH;
781         break;
782     default:
783         speed = USBIF_SPEED_NONE;
784         break;
785     }
786     if (speed == USBIF_SPEED_NONE) {
787         xen_pv_printf(&usbif->xendev, 0, "device %s wrong speed\n", busid);
788         object_unparent(OBJECT(usbif->ports[port - 1].dev));
789         usbif->ports[port - 1].dev = NULL;
790         return;
791     }
792     usb_device_reset(usbif->ports[port - 1].dev);
793     usbif->ports[port - 1].speed = speed;
794     usbif->ports[port - 1].attached = true;
795     QTAILQ_INIT(&usbif->ports[port - 1].submit_q);
796     usbback_hotplug_enq(usbif, port);
797 
798     TR_BUS(&usbif->xendev, "port %d attached\n", port);
799 }
800 
801 static void usbback_process_port(struct usbback_info *usbif, unsigned port)
802 {
803     char node[8];
804     char *busid;
805 
806     snprintf(node, sizeof(node), "port/%d", port);
807     busid = xenstore_read_be_str(&usbif->xendev, node);
808     if (busid == NULL) {
809         xen_pv_printf(&usbif->xendev, 0, "xenstore_read %s failed\n", node);
810         return;
811     }
812 
813     /* Remove portid, if the port is not connected.  */
814     if (strlen(busid) == 0) {
815         usbback_portid_remove(usbif, port);
816     } else {
817         usbback_portid_add(usbif, port, busid);
818     }
819 
820     g_free(busid);
821 }
822 
823 static void usbback_disconnect(struct XenLegacyDevice *xendev)
824 {
825     struct usbback_info *usbif;
826     unsigned int i;
827 
828     TR_BUS(xendev, "start\n");
829 
830     usbif = container_of(xendev, struct usbback_info, xendev);
831 
832     xen_pv_unbind_evtchn(xendev);
833 
834     if (usbif->urb_sring) {
835         xen_be_unmap_grant_ref(xendev, usbif->urb_sring);
836         usbif->urb_sring = NULL;
837     }
838     if (usbif->conn_sring) {
839         xen_be_unmap_grant_ref(xendev, usbif->conn_sring);
840         usbif->conn_sring = NULL;
841     }
842 
843     for (i = 0; i < usbif->num_ports; i++) {
844         if (usbif->ports[i].dev) {
845             usbback_portid_drain(usbif, i + 1);
846         }
847     }
848 
849     TR_BUS(xendev, "finished\n");
850 }
851 
852 static int usbback_connect(struct XenLegacyDevice *xendev)
853 {
854     struct usbback_info *usbif;
855     struct usbif_urb_sring *urb_sring;
856     struct usbif_conn_sring *conn_sring;
857     int urb_ring_ref;
858     int conn_ring_ref;
859     unsigned int i, max_grants;
860 
861     TR_BUS(xendev, "start\n");
862 
863     /* max_grants: for each request and for the rings (request and connect). */
864     max_grants = USBIF_MAX_SEGMENTS_PER_REQUEST * USB_URB_RING_SIZE + 2;
865     xen_be_set_max_grant_refs(xendev, max_grants);
866 
867     usbif = container_of(xendev, struct usbback_info, xendev);
868 
869     if (xenstore_read_fe_int(xendev, "urb-ring-ref", &urb_ring_ref)) {
870         xen_pv_printf(xendev, 0, "error reading urb-ring-ref\n");
871         return -1;
872     }
873     if (xenstore_read_fe_int(xendev, "conn-ring-ref", &conn_ring_ref)) {
874         xen_pv_printf(xendev, 0, "error reading conn-ring-ref\n");
875         return -1;
876     }
877     if (xenstore_read_fe_int(xendev, "event-channel", &xendev->remote_port)) {
878         xen_pv_printf(xendev, 0, "error reading event-channel\n");
879         return -1;
880     }
881 
882     usbif->urb_sring = xen_be_map_grant_ref(xendev, urb_ring_ref,
883                                             PROT_READ | PROT_WRITE);
884     usbif->conn_sring = xen_be_map_grant_ref(xendev, conn_ring_ref,
885                                              PROT_READ | PROT_WRITE);
886     if (!usbif->urb_sring || !usbif->conn_sring) {
887         xen_pv_printf(xendev, 0, "error mapping rings\n");
888         usbback_disconnect(xendev);
889         return -1;
890     }
891 
892     urb_sring = usbif->urb_sring;
893     conn_sring = usbif->conn_sring;
894     BACK_RING_INIT(&usbif->urb_ring, urb_sring, XC_PAGE_SIZE);
895     BACK_RING_INIT(&usbif->conn_ring, conn_sring, XC_PAGE_SIZE);
896 
897     xen_be_bind_evtchn(xendev);
898 
899     xen_pv_printf(xendev, 1, "urb-ring-ref %d, conn-ring-ref %d, "
900                   "remote port %d, local port %d\n", urb_ring_ref,
901                   conn_ring_ref, xendev->remote_port, xendev->local_port);
902 
903     for (i = 1; i <= usbif->num_ports; i++) {
904         if (usbif->ports[i - 1].dev) {
905             usbback_hotplug_enq(usbif, i);
906         }
907     }
908 
909     return 0;
910 }
911 
912 static void usbback_backend_changed(struct XenLegacyDevice *xendev,
913                                     const char *node)
914 {
915     struct usbback_info *usbif;
916     unsigned int i;
917 
918     TR_BUS(xendev, "path %s\n", node);
919 
920     usbif = container_of(xendev, struct usbback_info, xendev);
921     for (i = 1; i <= usbif->num_ports; i++) {
922         usbback_process_port(usbif, i);
923     }
924 }
925 
926 static int usbback_init(struct XenLegacyDevice *xendev)
927 {
928     struct usbback_info *usbif;
929 
930     TR_BUS(xendev, "start\n");
931 
932     usbif = container_of(xendev, struct usbback_info, xendev);
933 
934     if (xenstore_read_be_int(xendev, "num-ports", &usbif->num_ports) ||
935         usbif->num_ports < 1 || usbif->num_ports > USBBACK_MAXPORTS) {
936         xen_pv_printf(xendev, 0, "num-ports not readable or out of bounds\n");
937         return -1;
938     }
939     if (xenstore_read_be_int(xendev, "usb-ver", &usbif->usb_ver) ||
940         (usbif->usb_ver != USB_VER_USB11 && usbif->usb_ver != USB_VER_USB20)) {
941         xen_pv_printf(xendev, 0, "usb-ver not readable or out of bounds\n");
942         return -1;
943     }
944 
945     usbback_backend_changed(xendev, "port");
946 
947     TR_BUS(xendev, "finished\n");
948 
949     return 0;
950 }
951 
952 static void xen_bus_attach(USBPort *port)
953 {
954     struct usbback_info *usbif;
955 
956     usbif = port->opaque;
957     TR_BUS(&usbif->xendev, "\n");
958     usbif->ports[port->index].attached = true;
959     usbback_hotplug_enq(usbif, port->index + 1);
960 }
961 
962 static void xen_bus_detach(USBPort *port)
963 {
964     struct usbback_info *usbif;
965 
966     usbif = port->opaque;
967     TR_BUS(&usbif->xendev, "\n");
968     usbback_portid_detach(usbif, port->index + 1);
969 }
970 
971 static void xen_bus_child_detach(USBPort *port, USBDevice *child)
972 {
973     struct usbback_info *usbif;
974 
975     usbif = port->opaque;
976     TR_BUS(&usbif->xendev, "\n");
977 }
978 
979 static void xen_bus_complete(USBPort *port, USBPacket *packet)
980 {
981     struct usbback_req *usbback_req;
982     struct usbback_info *usbif;
983 
984     usbback_req = container_of(packet, struct usbback_req, packet);
985     if (usbback_req->cancelled) {
986         g_free(usbback_req);
987         return;
988     }
989 
990     usbif = usbback_req->usbif;
991     TR_REQ(&usbif->xendev, "\n");
992     usbback_packet_complete(usbback_req);
993 }
994 
995 static USBPortOps xen_usb_port_ops = {
996     .attach = xen_bus_attach,
997     .detach = xen_bus_detach,
998     .child_detach = xen_bus_child_detach,
999     .complete = xen_bus_complete,
1000 };
1001 
1002 static USBBusOps xen_usb_bus_ops = {
1003 };
1004 
1005 static void usbback_alloc(struct XenLegacyDevice *xendev)
1006 {
1007     struct usbback_info *usbif;
1008     USBPort *p;
1009     unsigned int i;
1010 
1011     usbif = container_of(xendev, struct usbback_info, xendev);
1012 
1013     usb_bus_new(&usbif->bus, sizeof(usbif->bus), &xen_usb_bus_ops,
1014                 DEVICE(&xendev->qdev));
1015     for (i = 0; i < USBBACK_MAXPORTS; i++) {
1016         p = &(usbif->ports[i].port);
1017         usb_register_port(&usbif->bus, p, usbif, i, &xen_usb_port_ops,
1018                           USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL |
1019                           USB_SPEED_MASK_HIGH);
1020     }
1021 
1022     QTAILQ_INIT(&usbif->req_free_q);
1023     QSIMPLEQ_INIT(&usbif->hotplug_q);
1024     usbif->bh = qemu_bh_new(usbback_bh, usbif);
1025 }
1026 
1027 static int usbback_free(struct XenLegacyDevice *xendev)
1028 {
1029     struct usbback_info *usbif;
1030     struct usbback_req *usbback_req;
1031     struct usbback_hotplug *usb_hp;
1032     unsigned int i;
1033 
1034     TR_BUS(xendev, "start\n");
1035 
1036     usbback_disconnect(xendev);
1037     usbif = container_of(xendev, struct usbback_info, xendev);
1038     for (i = 1; i <= usbif->num_ports; i++) {
1039         usbback_portid_remove(usbif, i);
1040     }
1041 
1042     while (!QTAILQ_EMPTY(&usbif->req_free_q)) {
1043         usbback_req = QTAILQ_FIRST(&usbif->req_free_q);
1044         QTAILQ_REMOVE(&usbif->req_free_q, usbback_req, q);
1045         g_free(usbback_req);
1046     }
1047     while (!QSIMPLEQ_EMPTY(&usbif->hotplug_q)) {
1048         usb_hp = QSIMPLEQ_FIRST(&usbif->hotplug_q);
1049         QSIMPLEQ_REMOVE_HEAD(&usbif->hotplug_q, q);
1050         g_free(usb_hp);
1051     }
1052 
1053     qemu_bh_delete(usbif->bh);
1054 
1055     for (i = 0; i < USBBACK_MAXPORTS; i++) {
1056         usb_unregister_port(&usbif->bus, &(usbif->ports[i].port));
1057     }
1058 
1059     usb_bus_release(&usbif->bus);
1060 
1061     TR_BUS(xendev, "finished\n");
1062 
1063     return 0;
1064 }
1065 
1066 static void usbback_event(struct XenLegacyDevice *xendev)
1067 {
1068     struct usbback_info *usbif;
1069 
1070     usbif = container_of(xendev, struct usbback_info, xendev);
1071     qemu_bh_schedule(usbif->bh);
1072 }
1073 
1074 struct XenDevOps xen_usb_ops = {
1075     .size            = sizeof(struct usbback_info),
1076     .flags           = DEVOPS_FLAG_NEED_GNTDEV,
1077     .init            = usbback_init,
1078     .alloc           = usbback_alloc,
1079     .free            = usbback_free,
1080     .backend_changed = usbback_backend_changed,
1081     .initialise      = usbback_connect,
1082     .disconnect      = usbback_disconnect,
1083     .event           = usbback_event,
1084 };
1085 
1086 #else /* USBIF_SHORT_NOT_OK */
1087 
1088 static int usbback_not_supported(void)
1089 {
1090     return -EINVAL;
1091 }
1092 
1093 struct XenDevOps xen_usb_ops = {
1094     .backend_register = usbback_not_supported,
1095 };
1096 
1097 #endif
1098