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