xref: /openbmc/qemu/hw/usb/hcd-ehci.c (revision d6032e06)
1 /*
2  * QEMU USB EHCI Emulation
3  *
4  * Copyright(c) 2008  Emutex Ltd. (address@hidden)
5  * Copyright(c) 2011-2012 Red Hat, Inc.
6  *
7  * Red Hat Authors:
8  * Gerd Hoffmann <kraxel@redhat.com>
9  * Hans de Goede <hdegoede@redhat.com>
10  *
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.
14  *
15  *
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.
20  *
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.
25  *
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/>.
28  */
29 
30 #include "hw/usb/hcd-ehci.h"
31 #include "trace.h"
32 
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
41 
42 #define USBCMD           0x0000
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
55 
56 #define USBSTS           0x0004
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
68 
69 /*
70  *  Interrupt enable bits correspond to the interrupt active bits in USBSTS
71  *  so no need to redefine here.
72  */
73 #define USBINTR              0x0008
74 #define USBINTR_MASK         0x0000003f
75 
76 #define FRINDEX              0x000c
77 #define CTRLDSSEGMENT        0x0010
78 #define PERIODICLISTBASE     0x0014
79 #define ASYNCLISTADDR        0x0018
80 #define ASYNCLISTADDR_MASK   0xffffffe0
81 
82 #define CONFIGFLAG           0x0040
83 
84 /*
85  * Bits that are reserved or are read-only are masked out of values
86  * written to us by software
87  */
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
110 
111 #define FRAME_TIMER_FREQ 1000
112 #define FRAME_TIMER_NS   (1000000000 / FRAME_TIMER_FREQ)
113 #define UFRAME_TIMER_NS  (FRAME_TIMER_NS / 8)
114 
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 */
120 
121 /*  Internal periodic / asynchronous schedule state machine states
122  */
123 typedef enum {
124     EST_INACTIVE = 1000,
125     EST_ACTIVE,
126     EST_EXECUTING,
127     EST_SLEEPING,
128     /*  The following states are internal to the state machine function
129     */
130     EST_WAITLISTHEAD,
131     EST_FETCHENTRY,
132     EST_FETCHQH,
133     EST_FETCHITD,
134     EST_FETCHSITD,
135     EST_ADVANCEQUEUE,
136     EST_FETCHQTD,
137     EST_EXECUTE,
138     EST_WRITEBACK,
139     EST_HORIZONTALQH
140 } EHCI_STATES;
141 
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
146 
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
152 
153 #define SET_LAST_RUN_CLOCK(s) \
154     (s)->last_run_ns = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
155 
156 /* nifty macros from Arnon's EHCI version  */
157 #define get_field(data, field) \
158     (((data) & field##_MASK) >> field##_SH)
159 
160 #define set_field(data, newval, field) do { \
161     uint32_t val = *data; \
162     val &= ~ field##_MASK; \
163     val |= ((newval) << field##_SH) & field##_MASK; \
164     *data = val; \
165     } while(0)
166 
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",
181 };
182 
183 static const char *ehci_mmio_names[] = {
184     [USBCMD]            = "USBCMD",
185     [USBSTS]            = "USBSTS",
186     [USBINTR]           = "USBINTR",
187     [FRINDEX]           = "FRINDEX",
188     [PERIODICLISTBASE]  = "P-LIST BASE",
189     [ASYNCLISTADDR]     = "A-LIST ADDR",
190     [CONFIGFLAG]        = "CONFIGFLAG",
191 };
192 
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);
198 
199 static const char *nr2str(const char **n, size_t len, uint32_t nr)
200 {
201     if (nr < len && n[nr] != NULL) {
202         return n[nr];
203     } else {
204         return "unknown";
205     }
206 }
207 
208 static const char *state2str(uint32_t state)
209 {
210     return nr2str(ehci_state_names, ARRAY_SIZE(ehci_state_names), state);
211 }
212 
213 static const char *addr2str(hwaddr addr)
214 {
215     return nr2str(ehci_mmio_names, ARRAY_SIZE(ehci_mmio_names), addr);
216 }
217 
218 static void ehci_trace_usbsts(uint32_t mask, int state)
219 {
220     /* interrupts */
221     if (mask & USBSTS_INT) {
222         trace_usb_ehci_usbsts("INT", state);
223     }
224     if (mask & USBSTS_ERRINT) {
225         trace_usb_ehci_usbsts("ERRINT", state);
226     }
227     if (mask & USBSTS_PCD) {
228         trace_usb_ehci_usbsts("PCD", state);
229     }
230     if (mask & USBSTS_FLR) {
231         trace_usb_ehci_usbsts("FLR", state);
232     }
233     if (mask & USBSTS_HSE) {
234         trace_usb_ehci_usbsts("HSE", state);
235     }
236     if (mask & USBSTS_IAA) {
237         trace_usb_ehci_usbsts("IAA", state);
238     }
239 
240     /* status */
241     if (mask & USBSTS_HALT) {
242         trace_usb_ehci_usbsts("HALT", state);
243     }
244     if (mask & USBSTS_REC) {
245         trace_usb_ehci_usbsts("REC", state);
246     }
247     if (mask & USBSTS_PSS) {
248         trace_usb_ehci_usbsts("PSS", state);
249     }
250     if (mask & USBSTS_ASS) {
251         trace_usb_ehci_usbsts("ASS", state);
252     }
253 }
254 
255 static inline void ehci_set_usbsts(EHCIState *s, int mask)
256 {
257     if ((s->usbsts & mask) == mask) {
258         return;
259     }
260     ehci_trace_usbsts(mask, 1);
261     s->usbsts |= mask;
262 }
263 
264 static inline void ehci_clear_usbsts(EHCIState *s, int mask)
265 {
266     if ((s->usbsts & mask) == 0) {
267         return;
268     }
269     ehci_trace_usbsts(mask, 0);
270     s->usbsts &= ~mask;
271 }
272 
273 /* update irq line */
274 static inline void ehci_update_irq(EHCIState *s)
275 {
276     int level = 0;
277 
278     if ((s->usbsts & USBINTR_MASK) & s->usbintr) {
279         level = 1;
280     }
281 
282     trace_usb_ehci_irq(level, s->frindex, s->usbsts, s->usbintr);
283     qemu_set_irq(s->irq, level);
284 }
285 
286 /* flag interrupt condition */
287 static inline void ehci_raise_irq(EHCIState *s, int intr)
288 {
289     if (intr & (USBSTS_PCD | USBSTS_FLR | USBSTS_HSE)) {
290         s->usbsts |= intr;
291         ehci_update_irq(s);
292     } else {
293         s->usbsts_pending |= intr;
294     }
295 }
296 
297 /*
298  * Commit pending interrupts (added via ehci_raise_irq),
299  * at the rate allowed by "Interrupt Threshold Control".
300  */
301 static inline void ehci_commit_irq(EHCIState *s)
302 {
303     uint32_t itc;
304 
305     if (!s->usbsts_pending) {
306         return;
307     }
308     if (s->usbsts_frindex > s->frindex) {
309         return;
310     }
311 
312     itc = (s->usbcmd >> 16) & 0xff;
313     s->usbsts |= s->usbsts_pending;
314     s->usbsts_pending = 0;
315     s->usbsts_frindex = s->frindex + itc;
316     ehci_update_irq(s);
317 }
318 
319 static void ehci_update_halt(EHCIState *s)
320 {
321     if (s->usbcmd & USBCMD_RUNSTOP) {
322         ehci_clear_usbsts(s, USBSTS_HALT);
323     } else {
324         if (s->astate == EST_INACTIVE && s->pstate == EST_INACTIVE) {
325             ehci_set_usbsts(s, USBSTS_HALT);
326         }
327     }
328 }
329 
330 static void ehci_set_state(EHCIState *s, int async, int state)
331 {
332     if (async) {
333         trace_usb_ehci_state("async", state2str(state));
334         s->astate = state;
335         if (s->astate == EST_INACTIVE) {
336             ehci_clear_usbsts(s, USBSTS_ASS);
337             ehci_update_halt(s);
338         } else {
339             ehci_set_usbsts(s, USBSTS_ASS);
340         }
341     } else {
342         trace_usb_ehci_state("periodic", state2str(state));
343         s->pstate = state;
344         if (s->pstate == EST_INACTIVE) {
345             ehci_clear_usbsts(s, USBSTS_PSS);
346             ehci_update_halt(s);
347         } else {
348             ehci_set_usbsts(s, USBSTS_PSS);
349         }
350     }
351 }
352 
353 static int ehci_get_state(EHCIState *s, int async)
354 {
355     return async ? s->astate : s->pstate;
356 }
357 
358 static void ehci_set_fetch_addr(EHCIState *s, int async, uint32_t addr)
359 {
360     if (async) {
361         s->a_fetch_addr = addr;
362     } else {
363         s->p_fetch_addr = addr;
364     }
365 }
366 
367 static int ehci_get_fetch_addr(EHCIState *s, int async)
368 {
369     return async ? s->a_fetch_addr : s->p_fetch_addr;
370 }
371 
372 static void ehci_trace_qh(EHCIQueue *q, hwaddr addr, EHCIqh *qh)
373 {
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));
388 }
389 
390 static void ehci_trace_qtd(EHCIQueue *q, hwaddr addr, EHCIqtd *qtd)
391 {
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));
405 }
406 
407 static void ehci_trace_itd(EHCIState *s, hwaddr addr, EHCIitd *itd)
408 {
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));
414 }
415 
416 static void ehci_trace_sitd(EHCIState *s, hwaddr addr,
417                             EHCIsitd *sitd)
418 {
419     trace_usb_ehci_sitd(addr, sitd->next,
420                         (bool)(sitd->results & SITD_RESULTS_ACTIVE));
421 }
422 
423 static void ehci_trace_guest_bug(EHCIState *s, const char *message)
424 {
425     trace_usb_ehci_guest_bug(message);
426     fprintf(stderr, "ehci warning: %s\n", message);
427 }
428 
429 static inline bool ehci_enabled(EHCIState *s)
430 {
431     return s->usbcmd & USBCMD_RUNSTOP;
432 }
433 
434 static inline bool ehci_async_enabled(EHCIState *s)
435 {
436     return ehci_enabled(s) && (s->usbcmd & USBCMD_ASE);
437 }
438 
439 static inline bool ehci_periodic_enabled(EHCIState *s)
440 {
441     return ehci_enabled(s) && (s->usbcmd & USBCMD_PSE);
442 }
443 
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)
447 {
448     int i;
449 
450     if (!ehci->as) {
451         ehci_raise_irq(ehci, USBSTS_HSE);
452         ehci->usbcmd &= ~USBCMD_RUNSTOP;
453         trace_usb_ehci_dma_error();
454         return -1;
455     }
456 
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);
460     }
461 
462     return num;
463 }
464 
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)
468 {
469     int i;
470 
471     if (!ehci->as) {
472         ehci_raise_irq(ehci, USBSTS_HSE);
473         ehci->usbcmd &= ~USBCMD_RUNSTOP;
474         trace_usb_ehci_dma_error();
475         return -1;
476     }
477 
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));
481     }
482 
483     return num;
484 }
485 
486 static int ehci_get_pid(EHCIqtd *qtd)
487 {
488     switch (get_field(qtd->token, QTD_TOKEN_PID)) {
489     case 0:
490         return USB_TOKEN_OUT;
491     case 1:
492         return USB_TOKEN_IN;
493     case 2:
494         return USB_TOKEN_SETUP;
495     default:
496         fprintf(stderr, "bad token\n");
497         return 0;
498     }
499 }
500 
501 static bool ehci_verify_qh(EHCIQueue *q, EHCIqh *qh)
502 {
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)) {
512         return false;
513     } else {
514         return true;
515     }
516 }
517 
518 static bool ehci_verify_qtd(EHCIPacket *p, EHCIqtd *qtd)
519 {
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]) {
526         return false;
527     } else {
528         return true;
529     }
530 }
531 
532 static bool ehci_verify_pid(EHCIQueue *q, EHCIqtd *qtd)
533 {
534     int ep  = get_field(q->qh.epchar, QH_EPCHAR_EP);
535     int pid = ehci_get_pid(qtd);
536 
537     /* Note the pid changing is normal for ep 0 (the control ep) */
538     if (q->last_pid && ep != 0 && pid != q->last_pid) {
539         return false;
540     } else {
541         return true;
542     }
543 }
544 
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)
548 {
549     EHCIQueue *q = p->queue;
550     EHCIqtd qtd;
551     EHCIqh qh;
552     int state;
553 
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;
561         ehci_free_packet(p);
562         return;
563     }
564 
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);
570     }
571     ehci_set_state(q->ehci, q->async, state);
572 }
573 
574 /* packet management */
575 
576 static EHCIPacket *ehci_alloc_packet(EHCIQueue *q)
577 {
578     EHCIPacket *p;
579 
580     p = g_new0(EHCIPacket, 1);
581     p->queue = q;
582     usb_packet_init(&p->packet);
583     QTAILQ_INSERT_TAIL(&q->packets, p, next);
584     trace_usb_ehci_packet_action(p->queue, p, "alloc");
585     return p;
586 }
587 
588 static void ehci_free_packet(EHCIPacket *p)
589 {
590     if (p->async == EHCI_ASYNC_FINISHED &&
591             !(p->queue->qh.token & QTD_TOKEN_HALT)) {
592         ehci_writeback_async_complete_packet(p);
593         return;
594     }
595     trace_usb_ehci_packet_action(p->queue, p, "free");
596     if (p->async == EHCI_ASYNC_INFLIGHT) {
597         usb_cancel_packet(&p->packet);
598     }
599     if (p->async == EHCI_ASYNC_FINISHED &&
600             p->packet.status == USB_RET_SUCCESS) {
601         fprintf(stderr,
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));
605     }
606     if (p->async != EHCI_ASYNC_NONE) {
607         usb_packet_unmap(&p->packet, &p->sgl);
608         qemu_sglist_destroy(&p->sgl);
609     }
610     QTAILQ_REMOVE(&p->queue->packets, p, next);
611     usb_packet_cleanup(&p->packet);
612     g_free(p);
613 }
614 
615 /* queue management */
616 
617 static EHCIQueue *ehci_alloc_queue(EHCIState *ehci, uint32_t addr, int async)
618 {
619     EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
620     EHCIQueue *q;
621 
622     q = g_malloc0(sizeof(*q));
623     q->ehci = ehci;
624     q->qhaddr = addr;
625     q->async = async;
626     QTAILQ_INIT(&q->packets);
627     QTAILQ_INSERT_HEAD(head, q, next);
628     trace_usb_ehci_queue_action(q, "alloc");
629     return q;
630 }
631 
632 static void ehci_queue_stopped(EHCIQueue *q)
633 {
634     int endp  = get_field(q->qh.epchar, QH_EPCHAR_EP);
635 
636     if (!q->last_pid || !q->dev) {
637         return;
638     }
639 
640     usb_device_ep_stopped(q->dev, usb_ep_get(q->dev, q->last_pid, endp));
641 }
642 
643 static int ehci_cancel_queue(EHCIQueue *q)
644 {
645     EHCIPacket *p;
646     int packets = 0;
647 
648     p = QTAILQ_FIRST(&q->packets);
649     if (p == NULL) {
650         goto leave;
651     }
652 
653     trace_usb_ehci_queue_action(q, "cancel");
654     do {
655         ehci_free_packet(p);
656         packets++;
657     } while ((p = QTAILQ_FIRST(&q->packets)) != NULL);
658 
659 leave:
660     ehci_queue_stopped(q);
661     return packets;
662 }
663 
664 static int ehci_reset_queue(EHCIQueue *q)
665 {
666     int packets;
667 
668     trace_usb_ehci_queue_action(q, "reset");
669     packets = ehci_cancel_queue(q);
670     q->dev = NULL;
671     q->qtdaddr = 0;
672     q->last_pid = 0;
673     return packets;
674 }
675 
676 static void ehci_free_queue(EHCIQueue *q, const char *warn)
677 {
678     EHCIQueueHead *head = q->async ? &q->ehci->aqueues : &q->ehci->pqueues;
679     int cancelled;
680 
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);
685     }
686     QTAILQ_REMOVE(head, q, next);
687     g_free(q);
688 }
689 
690 static EHCIQueue *ehci_find_queue_by_qh(EHCIState *ehci, uint32_t addr,
691                                         int async)
692 {
693     EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
694     EHCIQueue *q;
695 
696     QTAILQ_FOREACH(q, head, next) {
697         if (addr == q->qhaddr) {
698             return q;
699         }
700     }
701     return NULL;
702 }
703 
704 static void ehci_queues_rip_unused(EHCIState *ehci, int async)
705 {
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;
709     EHCIQueue *q, *tmp;
710 
711     QTAILQ_FOREACH_SAFE(q, head, next, tmp) {
712         if (q->seen) {
713             q->seen = 0;
714             q->ts = ehci->last_run_ns;
715             continue;
716         }
717         if (ehci->last_run_ns < q->ts + maxage) {
718             continue;
719         }
720         ehci_free_queue(q, warn);
721     }
722 }
723 
724 static void ehci_queues_rip_unseen(EHCIState *ehci, int async)
725 {
726     EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
727     EHCIQueue *q, *tmp;
728 
729     QTAILQ_FOREACH_SAFE(q, head, next, tmp) {
730         if (!q->seen) {
731             ehci_free_queue(q, NULL);
732         }
733     }
734 }
735 
736 static void ehci_queues_rip_device(EHCIState *ehci, USBDevice *dev, int async)
737 {
738     EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
739     EHCIQueue *q, *tmp;
740 
741     QTAILQ_FOREACH_SAFE(q, head, next, tmp) {
742         if (q->dev != dev) {
743             continue;
744         }
745         ehci_free_queue(q, NULL);
746     }
747 }
748 
749 static void ehci_queues_rip_all(EHCIState *ehci, int async)
750 {
751     EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;
752     const char *warn = async ? "guest stopped busy async schedule" : NULL;
753     EHCIQueue *q, *tmp;
754 
755     QTAILQ_FOREACH_SAFE(q, head, next, tmp) {
756         ehci_free_queue(q, warn);
757     }
758 }
759 
760 /* Attach or detach a device on root hub */
761 
762 static void ehci_attach(USBPort *port)
763 {
764     EHCIState *s = port->opaque;
765     uint32_t *portsc = &s->portsc[port->index];
766     const char *owner = (*portsc & PORTSC_POWNER) ? "comp" : "ehci";
767 
768     trace_usb_ehci_port_attach(port->index, owner, port->dev->product_desc);
769 
770     if (*portsc & PORTSC_POWNER) {
771         USBPort *companion = s->companion_ports[port->index];
772         companion->dev = port->dev;
773         companion->ops->attach(companion);
774         return;
775     }
776 
777     *portsc |= PORTSC_CONNECT;
778     *portsc |= PORTSC_CSC;
779 
780     ehci_raise_irq(s, USBSTS_PCD);
781 }
782 
783 static void ehci_detach(USBPort *port)
784 {
785     EHCIState *s = port->opaque;
786     uint32_t *portsc = &s->portsc[port->index];
787     const char *owner = (*portsc & PORTSC_POWNER) ? "comp" : "ehci";
788 
789     trace_usb_ehci_port_detach(port->index, owner);
790 
791     if (*portsc & PORTSC_POWNER) {
792         USBPort *companion = s->companion_ports[port->index];
793         companion->ops->detach(companion);
794         companion->dev = NULL;
795         /*
796          * EHCI spec 4.2.2: "When a disconnect occurs... On the event,
797          * the port ownership is returned immediately to the EHCI controller."
798          */
799         *portsc &= ~PORTSC_POWNER;
800         return;
801     }
802 
803     ehci_queues_rip_device(s, port->dev, 0);
804     ehci_queues_rip_device(s, port->dev, 1);
805 
806     *portsc &= ~(PORTSC_CONNECT|PORTSC_PED);
807     *portsc |= PORTSC_CSC;
808 
809     ehci_raise_irq(s, USBSTS_PCD);
810 }
811 
812 static void ehci_child_detach(USBPort *port, USBDevice *child)
813 {
814     EHCIState *s = port->opaque;
815     uint32_t portsc = s->portsc[port->index];
816 
817     if (portsc & PORTSC_POWNER) {
818         USBPort *companion = s->companion_ports[port->index];
819         companion->ops->child_detach(companion, child);
820         return;
821     }
822 
823     ehci_queues_rip_device(s, child, 0);
824     ehci_queues_rip_device(s, child, 1);
825 }
826 
827 static void ehci_wakeup(USBPort *port)
828 {
829     EHCIState *s = port->opaque;
830     uint32_t *portsc = &s->portsc[port->index];
831 
832     if (*portsc & PORTSC_POWNER) {
833         USBPort *companion = s->companion_ports[port->index];
834         if (companion->ops->wakeup) {
835             companion->ops->wakeup(companion);
836         }
837         return;
838     }
839 
840     if (*portsc & PORTSC_SUSPEND) {
841         trace_usb_ehci_port_wakeup(port->index);
842         *portsc |= PORTSC_FPRES;
843         ehci_raise_irq(s, USBSTS_PCD);
844     }
845 
846     qemu_bh_schedule(s->async_bh);
847 }
848 
849 static int ehci_register_companion(USBBus *bus, USBPort *ports[],
850                                    uint32_t portcount, uint32_t firstport)
851 {
852     EHCIState *s = container_of(bus, EHCIState, bus);
853     uint32_t i;
854 
855     if (firstport + portcount > NB_PORTS) {
856         qerror_report(QERR_INVALID_PARAMETER_VALUE, "firstport",
857                       "firstport on masterbus");
858         error_printf_unless_qmp(
859             "firstport value of %u makes companion take ports %u - %u, which "
860             "is outside of the valid range of 0 - %u\n", firstport, firstport,
861             firstport + portcount - 1, NB_PORTS - 1);
862         return -1;
863     }
864 
865     for (i = 0; i < portcount; i++) {
866         if (s->companion_ports[firstport + i]) {
867             qerror_report(QERR_INVALID_PARAMETER_VALUE, "masterbus",
868                           "an USB masterbus");
869             error_printf_unless_qmp(
870                 "port %u on masterbus %s already has a companion assigned\n",
871                 firstport + i, bus->qbus.name);
872             return -1;
873         }
874     }
875 
876     for (i = 0; i < portcount; i++) {
877         s->companion_ports[firstport + i] = ports[i];
878         s->ports[firstport + i].speedmask |=
879             USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL;
880         /* Ensure devs attached before the initial reset go to the companion */
881         s->portsc[firstport + i] = PORTSC_POWNER;
882     }
883 
884     s->companion_count++;
885     s->caps[0x05] = (s->companion_count << 4) | portcount;
886 
887     return 0;
888 }
889 
890 static void ehci_wakeup_endpoint(USBBus *bus, USBEndpoint *ep,
891                                  unsigned int stream)
892 {
893     EHCIState *s = container_of(bus, EHCIState, bus);
894     uint32_t portsc = s->portsc[ep->dev->port->index];
895 
896     if (portsc & PORTSC_POWNER) {
897         return;
898     }
899 
900     s->periodic_sched_active = PERIODIC_ACTIVE;
901     qemu_bh_schedule(s->async_bh);
902 }
903 
904 static USBDevice *ehci_find_device(EHCIState *ehci, uint8_t addr)
905 {
906     USBDevice *dev;
907     USBPort *port;
908     int i;
909 
910     for (i = 0; i < NB_PORTS; i++) {
911         port = &ehci->ports[i];
912         if (!(ehci->portsc[i] & PORTSC_PED)) {
913             DPRINTF("Port %d not enabled\n", i);
914             continue;
915         }
916         dev = usb_find_device(port, addr);
917         if (dev != NULL) {
918             return dev;
919         }
920     }
921     return NULL;
922 }
923 
924 /* 4.1 host controller initialization */
925 static void ehci_reset(void *opaque)
926 {
927     EHCIState *s = opaque;
928     int i;
929     USBDevice *devs[NB_PORTS];
930 
931     trace_usb_ehci_reset();
932 
933     /*
934      * Do the detach before touching portsc, so that it correctly gets send to
935      * us or to our companion based on PORTSC_POWNER before the reset.
936      */
937     for(i = 0; i < NB_PORTS; i++) {
938         devs[i] = s->ports[i].dev;
939         if (devs[i] && devs[i]->attached) {
940             usb_detach(&s->ports[i]);
941         }
942     }
943 
944     memset(&s->opreg, 0x00, sizeof(s->opreg));
945     memset(&s->portsc, 0x00, sizeof(s->portsc));
946 
947     s->usbcmd = NB_MAXINTRATE << USBCMD_ITC_SH;
948     s->usbsts = USBSTS_HALT;
949     s->usbsts_pending = 0;
950     s->usbsts_frindex = 0;
951 
952     s->astate = EST_INACTIVE;
953     s->pstate = EST_INACTIVE;
954 
955     for(i = 0; i < NB_PORTS; i++) {
956         if (s->companion_ports[i]) {
957             s->portsc[i] = PORTSC_POWNER | PORTSC_PPOWER;
958         } else {
959             s->portsc[i] = PORTSC_PPOWER;
960         }
961         if (devs[i] && devs[i]->attached) {
962             usb_attach(&s->ports[i]);
963             usb_device_reset(devs[i]);
964         }
965     }
966     ehci_queues_rip_all(s, 0);
967     ehci_queues_rip_all(s, 1);
968     timer_del(s->frame_timer);
969     qemu_bh_cancel(s->async_bh);
970 }
971 
972 static uint64_t ehci_caps_read(void *ptr, hwaddr addr,
973                                unsigned size)
974 {
975     EHCIState *s = ptr;
976     return s->caps[addr];
977 }
978 
979 static uint64_t ehci_opreg_read(void *ptr, hwaddr addr,
980                                 unsigned size)
981 {
982     EHCIState *s = ptr;
983     uint32_t val;
984 
985     switch (addr) {
986     case FRINDEX:
987         /* Round down to mult of 8, else it can go backwards on migration */
988         val = s->frindex & ~7;
989         break;
990     default:
991         val = s->opreg[addr >> 2];
992     }
993 
994     trace_usb_ehci_opreg_read(addr + s->opregbase, addr2str(addr), val);
995     return val;
996 }
997 
998 static uint64_t ehci_port_read(void *ptr, hwaddr addr,
999                                unsigned size)
1000 {
1001     EHCIState *s = ptr;
1002     uint32_t val;
1003 
1004     val = s->portsc[addr >> 2];
1005     trace_usb_ehci_portsc_read(addr + s->portscbase, addr >> 2, val);
1006     return val;
1007 }
1008 
1009 static void handle_port_owner_write(EHCIState *s, int port, uint32_t owner)
1010 {
1011     USBDevice *dev = s->ports[port].dev;
1012     uint32_t *portsc = &s->portsc[port];
1013     uint32_t orig;
1014 
1015     if (s->companion_ports[port] == NULL)
1016         return;
1017 
1018     owner = owner & PORTSC_POWNER;
1019     orig  = *portsc & PORTSC_POWNER;
1020 
1021     if (!(owner ^ orig)) {
1022         return;
1023     }
1024 
1025     if (dev && dev->attached) {
1026         usb_detach(&s->ports[port]);
1027     }
1028 
1029     *portsc &= ~PORTSC_POWNER;
1030     *portsc |= owner;
1031 
1032     if (dev && dev->attached) {
1033         usb_attach(&s->ports[port]);
1034     }
1035 }
1036 
1037 static void ehci_port_write(void *ptr, hwaddr addr,
1038                             uint64_t val, unsigned size)
1039 {
1040     EHCIState *s = ptr;
1041     int port = addr >> 2;
1042     uint32_t *portsc = &s->portsc[port];
1043     uint32_t old = *portsc;
1044     USBDevice *dev = s->ports[port].dev;
1045 
1046     trace_usb_ehci_portsc_write(addr + s->portscbase, addr >> 2, val);
1047 
1048     /* Clear rwc bits */
1049     *portsc &= ~(val & PORTSC_RWC_MASK);
1050     /* The guest may clear, but not set the PED bit */
1051     *portsc &= val | ~PORTSC_PED;
1052     /* POWNER is masked out by RO_MASK as it is RO when we've no companion */
1053     handle_port_owner_write(s, port, val);
1054     /* And finally apply RO_MASK */
1055     val &= PORTSC_RO_MASK;
1056 
1057     if ((val & PORTSC_PRESET) && !(*portsc & PORTSC_PRESET)) {
1058         trace_usb_ehci_port_reset(port, 1);
1059     }
1060 
1061     if (!(val & PORTSC_PRESET) &&(*portsc & PORTSC_PRESET)) {
1062         trace_usb_ehci_port_reset(port, 0);
1063         if (dev && dev->attached) {
1064             usb_port_reset(&s->ports[port]);
1065             *portsc &= ~PORTSC_CSC;
1066         }
1067 
1068         /*
1069          *  Table 2.16 Set the enable bit(and enable bit change) to indicate
1070          *  to SW that this port has a high speed device attached
1071          */
1072         if (dev && dev->attached && (dev->speedmask & USB_SPEED_MASK_HIGH)) {
1073             val |= PORTSC_PED;
1074         }
1075     }
1076 
1077     if ((val & PORTSC_SUSPEND) && !(*portsc & PORTSC_SUSPEND)) {
1078         trace_usb_ehci_port_suspend(port);
1079     }
1080     if (!(val & PORTSC_FPRES) && (*portsc & PORTSC_FPRES)) {
1081         trace_usb_ehci_port_resume(port);
1082         val &= ~PORTSC_SUSPEND;
1083     }
1084 
1085     *portsc &= ~PORTSC_RO_MASK;
1086     *portsc |= val;
1087     trace_usb_ehci_portsc_change(addr + s->portscbase, addr >> 2, *portsc, old);
1088 }
1089 
1090 static void ehci_opreg_write(void *ptr, hwaddr addr,
1091                              uint64_t val, unsigned size)
1092 {
1093     EHCIState *s = ptr;
1094     uint32_t *mmio = s->opreg + (addr >> 2);
1095     uint32_t old = *mmio;
1096     int i;
1097 
1098     trace_usb_ehci_opreg_write(addr + s->opregbase, addr2str(addr), val);
1099 
1100     switch (addr) {
1101     case USBCMD:
1102         if (val & USBCMD_HCRESET) {
1103             ehci_reset(s);
1104             val = s->usbcmd;
1105             break;
1106         }
1107 
1108         /* not supporting dynamic frame list size at the moment */
1109         if ((val & USBCMD_FLS) && !(s->usbcmd & USBCMD_FLS)) {
1110             fprintf(stderr, "attempt to set frame list size -- value %d\n",
1111                     (int)val & USBCMD_FLS);
1112             val &= ~USBCMD_FLS;
1113         }
1114 
1115         if (val & USBCMD_IAAD) {
1116             /*
1117              * Process IAAD immediately, otherwise the Linux IAAD watchdog may
1118              * trigger and re-use a qh without us seeing the unlink.
1119              */
1120             s->async_stepdown = 0;
1121             qemu_bh_schedule(s->async_bh);
1122             trace_usb_ehci_doorbell_ring();
1123         }
1124 
1125         if (((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & val) !=
1126             ((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & s->usbcmd)) {
1127             if (s->pstate == EST_INACTIVE) {
1128                 SET_LAST_RUN_CLOCK(s);
1129             }
1130             s->usbcmd = val; /* Set usbcmd for ehci_update_halt() */
1131             ehci_update_halt(s);
1132             s->async_stepdown = 0;
1133             qemu_bh_schedule(s->async_bh);
1134         }
1135         break;
1136 
1137     case USBSTS:
1138         val &= USBSTS_RO_MASK;              // bits 6 through 31 are RO
1139         ehci_clear_usbsts(s, val);          // bits 0 through 5 are R/WC
1140         val = s->usbsts;
1141         ehci_update_irq(s);
1142         break;
1143 
1144     case USBINTR:
1145         val &= USBINTR_MASK;
1146         if (ehci_enabled(s) && (USBSTS_FLR & val)) {
1147             qemu_bh_schedule(s->async_bh);
1148         }
1149         break;
1150 
1151     case FRINDEX:
1152         val &= 0x00003fff; /* frindex is 14bits */
1153         s->usbsts_frindex = val;
1154         break;
1155 
1156     case CONFIGFLAG:
1157         val &= 0x1;
1158         if (val) {
1159             for(i = 0; i < NB_PORTS; i++)
1160                 handle_port_owner_write(s, i, 0);
1161         }
1162         break;
1163 
1164     case PERIODICLISTBASE:
1165         if (ehci_periodic_enabled(s)) {
1166             fprintf(stderr,
1167               "ehci: PERIODIC list base register set while periodic schedule\n"
1168               "      is enabled and HC is enabled\n");
1169         }
1170         break;
1171 
1172     case ASYNCLISTADDR:
1173         if (ehci_async_enabled(s)) {
1174             fprintf(stderr,
1175               "ehci: ASYNC list address register set while async schedule\n"
1176               "      is enabled and HC is enabled\n");
1177         }
1178         break;
1179     }
1180 
1181     *mmio = val;
1182     trace_usb_ehci_opreg_change(addr + s->opregbase, addr2str(addr),
1183                                 *mmio, old);
1184 }
1185 
1186 /*
1187  *  Write the qh back to guest physical memory.  This step isn't
1188  *  in the EHCI spec but we need to do it since we don't share
1189  *  physical memory with our guest VM.
1190  *
1191  *  The first three dwords are read-only for the EHCI, so skip them
1192  *  when writing back the qh.
1193  */
1194 static void ehci_flush_qh(EHCIQueue *q)
1195 {
1196     uint32_t *qh = (uint32_t *) &q->qh;
1197     uint32_t dwords = sizeof(EHCIqh) >> 2;
1198     uint32_t addr = NLPTR_GET(q->qhaddr);
1199 
1200     put_dwords(q->ehci, addr + 3 * sizeof(uint32_t), qh + 3, dwords - 3);
1201 }
1202 
1203 // 4.10.2
1204 
1205 static int ehci_qh_do_overlay(EHCIQueue *q)
1206 {
1207     EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1208     int i;
1209     int dtoggle;
1210     int ping;
1211     int eps;
1212     int reload;
1213 
1214     assert(p != NULL);
1215     assert(p->qtdaddr == q->qtdaddr);
1216 
1217     // remember values in fields to preserve in qh after overlay
1218 
1219     dtoggle = q->qh.token & QTD_TOKEN_DTOGGLE;
1220     ping    = q->qh.token & QTD_TOKEN_PING;
1221 
1222     q->qh.current_qtd = p->qtdaddr;
1223     q->qh.next_qtd    = p->qtd.next;
1224     q->qh.altnext_qtd = p->qtd.altnext;
1225     q->qh.token       = p->qtd.token;
1226 
1227 
1228     eps = get_field(q->qh.epchar, QH_EPCHAR_EPS);
1229     if (eps == EHCI_QH_EPS_HIGH) {
1230         q->qh.token &= ~QTD_TOKEN_PING;
1231         q->qh.token |= ping;
1232     }
1233 
1234     reload = get_field(q->qh.epchar, QH_EPCHAR_RL);
1235     set_field(&q->qh.altnext_qtd, reload, QH_ALTNEXT_NAKCNT);
1236 
1237     for (i = 0; i < 5; i++) {
1238         q->qh.bufptr[i] = p->qtd.bufptr[i];
1239     }
1240 
1241     if (!(q->qh.epchar & QH_EPCHAR_DTC)) {
1242         // preserve QH DT bit
1243         q->qh.token &= ~QTD_TOKEN_DTOGGLE;
1244         q->qh.token |= dtoggle;
1245     }
1246 
1247     q->qh.bufptr[1] &= ~BUFPTR_CPROGMASK_MASK;
1248     q->qh.bufptr[2] &= ~BUFPTR_FRAMETAG_MASK;
1249 
1250     ehci_flush_qh(q);
1251 
1252     return 0;
1253 }
1254 
1255 static int ehci_init_transfer(EHCIPacket *p)
1256 {
1257     uint32_t cpage, offset, bytes, plen;
1258     dma_addr_t page;
1259 
1260     cpage  = get_field(p->qtd.token, QTD_TOKEN_CPAGE);
1261     bytes  = get_field(p->qtd.token, QTD_TOKEN_TBYTES);
1262     offset = p->qtd.bufptr[0] & ~QTD_BUFPTR_MASK;
1263     qemu_sglist_init(&p->sgl, p->queue->ehci->device, 5, p->queue->ehci->as);
1264 
1265     while (bytes > 0) {
1266         if (cpage > 4) {
1267             fprintf(stderr, "cpage out of range (%d)\n", cpage);
1268             return -1;
1269         }
1270 
1271         page  = p->qtd.bufptr[cpage] & QTD_BUFPTR_MASK;
1272         page += offset;
1273         plen  = bytes;
1274         if (plen > 4096 - offset) {
1275             plen = 4096 - offset;
1276             offset = 0;
1277             cpage++;
1278         }
1279 
1280         qemu_sglist_add(&p->sgl, page, plen);
1281         bytes -= plen;
1282     }
1283     return 0;
1284 }
1285 
1286 static void ehci_finish_transfer(EHCIQueue *q, int len)
1287 {
1288     uint32_t cpage, offset;
1289 
1290     if (len > 0) {
1291         /* update cpage & offset */
1292         cpage  = get_field(q->qh.token, QTD_TOKEN_CPAGE);
1293         offset = q->qh.bufptr[0] & ~QTD_BUFPTR_MASK;
1294 
1295         offset += len;
1296         cpage  += offset >> QTD_BUFPTR_SH;
1297         offset &= ~QTD_BUFPTR_MASK;
1298 
1299         set_field(&q->qh.token, cpage, QTD_TOKEN_CPAGE);
1300         q->qh.bufptr[0] &= QTD_BUFPTR_MASK;
1301         q->qh.bufptr[0] |= offset;
1302     }
1303 }
1304 
1305 static void ehci_async_complete_packet(USBPort *port, USBPacket *packet)
1306 {
1307     EHCIPacket *p;
1308     EHCIState *s = port->opaque;
1309     uint32_t portsc = s->portsc[port->index];
1310 
1311     if (portsc & PORTSC_POWNER) {
1312         USBPort *companion = s->companion_ports[port->index];
1313         companion->ops->complete(companion, packet);
1314         return;
1315     }
1316 
1317     p = container_of(packet, EHCIPacket, packet);
1318     assert(p->async == EHCI_ASYNC_INFLIGHT);
1319 
1320     if (packet->status == USB_RET_REMOVE_FROM_QUEUE) {
1321         trace_usb_ehci_packet_action(p->queue, p, "remove");
1322         ehci_free_packet(p);
1323         return;
1324     }
1325 
1326     trace_usb_ehci_packet_action(p->queue, p, "wakeup");
1327     p->async = EHCI_ASYNC_FINISHED;
1328 
1329     if (!p->queue->async) {
1330         s->periodic_sched_active = PERIODIC_ACTIVE;
1331     }
1332     qemu_bh_schedule(s->async_bh);
1333 }
1334 
1335 static void ehci_execute_complete(EHCIQueue *q)
1336 {
1337     EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1338     uint32_t tbytes;
1339 
1340     assert(p != NULL);
1341     assert(p->qtdaddr == q->qtdaddr);
1342     assert(p->async == EHCI_ASYNC_INITIALIZED ||
1343            p->async == EHCI_ASYNC_FINISHED);
1344 
1345     DPRINTF("execute_complete: qhaddr 0x%x, next 0x%x, qtdaddr 0x%x, "
1346             "status %d, actual_length %d\n",
1347             q->qhaddr, q->qh.next, q->qtdaddr,
1348             p->packet.status, p->packet.actual_length);
1349 
1350     switch (p->packet.status) {
1351     case USB_RET_SUCCESS:
1352         break;
1353     case USB_RET_IOERROR:
1354     case USB_RET_NODEV:
1355         q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_XACTERR);
1356         set_field(&q->qh.token, 0, QTD_TOKEN_CERR);
1357         ehci_raise_irq(q->ehci, USBSTS_ERRINT);
1358         break;
1359     case USB_RET_STALL:
1360         q->qh.token |= QTD_TOKEN_HALT;
1361         ehci_raise_irq(q->ehci, USBSTS_ERRINT);
1362         break;
1363     case USB_RET_NAK:
1364         set_field(&q->qh.altnext_qtd, 0, QH_ALTNEXT_NAKCNT);
1365         return; /* We're not done yet with this transaction */
1366     case USB_RET_BABBLE:
1367         q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_BABBLE);
1368         ehci_raise_irq(q->ehci, USBSTS_ERRINT);
1369         break;
1370     default:
1371         /* should not be triggerable */
1372         fprintf(stderr, "USB invalid response %d\n", p->packet.status);
1373         g_assert_not_reached();
1374         break;
1375     }
1376 
1377     /* TODO check 4.12 for splits */
1378     tbytes = get_field(q->qh.token, QTD_TOKEN_TBYTES);
1379     if (tbytes && p->pid == USB_TOKEN_IN) {
1380         tbytes -= p->packet.actual_length;
1381         if (tbytes) {
1382             /* 4.15.1.2 must raise int on a short input packet */
1383             ehci_raise_irq(q->ehci, USBSTS_INT);
1384             if (q->async) {
1385                 q->ehci->int_req_by_async = true;
1386             }
1387         }
1388     } else {
1389         tbytes = 0;
1390     }
1391     DPRINTF("updating tbytes to %d\n", tbytes);
1392     set_field(&q->qh.token, tbytes, QTD_TOKEN_TBYTES);
1393 
1394     ehci_finish_transfer(q, p->packet.actual_length);
1395     usb_packet_unmap(&p->packet, &p->sgl);
1396     qemu_sglist_destroy(&p->sgl);
1397     p->async = EHCI_ASYNC_NONE;
1398 
1399     q->qh.token ^= QTD_TOKEN_DTOGGLE;
1400     q->qh.token &= ~QTD_TOKEN_ACTIVE;
1401 
1402     if (q->qh.token & QTD_TOKEN_IOC) {
1403         ehci_raise_irq(q->ehci, USBSTS_INT);
1404         if (q->async) {
1405             q->ehci->int_req_by_async = true;
1406         }
1407     }
1408 }
1409 
1410 /* 4.10.3 returns "again" */
1411 static int ehci_execute(EHCIPacket *p, const char *action)
1412 {
1413     USBEndpoint *ep;
1414     int endp;
1415     bool spd;
1416 
1417     assert(p->async == EHCI_ASYNC_NONE ||
1418            p->async == EHCI_ASYNC_INITIALIZED);
1419 
1420     if (!(p->qtd.token & QTD_TOKEN_ACTIVE)) {
1421         fprintf(stderr, "Attempting to execute inactive qtd\n");
1422         return -1;
1423     }
1424 
1425     if (get_field(p->qtd.token, QTD_TOKEN_TBYTES) > BUFF_SIZE) {
1426         ehci_trace_guest_bug(p->queue->ehci,
1427                              "guest requested more bytes than allowed");
1428         return -1;
1429     }
1430 
1431     if (!ehci_verify_pid(p->queue, &p->qtd)) {
1432         ehci_queue_stopped(p->queue); /* Mark the ep in the prev dir stopped */
1433     }
1434     p->pid = ehci_get_pid(&p->qtd);
1435     p->queue->last_pid = p->pid;
1436     endp = get_field(p->queue->qh.epchar, QH_EPCHAR_EP);
1437     ep = usb_ep_get(p->queue->dev, p->pid, endp);
1438 
1439     if (p->async == EHCI_ASYNC_NONE) {
1440         if (ehci_init_transfer(p) != 0) {
1441             return -1;
1442         }
1443 
1444         spd = (p->pid == USB_TOKEN_IN && NLPTR_TBIT(p->qtd.altnext) == 0);
1445         usb_packet_setup(&p->packet, p->pid, ep, 0, p->qtdaddr, spd,
1446                          (p->qtd.token & QTD_TOKEN_IOC) != 0);
1447         usb_packet_map(&p->packet, &p->sgl);
1448         p->async = EHCI_ASYNC_INITIALIZED;
1449     }
1450 
1451     trace_usb_ehci_packet_action(p->queue, p, action);
1452     usb_handle_packet(p->queue->dev, &p->packet);
1453     DPRINTF("submit: qh 0x%x next 0x%x qtd 0x%x pid 0x%x len %zd endp 0x%x "
1454             "status %d actual_length %d\n", p->queue->qhaddr, p->qtd.next,
1455             p->qtdaddr, p->pid, p->packet.iov.size, endp, p->packet.status,
1456             p->packet.actual_length);
1457 
1458     if (p->packet.actual_length > BUFF_SIZE) {
1459         fprintf(stderr, "ret from usb_handle_packet > BUFF_SIZE\n");
1460         return -1;
1461     }
1462 
1463     return 1;
1464 }
1465 
1466 /*  4.7.2
1467  */
1468 
1469 static int ehci_process_itd(EHCIState *ehci,
1470                             EHCIitd *itd,
1471                             uint32_t addr)
1472 {
1473     USBDevice *dev;
1474     USBEndpoint *ep;
1475     uint32_t i, len, pid, dir, devaddr, endp;
1476     uint32_t pg, off, ptr1, ptr2, max, mult;
1477 
1478     ehci->periodic_sched_active = PERIODIC_ACTIVE;
1479 
1480     dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
1481     devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
1482     endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
1483     max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
1484     mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
1485 
1486     for(i = 0; i < 8; i++) {
1487         if (itd->transact[i] & ITD_XACT_ACTIVE) {
1488             pg   = get_field(itd->transact[i], ITD_XACT_PGSEL);
1489             off  = itd->transact[i] & ITD_XACT_OFFSET_MASK;
1490             ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
1491             ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK);
1492             len  = get_field(itd->transact[i], ITD_XACT_LENGTH);
1493 
1494             if (len > max * mult) {
1495                 len = max * mult;
1496             }
1497 
1498             if (len > BUFF_SIZE) {
1499                 return -1;
1500             }
1501 
1502             qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
1503             if (off + len > 4096) {
1504                 /* transfer crosses page border */
1505                 uint32_t len2 = off + len - 4096;
1506                 uint32_t len1 = len - len2;
1507                 qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
1508                 qemu_sglist_add(&ehci->isgl, ptr2, len2);
1509             } else {
1510                 qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
1511             }
1512 
1513             pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
1514 
1515             dev = ehci_find_device(ehci, devaddr);
1516             ep = usb_ep_get(dev, pid, endp);
1517             if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
1518                 usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
1519                                  (itd->transact[i] & ITD_XACT_IOC) != 0);
1520                 usb_packet_map(&ehci->ipacket, &ehci->isgl);
1521                 usb_handle_packet(dev, &ehci->ipacket);
1522                 usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
1523             } else {
1524                 DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
1525                 ehci->ipacket.status = USB_RET_NAK;
1526                 ehci->ipacket.actual_length = 0;
1527             }
1528             qemu_sglist_destroy(&ehci->isgl);
1529 
1530             switch (ehci->ipacket.status) {
1531             case USB_RET_SUCCESS:
1532                 break;
1533             default:
1534                 fprintf(stderr, "Unexpected iso usb result: %d\n",
1535                         ehci->ipacket.status);
1536                 /* Fall through */
1537             case USB_RET_IOERROR:
1538             case USB_RET_NODEV:
1539                 /* 3.3.2: XACTERR is only allowed on IN transactions */
1540                 if (dir) {
1541                     itd->transact[i] |= ITD_XACT_XACTERR;
1542                     ehci_raise_irq(ehci, USBSTS_ERRINT);
1543                 }
1544                 break;
1545             case USB_RET_BABBLE:
1546                 itd->transact[i] |= ITD_XACT_BABBLE;
1547                 ehci_raise_irq(ehci, USBSTS_ERRINT);
1548                 break;
1549             case USB_RET_NAK:
1550                 /* no data for us, so do a zero-length transfer */
1551                 ehci->ipacket.actual_length = 0;
1552                 break;
1553             }
1554             if (!dir) {
1555                 set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
1556                           ITD_XACT_LENGTH); /* OUT */
1557             } else {
1558                 set_field(&itd->transact[i], ehci->ipacket.actual_length,
1559                           ITD_XACT_LENGTH); /* IN */
1560             }
1561             if (itd->transact[i] & ITD_XACT_IOC) {
1562                 ehci_raise_irq(ehci, USBSTS_INT);
1563             }
1564             itd->transact[i] &= ~ITD_XACT_ACTIVE;
1565         }
1566     }
1567     return 0;
1568 }
1569 
1570 
1571 /*  This state is the entry point for asynchronous schedule
1572  *  processing.  Entry here consitutes a EHCI start event state (4.8.5)
1573  */
1574 static int ehci_state_waitlisthead(EHCIState *ehci,  int async)
1575 {
1576     EHCIqh qh;
1577     int i = 0;
1578     int again = 0;
1579     uint32_t entry = ehci->asynclistaddr;
1580 
1581     /* set reclamation flag at start event (4.8.6) */
1582     if (async) {
1583         ehci_set_usbsts(ehci, USBSTS_REC);
1584     }
1585 
1586     ehci_queues_rip_unused(ehci, async);
1587 
1588     /*  Find the head of the list (4.9.1.1) */
1589     for(i = 0; i < MAX_QH; i++) {
1590         if (get_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &qh,
1591                        sizeof(EHCIqh) >> 2) < 0) {
1592             return 0;
1593         }
1594         ehci_trace_qh(NULL, NLPTR_GET(entry), &qh);
1595 
1596         if (qh.epchar & QH_EPCHAR_H) {
1597             if (async) {
1598                 entry |= (NLPTR_TYPE_QH << 1);
1599             }
1600 
1601             ehci_set_fetch_addr(ehci, async, entry);
1602             ehci_set_state(ehci, async, EST_FETCHENTRY);
1603             again = 1;
1604             goto out;
1605         }
1606 
1607         entry = qh.next;
1608         if (entry == ehci->asynclistaddr) {
1609             break;
1610         }
1611     }
1612 
1613     /* no head found for list. */
1614 
1615     ehci_set_state(ehci, async, EST_ACTIVE);
1616 
1617 out:
1618     return again;
1619 }
1620 
1621 
1622 /*  This state is the entry point for periodic schedule processing as
1623  *  well as being a continuation state for async processing.
1624  */
1625 static int ehci_state_fetchentry(EHCIState *ehci, int async)
1626 {
1627     int again = 0;
1628     uint32_t entry = ehci_get_fetch_addr(ehci, async);
1629 
1630     if (NLPTR_TBIT(entry)) {
1631         ehci_set_state(ehci, async, EST_ACTIVE);
1632         goto out;
1633     }
1634 
1635     /* section 4.8, only QH in async schedule */
1636     if (async && (NLPTR_TYPE_GET(entry) != NLPTR_TYPE_QH)) {
1637         fprintf(stderr, "non queue head request in async schedule\n");
1638         return -1;
1639     }
1640 
1641     switch (NLPTR_TYPE_GET(entry)) {
1642     case NLPTR_TYPE_QH:
1643         ehci_set_state(ehci, async, EST_FETCHQH);
1644         again = 1;
1645         break;
1646 
1647     case NLPTR_TYPE_ITD:
1648         ehci_set_state(ehci, async, EST_FETCHITD);
1649         again = 1;
1650         break;
1651 
1652     case NLPTR_TYPE_STITD:
1653         ehci_set_state(ehci, async, EST_FETCHSITD);
1654         again = 1;
1655         break;
1656 
1657     default:
1658         /* TODO: handle FSTN type */
1659         fprintf(stderr, "FETCHENTRY: entry at %X is of type %d "
1660                 "which is not supported yet\n", entry, NLPTR_TYPE_GET(entry));
1661         return -1;
1662     }
1663 
1664 out:
1665     return again;
1666 }
1667 
1668 static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
1669 {
1670     uint32_t entry;
1671     EHCIQueue *q;
1672     EHCIqh qh;
1673 
1674     entry = ehci_get_fetch_addr(ehci, async);
1675     q = ehci_find_queue_by_qh(ehci, entry, async);
1676     if (NULL == q) {
1677         q = ehci_alloc_queue(ehci, entry, async);
1678     }
1679 
1680     q->seen++;
1681     if (q->seen > 1) {
1682         /* we are going in circles -- stop processing */
1683         ehci_set_state(ehci, async, EST_ACTIVE);
1684         q = NULL;
1685         goto out;
1686     }
1687 
1688     if (get_dwords(ehci, NLPTR_GET(q->qhaddr),
1689                    (uint32_t *) &qh, sizeof(EHCIqh) >> 2) < 0) {
1690         q = NULL;
1691         goto out;
1692     }
1693     ehci_trace_qh(q, NLPTR_GET(q->qhaddr), &qh);
1694 
1695     /*
1696      * The overlay area of the qh should never be changed by the guest,
1697      * except when idle, in which case the reset is a nop.
1698      */
1699     if (!ehci_verify_qh(q, &qh)) {
1700         if (ehci_reset_queue(q) > 0) {
1701             ehci_trace_guest_bug(ehci, "guest updated active QH");
1702         }
1703     }
1704     q->qh = qh;
1705 
1706     q->transact_ctr = get_field(q->qh.epcap, QH_EPCAP_MULT);
1707     if (q->transact_ctr == 0) { /* Guest bug in some versions of windows */
1708         q->transact_ctr = 4;
1709     }
1710 
1711     if (q->dev == NULL) {
1712         q->dev = ehci_find_device(q->ehci,
1713                                   get_field(q->qh.epchar, QH_EPCHAR_DEVADDR));
1714     }
1715 
1716     if (async && (q->qh.epchar & QH_EPCHAR_H)) {
1717 
1718         /*  EHCI spec version 1.0 Section 4.8.3 & 4.10.1 */
1719         if (ehci->usbsts & USBSTS_REC) {
1720             ehci_clear_usbsts(ehci, USBSTS_REC);
1721         } else {
1722             DPRINTF("FETCHQH:  QH 0x%08x. H-bit set, reclamation status reset"
1723                        " - done processing\n", q->qhaddr);
1724             ehci_set_state(ehci, async, EST_ACTIVE);
1725             q = NULL;
1726             goto out;
1727         }
1728     }
1729 
1730 #if EHCI_DEBUG
1731     if (q->qhaddr != q->qh.next) {
1732     DPRINTF("FETCHQH:  QH 0x%08x (h %x halt %x active %x) next 0x%08x\n",
1733                q->qhaddr,
1734                q->qh.epchar & QH_EPCHAR_H,
1735                q->qh.token & QTD_TOKEN_HALT,
1736                q->qh.token & QTD_TOKEN_ACTIVE,
1737                q->qh.next);
1738     }
1739 #endif
1740 
1741     if (q->qh.token & QTD_TOKEN_HALT) {
1742         ehci_set_state(ehci, async, EST_HORIZONTALQH);
1743 
1744     } else if ((q->qh.token & QTD_TOKEN_ACTIVE) &&
1745                (NLPTR_TBIT(q->qh.current_qtd) == 0)) {
1746         q->qtdaddr = q->qh.current_qtd;
1747         ehci_set_state(ehci, async, EST_FETCHQTD);
1748 
1749     } else {
1750         /*  EHCI spec version 1.0 Section 4.10.2 */
1751         ehci_set_state(ehci, async, EST_ADVANCEQUEUE);
1752     }
1753 
1754 out:
1755     return q;
1756 }
1757 
1758 static int ehci_state_fetchitd(EHCIState *ehci, int async)
1759 {
1760     uint32_t entry;
1761     EHCIitd itd;
1762 
1763     assert(!async);
1764     entry = ehci_get_fetch_addr(ehci, async);
1765 
1766     if (get_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &itd,
1767                    sizeof(EHCIitd) >> 2) < 0) {
1768         return -1;
1769     }
1770     ehci_trace_itd(ehci, entry, &itd);
1771 
1772     if (ehci_process_itd(ehci, &itd, entry) != 0) {
1773         return -1;
1774     }
1775 
1776     put_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &itd,
1777                sizeof(EHCIitd) >> 2);
1778     ehci_set_fetch_addr(ehci, async, itd.next);
1779     ehci_set_state(ehci, async, EST_FETCHENTRY);
1780 
1781     return 1;
1782 }
1783 
1784 static int ehci_state_fetchsitd(EHCIState *ehci, int async)
1785 {
1786     uint32_t entry;
1787     EHCIsitd sitd;
1788 
1789     assert(!async);
1790     entry = ehci_get_fetch_addr(ehci, async);
1791 
1792     if (get_dwords(ehci, NLPTR_GET(entry), (uint32_t *)&sitd,
1793                    sizeof(EHCIsitd) >> 2) < 0) {
1794         return 0;
1795     }
1796     ehci_trace_sitd(ehci, entry, &sitd);
1797 
1798     if (!(sitd.results & SITD_RESULTS_ACTIVE)) {
1799         /* siTD is not active, nothing to do */;
1800     } else {
1801         /* TODO: split transfers are not implemented */
1802         fprintf(stderr, "WARNING: Skipping active siTD\n");
1803     }
1804 
1805     ehci_set_fetch_addr(ehci, async, sitd.next);
1806     ehci_set_state(ehci, async, EST_FETCHENTRY);
1807     return 1;
1808 }
1809 
1810 /* Section 4.10.2 - paragraph 3 */
1811 static int ehci_state_advqueue(EHCIQueue *q)
1812 {
1813 #if 0
1814     /* TO-DO: 4.10.2 - paragraph 2
1815      * if I-bit is set to 1 and QH is not active
1816      * go to horizontal QH
1817      */
1818     if (I-bit set) {
1819         ehci_set_state(ehci, async, EST_HORIZONTALQH);
1820         goto out;
1821     }
1822 #endif
1823 
1824     /*
1825      * want data and alt-next qTD is valid
1826      */
1827     if (((q->qh.token & QTD_TOKEN_TBYTES_MASK) != 0) &&
1828         (NLPTR_TBIT(q->qh.altnext_qtd) == 0)) {
1829         q->qtdaddr = q->qh.altnext_qtd;
1830         ehci_set_state(q->ehci, q->async, EST_FETCHQTD);
1831 
1832     /*
1833      *  next qTD is valid
1834      */
1835     } else if (NLPTR_TBIT(q->qh.next_qtd) == 0) {
1836         q->qtdaddr = q->qh.next_qtd;
1837         ehci_set_state(q->ehci, q->async, EST_FETCHQTD);
1838 
1839     /*
1840      *  no valid qTD, try next QH
1841      */
1842     } else {
1843         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1844     }
1845 
1846     return 1;
1847 }
1848 
1849 /* Section 4.10.2 - paragraph 4 */
1850 static int ehci_state_fetchqtd(EHCIQueue *q)
1851 {
1852     EHCIqtd qtd;
1853     EHCIPacket *p;
1854     int again = 1;
1855 
1856     if (get_dwords(q->ehci, NLPTR_GET(q->qtdaddr), (uint32_t *) &qtd,
1857                    sizeof(EHCIqtd) >> 2) < 0) {
1858         return 0;
1859     }
1860     ehci_trace_qtd(q, NLPTR_GET(q->qtdaddr), &qtd);
1861 
1862     p = QTAILQ_FIRST(&q->packets);
1863     if (p != NULL) {
1864         if (!ehci_verify_qtd(p, &qtd)) {
1865             ehci_cancel_queue(q);
1866             if (qtd.token & QTD_TOKEN_ACTIVE) {
1867                 ehci_trace_guest_bug(q->ehci, "guest updated active qTD");
1868             }
1869             p = NULL;
1870         } else {
1871             p->qtd = qtd;
1872             ehci_qh_do_overlay(q);
1873         }
1874     }
1875 
1876     if (!(qtd.token & QTD_TOKEN_ACTIVE)) {
1877         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1878     } else if (p != NULL) {
1879         switch (p->async) {
1880         case EHCI_ASYNC_NONE:
1881         case EHCI_ASYNC_INITIALIZED:
1882             /* Not yet executed (MULT), or previously nacked (int) packet */
1883             ehci_set_state(q->ehci, q->async, EST_EXECUTE);
1884             break;
1885         case EHCI_ASYNC_INFLIGHT:
1886             /* Check if the guest has added new tds to the queue */
1887             again = ehci_fill_queue(QTAILQ_LAST(&q->packets, pkts_head));
1888             /* Unfinished async handled packet, go horizontal */
1889             ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1890             break;
1891         case EHCI_ASYNC_FINISHED:
1892             /* Complete executing of the packet */
1893             ehci_set_state(q->ehci, q->async, EST_EXECUTING);
1894             break;
1895         }
1896     } else {
1897         p = ehci_alloc_packet(q);
1898         p->qtdaddr = q->qtdaddr;
1899         p->qtd = qtd;
1900         ehci_set_state(q->ehci, q->async, EST_EXECUTE);
1901     }
1902 
1903     return again;
1904 }
1905 
1906 static int ehci_state_horizqh(EHCIQueue *q)
1907 {
1908     int again = 0;
1909 
1910     if (ehci_get_fetch_addr(q->ehci, q->async) != q->qh.next) {
1911         ehci_set_fetch_addr(q->ehci, q->async, q->qh.next);
1912         ehci_set_state(q->ehci, q->async, EST_FETCHENTRY);
1913         again = 1;
1914     } else {
1915         ehci_set_state(q->ehci, q->async, EST_ACTIVE);
1916     }
1917 
1918     return again;
1919 }
1920 
1921 /* Returns "again" */
1922 static int ehci_fill_queue(EHCIPacket *p)
1923 {
1924     USBEndpoint *ep = p->packet.ep;
1925     EHCIQueue *q = p->queue;
1926     EHCIqtd qtd = p->qtd;
1927     uint32_t qtdaddr;
1928 
1929     for (;;) {
1930         if (NLPTR_TBIT(qtd.next) != 0) {
1931             break;
1932         }
1933         qtdaddr = qtd.next;
1934         /*
1935          * Detect circular td lists, Windows creates these, counting on the
1936          * active bit going low after execution to make the queue stop.
1937          */
1938         QTAILQ_FOREACH(p, &q->packets, next) {
1939             if (p->qtdaddr == qtdaddr) {
1940                 goto leave;
1941             }
1942         }
1943         if (get_dwords(q->ehci, NLPTR_GET(qtdaddr),
1944                        (uint32_t *) &qtd, sizeof(EHCIqtd) >> 2) < 0) {
1945             return -1;
1946         }
1947         ehci_trace_qtd(q, NLPTR_GET(qtdaddr), &qtd);
1948         if (!(qtd.token & QTD_TOKEN_ACTIVE)) {
1949             break;
1950         }
1951         if (!ehci_verify_pid(q, &qtd)) {
1952             ehci_trace_guest_bug(q->ehci, "guest queued token with wrong pid");
1953             break;
1954         }
1955         p = ehci_alloc_packet(q);
1956         p->qtdaddr = qtdaddr;
1957         p->qtd = qtd;
1958         if (ehci_execute(p, "queue") == -1) {
1959             return -1;
1960         }
1961         assert(p->packet.status == USB_RET_ASYNC);
1962         p->async = EHCI_ASYNC_INFLIGHT;
1963     }
1964 leave:
1965     usb_device_flush_ep_queue(ep->dev, ep);
1966     return 1;
1967 }
1968 
1969 static int ehci_state_execute(EHCIQueue *q)
1970 {
1971     EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1972     int again = 0;
1973 
1974     assert(p != NULL);
1975     assert(p->qtdaddr == q->qtdaddr);
1976 
1977     if (ehci_qh_do_overlay(q) != 0) {
1978         return -1;
1979     }
1980 
1981     // TODO verify enough time remains in the uframe as in 4.4.1.1
1982     // TODO write back ptr to async list when done or out of time
1983 
1984     /* 4.10.3, bottom of page 82, go horizontal on transaction counter == 0 */
1985     if (!q->async && q->transact_ctr == 0) {
1986         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1987         again = 1;
1988         goto out;
1989     }
1990 
1991     if (q->async) {
1992         ehci_set_usbsts(q->ehci, USBSTS_REC);
1993     }
1994 
1995     again = ehci_execute(p, "process");
1996     if (again == -1) {
1997         goto out;
1998     }
1999     if (p->packet.status == USB_RET_ASYNC) {
2000         ehci_flush_qh(q);
2001         trace_usb_ehci_packet_action(p->queue, p, "async");
2002         p->async = EHCI_ASYNC_INFLIGHT;
2003         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
2004         if (q->async) {
2005             again = ehci_fill_queue(p);
2006         } else {
2007             again = 1;
2008         }
2009         goto out;
2010     }
2011 
2012     ehci_set_state(q->ehci, q->async, EST_EXECUTING);
2013     again = 1;
2014 
2015 out:
2016     return again;
2017 }
2018 
2019 static int ehci_state_executing(EHCIQueue *q)
2020 {
2021     EHCIPacket *p = QTAILQ_FIRST(&q->packets);
2022 
2023     assert(p != NULL);
2024     assert(p->qtdaddr == q->qtdaddr);
2025 
2026     ehci_execute_complete(q);
2027 
2028     /* 4.10.3 */
2029     if (!q->async && q->transact_ctr > 0) {
2030         q->transact_ctr--;
2031     }
2032 
2033     /* 4.10.5 */
2034     if (p->packet.status == USB_RET_NAK) {
2035         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
2036     } else {
2037         ehci_set_state(q->ehci, q->async, EST_WRITEBACK);
2038     }
2039 
2040     ehci_flush_qh(q);
2041     return 1;
2042 }
2043 
2044 
2045 static int ehci_state_writeback(EHCIQueue *q)
2046 {
2047     EHCIPacket *p = QTAILQ_FIRST(&q->packets);
2048     uint32_t *qtd, addr;
2049     int again = 0;
2050 
2051     /*  Write back the QTD from the QH area */
2052     assert(p != NULL);
2053     assert(p->qtdaddr == q->qtdaddr);
2054 
2055     ehci_trace_qtd(q, NLPTR_GET(p->qtdaddr), (EHCIqtd *) &q->qh.next_qtd);
2056     qtd = (uint32_t *) &q->qh.next_qtd;
2057     addr = NLPTR_GET(p->qtdaddr);
2058     put_dwords(q->ehci, addr + 2 * sizeof(uint32_t), qtd + 2, 2);
2059     ehci_free_packet(p);
2060 
2061     /*
2062      * EHCI specs say go horizontal here.
2063      *
2064      * We can also advance the queue here for performance reasons.  We
2065      * need to take care to only take that shortcut in case we've
2066      * processed the qtd just written back without errors, i.e. halt
2067      * bit is clear.
2068      */
2069     if (q->qh.token & QTD_TOKEN_HALT) {
2070         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
2071         again = 1;
2072     } else {
2073         ehci_set_state(q->ehci, q->async, EST_ADVANCEQUEUE);
2074         again = 1;
2075     }
2076     return again;
2077 }
2078 
2079 /*
2080  * This is the state machine that is common to both async and periodic
2081  */
2082 
2083 static void ehci_advance_state(EHCIState *ehci, int async)
2084 {
2085     EHCIQueue *q = NULL;
2086     int again;
2087 
2088     do {
2089         switch(ehci_get_state(ehci, async)) {
2090         case EST_WAITLISTHEAD:
2091             again = ehci_state_waitlisthead(ehci, async);
2092             break;
2093 
2094         case EST_FETCHENTRY:
2095             again = ehci_state_fetchentry(ehci, async);
2096             break;
2097 
2098         case EST_FETCHQH:
2099             q = ehci_state_fetchqh(ehci, async);
2100             if (q != NULL) {
2101                 assert(q->async == async);
2102                 again = 1;
2103             } else {
2104                 again = 0;
2105             }
2106             break;
2107 
2108         case EST_FETCHITD:
2109             again = ehci_state_fetchitd(ehci, async);
2110             break;
2111 
2112         case EST_FETCHSITD:
2113             again = ehci_state_fetchsitd(ehci, async);
2114             break;
2115 
2116         case EST_ADVANCEQUEUE:
2117             assert(q != NULL);
2118             again = ehci_state_advqueue(q);
2119             break;
2120 
2121         case EST_FETCHQTD:
2122             assert(q != NULL);
2123             again = ehci_state_fetchqtd(q);
2124             break;
2125 
2126         case EST_HORIZONTALQH:
2127             assert(q != NULL);
2128             again = ehci_state_horizqh(q);
2129             break;
2130 
2131         case EST_EXECUTE:
2132             assert(q != NULL);
2133             again = ehci_state_execute(q);
2134             if (async) {
2135                 ehci->async_stepdown = 0;
2136             }
2137             break;
2138 
2139         case EST_EXECUTING:
2140             assert(q != NULL);
2141             if (async) {
2142                 ehci->async_stepdown = 0;
2143             }
2144             again = ehci_state_executing(q);
2145             break;
2146 
2147         case EST_WRITEBACK:
2148             assert(q != NULL);
2149             again = ehci_state_writeback(q);
2150             if (!async) {
2151                 ehci->periodic_sched_active = PERIODIC_ACTIVE;
2152             }
2153             break;
2154 
2155         default:
2156             fprintf(stderr, "Bad state!\n");
2157             again = -1;
2158             g_assert_not_reached();
2159             break;
2160         }
2161 
2162         if (again < 0) {
2163             fprintf(stderr, "processing error - resetting ehci HC\n");
2164             ehci_reset(ehci);
2165             again = 0;
2166         }
2167     }
2168     while (again);
2169 }
2170 
2171 static void ehci_advance_async_state(EHCIState *ehci)
2172 {
2173     const int async = 1;
2174 
2175     switch(ehci_get_state(ehci, async)) {
2176     case EST_INACTIVE:
2177         if (!ehci_async_enabled(ehci)) {
2178             break;
2179         }
2180         ehci_set_state(ehci, async, EST_ACTIVE);
2181         // No break, fall through to ACTIVE
2182 
2183     case EST_ACTIVE:
2184         if (!ehci_async_enabled(ehci)) {
2185             ehci_queues_rip_all(ehci, async);
2186             ehci_set_state(ehci, async, EST_INACTIVE);
2187             break;
2188         }
2189 
2190         /* make sure guest has acknowledged the doorbell interrupt */
2191         /* TO-DO: is this really needed? */
2192         if (ehci->usbsts & USBSTS_IAA) {
2193             DPRINTF("IAA status bit still set.\n");
2194             break;
2195         }
2196 
2197         /* check that address register has been set */
2198         if (ehci->asynclistaddr == 0) {
2199             break;
2200         }
2201 
2202         ehci_set_state(ehci, async, EST_WAITLISTHEAD);
2203         ehci_advance_state(ehci, async);
2204 
2205         /* If the doorbell is set, the guest wants to make a change to the
2206          * schedule. The host controller needs to release cached data.
2207          * (section 4.8.2)
2208          */
2209         if (ehci->usbcmd & USBCMD_IAAD) {
2210             /* Remove all unseen qhs from the async qhs queue */
2211             ehci_queues_rip_unseen(ehci, async);
2212             trace_usb_ehci_doorbell_ack();
2213             ehci->usbcmd &= ~USBCMD_IAAD;
2214             ehci_raise_irq(ehci, USBSTS_IAA);
2215         }
2216         break;
2217 
2218     default:
2219         /* this should only be due to a developer mistake */
2220         fprintf(stderr, "ehci: Bad asynchronous state %d. "
2221                 "Resetting to active\n", ehci->astate);
2222         g_assert_not_reached();
2223     }
2224 }
2225 
2226 static void ehci_advance_periodic_state(EHCIState *ehci)
2227 {
2228     uint32_t entry;
2229     uint32_t list;
2230     const int async = 0;
2231 
2232     // 4.6
2233 
2234     switch(ehci_get_state(ehci, async)) {
2235     case EST_INACTIVE:
2236         if (!(ehci->frindex & 7) && ehci_periodic_enabled(ehci)) {
2237             ehci_set_state(ehci, async, EST_ACTIVE);
2238             // No break, fall through to ACTIVE
2239         } else
2240             break;
2241 
2242     case EST_ACTIVE:
2243         if (!(ehci->frindex & 7) && !ehci_periodic_enabled(ehci)) {
2244             ehci_queues_rip_all(ehci, async);
2245             ehci_set_state(ehci, async, EST_INACTIVE);
2246             break;
2247         }
2248 
2249         list = ehci->periodiclistbase & 0xfffff000;
2250         /* check that register has been set */
2251         if (list == 0) {
2252             break;
2253         }
2254         list |= ((ehci->frindex & 0x1ff8) >> 1);
2255 
2256         if (get_dwords(ehci, list, &entry, 1) < 0) {
2257             break;
2258         }
2259 
2260         DPRINTF("PERIODIC state adv fr=%d.  [%08X] -> %08X\n",
2261                 ehci->frindex / 8, list, entry);
2262         ehci_set_fetch_addr(ehci, async,entry);
2263         ehci_set_state(ehci, async, EST_FETCHENTRY);
2264         ehci_advance_state(ehci, async);
2265         ehci_queues_rip_unused(ehci, async);
2266         break;
2267 
2268     default:
2269         /* this should only be due to a developer mistake */
2270         fprintf(stderr, "ehci: Bad periodic state %d. "
2271                 "Resetting to active\n", ehci->pstate);
2272         g_assert_not_reached();
2273     }
2274 }
2275 
2276 static void ehci_update_frindex(EHCIState *ehci, int uframes)
2277 {
2278     int i;
2279 
2280     if (!ehci_enabled(ehci) && ehci->pstate == EST_INACTIVE) {
2281         return;
2282     }
2283 
2284     for (i = 0; i < uframes; i++) {
2285         ehci->frindex++;
2286 
2287         if (ehci->frindex == 0x00002000) {
2288             ehci_raise_irq(ehci, USBSTS_FLR);
2289         }
2290 
2291         if (ehci->frindex == 0x00004000) {
2292             ehci_raise_irq(ehci, USBSTS_FLR);
2293             ehci->frindex = 0;
2294             if (ehci->usbsts_frindex >= 0x00004000) {
2295                 ehci->usbsts_frindex -= 0x00004000;
2296             } else {
2297                 ehci->usbsts_frindex = 0;
2298             }
2299         }
2300     }
2301 }
2302 
2303 static void ehci_frame_timer(void *opaque)
2304 {
2305     EHCIState *ehci = opaque;
2306     int need_timer = 0;
2307     int64_t expire_time, t_now;
2308     uint64_t ns_elapsed;
2309     int uframes, skipped_uframes;
2310     int i;
2311 
2312     t_now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2313     ns_elapsed = t_now - ehci->last_run_ns;
2314     uframes = ns_elapsed / UFRAME_TIMER_NS;
2315 
2316     if (ehci_periodic_enabled(ehci) || ehci->pstate != EST_INACTIVE) {
2317         need_timer++;
2318 
2319         if (uframes > (ehci->maxframes * 8)) {
2320             skipped_uframes = uframes - (ehci->maxframes * 8);
2321             ehci_update_frindex(ehci, skipped_uframes);
2322             ehci->last_run_ns += UFRAME_TIMER_NS * skipped_uframes;
2323             uframes -= skipped_uframes;
2324             DPRINTF("WARNING - EHCI skipped %d uframes\n", skipped_uframes);
2325         }
2326 
2327         for (i = 0; i < uframes; i++) {
2328             /*
2329              * If we're running behind schedule, we should not catch up
2330              * too fast, as that will make some guests unhappy:
2331              * 1) We must process a minimum of MIN_UFR_PER_TICK frames,
2332              *    otherwise we will never catch up
2333              * 2) Process frames until the guest has requested an irq (IOC)
2334              */
2335             if (i >= MIN_UFR_PER_TICK) {
2336                 ehci_commit_irq(ehci);
2337                 if ((ehci->usbsts & USBINTR_MASK) & ehci->usbintr) {
2338                     break;
2339                 }
2340             }
2341             if (ehci->periodic_sched_active) {
2342                 ehci->periodic_sched_active--;
2343             }
2344             ehci_update_frindex(ehci, 1);
2345             if ((ehci->frindex & 7) == 0) {
2346                 ehci_advance_periodic_state(ehci);
2347             }
2348             ehci->last_run_ns += UFRAME_TIMER_NS;
2349         }
2350     } else {
2351         ehci->periodic_sched_active = 0;
2352         ehci_update_frindex(ehci, uframes);
2353         ehci->last_run_ns += UFRAME_TIMER_NS * uframes;
2354     }
2355 
2356     if (ehci->periodic_sched_active) {
2357         ehci->async_stepdown = 0;
2358     } else if (ehci->async_stepdown < ehci->maxframes / 2) {
2359         ehci->async_stepdown++;
2360     }
2361 
2362     /*  Async is not inside loop since it executes everything it can once
2363      *  called
2364      */
2365     if (ehci_async_enabled(ehci) || ehci->astate != EST_INACTIVE) {
2366         need_timer++;
2367         ehci_advance_async_state(ehci);
2368     }
2369 
2370     ehci_commit_irq(ehci);
2371     if (ehci->usbsts_pending) {
2372         need_timer++;
2373         ehci->async_stepdown = 0;
2374     }
2375 
2376     if (ehci_enabled(ehci) && (ehci->usbintr & USBSTS_FLR)) {
2377         need_timer++;
2378     }
2379 
2380     if (need_timer) {
2381         /* If we've raised int, we speed up the timer, so that we quickly
2382          * notice any new packets queued up in response */
2383         if (ehci->int_req_by_async && (ehci->usbsts & USBSTS_INT)) {
2384             expire_time = t_now + get_ticks_per_sec() / (FRAME_TIMER_FREQ * 4);
2385             ehci->int_req_by_async = false;
2386         } else {
2387             expire_time = t_now + (get_ticks_per_sec()
2388                                * (ehci->async_stepdown+1) / FRAME_TIMER_FREQ);
2389         }
2390         timer_mod(ehci->frame_timer, expire_time);
2391     }
2392 }
2393 
2394 static const MemoryRegionOps ehci_mmio_caps_ops = {
2395     .read = ehci_caps_read,
2396     .valid.min_access_size = 1,
2397     .valid.max_access_size = 4,
2398     .impl.min_access_size = 1,
2399     .impl.max_access_size = 1,
2400     .endianness = DEVICE_LITTLE_ENDIAN,
2401 };
2402 
2403 static const MemoryRegionOps ehci_mmio_opreg_ops = {
2404     .read = ehci_opreg_read,
2405     .write = ehci_opreg_write,
2406     .valid.min_access_size = 4,
2407     .valid.max_access_size = 4,
2408     .endianness = DEVICE_LITTLE_ENDIAN,
2409 };
2410 
2411 static const MemoryRegionOps ehci_mmio_port_ops = {
2412     .read = ehci_port_read,
2413     .write = ehci_port_write,
2414     .valid.min_access_size = 4,
2415     .valid.max_access_size = 4,
2416     .endianness = DEVICE_LITTLE_ENDIAN,
2417 };
2418 
2419 static USBPortOps ehci_port_ops = {
2420     .attach = ehci_attach,
2421     .detach = ehci_detach,
2422     .child_detach = ehci_child_detach,
2423     .wakeup = ehci_wakeup,
2424     .complete = ehci_async_complete_packet,
2425 };
2426 
2427 static USBBusOps ehci_bus_ops = {
2428     .register_companion = ehci_register_companion,
2429     .wakeup_endpoint = ehci_wakeup_endpoint,
2430 };
2431 
2432 static void usb_ehci_pre_save(void *opaque)
2433 {
2434     EHCIState *ehci = opaque;
2435     uint32_t new_frindex;
2436 
2437     /* Round down frindex to a multiple of 8 for migration compatibility */
2438     new_frindex = ehci->frindex & ~7;
2439     ehci->last_run_ns -= (ehci->frindex - new_frindex) * UFRAME_TIMER_NS;
2440     ehci->frindex = new_frindex;
2441 }
2442 
2443 static int usb_ehci_post_load(void *opaque, int version_id)
2444 {
2445     EHCIState *s = opaque;
2446     int i;
2447 
2448     for (i = 0; i < NB_PORTS; i++) {
2449         USBPort *companion = s->companion_ports[i];
2450         if (companion == NULL) {
2451             continue;
2452         }
2453         if (s->portsc[i] & PORTSC_POWNER) {
2454             companion->dev = s->ports[i].dev;
2455         } else {
2456             companion->dev = NULL;
2457         }
2458     }
2459 
2460     return 0;
2461 }
2462 
2463 static void usb_ehci_vm_state_change(void *opaque, int running, RunState state)
2464 {
2465     EHCIState *ehci = opaque;
2466 
2467     /*
2468      * We don't migrate the EHCIQueue-s, instead we rebuild them for the
2469      * schedule in guest memory. We must do the rebuilt ASAP, so that
2470      * USB-devices which have async handled packages have a packet in the
2471      * ep queue to match the completion with.
2472      */
2473     if (state == RUN_STATE_RUNNING) {
2474         ehci_advance_async_state(ehci);
2475     }
2476 
2477     /*
2478      * The schedule rebuilt from guest memory could cause the migration dest
2479      * to miss a QH unlink, and fail to cancel packets, since the unlinked QH
2480      * will never have existed on the destination. Therefor we must flush the
2481      * async schedule on savevm to catch any not yet noticed unlinks.
2482      */
2483     if (state == RUN_STATE_SAVE_VM) {
2484         ehci_advance_async_state(ehci);
2485         ehci_queues_rip_unseen(ehci, 1);
2486     }
2487 }
2488 
2489 const VMStateDescription vmstate_ehci = {
2490     .name        = "ehci-core",
2491     .version_id  = 2,
2492     .minimum_version_id  = 1,
2493     .pre_save    = usb_ehci_pre_save,
2494     .post_load   = usb_ehci_post_load,
2495     .fields      = (VMStateField[]) {
2496         /* mmio registers */
2497         VMSTATE_UINT32(usbcmd, EHCIState),
2498         VMSTATE_UINT32(usbsts, EHCIState),
2499         VMSTATE_UINT32_V(usbsts_pending, EHCIState, 2),
2500         VMSTATE_UINT32_V(usbsts_frindex, EHCIState, 2),
2501         VMSTATE_UINT32(usbintr, EHCIState),
2502         VMSTATE_UINT32(frindex, EHCIState),
2503         VMSTATE_UINT32(ctrldssegment, EHCIState),
2504         VMSTATE_UINT32(periodiclistbase, EHCIState),
2505         VMSTATE_UINT32(asynclistaddr, EHCIState),
2506         VMSTATE_UINT32(configflag, EHCIState),
2507         VMSTATE_UINT32(portsc[0], EHCIState),
2508         VMSTATE_UINT32(portsc[1], EHCIState),
2509         VMSTATE_UINT32(portsc[2], EHCIState),
2510         VMSTATE_UINT32(portsc[3], EHCIState),
2511         VMSTATE_UINT32(portsc[4], EHCIState),
2512         VMSTATE_UINT32(portsc[5], EHCIState),
2513         /* frame timer */
2514         VMSTATE_TIMER(frame_timer, EHCIState),
2515         VMSTATE_UINT64(last_run_ns, EHCIState),
2516         VMSTATE_UINT32(async_stepdown, EHCIState),
2517         /* schedule state */
2518         VMSTATE_UINT32(astate, EHCIState),
2519         VMSTATE_UINT32(pstate, EHCIState),
2520         VMSTATE_UINT32(a_fetch_addr, EHCIState),
2521         VMSTATE_UINT32(p_fetch_addr, EHCIState),
2522         VMSTATE_END_OF_LIST()
2523     }
2524 };
2525 
2526 void usb_ehci_realize(EHCIState *s, DeviceState *dev, Error **errp)
2527 {
2528     int i;
2529 
2530     if (s->portnr > NB_PORTS) {
2531         error_setg(errp, "Too many ports! Max. port number is %d.",
2532                    NB_PORTS);
2533         return;
2534     }
2535 
2536     usb_bus_new(&s->bus, sizeof(s->bus), &ehci_bus_ops, dev);
2537     for (i = 0; i < s->portnr; i++) {
2538         usb_register_port(&s->bus, &s->ports[i], s, i, &ehci_port_ops,
2539                           USB_SPEED_MASK_HIGH);
2540         s->ports[i].dev = 0;
2541     }
2542 
2543     s->frame_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, ehci_frame_timer, s);
2544     s->async_bh = qemu_bh_new(ehci_frame_timer, s);
2545     s->device = dev;
2546 
2547     qemu_register_reset(ehci_reset, s);
2548     qemu_add_vm_change_state_handler(usb_ehci_vm_state_change, s);
2549 }
2550 
2551 void usb_ehci_init(EHCIState *s, DeviceState *dev)
2552 {
2553     /* 2.2 host controller interface version */
2554     s->caps[0x00] = (uint8_t)(s->opregbase - s->capsbase);
2555     s->caps[0x01] = 0x00;
2556     s->caps[0x02] = 0x00;
2557     s->caps[0x03] = 0x01;        /* HC version */
2558     s->caps[0x04] = s->portnr;   /* Number of downstream ports */
2559     s->caps[0x05] = 0x00;        /* No companion ports at present */
2560     s->caps[0x06] = 0x00;
2561     s->caps[0x07] = 0x00;
2562     s->caps[0x08] = 0x80;        /* We can cache whole frame, no 64-bit */
2563     s->caps[0x0a] = 0x00;
2564     s->caps[0x0b] = 0x00;
2565 
2566     QTAILQ_INIT(&s->aqueues);
2567     QTAILQ_INIT(&s->pqueues);
2568     usb_packet_init(&s->ipacket);
2569 
2570     memory_region_init(&s->mem, OBJECT(dev), "ehci", MMIO_SIZE);
2571     memory_region_init_io(&s->mem_caps, OBJECT(dev), &ehci_mmio_caps_ops, s,
2572                           "capabilities", CAPA_SIZE);
2573     memory_region_init_io(&s->mem_opreg, OBJECT(dev), &ehci_mmio_opreg_ops, s,
2574                           "operational", s->portscbase);
2575     memory_region_init_io(&s->mem_ports, OBJECT(dev), &ehci_mmio_port_ops, s,
2576                           "ports", 4 * s->portnr);
2577 
2578     memory_region_add_subregion(&s->mem, s->capsbase, &s->mem_caps);
2579     memory_region_add_subregion(&s->mem, s->opregbase, &s->mem_opreg);
2580     memory_region_add_subregion(&s->mem, s->opregbase + s->portscbase,
2581                                 &s->mem_ports);
2582 }
2583 
2584 /*
2585  * vim: expandtab ts=4
2586  */
2587