2 * QEMU USB EHCI Emulation
4 * Copyright(c) 2008 Emutex Ltd. (address@hidden)
5 * Copyright(c) 2011-2012 Red Hat, Inc.
11 * EHCI project was started by Mark Burkley, with contributions by
12 * Niels de Vos. David S. Ahern continued working on it. Kevin Wolf,
13 * Jan Kiszka and Vincent Palatin contributed bugfixes.
16 * This library is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU Lesser General Public
18 * License as published by the Free Software Foundation; either
19 * version 2 of the License, or(at your option) any later version.
21 * This library is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 * Lesser General Public License for more details.
26 * You should have received a copy of the GNU General Public License
27 * along with this program; if not, see <http://www.gnu.org/licenses/>.
30 #include "hw/usb/hcd-ehci.h"
33 /* Capability Registers Base Address - section 2.2 */
34 #define CAPLENGTH 0x0000 /* 1-byte, 0x0001 reserved */
35 #define HCIVERSION 0x0002 /* 2-bytes, i/f version # */
36 #define HCSPARAMS 0x0004 /* 4-bytes, structural params */
37 #define HCCPARAMS 0x0008 /* 4-bytes, capability params */
38 #define EECP HCCPARAMS + 1
39 #define HCSPPORTROUTE1 0x000c
40 #define HCSPPORTROUTE2 0x0010
43 #define USBCMD_RUNSTOP (1 << 0) // run / Stop
44 #define USBCMD_HCRESET (1 << 1) // HC Reset
45 #define USBCMD_FLS (3 << 2) // Frame List Size
46 #define USBCMD_FLS_SH 2 // Frame List Size Shift
47 #define USBCMD_PSE (1 << 4) // Periodic Schedule Enable
48 #define USBCMD_ASE (1 << 5) // Asynch Schedule Enable
49 #define USBCMD_IAAD (1 << 6) // Int Asynch Advance Doorbell
50 #define USBCMD_LHCR (1 << 7) // Light Host Controller Reset
51 #define USBCMD_ASPMC (3 << 8) // Async Sched Park Mode Count
52 #define USBCMD_ASPME (1 << 11) // Async Sched Park Mode Enable
53 #define USBCMD_ITC (0x7f << 16) // Int Threshold Control
54 #define USBCMD_ITC_SH 16 // Int Threshold Control Shift
57 #define USBSTS_RO_MASK 0x0000003f
58 #define USBSTS_INT (1 << 0) // USB Interrupt
59 #define USBSTS_ERRINT (1 << 1) // Error Interrupt
60 #define USBSTS_PCD (1 << 2) // Port Change Detect
61 #define USBSTS_FLR (1 << 3) // Frame List Rollover
62 #define USBSTS_HSE (1 << 4) // Host System Error
63 #define USBSTS_IAA (1 << 5) // Interrupt on Async Advance
64 #define USBSTS_HALT (1 << 12) // HC Halted
65 #define USBSTS_REC (1 << 13) // Reclamation
66 #define USBSTS_PSS (1 << 14) // Periodic Schedule Status
67 #define USBSTS_ASS (1 << 15) // Asynchronous Schedule Status
70 * Interrupt enable bits correspond to the interrupt active bits in USBSTS
71 * so no need to redefine here.
73 #define USBINTR 0x0008
74 #define USBINTR_MASK 0x0000003f
76 #define FRINDEX 0x000c
77 #define CTRLDSSEGMENT 0x0010
78 #define PERIODICLISTBASE 0x0014
79 #define ASYNCLISTADDR 0x0018
80 #define ASYNCLISTADDR_MASK 0xffffffe0
82 #define CONFIGFLAG 0x0040
85 * Bits that are reserved or are read-only are masked out of values
86 * written to us by software
88 #define PORTSC_RO_MASK 0x007001c0
89 #define PORTSC_RWC_MASK 0x0000002a
90 #define PORTSC_WKOC_E (1 << 22) // Wake on Over Current Enable
91 #define PORTSC_WKDS_E (1 << 21) // Wake on Disconnect Enable
92 #define PORTSC_WKCN_E (1 << 20) // Wake on Connect Enable
93 #define PORTSC_PTC (15 << 16) // Port Test Control
94 #define PORTSC_PTC_SH 16 // Port Test Control shift
95 #define PORTSC_PIC (3 << 14) // Port Indicator Control
96 #define PORTSC_PIC_SH 14 // Port Indicator Control Shift
97 #define PORTSC_POWNER (1 << 13) // Port Owner
98 #define PORTSC_PPOWER (1 << 12) // Port Power
99 #define PORTSC_LINESTAT (3 << 10) // Port Line Status
100 #define PORTSC_LINESTAT_SH 10 // Port Line Status Shift
101 #define PORTSC_PRESET (1 << 8) // Port Reset
102 #define PORTSC_SUSPEND (1 << 7) // Port Suspend
103 #define PORTSC_FPRES (1 << 6) // Force Port Resume
104 #define PORTSC_OCC (1 << 5) // Over Current Change
105 #define PORTSC_OCA (1 << 4) // Over Current Active
106 #define PORTSC_PEDC (1 << 3) // Port Enable/Disable Change
107 #define PORTSC_PED (1 << 2) // Port Enable/Disable
108 #define PORTSC_CSC (1 << 1) // Connect Status Change
109 #define PORTSC_CONNECT (1 << 0) // Current Connect Status
111 #define FRAME_TIMER_FREQ 1000
112 #define FRAME_TIMER_NS (1000000000 / FRAME_TIMER_FREQ)
113 #define UFRAME_TIMER_NS (FRAME_TIMER_NS / 8)
115 #define NB_MAXINTRATE 8 // Max rate at which controller issues ints
116 #define BUFF_SIZE 5*4096 // Max bytes to transfer per transaction
117 #define MAX_QH 100 // Max allowable queue heads in a chain
118 #define MIN_UFR_PER_TICK 24 /* Min frames to process when catching up */
119 #define PERIODIC_ACTIVE 512 /* Micro-frames */
121 /* Internal periodic / asynchronous schedule state machine states
128 /* The following states are internal to the state machine function
142 /* macros for accessing fields within next link pointer entry */
143 #define NLPTR_GET(x) ((x) & 0xffffffe0)
144 #define NLPTR_TYPE_GET(x) (((x) >> 1) & 3)
145 #define NLPTR_TBIT(x) ((x) & 1) // 1=invalid, 0=valid
147 /* link pointer types */
148 #define NLPTR_TYPE_ITD 0 // isoc xfer descriptor
149 #define NLPTR_TYPE_QH 1 // queue head
150 #define NLPTR_TYPE_STITD 2 // split xaction, isoc xfer descriptor
151 #define NLPTR_TYPE_FSTN 3 // frame span traversal node
153 #define SET_LAST_RUN_CLOCK(s) \
154 (s)->last_run_ns = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
156 /* nifty macros from Arnon's EHCI version */
157 #define get_field(data, field) \
158 (((data) & field##_MASK) >> field##_SH)
160 #define set_field(data, newval, field) do { \
161 uint32_t val = *data; \
162 val &= ~ field##_MASK; \
163 val |= ((newval) << field##_SH) & field##_MASK; \
167 static const char *ehci_state_names[] = {
168 [EST_INACTIVE] = "INACTIVE",
169 [EST_ACTIVE] = "ACTIVE",
170 [EST_EXECUTING] = "EXECUTING",
171 [EST_SLEEPING] = "SLEEPING",
172 [EST_WAITLISTHEAD] = "WAITLISTHEAD",
173 [EST_FETCHENTRY] = "FETCH ENTRY",
174 [EST_FETCHQH] = "FETCH QH",
175 [EST_FETCHITD] = "FETCH ITD",
176 [EST_ADVANCEQUEUE] = "ADVANCEQUEUE",
177 [EST_FETCHQTD] = "FETCH QTD",
178 [EST_EXECUTE] = "EXECUTE",
179 [EST_WRITEBACK] = "WRITEBACK",
180 [EST_HORIZONTALQH] = "HORIZONTALQH",
183 static const char *ehci_mmio_names[] = {
186 [USBINTR] = "USBINTR",
187 [FRINDEX] = "FRINDEX",
188 [PERIODICLISTBASE] = "P-LIST BASE",
189 [ASYNCLISTADDR] = "A-LIST ADDR",
190 [CONFIGFLAG] = "CONFIGFLAG",
193 static int ehci_state_executing(EHCIQueue *q);
194 static int ehci_state_writeback(EHCIQueue *q);
195 static int ehci_state_advqueue(EHCIQueue *q);
196 static int ehci_fill_queue(EHCIPacket *p);
197 static void ehci_free_packet(EHCIPacket *p);
199 static const char *nr2str(const char **n, size_t len, uint32_t nr)
201 if (nr < len && n[nr] != NULL) {
208 static const char *state2str(uint32_t state)
210 return nr2str(ehci_state_names, ARRAY_SIZE(ehci_state_names), state);
213 static const char *addr2str(hwaddr addr)
215 return nr2str(ehci_mmio_names, ARRAY_SIZE(ehci_mmio_names), addr);
218 static void ehci_trace_usbsts(uint32_t mask, int state)
221 if (mask & USBSTS_INT) {
222 trace_usb_ehci_usbsts("INT", state);
224 if (mask & USBSTS_ERRINT) {
225 trace_usb_ehci_usbsts("ERRINT", state);
227 if (mask & USBSTS_PCD) {
228 trace_usb_ehci_usbsts("PCD", state);
230 if (mask & USBSTS_FLR) {
231 trace_usb_ehci_usbsts("FLR", state);
233 if (mask & USBSTS_HSE) {
234 trace_usb_ehci_usbsts("HSE", state);
236 if (mask & USBSTS_IAA) {
237 trace_usb_ehci_usbsts("IAA", state);
241 if (mask & USBSTS_HALT) {
242 trace_usb_ehci_usbsts("HALT", state);
244 if (mask & USBSTS_REC) {
245 trace_usb_ehci_usbsts("REC", state);
247 if (mask & USBSTS_PSS) {
248 trace_usb_ehci_usbsts("PSS", state);
250 if (mask & USBSTS_ASS) {
251 trace_usb_ehci_usbsts("ASS", state);
255 static inline void ehci_set_usbsts(EHCIState *s, int mask)
257 if ((s->usbsts & mask) == mask) {
260 ehci_trace_usbsts(mask, 1);
264 static inline void ehci_clear_usbsts(EHCIState *s, int mask)
266 if ((s->usbsts & mask) == 0) {
269 ehci_trace_usbsts(mask, 0);
273 /* update irq line */
274 static inline void ehci_update_irq(EHCIState *s)
278 if ((s->usbsts & USBINTR_MASK) & s->usbintr) {
282 trace_usb_ehci_irq(level, s->frindex, s->usbsts, s->usbintr);
283 qemu_set_irq(s->irq, level);
286 /* flag interrupt condition */
287 static inline void ehci_raise_irq(EHCIState *s, int intr)
289 if (intr & (USBSTS_PCD | USBSTS_FLR | USBSTS_HSE)) {
293 s->usbsts_pending |= intr;
298 * Commit pending interrupts (added via ehci_raise_irq),
299 * at the rate allowed by "Interrupt Threshold Control".
301 static inline void ehci_commit_irq(EHCIState *s)
305 if (!s->usbsts_pending) {
308 if (s->usbsts_frindex > s->frindex) {
312 itc = (s->usbcmd >> 16) & 0xff;
313 s->usbsts |= s->usbsts_pending;
314 s->usbsts_pending = 0;
315 s->usbsts_frindex = s->frindex + itc;
319 static void ehci_update_halt(EHCIState *s)
321 if (s->usbcmd & USBCMD_RUNSTOP) {
322 ehci_clear_usbsts(s, USBSTS_HALT);
324 if (s->astate == EST_INACTIVE && s->pstate == EST_INACTIVE) {
325 ehci_set_usbsts(s, USBSTS_HALT);
330 static void ehci_set_state(EHCIState *s, int async, int state)
333 trace_usb_ehci_state("async", state2str(state));
335 if (s->astate == EST_INACTIVE) {
336 ehci_clear_usbsts(s, USBSTS_ASS);
339 ehci_set_usbsts(s, USBSTS_ASS);
342 trace_usb_ehci_state("periodic", state2str(state));
344 if (s->pstate == EST_INACTIVE) {
345 ehci_clear_usbsts(s, USBSTS_PSS);
348 ehci_set_usbsts(s, USBSTS_PSS);
353 static int ehci_get_state(EHCIState *s, int async)
355 return async ? s->astate : s->pstate;
358 static void ehci_set_fetch_addr(EHCIState *s, int async, uint32_t addr)
361 s->a_fetch_addr = addr;
363 s->p_fetch_addr = addr;
367 static int ehci_get_fetch_addr(EHCIState *s, int async)
369 return async ? s->a_fetch_addr : s->p_fetch_addr;
372 static void ehci_trace_qh(EHCIQueue *q, hwaddr addr, EHCIqh *qh)
374 /* need three here due to argument count limits */
375 trace_usb_ehci_qh_ptrs(q, addr, qh->next,
376 qh->current_qtd, qh->next_qtd, qh->altnext_qtd);
377 trace_usb_ehci_qh_fields(addr,
378 get_field(qh->epchar, QH_EPCHAR_RL),
379 get_field(qh->epchar, QH_EPCHAR_MPLEN),
380 get_field(qh->epchar, QH_EPCHAR_EPS),
381 get_field(qh->epchar, QH_EPCHAR_EP),
382 get_field(qh->epchar, QH_EPCHAR_DEVADDR));
383 trace_usb_ehci_qh_bits(addr,
384 (bool)(qh->epchar & QH_EPCHAR_C),
385 (bool)(qh->epchar & QH_EPCHAR_H),
386 (bool)(qh->epchar & QH_EPCHAR_DTC),
387 (bool)(qh->epchar & QH_EPCHAR_I));
390 static void ehci_trace_qtd(EHCIQueue *q, hwaddr addr, EHCIqtd *qtd)
392 /* need three here due to argument count limits */
393 trace_usb_ehci_qtd_ptrs(q, addr, qtd->next, qtd->altnext);
394 trace_usb_ehci_qtd_fields(addr,
395 get_field(qtd->token, QTD_TOKEN_TBYTES),
396 get_field(qtd->token, QTD_TOKEN_CPAGE),
397 get_field(qtd->token, QTD_TOKEN_CERR),
398 get_field(qtd->token, QTD_TOKEN_PID));
399 trace_usb_ehci_qtd_bits(addr,
400 (bool)(qtd->token & QTD_TOKEN_IOC),
401 (bool)(qtd->token & QTD_TOKEN_ACTIVE),
402 (bool)(qtd->token & QTD_TOKEN_HALT),
403 (bool)(qtd->token & QTD_TOKEN_BABBLE),
404 (bool)(qtd->token & QTD_TOKEN_XACTERR));
407 static void ehci_trace_itd(EHCIState *s, hwaddr addr, EHCIitd *itd)
409 trace_usb_ehci_itd(addr, itd->next,
410 get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT),
411 get_field(itd->bufptr[2], ITD_BUFPTR_MULT),
412 get_field(itd->bufptr[0], ITD_BUFPTR_EP),
413 get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR));
416 static void ehci_trace_sitd(EHCIState *s, hwaddr addr,
419 trace_usb_ehci_sitd(addr, sitd->next,
420 (bool)(sitd->results & SITD_RESULTS_ACTIVE));
423 static void ehci_trace_guest_bug(EHCIState *s, const char *message)
425 trace_usb_ehci_guest_bug(message);
426 fprintf(stderr, "ehci warning: %s\n", message);
429 static inline bool ehci_enabled(EHCIState *s)
431 return s->usbcmd & USBCMD_RUNSTOP;
434 static inline bool ehci_async_enabled(EHCIState *s)
436 return ehci_enabled(s) && (s->usbcmd & USBCMD_ASE);
439 static inline bool ehci_periodic_enabled(EHCIState *s)
441 return ehci_enabled(s) && (s->usbcmd & USBCMD_PSE);
444 /* Get an array of dwords from main memory */
445 static inline int get_dwords(EHCIState *ehci, uint32_t addr,
446 uint32_t *buf, int num)
451 ehci_raise_irq(ehci, USBSTS_HSE);
452 ehci->usbcmd &= ~USBCMD_RUNSTOP;
453 trace_usb_ehci_dma_error();
457 for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
458 dma_memory_read(ehci->as, addr, buf, sizeof(*buf));
459 *buf = le32_to_cpu(*buf);
465 /* Put an array of dwords in to main memory */
466 static inline int put_dwords(EHCIState *ehci, uint32_t addr,
467 uint32_t *buf, int num)
472 ehci_raise_irq(ehci, USBSTS_HSE);
473 ehci->usbcmd &= ~USBCMD_RUNSTOP;
474 trace_usb_ehci_dma_error();
478 for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
479 uint32_t tmp = cpu_to_le32(*buf);
480 dma_memory_write(ehci->as, addr, &tmp, sizeof(tmp));
486 static int ehci_get_pid(EHCIqtd *qtd)
488 switch (get_field(qtd->token, QTD_TOKEN_PID)) {
490 return USB_TOKEN_OUT;
494 return USB_TOKEN_SETUP;
496 fprintf(stderr, "bad token\n");
501 static bool ehci_verify_qh(EHCIQueue *q, EHCIqh *qh)
503 uint32_t devaddr = get_field(qh->epchar, QH_EPCHAR_DEVADDR);
504 uint32_t endp = get_field(qh->epchar, QH_EPCHAR_EP);
505 if ((devaddr != get_field(q->qh.epchar, QH_EPCHAR_DEVADDR)) ||
506 (endp != get_field(q->qh.epchar, QH_EPCHAR_EP)) ||
507 (qh->current_qtd != q->qh.current_qtd) ||
508 (q->async && qh->next_qtd != q->qh.next_qtd) ||
509 (memcmp(&qh->altnext_qtd, &q->qh.altnext_qtd,
510 7 * sizeof(uint32_t)) != 0) ||
511 (q->dev != NULL && q->dev->addr != devaddr)) {
518 static bool ehci_verify_qtd(EHCIPacket *p, EHCIqtd *qtd)
520 if (p->qtdaddr != p->queue->qtdaddr ||
521 (p->queue->async && !NLPTR_TBIT(p->qtd.next) &&
522 (p->qtd.next != qtd->next)) ||
523 (!NLPTR_TBIT(p->qtd.altnext) && (p->qtd.altnext != qtd->altnext)) ||
524 p->qtd.token != qtd->token ||
525 p->qtd.bufptr[0] != qtd->bufptr[0]) {
532 static bool ehci_verify_pid(EHCIQueue *q, EHCIqtd *qtd)
534 int ep = get_field(q->qh.epchar, QH_EPCHAR_EP);
535 int pid = ehci_get_pid(qtd);
537 /* Note the pid changing is normal for ep 0 (the control ep) */
538 if (q->last_pid && ep != 0 && pid != q->last_pid) {
545 /* Finish executing and writeback a packet outside of the regular
546 fetchqh -> fetchqtd -> execute -> writeback cycle */
547 static void ehci_writeback_async_complete_packet(EHCIPacket *p)
549 EHCIQueue *q = p->queue;
554 /* Verify the qh + qtd, like we do when going through fetchqh & fetchqtd */
555 get_dwords(q->ehci, NLPTR_GET(q->qhaddr),
556 (uint32_t *) &qh, sizeof(EHCIqh) >> 2);
557 get_dwords(q->ehci, NLPTR_GET(q->qtdaddr),
558 (uint32_t *) &qtd, sizeof(EHCIqtd) >> 2);
559 if (!ehci_verify_qh(q, &qh) || !ehci_verify_qtd(p, &qtd)) {
560 p->async = EHCI_ASYNC_INITIALIZED;
565 state = ehci_get_state(q->ehci, q->async);
566 ehci_state_executing(q);
567 ehci_state_writeback(q); /* Frees the packet! */
568 if (!(q->qh.token & QTD_TOKEN_HALT)) {
569 ehci_state_advqueue(q);
571 ehci_set_state(q->ehci, q->async, state);
574 /* packet management */
576 static EHCIPacket *ehci_alloc_packet(EHCIQueue *q)
580 p = g_new0(EHCIPacket, 1);
582 usb_packet_init(&p->packet);
583 QTAILQ_INSERT_TAIL(&q->packets, p, next);
584 trace_usb_ehci_packet_action(p->queue, p, "alloc");
588 static void ehci_free_packet(EHCIPacket *p)
590 if (p->async == EHCI_ASYNC_FINISHED &&
591 !(p->queue->qh.token & QTD_TOKEN_HALT)) {
592 ehci_writeback_async_complete_packet(p);
595 trace_usb_ehci_packet_action(p->queue, p, "free");
596 if (p->async == EHCI_ASYNC_INFLIGHT) {
597 usb_cancel_packet(&p->packet);
599 if (p->async == EHCI_ASYNC_FINISHED &&
600 p->packet.status == USB_RET_SUCCESS) {
602 "EHCI: Dropping completed packet from halted %s ep %02X\n",
603 (p->pid == USB_TOKEN_IN) ? "in" : "out",
604 get_field(p->queue->qh.epchar, QH_EPCHAR_EP));
606 if (p->async != EHCI_ASYNC_NONE) {
607 usb_packet_unmap(&p->packet, &p->sgl);
608 qemu_sglist_destroy(&p->sgl);
610 QTAILQ_REMOVE(&p->queue->packets, p, next);
611 usb_packet_cleanup(&p->packet);
615 /* queue management */
617 static EHCIQueue *ehci_alloc_queue(EHCIState *ehci, uint32_t addr, int async)
619 EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
622 q = g_malloc0(sizeof(*q));
626 QTAILQ_INIT(&q->packets);
627 QTAILQ_INSERT_HEAD(head, q, next);
628 trace_usb_ehci_queue_action(q, "alloc");
632 static void ehci_queue_stopped(EHCIQueue *q)
634 int endp = get_field(q->qh.epchar, QH_EPCHAR_EP);
636 if (!q->last_pid || !q->dev) {
640 usb_device_ep_stopped(q->dev, usb_ep_get(q->dev, q->last_pid, endp));
643 static int ehci_cancel_queue(EHCIQueue *q)
648 p = QTAILQ_FIRST(&q->packets);
653 trace_usb_ehci_queue_action(q, "cancel");
657 } while ((p = QTAILQ_FIRST(&q->packets)) != NULL);
660 ehci_queue_stopped(q);
664 static int ehci_reset_queue(EHCIQueue *q)
668 trace_usb_ehci_queue_action(q, "reset");
669 packets = ehci_cancel_queue(q);
676 static void ehci_free_queue(EHCIQueue *q, const char *warn)
678 EHCIQueueHead *head = q->async ? &q->ehci->aqueues : &q->ehci->pqueues;
681 trace_usb_ehci_queue_action(q, "free");
682 cancelled = ehci_cancel_queue(q);
683 if (warn && cancelled > 0) {
684 ehci_trace_guest_bug(q->ehci, warn);
686 QTAILQ_REMOVE(head, q, next);
690 static EHCIQueue *ehci_find_queue_by_qh(EHCIState *ehci, uint32_t addr,
693 EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
696 QTAILQ_FOREACH(q, head, next) {
697 if (addr == q->qhaddr) {
704 static void ehci_queues_rip_unused(EHCIState *ehci, int async)
706 EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
707 const char *warn = async ? "guest unlinked busy QH" : NULL;
708 uint64_t maxage = FRAME_TIMER_NS * ehci->maxframes * 4;
711 QTAILQ_FOREACH_SAFE(q, head, next, tmp) {
714 q->ts = ehci->last_run_ns;
717 if (ehci->last_run_ns < q->ts + maxage) {
720 ehci_free_queue(q, warn);
724 static void ehci_queues_rip_unseen(EHCIState *ehci, int async)
726 EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
729 QTAILQ_FOREACH_SAFE(q, head, next, tmp) {
731 ehci_free_queue(q, NULL);
736 static void ehci_queues_rip_device(EHCIState *ehci, USBDevice *dev, int async)
738 EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
741 QTAILQ_FOREACH_SAFE(q, head, next, tmp) {
745 ehci_free_queue(q, NULL);
749 static void ehci_queues_rip_all(EHCIState *ehci, int async)
751 EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
752 const char *warn = async ? "guest stopped busy async schedule" : NULL;
755 QTAILQ_FOREACH_SAFE(q, head, next, tmp) {
756 ehci_free_queue(q, warn);
760 /* Attach or detach a device on root hub */
762 static void ehci_attach(USBPort *port)
764 EHCIState *s = port->opaque;
765 uint32_t *portsc = &s->portsc[port->index];
766 const char *owner = (*portsc & PORTSC_POWNER) ? "comp" : "ehci";
768 trace_usb_ehci_port_attach(port->index, owner, port->dev->product_desc);
770 if (*portsc & PORTSC_POWNER) {
771 USBPort *companion = s->companion_ports[port->index];
772 companion->dev = port->dev;
773 companion->ops->attach(companion);
777 *portsc |= PORTSC_CONNECT;
778 *portsc |= PORTSC_CSC;
780 ehci_raise_irq(s, USBSTS_PCD);
783 static void ehci_detach(USBPort *port)
785 EHCIState *s = port->opaque;
786 uint32_t *portsc = &s->portsc[port->index];
787 const char *owner = (*portsc & PORTSC_POWNER) ? "comp" : "ehci";
789 trace_usb_ehci_port_detach(port->index, owner);
791 if (*portsc & PORTSC_POWNER) {
792 USBPort *companion = s->companion_ports[port->index];
793 companion->ops->detach(companion);
794 companion->dev = NULL;
796 * EHCI spec 4.2.2: "When a disconnect occurs... On the event,
797 * the port ownership is returned immediately to the EHCI controller."
799 *portsc &= ~PORTSC_POWNER;
803 ehci_queues_rip_device(s, port->dev, 0);
804 ehci_queues_rip_device(s, port->dev, 1);
806 *portsc &= ~(PORTSC_CONNECT|PORTSC_PED);
807 *portsc |= PORTSC_CSC;
809 ehci_raise_irq(s, USBSTS_PCD);
812 static void ehci_child_detach(USBPort *port, USBDevice *child)
814 EHCIState *s = port->opaque;
815 uint32_t portsc = s->portsc[port->index];
817 if (portsc & PORTSC_POWNER) {
818 USBPort *companion = s->companion_ports[port->index];
819 companion->ops->child_detach(companion, child);
823 ehci_queues_rip_device(s, child, 0);
824 ehci_queues_rip_device(s, child, 1);
827 static void ehci_wakeup(USBPort *port)
829 EHCIState *s = port->opaque;
830 uint32_t portsc = s->portsc[port->index];
832 if (portsc & PORTSC_POWNER) {
833 USBPort *companion = s->companion_ports[port->index];
834 if (companion->ops->wakeup) {
835 companion->ops->wakeup(companion);
840 qemu_bh_schedule(s->async_bh);
843 static int ehci_register_companion(USBBus *bus, USBPort *ports[],
844 uint32_t portcount, uint32_t firstport)
846 EHCIState *s = container_of(bus, EHCIState, bus);
849 if (firstport + portcount > NB_PORTS) {
850 qerror_report(QERR_INVALID_PARAMETER_VALUE, "firstport",
851 "firstport on masterbus");
852 error_printf_unless_qmp(
853 "firstport value of %u makes companion take ports %u - %u, which "
854 "is outside of the valid range of 0 - %u\n", firstport, firstport,
855 firstport + portcount - 1, NB_PORTS - 1);
859 for (i = 0; i < portcount; i++) {
860 if (s->companion_ports[firstport + i]) {
861 qerror_report(QERR_INVALID_PARAMETER_VALUE, "masterbus",
863 error_printf_unless_qmp(
864 "port %u on masterbus %s already has a companion assigned\n",
865 firstport + i, bus->qbus.name);
870 for (i = 0; i < portcount; i++) {
871 s->companion_ports[firstport + i] = ports[i];
872 s->ports[firstport + i].speedmask |=
873 USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL;
874 /* Ensure devs attached before the initial reset go to the companion */
875 s->portsc[firstport + i] = PORTSC_POWNER;
878 s->companion_count++;
879 s->caps[0x05] = (s->companion_count << 4) | portcount;
884 static void ehci_wakeup_endpoint(USBBus *bus, USBEndpoint *ep,
887 EHCIState *s = container_of(bus, EHCIState, bus);
888 uint32_t portsc = s->portsc[ep->dev->port->index];
890 if (portsc & PORTSC_POWNER) {
894 s->periodic_sched_active = PERIODIC_ACTIVE;
895 qemu_bh_schedule(s->async_bh);
898 static USBDevice *ehci_find_device(EHCIState *ehci, uint8_t addr)
904 for (i = 0; i < NB_PORTS; i++) {
905 port = &ehci->ports[i];
906 if (!(ehci->portsc[i] & PORTSC_PED)) {
907 DPRINTF("Port %d not enabled\n", i);
910 dev = usb_find_device(port, addr);
918 /* 4.1 host controller initialization */
919 static void ehci_reset(void *opaque)
921 EHCIState *s = opaque;
923 USBDevice *devs[NB_PORTS];
925 trace_usb_ehci_reset();
928 * Do the detach before touching portsc, so that it correctly gets send to
929 * us or to our companion based on PORTSC_POWNER before the reset.
931 for(i = 0; i < NB_PORTS; i++) {
932 devs[i] = s->ports[i].dev;
933 if (devs[i] && devs[i]->attached) {
934 usb_detach(&s->ports[i]);
938 memset(&s->opreg, 0x00, sizeof(s->opreg));
939 memset(&s->portsc, 0x00, sizeof(s->portsc));
941 s->usbcmd = NB_MAXINTRATE << USBCMD_ITC_SH;
942 s->usbsts = USBSTS_HALT;
943 s->usbsts_pending = 0;
944 s->usbsts_frindex = 0;
946 s->astate = EST_INACTIVE;
947 s->pstate = EST_INACTIVE;
949 for(i = 0; i < NB_PORTS; i++) {
950 if (s->companion_ports[i]) {
951 s->portsc[i] = PORTSC_POWNER | PORTSC_PPOWER;
953 s->portsc[i] = PORTSC_PPOWER;
955 if (devs[i] && devs[i]->attached) {
956 usb_attach(&s->ports[i]);
957 usb_device_reset(devs[i]);
960 ehci_queues_rip_all(s, 0);
961 ehci_queues_rip_all(s, 1);
962 timer_del(s->frame_timer);
963 qemu_bh_cancel(s->async_bh);
966 static uint64_t ehci_caps_read(void *ptr, hwaddr addr,
970 return s->caps[addr];
973 static uint64_t ehci_opreg_read(void *ptr, hwaddr addr,
981 /* Round down to mult of 8, else it can go backwards on migration */
982 val = s->frindex & ~7;
985 val = s->opreg[addr >> 2];
988 trace_usb_ehci_opreg_read(addr + s->opregbase, addr2str(addr), val);
992 static uint64_t ehci_port_read(void *ptr, hwaddr addr,
998 val = s->portsc[addr >> 2];
999 trace_usb_ehci_portsc_read(addr + s->portscbase, addr >> 2, val);
1003 static void handle_port_owner_write(EHCIState *s, int port, uint32_t owner)
1005 USBDevice *dev = s->ports[port].dev;
1006 uint32_t *portsc = &s->portsc[port];
1009 if (s->companion_ports[port] == NULL)
1012 owner = owner & PORTSC_POWNER;
1013 orig = *portsc & PORTSC_POWNER;
1015 if (!(owner ^ orig)) {
1019 if (dev && dev->attached) {
1020 usb_detach(&s->ports[port]);
1023 *portsc &= ~PORTSC_POWNER;
1026 if (dev && dev->attached) {
1027 usb_attach(&s->ports[port]);
1031 static void ehci_port_write(void *ptr, hwaddr addr,
1032 uint64_t val, unsigned size)
1035 int port = addr >> 2;
1036 uint32_t *portsc = &s->portsc[port];
1037 uint32_t old = *portsc;
1038 USBDevice *dev = s->ports[port].dev;
1040 trace_usb_ehci_portsc_write(addr + s->portscbase, addr >> 2, val);
1042 /* Clear rwc bits */
1043 *portsc &= ~(val & PORTSC_RWC_MASK);
1044 /* The guest may clear, but not set the PED bit */
1045 *portsc &= val | ~PORTSC_PED;
1046 /* POWNER is masked out by RO_MASK as it is RO when we've no companion */
1047 handle_port_owner_write(s, port, val);
1048 /* And finally apply RO_MASK */
1049 val &= PORTSC_RO_MASK;
1051 if ((val & PORTSC_PRESET) && !(*portsc & PORTSC_PRESET)) {
1052 trace_usb_ehci_port_reset(port, 1);
1055 if (!(val & PORTSC_PRESET) &&(*portsc & PORTSC_PRESET)) {
1056 trace_usb_ehci_port_reset(port, 0);
1057 if (dev && dev->attached) {
1058 usb_port_reset(&s->ports[port]);
1059 *portsc &= ~PORTSC_CSC;
1063 * Table 2.16 Set the enable bit(and enable bit change) to indicate
1064 * to SW that this port has a high speed device attached
1066 if (dev && dev->attached && (dev->speedmask & USB_SPEED_MASK_HIGH)) {
1071 *portsc &= ~PORTSC_RO_MASK;
1073 trace_usb_ehci_portsc_change(addr + s->portscbase, addr >> 2, *portsc, old);
1076 static void ehci_opreg_write(void *ptr, hwaddr addr,
1077 uint64_t val, unsigned size)
1080 uint32_t *mmio = s->opreg + (addr >> 2);
1081 uint32_t old = *mmio;
1084 trace_usb_ehci_opreg_write(addr + s->opregbase, addr2str(addr), val);
1088 if (val & USBCMD_HCRESET) {
1094 /* not supporting dynamic frame list size at the moment */
1095 if ((val & USBCMD_FLS) && !(s->usbcmd & USBCMD_FLS)) {
1096 fprintf(stderr, "attempt to set frame list size -- value %d\n",
1097 (int)val & USBCMD_FLS);
1101 if (val & USBCMD_IAAD) {
1103 * Process IAAD immediately, otherwise the Linux IAAD watchdog may
1104 * trigger and re-use a qh without us seeing the unlink.
1106 s->async_stepdown = 0;
1107 qemu_bh_schedule(s->async_bh);
1108 trace_usb_ehci_doorbell_ring();
1111 if (((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & val) !=
1112 ((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & s->usbcmd)) {
1113 if (s->pstate == EST_INACTIVE) {
1114 SET_LAST_RUN_CLOCK(s);
1116 s->usbcmd = val; /* Set usbcmd for ehci_update_halt() */
1117 ehci_update_halt(s);
1118 s->async_stepdown = 0;
1119 qemu_bh_schedule(s->async_bh);
1124 val &= USBSTS_RO_MASK; // bits 6 through 31 are RO
1125 ehci_clear_usbsts(s, val); // bits 0 through 5 are R/WC
1131 val &= USBINTR_MASK;
1132 if (ehci_enabled(s) && (USBSTS_FLR & val)) {
1133 qemu_bh_schedule(s->async_bh);
1138 val &= 0x00003fff; /* frindex is 14bits */
1139 s->usbsts_frindex = val;
1145 for(i = 0; i < NB_PORTS; i++)
1146 handle_port_owner_write(s, i, 0);
1150 case PERIODICLISTBASE:
1151 if (ehci_periodic_enabled(s)) {
1153 "ehci: PERIODIC list base register set while periodic schedule\n"
1154 " is enabled and HC is enabled\n");
1159 if (ehci_async_enabled(s)) {
1161 "ehci: ASYNC list address register set while async schedule\n"
1162 " is enabled and HC is enabled\n");
1168 trace_usb_ehci_opreg_change(addr + s->opregbase, addr2str(addr),
1173 * Write the qh back to guest physical memory. This step isn't
1174 * in the EHCI spec but we need to do it since we don't share
1175 * physical memory with our guest VM.
1177 * The first three dwords are read-only for the EHCI, so skip them
1178 * when writing back the qh.
1180 static void ehci_flush_qh(EHCIQueue *q)
1182 uint32_t *qh = (uint32_t *) &q->qh;
1183 uint32_t dwords = sizeof(EHCIqh) >> 2;
1184 uint32_t addr = NLPTR_GET(q->qhaddr);
1186 put_dwords(q->ehci, addr + 3 * sizeof(uint32_t), qh + 3, dwords - 3);
1191 static int ehci_qh_do_overlay(EHCIQueue *q)
1193 EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1201 assert(p->qtdaddr == q->qtdaddr);
1203 // remember values in fields to preserve in qh after overlay
1205 dtoggle = q->qh.token & QTD_TOKEN_DTOGGLE;
1206 ping = q->qh.token & QTD_TOKEN_PING;
1208 q->qh.current_qtd = p->qtdaddr;
1209 q->qh.next_qtd = p->qtd.next;
1210 q->qh.altnext_qtd = p->qtd.altnext;
1211 q->qh.token = p->qtd.token;
1214 eps = get_field(q->qh.epchar, QH_EPCHAR_EPS);
1215 if (eps == EHCI_QH_EPS_HIGH) {
1216 q->qh.token &= ~QTD_TOKEN_PING;
1217 q->qh.token |= ping;
1220 reload = get_field(q->qh.epchar, QH_EPCHAR_RL);
1221 set_field(&q->qh.altnext_qtd, reload, QH_ALTNEXT_NAKCNT);
1223 for (i = 0; i < 5; i++) {
1224 q->qh.bufptr[i] = p->qtd.bufptr[i];
1227 if (!(q->qh.epchar & QH_EPCHAR_DTC)) {
1228 // preserve QH DT bit
1229 q->qh.token &= ~QTD_TOKEN_DTOGGLE;
1230 q->qh.token |= dtoggle;
1233 q->qh.bufptr[1] &= ~BUFPTR_CPROGMASK_MASK;
1234 q->qh.bufptr[2] &= ~BUFPTR_FRAMETAG_MASK;
1241 static int ehci_init_transfer(EHCIPacket *p)
1243 uint32_t cpage, offset, bytes, plen;
1246 cpage = get_field(p->qtd.token, QTD_TOKEN_CPAGE);
1247 bytes = get_field(p->qtd.token, QTD_TOKEN_TBYTES);
1248 offset = p->qtd.bufptr[0] & ~QTD_BUFPTR_MASK;
1249 qemu_sglist_init(&p->sgl, p->queue->ehci->device, 5, p->queue->ehci->as);
1253 fprintf(stderr, "cpage out of range (%d)\n", cpage);
1257 page = p->qtd.bufptr[cpage] & QTD_BUFPTR_MASK;
1260 if (plen > 4096 - offset) {
1261 plen = 4096 - offset;
1266 qemu_sglist_add(&p->sgl, page, plen);
1272 static void ehci_finish_transfer(EHCIQueue *q, int len)
1274 uint32_t cpage, offset;
1277 /* update cpage & offset */
1278 cpage = get_field(q->qh.token, QTD_TOKEN_CPAGE);
1279 offset = q->qh.bufptr[0] & ~QTD_BUFPTR_MASK;
1282 cpage += offset >> QTD_BUFPTR_SH;
1283 offset &= ~QTD_BUFPTR_MASK;
1285 set_field(&q->qh.token, cpage, QTD_TOKEN_CPAGE);
1286 q->qh.bufptr[0] &= QTD_BUFPTR_MASK;
1287 q->qh.bufptr[0] |= offset;
1291 static void ehci_async_complete_packet(USBPort *port, USBPacket *packet)
1294 EHCIState *s = port->opaque;
1295 uint32_t portsc = s->portsc[port->index];
1297 if (portsc & PORTSC_POWNER) {
1298 USBPort *companion = s->companion_ports[port->index];
1299 companion->ops->complete(companion, packet);
1303 p = container_of(packet, EHCIPacket, packet);
1304 assert(p->async == EHCI_ASYNC_INFLIGHT);
1306 if (packet->status == USB_RET_REMOVE_FROM_QUEUE) {
1307 trace_usb_ehci_packet_action(p->queue, p, "remove");
1308 ehci_free_packet(p);
1312 trace_usb_ehci_packet_action(p->queue, p, "wakeup");
1313 p->async = EHCI_ASYNC_FINISHED;
1315 if (!p->queue->async) {
1316 s->periodic_sched_active = PERIODIC_ACTIVE;
1318 qemu_bh_schedule(s->async_bh);
1321 static void ehci_execute_complete(EHCIQueue *q)
1323 EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1327 assert(p->qtdaddr == q->qtdaddr);
1328 assert(p->async == EHCI_ASYNC_INITIALIZED ||
1329 p->async == EHCI_ASYNC_FINISHED);
1331 DPRINTF("execute_complete: qhaddr 0x%x, next 0x%x, qtdaddr 0x%x, "
1332 "status %d, actual_length %d\n",
1333 q->qhaddr, q->qh.next, q->qtdaddr,
1334 p->packet.status, p->packet.actual_length);
1336 switch (p->packet.status) {
1337 case USB_RET_SUCCESS:
1339 case USB_RET_IOERROR:
1341 q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_XACTERR);
1342 set_field(&q->qh.token, 0, QTD_TOKEN_CERR);
1343 ehci_raise_irq(q->ehci, USBSTS_ERRINT);
1346 q->qh.token |= QTD_TOKEN_HALT;
1347 ehci_raise_irq(q->ehci, USBSTS_ERRINT);
1350 set_field(&q->qh.altnext_qtd, 0, QH_ALTNEXT_NAKCNT);
1351 return; /* We're not done yet with this transaction */
1352 case USB_RET_BABBLE:
1353 q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_BABBLE);
1354 ehci_raise_irq(q->ehci, USBSTS_ERRINT);
1357 /* should not be triggerable */
1358 fprintf(stderr, "USB invalid response %d\n", p->packet.status);
1359 g_assert_not_reached();
1363 /* TODO check 4.12 for splits */
1364 tbytes = get_field(q->qh.token, QTD_TOKEN_TBYTES);
1365 if (tbytes && p->pid == USB_TOKEN_IN) {
1366 tbytes -= p->packet.actual_length;
1368 /* 4.15.1.2 must raise int on a short input packet */
1369 ehci_raise_irq(q->ehci, USBSTS_INT);
1371 q->ehci->int_req_by_async = true;
1377 DPRINTF("updating tbytes to %d\n", tbytes);
1378 set_field(&q->qh.token, tbytes, QTD_TOKEN_TBYTES);
1380 ehci_finish_transfer(q, p->packet.actual_length);
1381 usb_packet_unmap(&p->packet, &p->sgl);
1382 qemu_sglist_destroy(&p->sgl);
1383 p->async = EHCI_ASYNC_NONE;
1385 q->qh.token ^= QTD_TOKEN_DTOGGLE;
1386 q->qh.token &= ~QTD_TOKEN_ACTIVE;
1388 if (q->qh.token & QTD_TOKEN_IOC) {
1389 ehci_raise_irq(q->ehci, USBSTS_INT);
1391 q->ehci->int_req_by_async = true;
1396 /* 4.10.3 returns "again" */
1397 static int ehci_execute(EHCIPacket *p, const char *action)
1403 assert(p->async == EHCI_ASYNC_NONE ||
1404 p->async == EHCI_ASYNC_INITIALIZED);
1406 if (!(p->qtd.token & QTD_TOKEN_ACTIVE)) {
1407 fprintf(stderr, "Attempting to execute inactive qtd\n");
1411 if (get_field(p->qtd.token, QTD_TOKEN_TBYTES) > BUFF_SIZE) {
1412 ehci_trace_guest_bug(p->queue->ehci,
1413 "guest requested more bytes than allowed");
1417 if (!ehci_verify_pid(p->queue, &p->qtd)) {
1418 ehci_queue_stopped(p->queue); /* Mark the ep in the prev dir stopped */
1420 p->pid = ehci_get_pid(&p->qtd);
1421 p->queue->last_pid = p->pid;
1422 endp = get_field(p->queue->qh.epchar, QH_EPCHAR_EP);
1423 ep = usb_ep_get(p->queue->dev, p->pid, endp);
1425 if (p->async == EHCI_ASYNC_NONE) {
1426 if (ehci_init_transfer(p) != 0) {
1430 spd = (p->pid == USB_TOKEN_IN && NLPTR_TBIT(p->qtd.altnext) == 0);
1431 usb_packet_setup(&p->packet, p->pid, ep, 0, p->qtdaddr, spd,
1432 (p->qtd.token & QTD_TOKEN_IOC) != 0);
1433 usb_packet_map(&p->packet, &p->sgl);
1434 p->async = EHCI_ASYNC_INITIALIZED;
1437 trace_usb_ehci_packet_action(p->queue, p, action);
1438 usb_handle_packet(p->queue->dev, &p->packet);
1439 DPRINTF("submit: qh 0x%x next 0x%x qtd 0x%x pid 0x%x len %zd endp 0x%x "
1440 "status %d actual_length %d\n", p->queue->qhaddr, p->qtd.next,
1441 p->qtdaddr, p->pid, p->packet.iov.size, endp, p->packet.status,
1442 p->packet.actual_length);
1444 if (p->packet.actual_length > BUFF_SIZE) {
1445 fprintf(stderr, "ret from usb_handle_packet > BUFF_SIZE\n");
1455 static int ehci_process_itd(EHCIState *ehci,
1461 uint32_t i, len, pid, dir, devaddr, endp;
1462 uint32_t pg, off, ptr1, ptr2, max, mult;
1464 ehci->periodic_sched_active = PERIODIC_ACTIVE;
1466 dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
1467 devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
1468 endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
1469 max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
1470 mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
1472 for(i = 0; i < 8; i++) {
1473 if (itd->transact[i] & ITD_XACT_ACTIVE) {
1474 pg = get_field(itd->transact[i], ITD_XACT_PGSEL);
1475 off = itd->transact[i] & ITD_XACT_OFFSET_MASK;
1476 ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
1477 ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK);
1478 len = get_field(itd->transact[i], ITD_XACT_LENGTH);
1480 if (len > max * mult) {
1484 if (len > BUFF_SIZE) {
1488 qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
1489 if (off + len > 4096) {
1490 /* transfer crosses page border */
1491 uint32_t len2 = off + len - 4096;
1492 uint32_t len1 = len - len2;
1493 qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
1494 qemu_sglist_add(&ehci->isgl, ptr2, len2);
1496 qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
1499 pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
1501 dev = ehci_find_device(ehci, devaddr);
1502 ep = usb_ep_get(dev, pid, endp);
1503 if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
1504 usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
1505 (itd->transact[i] & ITD_XACT_IOC) != 0);
1506 usb_packet_map(&ehci->ipacket, &ehci->isgl);
1507 usb_handle_packet(dev, &ehci->ipacket);
1508 usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
1510 DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
1511 ehci->ipacket.status = USB_RET_NAK;
1512 ehci->ipacket.actual_length = 0;
1514 qemu_sglist_destroy(&ehci->isgl);
1516 switch (ehci->ipacket.status) {
1517 case USB_RET_SUCCESS:
1520 fprintf(stderr, "Unexpected iso usb result: %d\n",
1521 ehci->ipacket.status);
1523 case USB_RET_IOERROR:
1525 /* 3.3.2: XACTERR is only allowed on IN transactions */
1527 itd->transact[i] |= ITD_XACT_XACTERR;
1528 ehci_raise_irq(ehci, USBSTS_ERRINT);
1531 case USB_RET_BABBLE:
1532 itd->transact[i] |= ITD_XACT_BABBLE;
1533 ehci_raise_irq(ehci, USBSTS_ERRINT);
1536 /* no data for us, so do a zero-length transfer */
1537 ehci->ipacket.actual_length = 0;
1541 set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
1542 ITD_XACT_LENGTH); /* OUT */
1544 set_field(&itd->transact[i], ehci->ipacket.actual_length,
1545 ITD_XACT_LENGTH); /* IN */
1547 if (itd->transact[i] & ITD_XACT_IOC) {
1548 ehci_raise_irq(ehci, USBSTS_INT);
1550 itd->transact[i] &= ~ITD_XACT_ACTIVE;
1557 /* This state is the entry point for asynchronous schedule
1558 * processing. Entry here consitutes a EHCI start event state (4.8.5)
1560 static int ehci_state_waitlisthead(EHCIState *ehci, int async)
1565 uint32_t entry = ehci->asynclistaddr;
1567 /* set reclamation flag at start event (4.8.6) */
1569 ehci_set_usbsts(ehci, USBSTS_REC);
1572 ehci_queues_rip_unused(ehci, async);
1574 /* Find the head of the list (4.9.1.1) */
1575 for(i = 0; i < MAX_QH; i++) {
1576 if (get_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &qh,
1577 sizeof(EHCIqh) >> 2) < 0) {
1580 ehci_trace_qh(NULL, NLPTR_GET(entry), &qh);
1582 if (qh.epchar & QH_EPCHAR_H) {
1584 entry |= (NLPTR_TYPE_QH << 1);
1587 ehci_set_fetch_addr(ehci, async, entry);
1588 ehci_set_state(ehci, async, EST_FETCHENTRY);
1594 if (entry == ehci->asynclistaddr) {
1599 /* no head found for list. */
1601 ehci_set_state(ehci, async, EST_ACTIVE);
1608 /* This state is the entry point for periodic schedule processing as
1609 * well as being a continuation state for async processing.
1611 static int ehci_state_fetchentry(EHCIState *ehci, int async)
1614 uint32_t entry = ehci_get_fetch_addr(ehci, async);
1616 if (NLPTR_TBIT(entry)) {
1617 ehci_set_state(ehci, async, EST_ACTIVE);
1621 /* section 4.8, only QH in async schedule */
1622 if (async && (NLPTR_TYPE_GET(entry) != NLPTR_TYPE_QH)) {
1623 fprintf(stderr, "non queue head request in async schedule\n");
1627 switch (NLPTR_TYPE_GET(entry)) {
1629 ehci_set_state(ehci, async, EST_FETCHQH);
1633 case NLPTR_TYPE_ITD:
1634 ehci_set_state(ehci, async, EST_FETCHITD);
1638 case NLPTR_TYPE_STITD:
1639 ehci_set_state(ehci, async, EST_FETCHSITD);
1644 /* TODO: handle FSTN type */
1645 fprintf(stderr, "FETCHENTRY: entry at %X is of type %d "
1646 "which is not supported yet\n", entry, NLPTR_TYPE_GET(entry));
1654 static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
1660 entry = ehci_get_fetch_addr(ehci, async);
1661 q = ehci_find_queue_by_qh(ehci, entry, async);
1663 q = ehci_alloc_queue(ehci, entry, async);
1668 /* we are going in circles -- stop processing */
1669 ehci_set_state(ehci, async, EST_ACTIVE);
1674 if (get_dwords(ehci, NLPTR_GET(q->qhaddr),
1675 (uint32_t *) &qh, sizeof(EHCIqh) >> 2) < 0) {
1679 ehci_trace_qh(q, NLPTR_GET(q->qhaddr), &qh);
1682 * The overlay area of the qh should never be changed by the guest,
1683 * except when idle, in which case the reset is a nop.
1685 if (!ehci_verify_qh(q, &qh)) {
1686 if (ehci_reset_queue(q) > 0) {
1687 ehci_trace_guest_bug(ehci, "guest updated active QH");
1692 q->transact_ctr = get_field(q->qh.epcap, QH_EPCAP_MULT);
1693 if (q->transact_ctr == 0) { /* Guest bug in some versions of windows */
1694 q->transact_ctr = 4;
1697 if (q->dev == NULL) {
1698 q->dev = ehci_find_device(q->ehci,
1699 get_field(q->qh.epchar, QH_EPCHAR_DEVADDR));
1702 if (async && (q->qh.epchar & QH_EPCHAR_H)) {
1704 /* EHCI spec version 1.0 Section 4.8.3 & 4.10.1 */
1705 if (ehci->usbsts & USBSTS_REC) {
1706 ehci_clear_usbsts(ehci, USBSTS_REC);
1708 DPRINTF("FETCHQH: QH 0x%08x. H-bit set, reclamation status reset"
1709 " - done processing\n", q->qhaddr);
1710 ehci_set_state(ehci, async, EST_ACTIVE);
1717 if (q->qhaddr != q->qh.next) {
1718 DPRINTF("FETCHQH: QH 0x%08x (h %x halt %x active %x) next 0x%08x\n",
1720 q->qh.epchar & QH_EPCHAR_H,
1721 q->qh.token & QTD_TOKEN_HALT,
1722 q->qh.token & QTD_TOKEN_ACTIVE,
1727 if (q->qh.token & QTD_TOKEN_HALT) {
1728 ehci_set_state(ehci, async, EST_HORIZONTALQH);
1730 } else if ((q->qh.token & QTD_TOKEN_ACTIVE) &&
1731 (NLPTR_TBIT(q->qh.current_qtd) == 0)) {
1732 q->qtdaddr = q->qh.current_qtd;
1733 ehci_set_state(ehci, async, EST_FETCHQTD);
1736 /* EHCI spec version 1.0 Section 4.10.2 */
1737 ehci_set_state(ehci, async, EST_ADVANCEQUEUE);
1744 static int ehci_state_fetchitd(EHCIState *ehci, int async)
1750 entry = ehci_get_fetch_addr(ehci, async);
1752 if (get_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &itd,
1753 sizeof(EHCIitd) >> 2) < 0) {
1756 ehci_trace_itd(ehci, entry, &itd);
1758 if (ehci_process_itd(ehci, &itd, entry) != 0) {
1762 put_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &itd,
1763 sizeof(EHCIitd) >> 2);
1764 ehci_set_fetch_addr(ehci, async, itd.next);
1765 ehci_set_state(ehci, async, EST_FETCHENTRY);
1770 static int ehci_state_fetchsitd(EHCIState *ehci, int async)
1776 entry = ehci_get_fetch_addr(ehci, async);
1778 if (get_dwords(ehci, NLPTR_GET(entry), (uint32_t *)&sitd,
1779 sizeof(EHCIsitd) >> 2) < 0) {
1782 ehci_trace_sitd(ehci, entry, &sitd);
1784 if (!(sitd.results & SITD_RESULTS_ACTIVE)) {
1785 /* siTD is not active, nothing to do */;
1787 /* TODO: split transfers are not implemented */
1788 fprintf(stderr, "WARNING: Skipping active siTD\n");
1791 ehci_set_fetch_addr(ehci, async, sitd.next);
1792 ehci_set_state(ehci, async, EST_FETCHENTRY);
1796 /* Section 4.10.2 - paragraph 3 */
1797 static int ehci_state_advqueue(EHCIQueue *q)
1800 /* TO-DO: 4.10.2 - paragraph 2
1801 * if I-bit is set to 1 and QH is not active
1802 * go to horizontal QH
1805 ehci_set_state(ehci, async, EST_HORIZONTALQH);
1811 * want data and alt-next qTD is valid
1813 if (((q->qh.token & QTD_TOKEN_TBYTES_MASK) != 0) &&
1814 (NLPTR_TBIT(q->qh.altnext_qtd) == 0)) {
1815 q->qtdaddr = q->qh.altnext_qtd;
1816 ehci_set_state(q->ehci, q->async, EST_FETCHQTD);
1821 } else if (NLPTR_TBIT(q->qh.next_qtd) == 0) {
1822 q->qtdaddr = q->qh.next_qtd;
1823 ehci_set_state(q->ehci, q->async, EST_FETCHQTD);
1826 * no valid qTD, try next QH
1829 ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1835 /* Section 4.10.2 - paragraph 4 */
1836 static int ehci_state_fetchqtd(EHCIQueue *q)
1842 if (get_dwords(q->ehci, NLPTR_GET(q->qtdaddr), (uint32_t *) &qtd,
1843 sizeof(EHCIqtd) >> 2) < 0) {
1846 ehci_trace_qtd(q, NLPTR_GET(q->qtdaddr), &qtd);
1848 p = QTAILQ_FIRST(&q->packets);
1850 if (!ehci_verify_qtd(p, &qtd)) {
1851 ehci_cancel_queue(q);
1852 if (qtd.token & QTD_TOKEN_ACTIVE) {
1853 ehci_trace_guest_bug(q->ehci, "guest updated active qTD");
1858 ehci_qh_do_overlay(q);
1862 if (!(qtd.token & QTD_TOKEN_ACTIVE)) {
1863 ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1864 } else if (p != NULL) {
1866 case EHCI_ASYNC_NONE:
1867 case EHCI_ASYNC_INITIALIZED:
1868 /* Not yet executed (MULT), or previously nacked (int) packet */
1869 ehci_set_state(q->ehci, q->async, EST_EXECUTE);
1871 case EHCI_ASYNC_INFLIGHT:
1872 /* Check if the guest has added new tds to the queue */
1873 again = ehci_fill_queue(QTAILQ_LAST(&q->packets, pkts_head));
1874 /* Unfinished async handled packet, go horizontal */
1875 ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1877 case EHCI_ASYNC_FINISHED:
1878 /* Complete executing of the packet */
1879 ehci_set_state(q->ehci, q->async, EST_EXECUTING);
1883 p = ehci_alloc_packet(q);
1884 p->qtdaddr = q->qtdaddr;
1886 ehci_set_state(q->ehci, q->async, EST_EXECUTE);
1892 static int ehci_state_horizqh(EHCIQueue *q)
1896 if (ehci_get_fetch_addr(q->ehci, q->async) != q->qh.next) {
1897 ehci_set_fetch_addr(q->ehci, q->async, q->qh.next);
1898 ehci_set_state(q->ehci, q->async, EST_FETCHENTRY);
1901 ehci_set_state(q->ehci, q->async, EST_ACTIVE);
1907 /* Returns "again" */
1908 static int ehci_fill_queue(EHCIPacket *p)
1910 USBEndpoint *ep = p->packet.ep;
1911 EHCIQueue *q = p->queue;
1912 EHCIqtd qtd = p->qtd;
1916 if (NLPTR_TBIT(qtd.next) != 0) {
1921 * Detect circular td lists, Windows creates these, counting on the
1922 * active bit going low after execution to make the queue stop.
1924 QTAILQ_FOREACH(p, &q->packets, next) {
1925 if (p->qtdaddr == qtdaddr) {
1929 if (get_dwords(q->ehci, NLPTR_GET(qtdaddr),
1930 (uint32_t *) &qtd, sizeof(EHCIqtd) >> 2) < 0) {
1933 ehci_trace_qtd(q, NLPTR_GET(qtdaddr), &qtd);
1934 if (!(qtd.token & QTD_TOKEN_ACTIVE)) {
1937 if (!ehci_verify_pid(q, &qtd)) {
1938 ehci_trace_guest_bug(q->ehci, "guest queued token with wrong pid");
1941 p = ehci_alloc_packet(q);
1942 p->qtdaddr = qtdaddr;
1944 if (ehci_execute(p, "queue") == -1) {
1947 assert(p->packet.status == USB_RET_ASYNC);
1948 p->async = EHCI_ASYNC_INFLIGHT;
1951 usb_device_flush_ep_queue(ep->dev, ep);
1955 static int ehci_state_execute(EHCIQueue *q)
1957 EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1961 assert(p->qtdaddr == q->qtdaddr);
1963 if (ehci_qh_do_overlay(q) != 0) {
1967 // TODO verify enough time remains in the uframe as in 4.4.1.1
1968 // TODO write back ptr to async list when done or out of time
1970 /* 4.10.3, bottom of page 82, go horizontal on transaction counter == 0 */
1971 if (!q->async && q->transact_ctr == 0) {
1972 ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1978 ehci_set_usbsts(q->ehci, USBSTS_REC);
1981 again = ehci_execute(p, "process");
1985 if (p->packet.status == USB_RET_ASYNC) {
1987 trace_usb_ehci_packet_action(p->queue, p, "async");
1988 p->async = EHCI_ASYNC_INFLIGHT;
1989 ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1991 again = ehci_fill_queue(p);
1998 ehci_set_state(q->ehci, q->async, EST_EXECUTING);
2005 static int ehci_state_executing(EHCIQueue *q)
2007 EHCIPacket *p = QTAILQ_FIRST(&q->packets);
2010 assert(p->qtdaddr == q->qtdaddr);
2012 ehci_execute_complete(q);
2015 if (!q->async && q->transact_ctr > 0) {
2020 if (p->packet.status == USB_RET_NAK) {
2021 ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
2023 ehci_set_state(q->ehci, q->async, EST_WRITEBACK);
2031 static int ehci_state_writeback(EHCIQueue *q)
2033 EHCIPacket *p = QTAILQ_FIRST(&q->packets);
2034 uint32_t *qtd, addr;
2037 /* Write back the QTD from the QH area */
2039 assert(p->qtdaddr == q->qtdaddr);
2041 ehci_trace_qtd(q, NLPTR_GET(p->qtdaddr), (EHCIqtd *) &q->qh.next_qtd);
2042 qtd = (uint32_t *) &q->qh.next_qtd;
2043 addr = NLPTR_GET(p->qtdaddr);
2044 put_dwords(q->ehci, addr + 2 * sizeof(uint32_t), qtd + 2, 2);
2045 ehci_free_packet(p);
2048 * EHCI specs say go horizontal here.
2050 * We can also advance the queue here for performance reasons. We
2051 * need to take care to only take that shortcut in case we've
2052 * processed the qtd just written back without errors, i.e. halt
2055 if (q->qh.token & QTD_TOKEN_HALT) {
2056 ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
2059 ehci_set_state(q->ehci, q->async, EST_ADVANCEQUEUE);
2066 * This is the state machine that is common to both async and periodic
2069 static void ehci_advance_state(EHCIState *ehci, int async)
2071 EHCIQueue *q = NULL;
2075 switch(ehci_get_state(ehci, async)) {
2076 case EST_WAITLISTHEAD:
2077 again = ehci_state_waitlisthead(ehci, async);
2080 case EST_FETCHENTRY:
2081 again = ehci_state_fetchentry(ehci, async);
2085 q = ehci_state_fetchqh(ehci, async);
2087 assert(q->async == async);
2095 again = ehci_state_fetchitd(ehci, async);
2099 again = ehci_state_fetchsitd(ehci, async);
2102 case EST_ADVANCEQUEUE:
2104 again = ehci_state_advqueue(q);
2109 again = ehci_state_fetchqtd(q);
2112 case EST_HORIZONTALQH:
2114 again = ehci_state_horizqh(q);
2119 again = ehci_state_execute(q);
2121 ehci->async_stepdown = 0;
2128 ehci->async_stepdown = 0;
2130 again = ehci_state_executing(q);
2135 again = ehci_state_writeback(q);
2137 ehci->periodic_sched_active = PERIODIC_ACTIVE;
2142 fprintf(stderr, "Bad state!\n");
2144 g_assert_not_reached();
2149 fprintf(stderr, "processing error - resetting ehci HC\n");
2157 static void ehci_advance_async_state(EHCIState *ehci)
2159 const int async = 1;
2161 switch(ehci_get_state(ehci, async)) {
2163 if (!ehci_async_enabled(ehci)) {
2166 ehci_set_state(ehci, async, EST_ACTIVE);
2167 // No break, fall through to ACTIVE
2170 if (!ehci_async_enabled(ehci)) {
2171 ehci_queues_rip_all(ehci, async);
2172 ehci_set_state(ehci, async, EST_INACTIVE);
2176 /* make sure guest has acknowledged the doorbell interrupt */
2177 /* TO-DO: is this really needed? */
2178 if (ehci->usbsts & USBSTS_IAA) {
2179 DPRINTF("IAA status bit still set.\n");
2183 /* check that address register has been set */
2184 if (ehci->asynclistaddr == 0) {
2188 ehci_set_state(ehci, async, EST_WAITLISTHEAD);
2189 ehci_advance_state(ehci, async);
2191 /* If the doorbell is set, the guest wants to make a change to the
2192 * schedule. The host controller needs to release cached data.
2195 if (ehci->usbcmd & USBCMD_IAAD) {
2196 /* Remove all unseen qhs from the async qhs queue */
2197 ehci_queues_rip_unseen(ehci, async);
2198 trace_usb_ehci_doorbell_ack();
2199 ehci->usbcmd &= ~USBCMD_IAAD;
2200 ehci_raise_irq(ehci, USBSTS_IAA);
2205 /* this should only be due to a developer mistake */
2206 fprintf(stderr, "ehci: Bad asynchronous state %d. "
2207 "Resetting to active\n", ehci->astate);
2208 g_assert_not_reached();
2212 static void ehci_advance_periodic_state(EHCIState *ehci)
2216 const int async = 0;
2220 switch(ehci_get_state(ehci, async)) {
2222 if (!(ehci->frindex & 7) && ehci_periodic_enabled(ehci)) {
2223 ehci_set_state(ehci, async, EST_ACTIVE);
2224 // No break, fall through to ACTIVE
2229 if (!(ehci->frindex & 7) && !ehci_periodic_enabled(ehci)) {
2230 ehci_queues_rip_all(ehci, async);
2231 ehci_set_state(ehci, async, EST_INACTIVE);
2235 list = ehci->periodiclistbase & 0xfffff000;
2236 /* check that register has been set */
2240 list |= ((ehci->frindex & 0x1ff8) >> 1);
2242 if (get_dwords(ehci, list, &entry, 1) < 0) {
2246 DPRINTF("PERIODIC state adv fr=%d. [%08X] -> %08X\n",
2247 ehci->frindex / 8, list, entry);
2248 ehci_set_fetch_addr(ehci, async,entry);
2249 ehci_set_state(ehci, async, EST_FETCHENTRY);
2250 ehci_advance_state(ehci, async);
2251 ehci_queues_rip_unused(ehci, async);
2255 /* this should only be due to a developer mistake */
2256 fprintf(stderr, "ehci: Bad periodic state %d. "
2257 "Resetting to active\n", ehci->pstate);
2258 g_assert_not_reached();
2262 static void ehci_update_frindex(EHCIState *ehci, int uframes)
2266 if (!ehci_enabled(ehci) && ehci->pstate == EST_INACTIVE) {
2270 for (i = 0; i < uframes; i++) {
2273 if (ehci->frindex == 0x00002000) {
2274 ehci_raise_irq(ehci, USBSTS_FLR);
2277 if (ehci->frindex == 0x00004000) {
2278 ehci_raise_irq(ehci, USBSTS_FLR);
2280 if (ehci->usbsts_frindex >= 0x00004000) {
2281 ehci->usbsts_frindex -= 0x00004000;
2283 ehci->usbsts_frindex = 0;
2289 static void ehci_frame_timer(void *opaque)
2291 EHCIState *ehci = opaque;
2293 int64_t expire_time, t_now;
2294 uint64_t ns_elapsed;
2295 int uframes, skipped_uframes;
2298 t_now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2299 ns_elapsed = t_now - ehci->last_run_ns;
2300 uframes = ns_elapsed / UFRAME_TIMER_NS;
2302 if (ehci_periodic_enabled(ehci) || ehci->pstate != EST_INACTIVE) {
2305 if (uframes > (ehci->maxframes * 8)) {
2306 skipped_uframes = uframes - (ehci->maxframes * 8);
2307 ehci_update_frindex(ehci, skipped_uframes);
2308 ehci->last_run_ns += UFRAME_TIMER_NS * skipped_uframes;
2309 uframes -= skipped_uframes;
2310 DPRINTF("WARNING - EHCI skipped %d uframes\n", skipped_uframes);
2313 for (i = 0; i < uframes; i++) {
2315 * If we're running behind schedule, we should not catch up
2316 * too fast, as that will make some guests unhappy:
2317 * 1) We must process a minimum of MIN_UFR_PER_TICK frames,
2318 * otherwise we will never catch up
2319 * 2) Process frames until the guest has requested an irq (IOC)
2321 if (i >= MIN_UFR_PER_TICK) {
2322 ehci_commit_irq(ehci);
2323 if ((ehci->usbsts & USBINTR_MASK) & ehci->usbintr) {
2327 if (ehci->periodic_sched_active) {
2328 ehci->periodic_sched_active--;
2330 ehci_update_frindex(ehci, 1);
2331 if ((ehci->frindex & 7) == 0) {
2332 ehci_advance_periodic_state(ehci);
2334 ehci->last_run_ns += UFRAME_TIMER_NS;
2337 ehci->periodic_sched_active = 0;
2338 ehci_update_frindex(ehci, uframes);
2339 ehci->last_run_ns += UFRAME_TIMER_NS * uframes;
2342 if (ehci->periodic_sched_active) {
2343 ehci->async_stepdown = 0;
2344 } else if (ehci->async_stepdown < ehci->maxframes / 2) {
2345 ehci->async_stepdown++;
2348 /* Async is not inside loop since it executes everything it can once
2351 if (ehci_async_enabled(ehci) || ehci->astate != EST_INACTIVE) {
2353 ehci_advance_async_state(ehci);
2356 ehci_commit_irq(ehci);
2357 if (ehci->usbsts_pending) {
2359 ehci->async_stepdown = 0;
2362 if (ehci_enabled(ehci) && (ehci->usbintr & USBSTS_FLR)) {
2367 /* If we've raised int, we speed up the timer, so that we quickly
2368 * notice any new packets queued up in response */
2369 if (ehci->int_req_by_async && (ehci->usbsts & USBSTS_INT)) {
2370 expire_time = t_now + get_ticks_per_sec() / (FRAME_TIMER_FREQ * 4);
2371 ehci->int_req_by_async = false;
2373 expire_time = t_now + (get_ticks_per_sec()
2374 * (ehci->async_stepdown+1) / FRAME_TIMER_FREQ);
2376 timer_mod(ehci->frame_timer, expire_time);
2380 static const MemoryRegionOps ehci_mmio_caps_ops = {
2381 .read = ehci_caps_read,
2382 .valid.min_access_size = 1,
2383 .valid.max_access_size = 4,
2384 .impl.min_access_size = 1,
2385 .impl.max_access_size = 1,
2386 .endianness = DEVICE_LITTLE_ENDIAN,
2389 static const MemoryRegionOps ehci_mmio_opreg_ops = {
2390 .read = ehci_opreg_read,
2391 .write = ehci_opreg_write,
2392 .valid.min_access_size = 4,
2393 .valid.max_access_size = 4,
2394 .endianness = DEVICE_LITTLE_ENDIAN,
2397 static const MemoryRegionOps ehci_mmio_port_ops = {
2398 .read = ehci_port_read,
2399 .write = ehci_port_write,
2400 .valid.min_access_size = 4,
2401 .valid.max_access_size = 4,
2402 .endianness = DEVICE_LITTLE_ENDIAN,
2405 static USBPortOps ehci_port_ops = {
2406 .attach = ehci_attach,
2407 .detach = ehci_detach,
2408 .child_detach = ehci_child_detach,
2409 .wakeup = ehci_wakeup,
2410 .complete = ehci_async_complete_packet,
2413 static USBBusOps ehci_bus_ops = {
2414 .register_companion = ehci_register_companion,
2415 .wakeup_endpoint = ehci_wakeup_endpoint,
2418 static void usb_ehci_pre_save(void *opaque)
2420 EHCIState *ehci = opaque;
2421 uint32_t new_frindex;
2423 /* Round down frindex to a multiple of 8 for migration compatibility */
2424 new_frindex = ehci->frindex & ~7;
2425 ehci->last_run_ns -= (ehci->frindex - new_frindex) * UFRAME_TIMER_NS;
2426 ehci->frindex = new_frindex;
2429 static int usb_ehci_post_load(void *opaque, int version_id)
2431 EHCIState *s = opaque;
2434 for (i = 0; i < NB_PORTS; i++) {
2435 USBPort *companion = s->companion_ports[i];
2436 if (companion == NULL) {
2439 if (s->portsc[i] & PORTSC_POWNER) {
2440 companion->dev = s->ports[i].dev;
2442 companion->dev = NULL;
2449 static void usb_ehci_vm_state_change(void *opaque, int running, RunState state)
2451 EHCIState *ehci = opaque;
2454 * We don't migrate the EHCIQueue-s, instead we rebuild them for the
2455 * schedule in guest memory. We must do the rebuilt ASAP, so that
2456 * USB-devices which have async handled packages have a packet in the
2457 * ep queue to match the completion with.
2459 if (state == RUN_STATE_RUNNING) {
2460 ehci_advance_async_state(ehci);
2464 * The schedule rebuilt from guest memory could cause the migration dest
2465 * to miss a QH unlink, and fail to cancel packets, since the unlinked QH
2466 * will never have existed on the destination. Therefor we must flush the
2467 * async schedule on savevm to catch any not yet noticed unlinks.
2469 if (state == RUN_STATE_SAVE_VM) {
2470 ehci_advance_async_state(ehci);
2471 ehci_queues_rip_unseen(ehci, 1);
2475 const VMStateDescription vmstate_ehci = {
2476 .name = "ehci-core",
2478 .minimum_version_id = 1,
2479 .pre_save = usb_ehci_pre_save,
2480 .post_load = usb_ehci_post_load,
2481 .fields = (VMStateField[]) {
2482 /* mmio registers */
2483 VMSTATE_UINT32(usbcmd, EHCIState),
2484 VMSTATE_UINT32(usbsts, EHCIState),
2485 VMSTATE_UINT32_V(usbsts_pending, EHCIState, 2),
2486 VMSTATE_UINT32_V(usbsts_frindex, EHCIState, 2),
2487 VMSTATE_UINT32(usbintr, EHCIState),
2488 VMSTATE_UINT32(frindex, EHCIState),
2489 VMSTATE_UINT32(ctrldssegment, EHCIState),
2490 VMSTATE_UINT32(periodiclistbase, EHCIState),
2491 VMSTATE_UINT32(asynclistaddr, EHCIState),
2492 VMSTATE_UINT32(configflag, EHCIState),
2493 VMSTATE_UINT32(portsc[0], EHCIState),
2494 VMSTATE_UINT32(portsc[1], EHCIState),
2495 VMSTATE_UINT32(portsc[2], EHCIState),
2496 VMSTATE_UINT32(portsc[3], EHCIState),
2497 VMSTATE_UINT32(portsc[4], EHCIState),
2498 VMSTATE_UINT32(portsc[5], EHCIState),
2500 VMSTATE_TIMER(frame_timer, EHCIState),
2501 VMSTATE_UINT64(last_run_ns, EHCIState),
2502 VMSTATE_UINT32(async_stepdown, EHCIState),
2503 /* schedule state */
2504 VMSTATE_UINT32(astate, EHCIState),
2505 VMSTATE_UINT32(pstate, EHCIState),
2506 VMSTATE_UINT32(a_fetch_addr, EHCIState),
2507 VMSTATE_UINT32(p_fetch_addr, EHCIState),
2508 VMSTATE_END_OF_LIST()
2512 void usb_ehci_realize(EHCIState *s, DeviceState *dev, Error **errp)
2516 if (s->portnr > NB_PORTS) {
2517 error_setg(errp, "Too many ports! Max. port number is %d.",
2522 usb_bus_new(&s->bus, sizeof(s->bus), &ehci_bus_ops, dev);
2523 for (i = 0; i < s->portnr; i++) {
2524 usb_register_port(&s->bus, &s->ports[i], s, i, &ehci_port_ops,
2525 USB_SPEED_MASK_HIGH);
2526 s->ports[i].dev = 0;
2529 s->frame_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, ehci_frame_timer, s);
2530 s->async_bh = qemu_bh_new(ehci_frame_timer, s);
2533 qemu_register_reset(ehci_reset, s);
2534 qemu_add_vm_change_state_handler(usb_ehci_vm_state_change, s);
2537 void usb_ehci_init(EHCIState *s, DeviceState *dev)
2539 /* 2.2 host controller interface version */
2540 s->caps[0x00] = (uint8_t)(s->opregbase - s->capsbase);
2541 s->caps[0x01] = 0x00;
2542 s->caps[0x02] = 0x00;
2543 s->caps[0x03] = 0x01; /* HC version */
2544 s->caps[0x04] = s->portnr; /* Number of downstream ports */
2545 s->caps[0x05] = 0x00; /* No companion ports at present */
2546 s->caps[0x06] = 0x00;
2547 s->caps[0x07] = 0x00;
2548 s->caps[0x08] = 0x80; /* We can cache whole frame, no 64-bit */
2549 s->caps[0x0a] = 0x00;
2550 s->caps[0x0b] = 0x00;
2552 QTAILQ_INIT(&s->aqueues);
2553 QTAILQ_INIT(&s->pqueues);
2554 usb_packet_init(&s->ipacket);
2556 memory_region_init(&s->mem, OBJECT(dev), "ehci", MMIO_SIZE);
2557 memory_region_init_io(&s->mem_caps, OBJECT(dev), &ehci_mmio_caps_ops, s,
2558 "capabilities", CAPA_SIZE);
2559 memory_region_init_io(&s->mem_opreg, OBJECT(dev), &ehci_mmio_opreg_ops, s,
2560 "operational", s->portscbase);
2561 memory_region_init_io(&s->mem_ports, OBJECT(dev), &ehci_mmio_port_ops, s,
2562 "ports", 4 * s->portnr);
2564 memory_region_add_subregion(&s->mem, s->capsbase, &s->mem_caps);
2565 memory_region_add_subregion(&s->mem, s->opregbase, &s->mem_opreg);
2566 memory_region_add_subregion(&s->mem, s->opregbase + s->portscbase,
2571 * vim: expandtab ts=4