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