net: check packet payload length
[qemu/ar7.git] / hw / usb / hcd-uhci.c
blobc370240be298b833babe05f4ca1b775cbb3cea92
1 /*
2 * USB UHCI controller emulation
4 * Copyright (c) 2005 Fabrice Bellard
6 * Copyright (c) 2008 Max Krasnyansky
7 * Magor rewrite of the UHCI data structures parser and frame processor
8 * Support for fully async operation and multiple outstanding transactions
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 * THE SOFTWARE.
28 #include "qemu/osdep.h"
29 #include "hw/hw.h"
30 #include "hw/usb.h"
31 #include "hw/usb/uhci-regs.h"
32 #include "hw/pci/pci.h"
33 #include "qemu/timer.h"
34 #include "qemu/iov.h"
35 #include "sysemu/dma.h"
36 #include "trace.h"
37 #include "qemu/main-loop.h"
39 #define FRAME_TIMER_FREQ 1000
41 #define FRAME_MAX_LOOPS 256
43 /* Must be large enough to handle 10 frame delay for initial isoc requests */
44 #define QH_VALID 32
46 #define MAX_FRAMES_PER_TICK (QH_VALID / 2)
48 #define NB_PORTS 2
50 enum {
51 TD_RESULT_STOP_FRAME = 10,
52 TD_RESULT_COMPLETE,
53 TD_RESULT_NEXT_QH,
54 TD_RESULT_ASYNC_START,
55 TD_RESULT_ASYNC_CONT,
58 typedef struct UHCIState UHCIState;
59 typedef struct UHCIAsync UHCIAsync;
60 typedef struct UHCIQueue UHCIQueue;
61 typedef struct UHCIInfo UHCIInfo;
62 typedef struct UHCIPCIDeviceClass UHCIPCIDeviceClass;
64 struct UHCIInfo {
65 const char *name;
66 uint16_t vendor_id;
67 uint16_t device_id;
68 uint8_t revision;
69 uint8_t irq_pin;
70 void (*realize)(PCIDevice *dev, Error **errp);
71 bool unplug;
74 struct UHCIPCIDeviceClass {
75 PCIDeviceClass parent_class;
76 UHCIInfo info;
79 /*
80 * Pending async transaction.
81 * 'packet' must be the first field because completion
82 * handler does "(UHCIAsync *) pkt" cast.
85 struct UHCIAsync {
86 USBPacket packet;
87 uint8_t static_buf[64]; /* 64 bytes is enough, except for isoc packets */
88 uint8_t *buf;
89 UHCIQueue *queue;
90 QTAILQ_ENTRY(UHCIAsync) next;
91 uint32_t td_addr;
92 uint8_t done;
95 struct UHCIQueue {
96 uint32_t qh_addr;
97 uint32_t token;
98 UHCIState *uhci;
99 USBEndpoint *ep;
100 QTAILQ_ENTRY(UHCIQueue) next;
101 QTAILQ_HEAD(asyncs_head, UHCIAsync) asyncs;
102 int8_t valid;
105 typedef struct UHCIPort {
106 USBPort port;
107 uint16_t ctrl;
108 } UHCIPort;
110 struct UHCIState {
111 PCIDevice dev;
112 MemoryRegion io_bar;
113 USBBus bus; /* Note unused when we're a companion controller */
114 uint16_t cmd; /* cmd register */
115 uint16_t status;
116 uint16_t intr; /* interrupt enable register */
117 uint16_t frnum; /* frame number */
118 uint32_t fl_base_addr; /* frame list base address */
119 uint8_t sof_timing;
120 uint8_t status2; /* bit 0 and 1 are used to generate UHCI_STS_USBINT */
121 int64_t expire_time;
122 QEMUTimer *frame_timer;
123 QEMUBH *bh;
124 uint32_t frame_bytes;
125 uint32_t frame_bandwidth;
126 bool completions_only;
127 UHCIPort ports[NB_PORTS];
129 /* Interrupts that should be raised at the end of the current frame. */
130 uint32_t pending_int_mask;
132 /* Active packets */
133 QTAILQ_HEAD(, UHCIQueue) queues;
134 uint8_t num_ports_vmstate;
136 /* Properties */
137 char *masterbus;
138 uint32_t firstport;
139 uint32_t maxframes;
142 typedef struct UHCI_TD {
143 uint32_t link;
144 uint32_t ctrl; /* see TD_CTRL_xxx */
145 uint32_t token;
146 uint32_t buffer;
147 } UHCI_TD;
149 typedef struct UHCI_QH {
150 uint32_t link;
151 uint32_t el_link;
152 } UHCI_QH;
154 static void uhci_async_cancel(UHCIAsync *async);
155 static void uhci_queue_fill(UHCIQueue *q, UHCI_TD *td);
156 static void uhci_resume(void *opaque);
158 #define TYPE_UHCI "pci-uhci-usb"
159 #define UHCI(obj) OBJECT_CHECK(UHCIState, (obj), TYPE_UHCI)
161 static inline int32_t uhci_queue_token(UHCI_TD *td)
163 if ((td->token & (0xf << 15)) == 0) {
164 /* ctrl ep, cover ep and dev, not pid! */
165 return td->token & 0x7ff00;
166 } else {
167 /* covers ep, dev, pid -> identifies the endpoint */
168 return td->token & 0x7ffff;
172 static UHCIQueue *uhci_queue_new(UHCIState *s, uint32_t qh_addr, UHCI_TD *td,
173 USBEndpoint *ep)
175 UHCIQueue *queue;
177 queue = g_new0(UHCIQueue, 1);
178 queue->uhci = s;
179 queue->qh_addr = qh_addr;
180 queue->token = uhci_queue_token(td);
181 queue->ep = ep;
182 QTAILQ_INIT(&queue->asyncs);
183 QTAILQ_INSERT_HEAD(&s->queues, queue, next);
184 queue->valid = QH_VALID;
185 trace_usb_uhci_queue_add(queue->token);
186 return queue;
189 static void uhci_queue_free(UHCIQueue *queue, const char *reason)
191 UHCIState *s = queue->uhci;
192 UHCIAsync *async;
194 while (!QTAILQ_EMPTY(&queue->asyncs)) {
195 async = QTAILQ_FIRST(&queue->asyncs);
196 uhci_async_cancel(async);
198 usb_device_ep_stopped(queue->ep->dev, queue->ep);
200 trace_usb_uhci_queue_del(queue->token, reason);
201 QTAILQ_REMOVE(&s->queues, queue, next);
202 g_free(queue);
205 static UHCIQueue *uhci_queue_find(UHCIState *s, UHCI_TD *td)
207 uint32_t token = uhci_queue_token(td);
208 UHCIQueue *queue;
210 QTAILQ_FOREACH(queue, &s->queues, next) {
211 if (queue->token == token) {
212 return queue;
215 return NULL;
218 static bool uhci_queue_verify(UHCIQueue *queue, uint32_t qh_addr, UHCI_TD *td,
219 uint32_t td_addr, bool queuing)
221 UHCIAsync *first = QTAILQ_FIRST(&queue->asyncs);
222 uint32_t queue_token_addr = (queue->token >> 8) & 0x7f;
224 return queue->qh_addr == qh_addr &&
225 queue->token == uhci_queue_token(td) &&
226 queue_token_addr == queue->ep->dev->addr &&
227 (queuing || !(td->ctrl & TD_CTRL_ACTIVE) || first == NULL ||
228 first->td_addr == td_addr);
231 static UHCIAsync *uhci_async_alloc(UHCIQueue *queue, uint32_t td_addr)
233 UHCIAsync *async = g_new0(UHCIAsync, 1);
235 async->queue = queue;
236 async->td_addr = td_addr;
237 usb_packet_init(&async->packet);
238 trace_usb_uhci_packet_add(async->queue->token, async->td_addr);
240 return async;
243 static void uhci_async_free(UHCIAsync *async)
245 trace_usb_uhci_packet_del(async->queue->token, async->td_addr);
246 usb_packet_cleanup(&async->packet);
247 if (async->buf != async->static_buf) {
248 g_free(async->buf);
250 g_free(async);
253 static void uhci_async_link(UHCIAsync *async)
255 UHCIQueue *queue = async->queue;
256 QTAILQ_INSERT_TAIL(&queue->asyncs, async, next);
257 trace_usb_uhci_packet_link_async(async->queue->token, async->td_addr);
260 static void uhci_async_unlink(UHCIAsync *async)
262 UHCIQueue *queue = async->queue;
263 QTAILQ_REMOVE(&queue->asyncs, async, next);
264 trace_usb_uhci_packet_unlink_async(async->queue->token, async->td_addr);
267 static void uhci_async_cancel(UHCIAsync *async)
269 uhci_async_unlink(async);
270 trace_usb_uhci_packet_cancel(async->queue->token, async->td_addr,
271 async->done);
272 if (!async->done)
273 usb_cancel_packet(&async->packet);
274 uhci_async_free(async);
278 * Mark all outstanding async packets as invalid.
279 * This is used for canceling them when TDs are removed by the HCD.
281 static void uhci_async_validate_begin(UHCIState *s)
283 UHCIQueue *queue;
285 QTAILQ_FOREACH(queue, &s->queues, next) {
286 queue->valid--;
291 * Cancel async packets that are no longer valid
293 static void uhci_async_validate_end(UHCIState *s)
295 UHCIQueue *queue, *n;
297 QTAILQ_FOREACH_SAFE(queue, &s->queues, next, n) {
298 if (!queue->valid) {
299 uhci_queue_free(queue, "validate-end");
304 static void uhci_async_cancel_device(UHCIState *s, USBDevice *dev)
306 UHCIQueue *queue, *n;
308 QTAILQ_FOREACH_SAFE(queue, &s->queues, next, n) {
309 if (queue->ep->dev == dev) {
310 uhci_queue_free(queue, "cancel-device");
315 static void uhci_async_cancel_all(UHCIState *s)
317 UHCIQueue *queue, *nq;
319 QTAILQ_FOREACH_SAFE(queue, &s->queues, next, nq) {
320 uhci_queue_free(queue, "cancel-all");
324 static UHCIAsync *uhci_async_find_td(UHCIState *s, uint32_t td_addr)
326 UHCIQueue *queue;
327 UHCIAsync *async;
329 QTAILQ_FOREACH(queue, &s->queues, next) {
330 QTAILQ_FOREACH(async, &queue->asyncs, next) {
331 if (async->td_addr == td_addr) {
332 return async;
336 return NULL;
339 static void uhci_update_irq(UHCIState *s)
341 int level;
342 if (((s->status2 & 1) && (s->intr & (1 << 2))) ||
343 ((s->status2 & 2) && (s->intr & (1 << 3))) ||
344 ((s->status & UHCI_STS_USBERR) && (s->intr & (1 << 0))) ||
345 ((s->status & UHCI_STS_RD) && (s->intr & (1 << 1))) ||
346 (s->status & UHCI_STS_HSERR) ||
347 (s->status & UHCI_STS_HCPERR)) {
348 level = 1;
349 } else {
350 level = 0;
352 pci_set_irq(&s->dev, level);
355 static void uhci_reset(DeviceState *dev)
357 PCIDevice *d = PCI_DEVICE(dev);
358 UHCIState *s = UHCI(d);
359 uint8_t *pci_conf;
360 int i;
361 UHCIPort *port;
363 trace_usb_uhci_reset();
365 pci_conf = s->dev.config;
367 pci_conf[0x6a] = 0x01; /* usb clock */
368 pci_conf[0x6b] = 0x00;
369 s->cmd = 0;
370 s->status = UHCI_STS_HCHALTED;
371 s->status2 = 0;
372 s->intr = 0;
373 s->fl_base_addr = 0;
374 s->sof_timing = 64;
376 for(i = 0; i < NB_PORTS; i++) {
377 port = &s->ports[i];
378 port->ctrl = 0x0080;
379 if (port->port.dev && port->port.dev->attached) {
380 usb_port_reset(&port->port);
384 uhci_async_cancel_all(s);
385 qemu_bh_cancel(s->bh);
386 uhci_update_irq(s);
389 static const VMStateDescription vmstate_uhci_port = {
390 .name = "uhci port",
391 .version_id = 1,
392 .minimum_version_id = 1,
393 .fields = (VMStateField[]) {
394 VMSTATE_UINT16(ctrl, UHCIPort),
395 VMSTATE_END_OF_LIST()
399 static int uhci_post_load(void *opaque, int version_id)
401 UHCIState *s = opaque;
403 if (version_id < 2) {
404 s->expire_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
405 (get_ticks_per_sec() / FRAME_TIMER_FREQ);
407 return 0;
410 static const VMStateDescription vmstate_uhci = {
411 .name = "uhci",
412 .version_id = 3,
413 .minimum_version_id = 1,
414 .post_load = uhci_post_load,
415 .fields = (VMStateField[]) {
416 VMSTATE_PCI_DEVICE(dev, UHCIState),
417 VMSTATE_UINT8_EQUAL(num_ports_vmstate, UHCIState),
418 VMSTATE_STRUCT_ARRAY(ports, UHCIState, NB_PORTS, 1,
419 vmstate_uhci_port, UHCIPort),
420 VMSTATE_UINT16(cmd, UHCIState),
421 VMSTATE_UINT16(status, UHCIState),
422 VMSTATE_UINT16(intr, UHCIState),
423 VMSTATE_UINT16(frnum, UHCIState),
424 VMSTATE_UINT32(fl_base_addr, UHCIState),
425 VMSTATE_UINT8(sof_timing, UHCIState),
426 VMSTATE_UINT8(status2, UHCIState),
427 VMSTATE_TIMER_PTR(frame_timer, UHCIState),
428 VMSTATE_INT64_V(expire_time, UHCIState, 2),
429 VMSTATE_UINT32_V(pending_int_mask, UHCIState, 3),
430 VMSTATE_END_OF_LIST()
434 static void uhci_port_write(void *opaque, hwaddr addr,
435 uint64_t val, unsigned size)
437 UHCIState *s = opaque;
439 trace_usb_uhci_mmio_writew(addr, val);
441 switch(addr) {
442 case 0x00:
443 if ((val & UHCI_CMD_RS) && !(s->cmd & UHCI_CMD_RS)) {
444 /* start frame processing */
445 trace_usb_uhci_schedule_start();
446 s->expire_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
447 (get_ticks_per_sec() / FRAME_TIMER_FREQ);
448 timer_mod(s->frame_timer, s->expire_time);
449 s->status &= ~UHCI_STS_HCHALTED;
450 } else if (!(val & UHCI_CMD_RS)) {
451 s->status |= UHCI_STS_HCHALTED;
453 if (val & UHCI_CMD_GRESET) {
454 UHCIPort *port;
455 int i;
457 /* send reset on the USB bus */
458 for(i = 0; i < NB_PORTS; i++) {
459 port = &s->ports[i];
460 usb_device_reset(port->port.dev);
462 uhci_reset(DEVICE(s));
463 return;
465 if (val & UHCI_CMD_HCRESET) {
466 uhci_reset(DEVICE(s));
467 return;
469 s->cmd = val;
470 if (val & UHCI_CMD_EGSM) {
471 if ((s->ports[0].ctrl & UHCI_PORT_RD) ||
472 (s->ports[1].ctrl & UHCI_PORT_RD)) {
473 uhci_resume(s);
476 break;
477 case 0x02:
478 s->status &= ~val;
479 /* XXX: the chip spec is not coherent, so we add a hidden
480 register to distinguish between IOC and SPD */
481 if (val & UHCI_STS_USBINT)
482 s->status2 = 0;
483 uhci_update_irq(s);
484 break;
485 case 0x04:
486 s->intr = val;
487 uhci_update_irq(s);
488 break;
489 case 0x06:
490 if (s->status & UHCI_STS_HCHALTED)
491 s->frnum = val & 0x7ff;
492 break;
493 case 0x08:
494 s->fl_base_addr &= 0xffff0000;
495 s->fl_base_addr |= val & ~0xfff;
496 break;
497 case 0x0a:
498 s->fl_base_addr &= 0x0000ffff;
499 s->fl_base_addr |= (val << 16);
500 break;
501 case 0x0c:
502 s->sof_timing = val & 0xff;
503 break;
504 case 0x10 ... 0x1f:
506 UHCIPort *port;
507 USBDevice *dev;
508 int n;
510 n = (addr >> 1) & 7;
511 if (n >= NB_PORTS)
512 return;
513 port = &s->ports[n];
514 dev = port->port.dev;
515 if (dev && dev->attached) {
516 /* port reset */
517 if ( (val & UHCI_PORT_RESET) &&
518 !(port->ctrl & UHCI_PORT_RESET) ) {
519 usb_device_reset(dev);
522 port->ctrl &= UHCI_PORT_READ_ONLY;
523 /* enabled may only be set if a device is connected */
524 if (!(port->ctrl & UHCI_PORT_CCS)) {
525 val &= ~UHCI_PORT_EN;
527 port->ctrl |= (val & ~UHCI_PORT_READ_ONLY);
528 /* some bits are reset when a '1' is written to them */
529 port->ctrl &= ~(val & UHCI_PORT_WRITE_CLEAR);
531 break;
535 static uint64_t uhci_port_read(void *opaque, hwaddr addr, unsigned size)
537 UHCIState *s = opaque;
538 uint32_t val;
540 switch(addr) {
541 case 0x00:
542 val = s->cmd;
543 break;
544 case 0x02:
545 val = s->status;
546 break;
547 case 0x04:
548 val = s->intr;
549 break;
550 case 0x06:
551 val = s->frnum;
552 break;
553 case 0x08:
554 val = s->fl_base_addr & 0xffff;
555 break;
556 case 0x0a:
557 val = (s->fl_base_addr >> 16) & 0xffff;
558 break;
559 case 0x0c:
560 val = s->sof_timing;
561 break;
562 case 0x10 ... 0x1f:
564 UHCIPort *port;
565 int n;
566 n = (addr >> 1) & 7;
567 if (n >= NB_PORTS)
568 goto read_default;
569 port = &s->ports[n];
570 val = port->ctrl;
572 break;
573 default:
574 read_default:
575 val = 0xff7f; /* disabled port */
576 break;
579 trace_usb_uhci_mmio_readw(addr, val);
581 return val;
584 /* signal resume if controller suspended */
585 static void uhci_resume (void *opaque)
587 UHCIState *s = (UHCIState *)opaque;
589 if (!s)
590 return;
592 if (s->cmd & UHCI_CMD_EGSM) {
593 s->cmd |= UHCI_CMD_FGR;
594 s->status |= UHCI_STS_RD;
595 uhci_update_irq(s);
599 static void uhci_attach(USBPort *port1)
601 UHCIState *s = port1->opaque;
602 UHCIPort *port = &s->ports[port1->index];
604 /* set connect status */
605 port->ctrl |= UHCI_PORT_CCS | UHCI_PORT_CSC;
607 /* update speed */
608 if (port->port.dev->speed == USB_SPEED_LOW) {
609 port->ctrl |= UHCI_PORT_LSDA;
610 } else {
611 port->ctrl &= ~UHCI_PORT_LSDA;
614 uhci_resume(s);
617 static void uhci_detach(USBPort *port1)
619 UHCIState *s = port1->opaque;
620 UHCIPort *port = &s->ports[port1->index];
622 uhci_async_cancel_device(s, port1->dev);
624 /* set connect status */
625 if (port->ctrl & UHCI_PORT_CCS) {
626 port->ctrl &= ~UHCI_PORT_CCS;
627 port->ctrl |= UHCI_PORT_CSC;
629 /* disable port */
630 if (port->ctrl & UHCI_PORT_EN) {
631 port->ctrl &= ~UHCI_PORT_EN;
632 port->ctrl |= UHCI_PORT_ENC;
635 uhci_resume(s);
638 static void uhci_child_detach(USBPort *port1, USBDevice *child)
640 UHCIState *s = port1->opaque;
642 uhci_async_cancel_device(s, child);
645 static void uhci_wakeup(USBPort *port1)
647 UHCIState *s = port1->opaque;
648 UHCIPort *port = &s->ports[port1->index];
650 if (port->ctrl & UHCI_PORT_SUSPEND && !(port->ctrl & UHCI_PORT_RD)) {
651 port->ctrl |= UHCI_PORT_RD;
652 uhci_resume(s);
656 static USBDevice *uhci_find_device(UHCIState *s, uint8_t addr)
658 USBDevice *dev;
659 int i;
661 for (i = 0; i < NB_PORTS; i++) {
662 UHCIPort *port = &s->ports[i];
663 if (!(port->ctrl & UHCI_PORT_EN)) {
664 continue;
666 dev = usb_find_device(&port->port, addr);
667 if (dev != NULL) {
668 return dev;
671 return NULL;
674 static void uhci_read_td(UHCIState *s, UHCI_TD *td, uint32_t link)
676 pci_dma_read(&s->dev, link & ~0xf, td, sizeof(*td));
677 le32_to_cpus(&td->link);
678 le32_to_cpus(&td->ctrl);
679 le32_to_cpus(&td->token);
680 le32_to_cpus(&td->buffer);
683 static int uhci_handle_td_error(UHCIState *s, UHCI_TD *td, uint32_t td_addr,
684 int status, uint32_t *int_mask)
686 uint32_t queue_token = uhci_queue_token(td);
687 int ret;
689 switch (status) {
690 case USB_RET_NAK:
691 td->ctrl |= TD_CTRL_NAK;
692 return TD_RESULT_NEXT_QH;
694 case USB_RET_STALL:
695 td->ctrl |= TD_CTRL_STALL;
696 trace_usb_uhci_packet_complete_stall(queue_token, td_addr);
697 ret = TD_RESULT_NEXT_QH;
698 break;
700 case USB_RET_BABBLE:
701 td->ctrl |= TD_CTRL_BABBLE | TD_CTRL_STALL;
702 /* frame interrupted */
703 trace_usb_uhci_packet_complete_babble(queue_token, td_addr);
704 ret = TD_RESULT_STOP_FRAME;
705 break;
707 case USB_RET_IOERROR:
708 case USB_RET_NODEV:
709 default:
710 td->ctrl |= TD_CTRL_TIMEOUT;
711 td->ctrl &= ~(3 << TD_CTRL_ERROR_SHIFT);
712 trace_usb_uhci_packet_complete_error(queue_token, td_addr);
713 ret = TD_RESULT_NEXT_QH;
714 break;
717 td->ctrl &= ~TD_CTRL_ACTIVE;
718 s->status |= UHCI_STS_USBERR;
719 if (td->ctrl & TD_CTRL_IOC) {
720 *int_mask |= 0x01;
722 uhci_update_irq(s);
723 return ret;
726 static int uhci_complete_td(UHCIState *s, UHCI_TD *td, UHCIAsync *async, uint32_t *int_mask)
728 int len = 0, max_len;
729 uint8_t pid;
731 max_len = ((td->token >> 21) + 1) & 0x7ff;
732 pid = td->token & 0xff;
734 if (td->ctrl & TD_CTRL_IOS)
735 td->ctrl &= ~TD_CTRL_ACTIVE;
737 if (async->packet.status != USB_RET_SUCCESS) {
738 return uhci_handle_td_error(s, td, async->td_addr,
739 async->packet.status, int_mask);
742 len = async->packet.actual_length;
743 td->ctrl = (td->ctrl & ~0x7ff) | ((len - 1) & 0x7ff);
745 /* The NAK bit may have been set by a previous frame, so clear it
746 here. The docs are somewhat unclear, but win2k relies on this
747 behavior. */
748 td->ctrl &= ~(TD_CTRL_ACTIVE | TD_CTRL_NAK);
749 if (td->ctrl & TD_CTRL_IOC)
750 *int_mask |= 0x01;
752 if (pid == USB_TOKEN_IN) {
753 pci_dma_write(&s->dev, td->buffer, async->buf, len);
754 if ((td->ctrl & TD_CTRL_SPD) && len < max_len) {
755 *int_mask |= 0x02;
756 /* short packet: do not update QH */
757 trace_usb_uhci_packet_complete_shortxfer(async->queue->token,
758 async->td_addr);
759 return TD_RESULT_NEXT_QH;
763 /* success */
764 trace_usb_uhci_packet_complete_success(async->queue->token,
765 async->td_addr);
766 return TD_RESULT_COMPLETE;
769 static int uhci_handle_td(UHCIState *s, UHCIQueue *q, uint32_t qh_addr,
770 UHCI_TD *td, uint32_t td_addr, uint32_t *int_mask)
772 int ret, max_len;
773 bool spd;
774 bool queuing = (q != NULL);
775 uint8_t pid = td->token & 0xff;
776 UHCIAsync *async;
778 switch (pid) {
779 case USB_TOKEN_OUT:
780 case USB_TOKEN_SETUP:
781 case USB_TOKEN_IN:
782 break;
783 default:
784 /* invalid pid : frame interrupted */
785 s->status |= UHCI_STS_HCPERR;
786 s->cmd &= ~UHCI_CMD_RS;
787 uhci_update_irq(s);
788 return TD_RESULT_STOP_FRAME;
791 async = uhci_async_find_td(s, td_addr);
792 if (async) {
793 if (uhci_queue_verify(async->queue, qh_addr, td, td_addr, queuing)) {
794 assert(q == NULL || q == async->queue);
795 q = async->queue;
796 } else {
797 uhci_queue_free(async->queue, "guest re-used pending td");
798 async = NULL;
802 if (q == NULL) {
803 q = uhci_queue_find(s, td);
804 if (q && !uhci_queue_verify(q, qh_addr, td, td_addr, queuing)) {
805 uhci_queue_free(q, "guest re-used qh");
806 q = NULL;
810 if (q) {
811 q->valid = QH_VALID;
814 /* Is active ? */
815 if (!(td->ctrl & TD_CTRL_ACTIVE)) {
816 if (async) {
817 /* Guest marked a pending td non-active, cancel the queue */
818 uhci_queue_free(async->queue, "pending td non-active");
821 * ehci11d spec page 22: "Even if the Active bit in the TD is already
822 * cleared when the TD is fetched ... an IOC interrupt is generated"
824 if (td->ctrl & TD_CTRL_IOC) {
825 *int_mask |= 0x01;
827 return TD_RESULT_NEXT_QH;
830 if (async) {
831 if (queuing) {
832 /* we are busy filling the queue, we are not prepared
833 to consume completed packages then, just leave them
834 in async state */
835 return TD_RESULT_ASYNC_CONT;
837 if (!async->done) {
838 UHCI_TD last_td;
839 UHCIAsync *last = QTAILQ_LAST(&async->queue->asyncs, asyncs_head);
841 * While we are waiting for the current td to complete, the guest
842 * may have added more tds to the queue. Note we re-read the td
843 * rather then caching it, as we want to see guest made changes!
845 uhci_read_td(s, &last_td, last->td_addr);
846 uhci_queue_fill(async->queue, &last_td);
848 return TD_RESULT_ASYNC_CONT;
850 uhci_async_unlink(async);
851 goto done;
854 if (s->completions_only) {
855 return TD_RESULT_ASYNC_CONT;
858 /* Allocate new packet */
859 if (q == NULL) {
860 USBDevice *dev = uhci_find_device(s, (td->token >> 8) & 0x7f);
861 USBEndpoint *ep = usb_ep_get(dev, pid, (td->token >> 15) & 0xf);
863 if (ep == NULL) {
864 return uhci_handle_td_error(s, td, td_addr, USB_RET_NODEV,
865 int_mask);
867 q = uhci_queue_new(s, qh_addr, td, ep);
869 async = uhci_async_alloc(q, td_addr);
871 max_len = ((td->token >> 21) + 1) & 0x7ff;
872 spd = (pid == USB_TOKEN_IN && (td->ctrl & TD_CTRL_SPD) != 0);
873 usb_packet_setup(&async->packet, pid, q->ep, 0, td_addr, spd,
874 (td->ctrl & TD_CTRL_IOC) != 0);
875 if (max_len <= sizeof(async->static_buf)) {
876 async->buf = async->static_buf;
877 } else {
878 async->buf = g_malloc(max_len);
880 usb_packet_addbuf(&async->packet, async->buf, max_len);
882 switch(pid) {
883 case USB_TOKEN_OUT:
884 case USB_TOKEN_SETUP:
885 pci_dma_read(&s->dev, td->buffer, async->buf, max_len);
886 usb_handle_packet(q->ep->dev, &async->packet);
887 if (async->packet.status == USB_RET_SUCCESS) {
888 async->packet.actual_length = max_len;
890 break;
892 case USB_TOKEN_IN:
893 usb_handle_packet(q->ep->dev, &async->packet);
894 break;
896 default:
897 abort(); /* Never to execute */
900 if (async->packet.status == USB_RET_ASYNC) {
901 uhci_async_link(async);
902 if (!queuing) {
903 uhci_queue_fill(q, td);
905 return TD_RESULT_ASYNC_START;
908 done:
909 ret = uhci_complete_td(s, td, async, int_mask);
910 uhci_async_free(async);
911 return ret;
914 static void uhci_async_complete(USBPort *port, USBPacket *packet)
916 UHCIAsync *async = container_of(packet, UHCIAsync, packet);
917 UHCIState *s = async->queue->uhci;
919 if (packet->status == USB_RET_REMOVE_FROM_QUEUE) {
920 uhci_async_cancel(async);
921 return;
924 async->done = 1;
925 /* Force processing of this packet *now*, needed for migration */
926 s->completions_only = true;
927 qemu_bh_schedule(s->bh);
930 static int is_valid(uint32_t link)
932 return (link & 1) == 0;
935 static int is_qh(uint32_t link)
937 return (link & 2) != 0;
940 static int depth_first(uint32_t link)
942 return (link & 4) != 0;
945 /* QH DB used for detecting QH loops */
946 #define UHCI_MAX_QUEUES 128
947 typedef struct {
948 uint32_t addr[UHCI_MAX_QUEUES];
949 int count;
950 } QhDb;
952 static void qhdb_reset(QhDb *db)
954 db->count = 0;
957 /* Add QH to DB. Returns 1 if already present or DB is full. */
958 static int qhdb_insert(QhDb *db, uint32_t addr)
960 int i;
961 for (i = 0; i < db->count; i++)
962 if (db->addr[i] == addr)
963 return 1;
965 if (db->count >= UHCI_MAX_QUEUES)
966 return 1;
968 db->addr[db->count++] = addr;
969 return 0;
972 static void uhci_queue_fill(UHCIQueue *q, UHCI_TD *td)
974 uint32_t int_mask = 0;
975 uint32_t plink = td->link;
976 UHCI_TD ptd;
977 int ret;
979 while (is_valid(plink)) {
980 uhci_read_td(q->uhci, &ptd, plink);
981 if (!(ptd.ctrl & TD_CTRL_ACTIVE)) {
982 break;
984 if (uhci_queue_token(&ptd) != q->token) {
985 break;
987 trace_usb_uhci_td_queue(plink & ~0xf, ptd.ctrl, ptd.token);
988 ret = uhci_handle_td(q->uhci, q, q->qh_addr, &ptd, plink, &int_mask);
989 if (ret == TD_RESULT_ASYNC_CONT) {
990 break;
992 assert(ret == TD_RESULT_ASYNC_START);
993 assert(int_mask == 0);
994 plink = ptd.link;
996 usb_device_flush_ep_queue(q->ep->dev, q->ep);
999 static void uhci_process_frame(UHCIState *s)
1001 uint32_t frame_addr, link, old_td_ctrl, val, int_mask;
1002 uint32_t curr_qh, td_count = 0;
1003 int cnt, ret;
1004 UHCI_TD td;
1005 UHCI_QH qh;
1006 QhDb qhdb;
1008 frame_addr = s->fl_base_addr + ((s->frnum & 0x3ff) << 2);
1010 pci_dma_read(&s->dev, frame_addr, &link, 4);
1011 le32_to_cpus(&link);
1013 int_mask = 0;
1014 curr_qh = 0;
1016 qhdb_reset(&qhdb);
1018 for (cnt = FRAME_MAX_LOOPS; is_valid(link) && cnt; cnt--) {
1019 if (!s->completions_only && s->frame_bytes >= s->frame_bandwidth) {
1020 /* We've reached the usb 1.1 bandwidth, which is
1021 1280 bytes/frame, stop processing */
1022 trace_usb_uhci_frame_stop_bandwidth();
1023 break;
1025 if (is_qh(link)) {
1026 /* QH */
1027 trace_usb_uhci_qh_load(link & ~0xf);
1029 if (qhdb_insert(&qhdb, link)) {
1031 * We're going in circles. Which is not a bug because
1032 * HCD is allowed to do that as part of the BW management.
1034 * Stop processing here if no transaction has been done
1035 * since we've been here last time.
1037 if (td_count == 0) {
1038 trace_usb_uhci_frame_loop_stop_idle();
1039 break;
1040 } else {
1041 trace_usb_uhci_frame_loop_continue();
1042 td_count = 0;
1043 qhdb_reset(&qhdb);
1044 qhdb_insert(&qhdb, link);
1048 pci_dma_read(&s->dev, link & ~0xf, &qh, sizeof(qh));
1049 le32_to_cpus(&qh.link);
1050 le32_to_cpus(&qh.el_link);
1052 if (!is_valid(qh.el_link)) {
1053 /* QH w/o elements */
1054 curr_qh = 0;
1055 link = qh.link;
1056 } else {
1057 /* QH with elements */
1058 curr_qh = link;
1059 link = qh.el_link;
1061 continue;
1064 /* TD */
1065 uhci_read_td(s, &td, link);
1066 trace_usb_uhci_td_load(curr_qh & ~0xf, link & ~0xf, td.ctrl, td.token);
1068 old_td_ctrl = td.ctrl;
1069 ret = uhci_handle_td(s, NULL, curr_qh, &td, link, &int_mask);
1070 if (old_td_ctrl != td.ctrl) {
1071 /* update the status bits of the TD */
1072 val = cpu_to_le32(td.ctrl);
1073 pci_dma_write(&s->dev, (link & ~0xf) + 4, &val, sizeof(val));
1076 switch (ret) {
1077 case TD_RESULT_STOP_FRAME: /* interrupted frame */
1078 goto out;
1080 case TD_RESULT_NEXT_QH:
1081 case TD_RESULT_ASYNC_CONT:
1082 trace_usb_uhci_td_nextqh(curr_qh & ~0xf, link & ~0xf);
1083 link = curr_qh ? qh.link : td.link;
1084 continue;
1086 case TD_RESULT_ASYNC_START:
1087 trace_usb_uhci_td_async(curr_qh & ~0xf, link & ~0xf);
1088 link = curr_qh ? qh.link : td.link;
1089 continue;
1091 case TD_RESULT_COMPLETE:
1092 trace_usb_uhci_td_complete(curr_qh & ~0xf, link & ~0xf);
1093 link = td.link;
1094 td_count++;
1095 s->frame_bytes += (td.ctrl & 0x7ff) + 1;
1097 if (curr_qh) {
1098 /* update QH element link */
1099 qh.el_link = link;
1100 val = cpu_to_le32(qh.el_link);
1101 pci_dma_write(&s->dev, (curr_qh & ~0xf) + 4, &val, sizeof(val));
1103 if (!depth_first(link)) {
1104 /* done with this QH */
1105 curr_qh = 0;
1106 link = qh.link;
1109 break;
1111 default:
1112 assert(!"unknown return code");
1115 /* go to the next entry */
1118 out:
1119 s->pending_int_mask |= int_mask;
1122 static void uhci_bh(void *opaque)
1124 UHCIState *s = opaque;
1125 uhci_process_frame(s);
1128 static void uhci_frame_timer(void *opaque)
1130 UHCIState *s = opaque;
1131 uint64_t t_now, t_last_run;
1132 int i, frames;
1133 const uint64_t frame_t = get_ticks_per_sec() / FRAME_TIMER_FREQ;
1135 s->completions_only = false;
1136 qemu_bh_cancel(s->bh);
1138 if (!(s->cmd & UHCI_CMD_RS)) {
1139 /* Full stop */
1140 trace_usb_uhci_schedule_stop();
1141 timer_del(s->frame_timer);
1142 uhci_async_cancel_all(s);
1143 /* set hchalted bit in status - UHCI11D 2.1.2 */
1144 s->status |= UHCI_STS_HCHALTED;
1145 return;
1148 /* We still store expire_time in our state, for migration */
1149 t_last_run = s->expire_time - frame_t;
1150 t_now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1152 /* Process up to MAX_FRAMES_PER_TICK frames */
1153 frames = (t_now - t_last_run) / frame_t;
1154 if (frames > s->maxframes) {
1155 int skipped = frames - s->maxframes;
1156 s->expire_time += skipped * frame_t;
1157 s->frnum = (s->frnum + skipped) & 0x7ff;
1158 frames -= skipped;
1160 if (frames > MAX_FRAMES_PER_TICK) {
1161 frames = MAX_FRAMES_PER_TICK;
1164 for (i = 0; i < frames; i++) {
1165 s->frame_bytes = 0;
1166 trace_usb_uhci_frame_start(s->frnum);
1167 uhci_async_validate_begin(s);
1168 uhci_process_frame(s);
1169 uhci_async_validate_end(s);
1170 /* The spec says frnum is the frame currently being processed, and
1171 * the guest must look at frnum - 1 on interrupt, so inc frnum now */
1172 s->frnum = (s->frnum + 1) & 0x7ff;
1173 s->expire_time += frame_t;
1176 /* Complete the previous frame(s) */
1177 if (s->pending_int_mask) {
1178 s->status2 |= s->pending_int_mask;
1179 s->status |= UHCI_STS_USBINT;
1180 uhci_update_irq(s);
1182 s->pending_int_mask = 0;
1184 timer_mod(s->frame_timer, t_now + frame_t);
1187 static const MemoryRegionOps uhci_ioport_ops = {
1188 .read = uhci_port_read,
1189 .write = uhci_port_write,
1190 .valid.min_access_size = 1,
1191 .valid.max_access_size = 4,
1192 .impl.min_access_size = 2,
1193 .impl.max_access_size = 2,
1194 .endianness = DEVICE_LITTLE_ENDIAN,
1197 static USBPortOps uhci_port_ops = {
1198 .attach = uhci_attach,
1199 .detach = uhci_detach,
1200 .child_detach = uhci_child_detach,
1201 .wakeup = uhci_wakeup,
1202 .complete = uhci_async_complete,
1205 static USBBusOps uhci_bus_ops = {
1208 static void usb_uhci_common_realize(PCIDevice *dev, Error **errp)
1210 Error *err = NULL;
1211 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
1212 UHCIPCIDeviceClass *u = container_of(pc, UHCIPCIDeviceClass, parent_class);
1213 UHCIState *s = UHCI(dev);
1214 uint8_t *pci_conf = s->dev.config;
1215 int i;
1217 pci_conf[PCI_CLASS_PROG] = 0x00;
1218 /* TODO: reset value should be 0. */
1219 pci_conf[USB_SBRN] = USB_RELEASE_1; // release number
1221 pci_config_set_interrupt_pin(pci_conf, u->info.irq_pin + 1);
1223 if (s->masterbus) {
1224 USBPort *ports[NB_PORTS];
1225 for(i = 0; i < NB_PORTS; i++) {
1226 ports[i] = &s->ports[i].port;
1228 usb_register_companion(s->masterbus, ports, NB_PORTS,
1229 s->firstport, s, &uhci_port_ops,
1230 USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL,
1231 &err);
1232 if (err) {
1233 error_propagate(errp, err);
1234 return;
1236 } else {
1237 usb_bus_new(&s->bus, sizeof(s->bus), &uhci_bus_ops, DEVICE(dev));
1238 for (i = 0; i < NB_PORTS; i++) {
1239 usb_register_port(&s->bus, &s->ports[i].port, s, i, &uhci_port_ops,
1240 USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL);
1243 s->bh = qemu_bh_new(uhci_bh, s);
1244 s->frame_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, uhci_frame_timer, s);
1245 s->num_ports_vmstate = NB_PORTS;
1246 QTAILQ_INIT(&s->queues);
1248 memory_region_init_io(&s->io_bar, OBJECT(s), &uhci_ioport_ops, s,
1249 "uhci", 0x20);
1251 /* Use region 4 for consistency with real hardware. BSD guests seem
1252 to rely on this. */
1253 pci_register_bar(&s->dev, 4, PCI_BASE_ADDRESS_SPACE_IO, &s->io_bar);
1256 static void usb_uhci_vt82c686b_realize(PCIDevice *dev, Error **errp)
1258 UHCIState *s = UHCI(dev);
1259 uint8_t *pci_conf = s->dev.config;
1261 /* USB misc control 1/2 */
1262 pci_set_long(pci_conf + 0x40,0x00001000);
1263 /* PM capability */
1264 pci_set_long(pci_conf + 0x80,0x00020001);
1265 /* USB legacy support */
1266 pci_set_long(pci_conf + 0xc0,0x00002000);
1268 usb_uhci_common_realize(dev, errp);
1271 static void usb_uhci_exit(PCIDevice *dev)
1273 UHCIState *s = UHCI(dev);
1275 trace_usb_uhci_exit();
1277 if (s->frame_timer) {
1278 timer_del(s->frame_timer);
1279 timer_free(s->frame_timer);
1280 s->frame_timer = NULL;
1283 if (s->bh) {
1284 qemu_bh_delete(s->bh);
1287 uhci_async_cancel_all(s);
1289 if (!s->masterbus) {
1290 usb_bus_release(&s->bus);
1294 static Property uhci_properties_companion[] = {
1295 DEFINE_PROP_STRING("masterbus", UHCIState, masterbus),
1296 DEFINE_PROP_UINT32("firstport", UHCIState, firstport, 0),
1297 DEFINE_PROP_UINT32("bandwidth", UHCIState, frame_bandwidth, 1280),
1298 DEFINE_PROP_UINT32("maxframes", UHCIState, maxframes, 128),
1299 DEFINE_PROP_END_OF_LIST(),
1301 static Property uhci_properties_standalone[] = {
1302 DEFINE_PROP_UINT32("bandwidth", UHCIState, frame_bandwidth, 1280),
1303 DEFINE_PROP_UINT32("maxframes", UHCIState, maxframes, 128),
1304 DEFINE_PROP_END_OF_LIST(),
1307 static void uhci_class_init(ObjectClass *klass, void *data)
1309 DeviceClass *dc = DEVICE_CLASS(klass);
1310 PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1312 k->class_id = PCI_CLASS_SERIAL_USB;
1313 dc->vmsd = &vmstate_uhci;
1314 dc->reset = uhci_reset;
1315 set_bit(DEVICE_CATEGORY_USB, dc->categories);
1318 static const TypeInfo uhci_pci_type_info = {
1319 .name = TYPE_UHCI,
1320 .parent = TYPE_PCI_DEVICE,
1321 .instance_size = sizeof(UHCIState),
1322 .class_size = sizeof(UHCIPCIDeviceClass),
1323 .abstract = true,
1324 .class_init = uhci_class_init,
1327 static void uhci_data_class_init(ObjectClass *klass, void *data)
1329 PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1330 DeviceClass *dc = DEVICE_CLASS(klass);
1331 UHCIPCIDeviceClass *u = container_of(k, UHCIPCIDeviceClass, parent_class);
1332 UHCIInfo *info = data;
1334 k->realize = info->realize ? info->realize : usb_uhci_common_realize;
1335 k->exit = info->unplug ? usb_uhci_exit : NULL;
1336 k->vendor_id = info->vendor_id;
1337 k->device_id = info->device_id;
1338 k->revision = info->revision;
1339 if (!info->unplug) {
1340 /* uhci controllers in companion setups can't be hotplugged */
1341 dc->hotpluggable = false;
1342 dc->props = uhci_properties_companion;
1343 } else {
1344 dc->props = uhci_properties_standalone;
1346 u->info = *info;
1349 static UHCIInfo uhci_info[] = {
1351 .name = "piix3-usb-uhci",
1352 .vendor_id = PCI_VENDOR_ID_INTEL,
1353 .device_id = PCI_DEVICE_ID_INTEL_82371SB_2,
1354 .revision = 0x01,
1355 .irq_pin = 3,
1356 .unplug = true,
1358 .name = "piix4-usb-uhci",
1359 .vendor_id = PCI_VENDOR_ID_INTEL,
1360 .device_id = PCI_DEVICE_ID_INTEL_82371AB_2,
1361 .revision = 0x01,
1362 .irq_pin = 3,
1363 .unplug = true,
1365 .name = "vt82c686b-usb-uhci",
1366 .vendor_id = PCI_VENDOR_ID_VIA,
1367 .device_id = PCI_DEVICE_ID_VIA_UHCI,
1368 .revision = 0x01,
1369 .irq_pin = 3,
1370 .realize = usb_uhci_vt82c686b_realize,
1371 .unplug = true,
1373 .name = "ich9-usb-uhci1", /* 00:1d.0 */
1374 .vendor_id = PCI_VENDOR_ID_INTEL,
1375 .device_id = PCI_DEVICE_ID_INTEL_82801I_UHCI1,
1376 .revision = 0x03,
1377 .irq_pin = 0,
1378 .unplug = false,
1380 .name = "ich9-usb-uhci2", /* 00:1d.1 */
1381 .vendor_id = PCI_VENDOR_ID_INTEL,
1382 .device_id = PCI_DEVICE_ID_INTEL_82801I_UHCI2,
1383 .revision = 0x03,
1384 .irq_pin = 1,
1385 .unplug = false,
1387 .name = "ich9-usb-uhci3", /* 00:1d.2 */
1388 .vendor_id = PCI_VENDOR_ID_INTEL,
1389 .device_id = PCI_DEVICE_ID_INTEL_82801I_UHCI3,
1390 .revision = 0x03,
1391 .irq_pin = 2,
1392 .unplug = false,
1394 .name = "ich9-usb-uhci4", /* 00:1a.0 */
1395 .vendor_id = PCI_VENDOR_ID_INTEL,
1396 .device_id = PCI_DEVICE_ID_INTEL_82801I_UHCI4,
1397 .revision = 0x03,
1398 .irq_pin = 0,
1399 .unplug = false,
1401 .name = "ich9-usb-uhci5", /* 00:1a.1 */
1402 .vendor_id = PCI_VENDOR_ID_INTEL,
1403 .device_id = PCI_DEVICE_ID_INTEL_82801I_UHCI5,
1404 .revision = 0x03,
1405 .irq_pin = 1,
1406 .unplug = false,
1408 .name = "ich9-usb-uhci6", /* 00:1a.2 */
1409 .vendor_id = PCI_VENDOR_ID_INTEL,
1410 .device_id = PCI_DEVICE_ID_INTEL_82801I_UHCI6,
1411 .revision = 0x03,
1412 .irq_pin = 2,
1413 .unplug = false,
1417 static void uhci_register_types(void)
1419 TypeInfo uhci_type_info = {
1420 .parent = TYPE_UHCI,
1421 .class_init = uhci_data_class_init,
1423 int i;
1425 type_register_static(&uhci_pci_type_info);
1427 for (i = 0; i < ARRAY_SIZE(uhci_info); i++) {
1428 uhci_type_info.name = uhci_info[i].name;
1429 uhci_type_info.class_data = uhci_info + i;
1430 type_register(&uhci_type_info);
1434 type_init(uhci_register_types)