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