]> Git Repo - qemu.git/blob - hw/usb/hcd-ehci.c
trace: Remove trace.h from hw/usb/hcd-ehci.h (less dependencies)
[qemu.git] / hw / usb / hcd-ehci.c
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 <[email protected]>
9  * Hans de Goede <[email protected]>
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     qemu_bh_schedule(s->async_bh);
841 }
842
843 static int ehci_register_companion(USBBus *bus, USBPort *ports[],
844                                    uint32_t portcount, uint32_t firstport)
845 {
846     EHCIState *s = container_of(bus, EHCIState, bus);
847     uint32_t i;
848
849     if (firstport + portcount > NB_PORTS) {
850         qerror_report(QERR_INVALID_PARAMETER_VALUE, "firstport",
851                       "firstport on masterbus");
852         error_printf_unless_qmp(
853             "firstport value of %u makes companion take ports %u - %u, which "
854             "is outside of the valid range of 0 - %u\n", firstport, firstport,
855             firstport + portcount - 1, NB_PORTS - 1);
856         return -1;
857     }
858
859     for (i = 0; i < portcount; i++) {
860         if (s->companion_ports[firstport + i]) {
861             qerror_report(QERR_INVALID_PARAMETER_VALUE, "masterbus",
862                           "an USB masterbus");
863             error_printf_unless_qmp(
864                 "port %u on masterbus %s already has a companion assigned\n",
865                 firstport + i, bus->qbus.name);
866             return -1;
867         }
868     }
869
870     for (i = 0; i < portcount; i++) {
871         s->companion_ports[firstport + i] = ports[i];
872         s->ports[firstport + i].speedmask |=
873             USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL;
874         /* Ensure devs attached before the initial reset go to the companion */
875         s->portsc[firstport + i] = PORTSC_POWNER;
876     }
877
878     s->companion_count++;
879     s->caps[0x05] = (s->companion_count << 4) | portcount;
880
881     return 0;
882 }
883
884 static void ehci_wakeup_endpoint(USBBus *bus, USBEndpoint *ep,
885                                  unsigned int stream)
886 {
887     EHCIState *s = container_of(bus, EHCIState, bus);
888     uint32_t portsc = s->portsc[ep->dev->port->index];
889
890     if (portsc & PORTSC_POWNER) {
891         return;
892     }
893
894     s->periodic_sched_active = PERIODIC_ACTIVE;
895     qemu_bh_schedule(s->async_bh);
896 }
897
898 static USBDevice *ehci_find_device(EHCIState *ehci, uint8_t addr)
899 {
900     USBDevice *dev;
901     USBPort *port;
902     int i;
903
904     for (i = 0; i < NB_PORTS; i++) {
905         port = &ehci->ports[i];
906         if (!(ehci->portsc[i] & PORTSC_PED)) {
907             DPRINTF("Port %d not enabled\n", i);
908             continue;
909         }
910         dev = usb_find_device(port, addr);
911         if (dev != NULL) {
912             return dev;
913         }
914     }
915     return NULL;
916 }
917
918 /* 4.1 host controller initialization */
919 static void ehci_reset(void *opaque)
920 {
921     EHCIState *s = opaque;
922     int i;
923     USBDevice *devs[NB_PORTS];
924
925     trace_usb_ehci_reset();
926
927     /*
928      * Do the detach before touching portsc, so that it correctly gets send to
929      * us or to our companion based on PORTSC_POWNER before the reset.
930      */
931     for(i = 0; i < NB_PORTS; i++) {
932         devs[i] = s->ports[i].dev;
933         if (devs[i] && devs[i]->attached) {
934             usb_detach(&s->ports[i]);
935         }
936     }
937
938     memset(&s->opreg, 0x00, sizeof(s->opreg));
939     memset(&s->portsc, 0x00, sizeof(s->portsc));
940
941     s->usbcmd = NB_MAXINTRATE << USBCMD_ITC_SH;
942     s->usbsts = USBSTS_HALT;
943     s->usbsts_pending = 0;
944     s->usbsts_frindex = 0;
945
946     s->astate = EST_INACTIVE;
947     s->pstate = EST_INACTIVE;
948
949     for(i = 0; i < NB_PORTS; i++) {
950         if (s->companion_ports[i]) {
951             s->portsc[i] = PORTSC_POWNER | PORTSC_PPOWER;
952         } else {
953             s->portsc[i] = PORTSC_PPOWER;
954         }
955         if (devs[i] && devs[i]->attached) {
956             usb_attach(&s->ports[i]);
957             usb_device_reset(devs[i]);
958         }
959     }
960     ehci_queues_rip_all(s, 0);
961     ehci_queues_rip_all(s, 1);
962     timer_del(s->frame_timer);
963     qemu_bh_cancel(s->async_bh);
964 }
965
966 static uint64_t ehci_caps_read(void *ptr, hwaddr addr,
967                                unsigned size)
968 {
969     EHCIState *s = ptr;
970     return s->caps[addr];
971 }
972
973 static uint64_t ehci_opreg_read(void *ptr, hwaddr addr,
974                                 unsigned size)
975 {
976     EHCIState *s = ptr;
977     uint32_t val;
978
979     switch (addr) {
980     case FRINDEX:
981         /* Round down to mult of 8, else it can go backwards on migration */
982         val = s->frindex & ~7;
983         break;
984     default:
985         val = s->opreg[addr >> 2];
986     }
987
988     trace_usb_ehci_opreg_read(addr + s->opregbase, addr2str(addr), val);
989     return val;
990 }
991
992 static uint64_t ehci_port_read(void *ptr, hwaddr addr,
993                                unsigned size)
994 {
995     EHCIState *s = ptr;
996     uint32_t val;
997
998     val = s->portsc[addr >> 2];
999     trace_usb_ehci_portsc_read(addr + s->portscbase, addr >> 2, val);
1000     return val;
1001 }
1002
1003 static void handle_port_owner_write(EHCIState *s, int port, uint32_t owner)
1004 {
1005     USBDevice *dev = s->ports[port].dev;
1006     uint32_t *portsc = &s->portsc[port];
1007     uint32_t orig;
1008
1009     if (s->companion_ports[port] == NULL)
1010         return;
1011
1012     owner = owner & PORTSC_POWNER;
1013     orig  = *portsc & PORTSC_POWNER;
1014
1015     if (!(owner ^ orig)) {
1016         return;
1017     }
1018
1019     if (dev && dev->attached) {
1020         usb_detach(&s->ports[port]);
1021     }
1022
1023     *portsc &= ~PORTSC_POWNER;
1024     *portsc |= owner;
1025
1026     if (dev && dev->attached) {
1027         usb_attach(&s->ports[port]);
1028     }
1029 }
1030
1031 static void ehci_port_write(void *ptr, hwaddr addr,
1032                             uint64_t val, unsigned size)
1033 {
1034     EHCIState *s = ptr;
1035     int port = addr >> 2;
1036     uint32_t *portsc = &s->portsc[port];
1037     uint32_t old = *portsc;
1038     USBDevice *dev = s->ports[port].dev;
1039
1040     trace_usb_ehci_portsc_write(addr + s->portscbase, addr >> 2, val);
1041
1042     /* Clear rwc bits */
1043     *portsc &= ~(val & PORTSC_RWC_MASK);
1044     /* The guest may clear, but not set the PED bit */
1045     *portsc &= val | ~PORTSC_PED;
1046     /* POWNER is masked out by RO_MASK as it is RO when we've no companion */
1047     handle_port_owner_write(s, port, val);
1048     /* And finally apply RO_MASK */
1049     val &= PORTSC_RO_MASK;
1050
1051     if ((val & PORTSC_PRESET) && !(*portsc & PORTSC_PRESET)) {
1052         trace_usb_ehci_port_reset(port, 1);
1053     }
1054
1055     if (!(val & PORTSC_PRESET) &&(*portsc & PORTSC_PRESET)) {
1056         trace_usb_ehci_port_reset(port, 0);
1057         if (dev && dev->attached) {
1058             usb_port_reset(&s->ports[port]);
1059             *portsc &= ~PORTSC_CSC;
1060         }
1061
1062         /*
1063          *  Table 2.16 Set the enable bit(and enable bit change) to indicate
1064          *  to SW that this port has a high speed device attached
1065          */
1066         if (dev && dev->attached && (dev->speedmask & USB_SPEED_MASK_HIGH)) {
1067             val |= PORTSC_PED;
1068         }
1069     }
1070
1071     *portsc &= ~PORTSC_RO_MASK;
1072     *portsc |= val;
1073     trace_usb_ehci_portsc_change(addr + s->portscbase, addr >> 2, *portsc, old);
1074 }
1075
1076 static void ehci_opreg_write(void *ptr, hwaddr addr,
1077                              uint64_t val, unsigned size)
1078 {
1079     EHCIState *s = ptr;
1080     uint32_t *mmio = s->opreg + (addr >> 2);
1081     uint32_t old = *mmio;
1082     int i;
1083
1084     trace_usb_ehci_opreg_write(addr + s->opregbase, addr2str(addr), val);
1085
1086     switch (addr) {
1087     case USBCMD:
1088         if (val & USBCMD_HCRESET) {
1089             ehci_reset(s);
1090             val = s->usbcmd;
1091             break;
1092         }
1093
1094         /* not supporting dynamic frame list size at the moment */
1095         if ((val & USBCMD_FLS) && !(s->usbcmd & USBCMD_FLS)) {
1096             fprintf(stderr, "attempt to set frame list size -- value %d\n",
1097                     (int)val & USBCMD_FLS);
1098             val &= ~USBCMD_FLS;
1099         }
1100
1101         if (val & USBCMD_IAAD) {
1102             /*
1103              * Process IAAD immediately, otherwise the Linux IAAD watchdog may
1104              * trigger and re-use a qh without us seeing the unlink.
1105              */
1106             s->async_stepdown = 0;
1107             qemu_bh_schedule(s->async_bh);
1108             trace_usb_ehci_doorbell_ring();
1109         }
1110
1111         if (((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & val) !=
1112             ((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & s->usbcmd)) {
1113             if (s->pstate == EST_INACTIVE) {
1114                 SET_LAST_RUN_CLOCK(s);
1115             }
1116             s->usbcmd = val; /* Set usbcmd for ehci_update_halt() */
1117             ehci_update_halt(s);
1118             s->async_stepdown = 0;
1119             qemu_bh_schedule(s->async_bh);
1120         }
1121         break;
1122
1123     case USBSTS:
1124         val &= USBSTS_RO_MASK;              // bits 6 through 31 are RO
1125         ehci_clear_usbsts(s, val);          // bits 0 through 5 are R/WC
1126         val = s->usbsts;
1127         ehci_update_irq(s);
1128         break;
1129
1130     case USBINTR:
1131         val &= USBINTR_MASK;
1132         if (ehci_enabled(s) && (USBSTS_FLR & val)) {
1133             qemu_bh_schedule(s->async_bh);
1134         }
1135         break;
1136
1137     case FRINDEX:
1138         val &= 0x00003fff; /* frindex is 14bits */
1139         s->usbsts_frindex = val;
1140         break;
1141
1142     case CONFIGFLAG:
1143         val &= 0x1;
1144         if (val) {
1145             for(i = 0; i < NB_PORTS; i++)
1146                 handle_port_owner_write(s, i, 0);
1147         }
1148         break;
1149
1150     case PERIODICLISTBASE:
1151         if (ehci_periodic_enabled(s)) {
1152             fprintf(stderr,
1153               "ehci: PERIODIC list base register set while periodic schedule\n"
1154               "      is enabled and HC is enabled\n");
1155         }
1156         break;
1157
1158     case ASYNCLISTADDR:
1159         if (ehci_async_enabled(s)) {
1160             fprintf(stderr,
1161               "ehci: ASYNC list address register set while async schedule\n"
1162               "      is enabled and HC is enabled\n");
1163         }
1164         break;
1165     }
1166
1167     *mmio = val;
1168     trace_usb_ehci_opreg_change(addr + s->opregbase, addr2str(addr),
1169                                 *mmio, old);
1170 }
1171
1172 /*
1173  *  Write the qh back to guest physical memory.  This step isn't
1174  *  in the EHCI spec but we need to do it since we don't share
1175  *  physical memory with our guest VM.
1176  *
1177  *  The first three dwords are read-only for the EHCI, so skip them
1178  *  when writing back the qh.
1179  */
1180 static void ehci_flush_qh(EHCIQueue *q)
1181 {
1182     uint32_t *qh = (uint32_t *) &q->qh;
1183     uint32_t dwords = sizeof(EHCIqh) >> 2;
1184     uint32_t addr = NLPTR_GET(q->qhaddr);
1185
1186     put_dwords(q->ehci, addr + 3 * sizeof(uint32_t), qh + 3, dwords - 3);
1187 }
1188
1189 // 4.10.2
1190
1191 static int ehci_qh_do_overlay(EHCIQueue *q)
1192 {
1193     EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1194     int i;
1195     int dtoggle;
1196     int ping;
1197     int eps;
1198     int reload;
1199
1200     assert(p != NULL);
1201     assert(p->qtdaddr == q->qtdaddr);
1202
1203     // remember values in fields to preserve in qh after overlay
1204
1205     dtoggle = q->qh.token & QTD_TOKEN_DTOGGLE;
1206     ping    = q->qh.token & QTD_TOKEN_PING;
1207
1208     q->qh.current_qtd = p->qtdaddr;
1209     q->qh.next_qtd    = p->qtd.next;
1210     q->qh.altnext_qtd = p->qtd.altnext;
1211     q->qh.token       = p->qtd.token;
1212
1213
1214     eps = get_field(q->qh.epchar, QH_EPCHAR_EPS);
1215     if (eps == EHCI_QH_EPS_HIGH) {
1216         q->qh.token &= ~QTD_TOKEN_PING;
1217         q->qh.token |= ping;
1218     }
1219
1220     reload = get_field(q->qh.epchar, QH_EPCHAR_RL);
1221     set_field(&q->qh.altnext_qtd, reload, QH_ALTNEXT_NAKCNT);
1222
1223     for (i = 0; i < 5; i++) {
1224         q->qh.bufptr[i] = p->qtd.bufptr[i];
1225     }
1226
1227     if (!(q->qh.epchar & QH_EPCHAR_DTC)) {
1228         // preserve QH DT bit
1229         q->qh.token &= ~QTD_TOKEN_DTOGGLE;
1230         q->qh.token |= dtoggle;
1231     }
1232
1233     q->qh.bufptr[1] &= ~BUFPTR_CPROGMASK_MASK;
1234     q->qh.bufptr[2] &= ~BUFPTR_FRAMETAG_MASK;
1235
1236     ehci_flush_qh(q);
1237
1238     return 0;
1239 }
1240
1241 static int ehci_init_transfer(EHCIPacket *p)
1242 {
1243     uint32_t cpage, offset, bytes, plen;
1244     dma_addr_t page;
1245
1246     cpage  = get_field(p->qtd.token, QTD_TOKEN_CPAGE);
1247     bytes  = get_field(p->qtd.token, QTD_TOKEN_TBYTES);
1248     offset = p->qtd.bufptr[0] & ~QTD_BUFPTR_MASK;
1249     qemu_sglist_init(&p->sgl, p->queue->ehci->device, 5, p->queue->ehci->as);
1250
1251     while (bytes > 0) {
1252         if (cpage > 4) {
1253             fprintf(stderr, "cpage out of range (%d)\n", cpage);
1254             return -1;
1255         }
1256
1257         page  = p->qtd.bufptr[cpage] & QTD_BUFPTR_MASK;
1258         page += offset;
1259         plen  = bytes;
1260         if (plen > 4096 - offset) {
1261             plen = 4096 - offset;
1262             offset = 0;
1263             cpage++;
1264         }
1265
1266         qemu_sglist_add(&p->sgl, page, plen);
1267         bytes -= plen;
1268     }
1269     return 0;
1270 }
1271
1272 static void ehci_finish_transfer(EHCIQueue *q, int len)
1273 {
1274     uint32_t cpage, offset;
1275
1276     if (len > 0) {
1277         /* update cpage & offset */
1278         cpage  = get_field(q->qh.token, QTD_TOKEN_CPAGE);
1279         offset = q->qh.bufptr[0] & ~QTD_BUFPTR_MASK;
1280
1281         offset += len;
1282         cpage  += offset >> QTD_BUFPTR_SH;
1283         offset &= ~QTD_BUFPTR_MASK;
1284
1285         set_field(&q->qh.token, cpage, QTD_TOKEN_CPAGE);
1286         q->qh.bufptr[0] &= QTD_BUFPTR_MASK;
1287         q->qh.bufptr[0] |= offset;
1288     }
1289 }
1290
1291 static void ehci_async_complete_packet(USBPort *port, USBPacket *packet)
1292 {
1293     EHCIPacket *p;
1294     EHCIState *s = port->opaque;
1295     uint32_t portsc = s->portsc[port->index];
1296
1297     if (portsc & PORTSC_POWNER) {
1298         USBPort *companion = s->companion_ports[port->index];
1299         companion->ops->complete(companion, packet);
1300         return;
1301     }
1302
1303     p = container_of(packet, EHCIPacket, packet);
1304     assert(p->async == EHCI_ASYNC_INFLIGHT);
1305
1306     if (packet->status == USB_RET_REMOVE_FROM_QUEUE) {
1307         trace_usb_ehci_packet_action(p->queue, p, "remove");
1308         ehci_free_packet(p);
1309         return;
1310     }
1311
1312     trace_usb_ehci_packet_action(p->queue, p, "wakeup");
1313     p->async = EHCI_ASYNC_FINISHED;
1314
1315     if (!p->queue->async) {
1316         s->periodic_sched_active = PERIODIC_ACTIVE;
1317     }
1318     qemu_bh_schedule(s->async_bh);
1319 }
1320
1321 static void ehci_execute_complete(EHCIQueue *q)
1322 {
1323     EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1324     uint32_t tbytes;
1325
1326     assert(p != NULL);
1327     assert(p->qtdaddr == q->qtdaddr);
1328     assert(p->async == EHCI_ASYNC_INITIALIZED ||
1329            p->async == EHCI_ASYNC_FINISHED);
1330
1331     DPRINTF("execute_complete: qhaddr 0x%x, next 0x%x, qtdaddr 0x%x, "
1332             "status %d, actual_length %d\n",
1333             q->qhaddr, q->qh.next, q->qtdaddr,
1334             p->packet.status, p->packet.actual_length);
1335
1336     switch (p->packet.status) {
1337     case USB_RET_SUCCESS:
1338         break;
1339     case USB_RET_IOERROR:
1340     case USB_RET_NODEV:
1341         q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_XACTERR);
1342         set_field(&q->qh.token, 0, QTD_TOKEN_CERR);
1343         ehci_raise_irq(q->ehci, USBSTS_ERRINT);
1344         break;
1345     case USB_RET_STALL:
1346         q->qh.token |= QTD_TOKEN_HALT;
1347         ehci_raise_irq(q->ehci, USBSTS_ERRINT);
1348         break;
1349     case USB_RET_NAK:
1350         set_field(&q->qh.altnext_qtd, 0, QH_ALTNEXT_NAKCNT);
1351         return; /* We're not done yet with this transaction */
1352     case USB_RET_BABBLE:
1353         q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_BABBLE);
1354         ehci_raise_irq(q->ehci, USBSTS_ERRINT);
1355         break;
1356     default:
1357         /* should not be triggerable */
1358         fprintf(stderr, "USB invalid response %d\n", p->packet.status);
1359         g_assert_not_reached();
1360         break;
1361     }
1362
1363     /* TODO check 4.12 for splits */
1364     tbytes = get_field(q->qh.token, QTD_TOKEN_TBYTES);
1365     if (tbytes && p->pid == USB_TOKEN_IN) {
1366         tbytes -= p->packet.actual_length;
1367         if (tbytes) {
1368             /* 4.15.1.2 must raise int on a short input packet */
1369             ehci_raise_irq(q->ehci, USBSTS_INT);
1370             if (q->async) {
1371                 q->ehci->int_req_by_async = true;
1372             }
1373         }
1374     } else {
1375         tbytes = 0;
1376     }
1377     DPRINTF("updating tbytes to %d\n", tbytes);
1378     set_field(&q->qh.token, tbytes, QTD_TOKEN_TBYTES);
1379
1380     ehci_finish_transfer(q, p->packet.actual_length);
1381     usb_packet_unmap(&p->packet, &p->sgl);
1382     qemu_sglist_destroy(&p->sgl);
1383     p->async = EHCI_ASYNC_NONE;
1384
1385     q->qh.token ^= QTD_TOKEN_DTOGGLE;
1386     q->qh.token &= ~QTD_TOKEN_ACTIVE;
1387
1388     if (q->qh.token & QTD_TOKEN_IOC) {
1389         ehci_raise_irq(q->ehci, USBSTS_INT);
1390         if (q->async) {
1391             q->ehci->int_req_by_async = true;
1392         }
1393     }
1394 }
1395
1396 /* 4.10.3 returns "again" */
1397 static int ehci_execute(EHCIPacket *p, const char *action)
1398 {
1399     USBEndpoint *ep;
1400     int endp;
1401     bool spd;
1402
1403     assert(p->async == EHCI_ASYNC_NONE ||
1404            p->async == EHCI_ASYNC_INITIALIZED);
1405
1406     if (!(p->qtd.token & QTD_TOKEN_ACTIVE)) {
1407         fprintf(stderr, "Attempting to execute inactive qtd\n");
1408         return -1;
1409     }
1410
1411     if (get_field(p->qtd.token, QTD_TOKEN_TBYTES) > BUFF_SIZE) {
1412         ehci_trace_guest_bug(p->queue->ehci,
1413                              "guest requested more bytes than allowed");
1414         return -1;
1415     }
1416
1417     if (!ehci_verify_pid(p->queue, &p->qtd)) {
1418         ehci_queue_stopped(p->queue); /* Mark the ep in the prev dir stopped */
1419     }
1420     p->pid = ehci_get_pid(&p->qtd);
1421     p->queue->last_pid = p->pid;
1422     endp = get_field(p->queue->qh.epchar, QH_EPCHAR_EP);
1423     ep = usb_ep_get(p->queue->dev, p->pid, endp);
1424
1425     if (p->async == EHCI_ASYNC_NONE) {
1426         if (ehci_init_transfer(p) != 0) {
1427             return -1;
1428         }
1429
1430         spd = (p->pid == USB_TOKEN_IN && NLPTR_TBIT(p->qtd.altnext) == 0);
1431         usb_packet_setup(&p->packet, p->pid, ep, 0, p->qtdaddr, spd,
1432                          (p->qtd.token & QTD_TOKEN_IOC) != 0);
1433         usb_packet_map(&p->packet, &p->sgl);
1434         p->async = EHCI_ASYNC_INITIALIZED;
1435     }
1436
1437     trace_usb_ehci_packet_action(p->queue, p, action);
1438     usb_handle_packet(p->queue->dev, &p->packet);
1439     DPRINTF("submit: qh 0x%x next 0x%x qtd 0x%x pid 0x%x len %zd endp 0x%x "
1440             "status %d actual_length %d\n", p->queue->qhaddr, p->qtd.next,
1441             p->qtdaddr, p->pid, p->packet.iov.size, endp, p->packet.status,
1442             p->packet.actual_length);
1443
1444     if (p->packet.actual_length > BUFF_SIZE) {
1445         fprintf(stderr, "ret from usb_handle_packet > BUFF_SIZE\n");
1446         return -1;
1447     }
1448
1449     return 1;
1450 }
1451
1452 /*  4.7.2
1453  */
1454
1455 static int ehci_process_itd(EHCIState *ehci,
1456                             EHCIitd *itd,
1457                             uint32_t addr)
1458 {
1459     USBDevice *dev;
1460     USBEndpoint *ep;
1461     uint32_t i, len, pid, dir, devaddr, endp;
1462     uint32_t pg, off, ptr1, ptr2, max, mult;
1463
1464     ehci->periodic_sched_active = PERIODIC_ACTIVE;
1465
1466     dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
1467     devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
1468     endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
1469     max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
1470     mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
1471
1472     for(i = 0; i < 8; i++) {
1473         if (itd->transact[i] & ITD_XACT_ACTIVE) {
1474             pg   = get_field(itd->transact[i], ITD_XACT_PGSEL);
1475             off  = itd->transact[i] & ITD_XACT_OFFSET_MASK;
1476             ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
1477             ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK);
1478             len  = get_field(itd->transact[i], ITD_XACT_LENGTH);
1479
1480             if (len > max * mult) {
1481                 len = max * mult;
1482             }
1483
1484             if (len > BUFF_SIZE) {
1485                 return -1;
1486             }
1487
1488             qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
1489             if (off + len > 4096) {
1490                 /* transfer crosses page border */
1491                 uint32_t len2 = off + len - 4096;
1492                 uint32_t len1 = len - len2;
1493                 qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
1494                 qemu_sglist_add(&ehci->isgl, ptr2, len2);
1495             } else {
1496                 qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
1497             }
1498
1499             pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
1500
1501             dev = ehci_find_device(ehci, devaddr);
1502             ep = usb_ep_get(dev, pid, endp);
1503             if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
1504                 usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
1505                                  (itd->transact[i] & ITD_XACT_IOC) != 0);
1506                 usb_packet_map(&ehci->ipacket, &ehci->isgl);
1507                 usb_handle_packet(dev, &ehci->ipacket);
1508                 usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
1509             } else {
1510                 DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
1511                 ehci->ipacket.status = USB_RET_NAK;
1512                 ehci->ipacket.actual_length = 0;
1513             }
1514             qemu_sglist_destroy(&ehci->isgl);
1515
1516             switch (ehci->ipacket.status) {
1517             case USB_RET_SUCCESS:
1518                 break;
1519             default:
1520                 fprintf(stderr, "Unexpected iso usb result: %d\n",
1521                         ehci->ipacket.status);
1522                 /* Fall through */
1523             case USB_RET_IOERROR:
1524             case USB_RET_NODEV:
1525                 /* 3.3.2: XACTERR is only allowed on IN transactions */
1526                 if (dir) {
1527                     itd->transact[i] |= ITD_XACT_XACTERR;
1528                     ehci_raise_irq(ehci, USBSTS_ERRINT);
1529                 }
1530                 break;
1531             case USB_RET_BABBLE:
1532                 itd->transact[i] |= ITD_XACT_BABBLE;
1533                 ehci_raise_irq(ehci, USBSTS_ERRINT);
1534                 break;
1535             case USB_RET_NAK:
1536                 /* no data for us, so do a zero-length transfer */
1537                 ehci->ipacket.actual_length = 0;
1538                 break;
1539             }
1540             if (!dir) {
1541                 set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
1542                           ITD_XACT_LENGTH); /* OUT */
1543             } else {
1544                 set_field(&itd->transact[i], ehci->ipacket.actual_length,
1545                           ITD_XACT_LENGTH); /* IN */
1546             }
1547             if (itd->transact[i] & ITD_XACT_IOC) {
1548                 ehci_raise_irq(ehci, USBSTS_INT);
1549             }
1550             itd->transact[i] &= ~ITD_XACT_ACTIVE;
1551         }
1552     }
1553     return 0;
1554 }
1555
1556
1557 /*  This state is the entry point for asynchronous schedule
1558  *  processing.  Entry here consitutes a EHCI start event state (4.8.5)
1559  */
1560 static int ehci_state_waitlisthead(EHCIState *ehci,  int async)
1561 {
1562     EHCIqh qh;
1563     int i = 0;
1564     int again = 0;
1565     uint32_t entry = ehci->asynclistaddr;
1566
1567     /* set reclamation flag at start event (4.8.6) */
1568     if (async) {
1569         ehci_set_usbsts(ehci, USBSTS_REC);
1570     }
1571
1572     ehci_queues_rip_unused(ehci, async);
1573
1574     /*  Find the head of the list (4.9.1.1) */
1575     for(i = 0; i < MAX_QH; i++) {
1576         if (get_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &qh,
1577                        sizeof(EHCIqh) >> 2) < 0) {
1578             return 0;
1579         }
1580         ehci_trace_qh(NULL, NLPTR_GET(entry), &qh);
1581
1582         if (qh.epchar & QH_EPCHAR_H) {
1583             if (async) {
1584                 entry |= (NLPTR_TYPE_QH << 1);
1585             }
1586
1587             ehci_set_fetch_addr(ehci, async, entry);
1588             ehci_set_state(ehci, async, EST_FETCHENTRY);
1589             again = 1;
1590             goto out;
1591         }
1592
1593         entry = qh.next;
1594         if (entry == ehci->asynclistaddr) {
1595             break;
1596         }
1597     }
1598
1599     /* no head found for list. */
1600
1601     ehci_set_state(ehci, async, EST_ACTIVE);
1602
1603 out:
1604     return again;
1605 }
1606
1607
1608 /*  This state is the entry point for periodic schedule processing as
1609  *  well as being a continuation state for async processing.
1610  */
1611 static int ehci_state_fetchentry(EHCIState *ehci, int async)
1612 {
1613     int again = 0;
1614     uint32_t entry = ehci_get_fetch_addr(ehci, async);
1615
1616     if (NLPTR_TBIT(entry)) {
1617         ehci_set_state(ehci, async, EST_ACTIVE);
1618         goto out;
1619     }
1620
1621     /* section 4.8, only QH in async schedule */
1622     if (async && (NLPTR_TYPE_GET(entry) != NLPTR_TYPE_QH)) {
1623         fprintf(stderr, "non queue head request in async schedule\n");
1624         return -1;
1625     }
1626
1627     switch (NLPTR_TYPE_GET(entry)) {
1628     case NLPTR_TYPE_QH:
1629         ehci_set_state(ehci, async, EST_FETCHQH);
1630         again = 1;
1631         break;
1632
1633     case NLPTR_TYPE_ITD:
1634         ehci_set_state(ehci, async, EST_FETCHITD);
1635         again = 1;
1636         break;
1637
1638     case NLPTR_TYPE_STITD:
1639         ehci_set_state(ehci, async, EST_FETCHSITD);
1640         again = 1;
1641         break;
1642
1643     default:
1644         /* TODO: handle FSTN type */
1645         fprintf(stderr, "FETCHENTRY: entry at %X is of type %d "
1646                 "which is not supported yet\n", entry, NLPTR_TYPE_GET(entry));
1647         return -1;
1648     }
1649
1650 out:
1651     return again;
1652 }
1653
1654 static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
1655 {
1656     uint32_t entry;
1657     EHCIQueue *q;
1658     EHCIqh qh;
1659
1660     entry = ehci_get_fetch_addr(ehci, async);
1661     q = ehci_find_queue_by_qh(ehci, entry, async);
1662     if (NULL == q) {
1663         q = ehci_alloc_queue(ehci, entry, async);
1664     }
1665
1666     q->seen++;
1667     if (q->seen > 1) {
1668         /* we are going in circles -- stop processing */
1669         ehci_set_state(ehci, async, EST_ACTIVE);
1670         q = NULL;
1671         goto out;
1672     }
1673
1674     if (get_dwords(ehci, NLPTR_GET(q->qhaddr),
1675                    (uint32_t *) &qh, sizeof(EHCIqh) >> 2) < 0) {
1676         q = NULL;
1677         goto out;
1678     }
1679     ehci_trace_qh(q, NLPTR_GET(q->qhaddr), &qh);
1680
1681     /*
1682      * The overlay area of the qh should never be changed by the guest,
1683      * except when idle, in which case the reset is a nop.
1684      */
1685     if (!ehci_verify_qh(q, &qh)) {
1686         if (ehci_reset_queue(q) > 0) {
1687             ehci_trace_guest_bug(ehci, "guest updated active QH");
1688         }
1689     }
1690     q->qh = qh;
1691
1692     q->transact_ctr = get_field(q->qh.epcap, QH_EPCAP_MULT);
1693     if (q->transact_ctr == 0) { /* Guest bug in some versions of windows */
1694         q->transact_ctr = 4;
1695     }
1696
1697     if (q->dev == NULL) {
1698         q->dev = ehci_find_device(q->ehci,
1699                                   get_field(q->qh.epchar, QH_EPCHAR_DEVADDR));
1700     }
1701
1702     if (async && (q->qh.epchar & QH_EPCHAR_H)) {
1703
1704         /*  EHCI spec version 1.0 Section 4.8.3 & 4.10.1 */
1705         if (ehci->usbsts & USBSTS_REC) {
1706             ehci_clear_usbsts(ehci, USBSTS_REC);
1707         } else {
1708             DPRINTF("FETCHQH:  QH 0x%08x. H-bit set, reclamation status reset"
1709                        " - done processing\n", q->qhaddr);
1710             ehci_set_state(ehci, async, EST_ACTIVE);
1711             q = NULL;
1712             goto out;
1713         }
1714     }
1715
1716 #if EHCI_DEBUG
1717     if (q->qhaddr != q->qh.next) {
1718     DPRINTF("FETCHQH:  QH 0x%08x (h %x halt %x active %x) next 0x%08x\n",
1719                q->qhaddr,
1720                q->qh.epchar & QH_EPCHAR_H,
1721                q->qh.token & QTD_TOKEN_HALT,
1722                q->qh.token & QTD_TOKEN_ACTIVE,
1723                q->qh.next);
1724     }
1725 #endif
1726
1727     if (q->qh.token & QTD_TOKEN_HALT) {
1728         ehci_set_state(ehci, async, EST_HORIZONTALQH);
1729
1730     } else if ((q->qh.token & QTD_TOKEN_ACTIVE) &&
1731                (NLPTR_TBIT(q->qh.current_qtd) == 0)) {
1732         q->qtdaddr = q->qh.current_qtd;
1733         ehci_set_state(ehci, async, EST_FETCHQTD);
1734
1735     } else {
1736         /*  EHCI spec version 1.0 Section 4.10.2 */
1737         ehci_set_state(ehci, async, EST_ADVANCEQUEUE);
1738     }
1739
1740 out:
1741     return q;
1742 }
1743
1744 static int ehci_state_fetchitd(EHCIState *ehci, int async)
1745 {
1746     uint32_t entry;
1747     EHCIitd itd;
1748
1749     assert(!async);
1750     entry = ehci_get_fetch_addr(ehci, async);
1751
1752     if (get_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &itd,
1753                    sizeof(EHCIitd) >> 2) < 0) {
1754         return -1;
1755     }
1756     ehci_trace_itd(ehci, entry, &itd);
1757
1758     if (ehci_process_itd(ehci, &itd, entry) != 0) {
1759         return -1;
1760     }
1761
1762     put_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &itd,
1763                sizeof(EHCIitd) >> 2);
1764     ehci_set_fetch_addr(ehci, async, itd.next);
1765     ehci_set_state(ehci, async, EST_FETCHENTRY);
1766
1767     return 1;
1768 }
1769
1770 static int ehci_state_fetchsitd(EHCIState *ehci, int async)
1771 {
1772     uint32_t entry;
1773     EHCIsitd sitd;
1774
1775     assert(!async);
1776     entry = ehci_get_fetch_addr(ehci, async);
1777
1778     if (get_dwords(ehci, NLPTR_GET(entry), (uint32_t *)&sitd,
1779                    sizeof(EHCIsitd) >> 2) < 0) {
1780         return 0;
1781     }
1782     ehci_trace_sitd(ehci, entry, &sitd);
1783
1784     if (!(sitd.results & SITD_RESULTS_ACTIVE)) {
1785         /* siTD is not active, nothing to do */;
1786     } else {
1787         /* TODO: split transfers are not implemented */
1788         fprintf(stderr, "WARNING: Skipping active siTD\n");
1789     }
1790
1791     ehci_set_fetch_addr(ehci, async, sitd.next);
1792     ehci_set_state(ehci, async, EST_FETCHENTRY);
1793     return 1;
1794 }
1795
1796 /* Section 4.10.2 - paragraph 3 */
1797 static int ehci_state_advqueue(EHCIQueue *q)
1798 {
1799 #if 0
1800     /* TO-DO: 4.10.2 - paragraph 2
1801      * if I-bit is set to 1 and QH is not active
1802      * go to horizontal QH
1803      */
1804     if (I-bit set) {
1805         ehci_set_state(ehci, async, EST_HORIZONTALQH);
1806         goto out;
1807     }
1808 #endif
1809
1810     /*
1811      * want data and alt-next qTD is valid
1812      */
1813     if (((q->qh.token & QTD_TOKEN_TBYTES_MASK) != 0) &&
1814         (NLPTR_TBIT(q->qh.altnext_qtd) == 0)) {
1815         q->qtdaddr = q->qh.altnext_qtd;
1816         ehci_set_state(q->ehci, q->async, EST_FETCHQTD);
1817
1818     /*
1819      *  next qTD is valid
1820      */
1821     } else if (NLPTR_TBIT(q->qh.next_qtd) == 0) {
1822         q->qtdaddr = q->qh.next_qtd;
1823         ehci_set_state(q->ehci, q->async, EST_FETCHQTD);
1824
1825     /*
1826      *  no valid qTD, try next QH
1827      */
1828     } else {
1829         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1830     }
1831
1832     return 1;
1833 }
1834
1835 /* Section 4.10.2 - paragraph 4 */
1836 static int ehci_state_fetchqtd(EHCIQueue *q)
1837 {
1838     EHCIqtd qtd;
1839     EHCIPacket *p;
1840     int again = 1;
1841
1842     if (get_dwords(q->ehci, NLPTR_GET(q->qtdaddr), (uint32_t *) &qtd,
1843                    sizeof(EHCIqtd) >> 2) < 0) {
1844         return 0;
1845     }
1846     ehci_trace_qtd(q, NLPTR_GET(q->qtdaddr), &qtd);
1847
1848     p = QTAILQ_FIRST(&q->packets);
1849     if (p != NULL) {
1850         if (!ehci_verify_qtd(p, &qtd)) {
1851             ehci_cancel_queue(q);
1852             if (qtd.token & QTD_TOKEN_ACTIVE) {
1853                 ehci_trace_guest_bug(q->ehci, "guest updated active qTD");
1854             }
1855             p = NULL;
1856         } else {
1857             p->qtd = qtd;
1858             ehci_qh_do_overlay(q);
1859         }
1860     }
1861
1862     if (!(qtd.token & QTD_TOKEN_ACTIVE)) {
1863         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1864     } else if (p != NULL) {
1865         switch (p->async) {
1866         case EHCI_ASYNC_NONE:
1867         case EHCI_ASYNC_INITIALIZED:
1868             /* Not yet executed (MULT), or previously nacked (int) packet */
1869             ehci_set_state(q->ehci, q->async, EST_EXECUTE);
1870             break;
1871         case EHCI_ASYNC_INFLIGHT:
1872             /* Check if the guest has added new tds to the queue */
1873             again = ehci_fill_queue(QTAILQ_LAST(&q->packets, pkts_head));
1874             /* Unfinished async handled packet, go horizontal */
1875             ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1876             break;
1877         case EHCI_ASYNC_FINISHED:
1878             /* Complete executing of the packet */
1879             ehci_set_state(q->ehci, q->async, EST_EXECUTING);
1880             break;
1881         }
1882     } else {
1883         p = ehci_alloc_packet(q);
1884         p->qtdaddr = q->qtdaddr;
1885         p->qtd = qtd;
1886         ehci_set_state(q->ehci, q->async, EST_EXECUTE);
1887     }
1888
1889     return again;
1890 }
1891
1892 static int ehci_state_horizqh(EHCIQueue *q)
1893 {
1894     int again = 0;
1895
1896     if (ehci_get_fetch_addr(q->ehci, q->async) != q->qh.next) {
1897         ehci_set_fetch_addr(q->ehci, q->async, q->qh.next);
1898         ehci_set_state(q->ehci, q->async, EST_FETCHENTRY);
1899         again = 1;
1900     } else {
1901         ehci_set_state(q->ehci, q->async, EST_ACTIVE);
1902     }
1903
1904     return again;
1905 }
1906
1907 /* Returns "again" */
1908 static int ehci_fill_queue(EHCIPacket *p)
1909 {
1910     USBEndpoint *ep = p->packet.ep;
1911     EHCIQueue *q = p->queue;
1912     EHCIqtd qtd = p->qtd;
1913     uint32_t qtdaddr;
1914
1915     for (;;) {
1916         if (NLPTR_TBIT(qtd.next) != 0) {
1917             break;
1918         }
1919         qtdaddr = qtd.next;
1920         /*
1921          * Detect circular td lists, Windows creates these, counting on the
1922          * active bit going low after execution to make the queue stop.
1923          */
1924         QTAILQ_FOREACH(p, &q->packets, next) {
1925             if (p->qtdaddr == qtdaddr) {
1926                 goto leave;
1927             }
1928         }
1929         if (get_dwords(q->ehci, NLPTR_GET(qtdaddr),
1930                        (uint32_t *) &qtd, sizeof(EHCIqtd) >> 2) < 0) {
1931             return -1;
1932         }
1933         ehci_trace_qtd(q, NLPTR_GET(qtdaddr), &qtd);
1934         if (!(qtd.token & QTD_TOKEN_ACTIVE)) {
1935             break;
1936         }
1937         if (!ehci_verify_pid(q, &qtd)) {
1938             ehci_trace_guest_bug(q->ehci, "guest queued token with wrong pid");
1939             break;
1940         }
1941         p = ehci_alloc_packet(q);
1942         p->qtdaddr = qtdaddr;
1943         p->qtd = qtd;
1944         if (ehci_execute(p, "queue") == -1) {
1945             return -1;
1946         }
1947         assert(p->packet.status == USB_RET_ASYNC);
1948         p->async = EHCI_ASYNC_INFLIGHT;
1949     }
1950 leave:
1951     usb_device_flush_ep_queue(ep->dev, ep);
1952     return 1;
1953 }
1954
1955 static int ehci_state_execute(EHCIQueue *q)
1956 {
1957     EHCIPacket *p = QTAILQ_FIRST(&q->packets);
1958     int again = 0;
1959
1960     assert(p != NULL);
1961     assert(p->qtdaddr == q->qtdaddr);
1962
1963     if (ehci_qh_do_overlay(q) != 0) {
1964         return -1;
1965     }
1966
1967     // TODO verify enough time remains in the uframe as in 4.4.1.1
1968     // TODO write back ptr to async list when done or out of time
1969
1970     /* 4.10.3, bottom of page 82, go horizontal on transaction counter == 0 */
1971     if (!q->async && q->transact_ctr == 0) {
1972         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1973         again = 1;
1974         goto out;
1975     }
1976
1977     if (q->async) {
1978         ehci_set_usbsts(q->ehci, USBSTS_REC);
1979     }
1980
1981     again = ehci_execute(p, "process");
1982     if (again == -1) {
1983         goto out;
1984     }
1985     if (p->packet.status == USB_RET_ASYNC) {
1986         ehci_flush_qh(q);
1987         trace_usb_ehci_packet_action(p->queue, p, "async");
1988         p->async = EHCI_ASYNC_INFLIGHT;
1989         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
1990         if (q->async) {
1991             again = ehci_fill_queue(p);
1992         } else {
1993             again = 1;
1994         }
1995         goto out;
1996     }
1997
1998     ehci_set_state(q->ehci, q->async, EST_EXECUTING);
1999     again = 1;
2000
2001 out:
2002     return again;
2003 }
2004
2005 static int ehci_state_executing(EHCIQueue *q)
2006 {
2007     EHCIPacket *p = QTAILQ_FIRST(&q->packets);
2008
2009     assert(p != NULL);
2010     assert(p->qtdaddr == q->qtdaddr);
2011
2012     ehci_execute_complete(q);
2013
2014     /* 4.10.3 */
2015     if (!q->async && q->transact_ctr > 0) {
2016         q->transact_ctr--;
2017     }
2018
2019     /* 4.10.5 */
2020     if (p->packet.status == USB_RET_NAK) {
2021         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
2022     } else {
2023         ehci_set_state(q->ehci, q->async, EST_WRITEBACK);
2024     }
2025
2026     ehci_flush_qh(q);
2027     return 1;
2028 }
2029
2030
2031 static int ehci_state_writeback(EHCIQueue *q)
2032 {
2033     EHCIPacket *p = QTAILQ_FIRST(&q->packets);
2034     uint32_t *qtd, addr;
2035     int again = 0;
2036
2037     /*  Write back the QTD from the QH area */
2038     assert(p != NULL);
2039     assert(p->qtdaddr == q->qtdaddr);
2040
2041     ehci_trace_qtd(q, NLPTR_GET(p->qtdaddr), (EHCIqtd *) &q->qh.next_qtd);
2042     qtd = (uint32_t *) &q->qh.next_qtd;
2043     addr = NLPTR_GET(p->qtdaddr);
2044     put_dwords(q->ehci, addr + 2 * sizeof(uint32_t), qtd + 2, 2);
2045     ehci_free_packet(p);
2046
2047     /*
2048      * EHCI specs say go horizontal here.
2049      *
2050      * We can also advance the queue here for performance reasons.  We
2051      * need to take care to only take that shortcut in case we've
2052      * processed the qtd just written back without errors, i.e. halt
2053      * bit is clear.
2054      */
2055     if (q->qh.token & QTD_TOKEN_HALT) {
2056         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
2057         again = 1;
2058     } else {
2059         ehci_set_state(q->ehci, q->async, EST_ADVANCEQUEUE);
2060         again = 1;
2061     }
2062     return again;
2063 }
2064
2065 /*
2066  * This is the state machine that is common to both async and periodic
2067  */
2068
2069 static void ehci_advance_state(EHCIState *ehci, int async)
2070 {
2071     EHCIQueue *q = NULL;
2072     int again;
2073
2074     do {
2075         switch(ehci_get_state(ehci, async)) {
2076         case EST_WAITLISTHEAD:
2077             again = ehci_state_waitlisthead(ehci, async);
2078             break;
2079
2080         case EST_FETCHENTRY:
2081             again = ehci_state_fetchentry(ehci, async);
2082             break;
2083
2084         case EST_FETCHQH:
2085             q = ehci_state_fetchqh(ehci, async);
2086             if (q != NULL) {
2087                 assert(q->async == async);
2088                 again = 1;
2089             } else {
2090                 again = 0;
2091             }
2092             break;
2093
2094         case EST_FETCHITD:
2095             again = ehci_state_fetchitd(ehci, async);
2096             break;
2097
2098         case EST_FETCHSITD:
2099             again = ehci_state_fetchsitd(ehci, async);
2100             break;
2101
2102         case EST_ADVANCEQUEUE:
2103             assert(q != NULL);
2104             again = ehci_state_advqueue(q);
2105             break;
2106
2107         case EST_FETCHQTD:
2108             assert(q != NULL);
2109             again = ehci_state_fetchqtd(q);
2110             break;
2111
2112         case EST_HORIZONTALQH:
2113             assert(q != NULL);
2114             again = ehci_state_horizqh(q);
2115             break;
2116
2117         case EST_EXECUTE:
2118             assert(q != NULL);
2119             again = ehci_state_execute(q);
2120             if (async) {
2121                 ehci->async_stepdown = 0;
2122             }
2123             break;
2124
2125         case EST_EXECUTING:
2126             assert(q != NULL);
2127             if (async) {
2128                 ehci->async_stepdown = 0;
2129             }
2130             again = ehci_state_executing(q);
2131             break;
2132
2133         case EST_WRITEBACK:
2134             assert(q != NULL);
2135             again = ehci_state_writeback(q);
2136             if (!async) {
2137                 ehci->periodic_sched_active = PERIODIC_ACTIVE;
2138             }
2139             break;
2140
2141         default:
2142             fprintf(stderr, "Bad state!\n");
2143             again = -1;
2144             g_assert_not_reached();
2145             break;
2146         }
2147
2148         if (again < 0) {
2149             fprintf(stderr, "processing error - resetting ehci HC\n");
2150             ehci_reset(ehci);
2151             again = 0;
2152         }
2153     }
2154     while (again);
2155 }
2156
2157 static void ehci_advance_async_state(EHCIState *ehci)
2158 {
2159     const int async = 1;
2160
2161     switch(ehci_get_state(ehci, async)) {
2162     case EST_INACTIVE:
2163         if (!ehci_async_enabled(ehci)) {
2164             break;
2165         }
2166         ehci_set_state(ehci, async, EST_ACTIVE);
2167         // No break, fall through to ACTIVE
2168
2169     case EST_ACTIVE:
2170         if (!ehci_async_enabled(ehci)) {
2171             ehci_queues_rip_all(ehci, async);
2172             ehci_set_state(ehci, async, EST_INACTIVE);
2173             break;
2174         }
2175
2176         /* make sure guest has acknowledged the doorbell interrupt */
2177         /* TO-DO: is this really needed? */
2178         if (ehci->usbsts & USBSTS_IAA) {
2179             DPRINTF("IAA status bit still set.\n");
2180             break;
2181         }
2182
2183         /* check that address register has been set */
2184         if (ehci->asynclistaddr == 0) {
2185             break;
2186         }
2187
2188         ehci_set_state(ehci, async, EST_WAITLISTHEAD);
2189         ehci_advance_state(ehci, async);
2190
2191         /* If the doorbell is set, the guest wants to make a change to the
2192          * schedule. The host controller needs to release cached data.
2193          * (section 4.8.2)
2194          */
2195         if (ehci->usbcmd & USBCMD_IAAD) {
2196             /* Remove all unseen qhs from the async qhs queue */
2197             ehci_queues_rip_unseen(ehci, async);
2198             trace_usb_ehci_doorbell_ack();
2199             ehci->usbcmd &= ~USBCMD_IAAD;
2200             ehci_raise_irq(ehci, USBSTS_IAA);
2201         }
2202         break;
2203
2204     default:
2205         /* this should only be due to a developer mistake */
2206         fprintf(stderr, "ehci: Bad asynchronous state %d. "
2207                 "Resetting to active\n", ehci->astate);
2208         g_assert_not_reached();
2209     }
2210 }
2211
2212 static void ehci_advance_periodic_state(EHCIState *ehci)
2213 {
2214     uint32_t entry;
2215     uint32_t list;
2216     const int async = 0;
2217
2218     // 4.6
2219
2220     switch(ehci_get_state(ehci, async)) {
2221     case EST_INACTIVE:
2222         if (!(ehci->frindex & 7) && ehci_periodic_enabled(ehci)) {
2223             ehci_set_state(ehci, async, EST_ACTIVE);
2224             // No break, fall through to ACTIVE
2225         } else
2226             break;
2227
2228     case EST_ACTIVE:
2229         if (!(ehci->frindex & 7) && !ehci_periodic_enabled(ehci)) {
2230             ehci_queues_rip_all(ehci, async);
2231             ehci_set_state(ehci, async, EST_INACTIVE);
2232             break;
2233         }
2234
2235         list = ehci->periodiclistbase & 0xfffff000;
2236         /* check that register has been set */
2237         if (list == 0) {
2238             break;
2239         }
2240         list |= ((ehci->frindex & 0x1ff8) >> 1);
2241
2242         if (get_dwords(ehci, list, &entry, 1) < 0) {
2243             break;
2244         }
2245
2246         DPRINTF("PERIODIC state adv fr=%d.  [%08X] -> %08X\n",
2247                 ehci->frindex / 8, list, entry);
2248         ehci_set_fetch_addr(ehci, async,entry);
2249         ehci_set_state(ehci, async, EST_FETCHENTRY);
2250         ehci_advance_state(ehci, async);
2251         ehci_queues_rip_unused(ehci, async);
2252         break;
2253
2254     default:
2255         /* this should only be due to a developer mistake */
2256         fprintf(stderr, "ehci: Bad periodic state %d. "
2257                 "Resetting to active\n", ehci->pstate);
2258         g_assert_not_reached();
2259     }
2260 }
2261
2262 static void ehci_update_frindex(EHCIState *ehci, int uframes)
2263 {
2264     int i;
2265
2266     if (!ehci_enabled(ehci) && ehci->pstate == EST_INACTIVE) {
2267         return;
2268     }
2269
2270     for (i = 0; i < uframes; i++) {
2271         ehci->frindex++;
2272
2273         if (ehci->frindex == 0x00002000) {
2274             ehci_raise_irq(ehci, USBSTS_FLR);
2275         }
2276
2277         if (ehci->frindex == 0x00004000) {
2278             ehci_raise_irq(ehci, USBSTS_FLR);
2279             ehci->frindex = 0;
2280             if (ehci->usbsts_frindex >= 0x00004000) {
2281                 ehci->usbsts_frindex -= 0x00004000;
2282             } else {
2283                 ehci->usbsts_frindex = 0;
2284             }
2285         }
2286     }
2287 }
2288
2289 static void ehci_frame_timer(void *opaque)
2290 {
2291     EHCIState *ehci = opaque;
2292     int need_timer = 0;
2293     int64_t expire_time, t_now;
2294     uint64_t ns_elapsed;
2295     int uframes, skipped_uframes;
2296     int i;
2297
2298     t_now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2299     ns_elapsed = t_now - ehci->last_run_ns;
2300     uframes = ns_elapsed / UFRAME_TIMER_NS;
2301
2302     if (ehci_periodic_enabled(ehci) || ehci->pstate != EST_INACTIVE) {
2303         need_timer++;
2304
2305         if (uframes > (ehci->maxframes * 8)) {
2306             skipped_uframes = uframes - (ehci->maxframes * 8);
2307             ehci_update_frindex(ehci, skipped_uframes);
2308             ehci->last_run_ns += UFRAME_TIMER_NS * skipped_uframes;
2309             uframes -= skipped_uframes;
2310             DPRINTF("WARNING - EHCI skipped %d uframes\n", skipped_uframes);
2311         }
2312
2313         for (i = 0; i < uframes; i++) {
2314             /*
2315              * If we're running behind schedule, we should not catch up
2316              * too fast, as that will make some guests unhappy:
2317              * 1) We must process a minimum of MIN_UFR_PER_TICK frames,
2318              *    otherwise we will never catch up
2319              * 2) Process frames until the guest has requested an irq (IOC)
2320              */
2321             if (i >= MIN_UFR_PER_TICK) {
2322                 ehci_commit_irq(ehci);
2323                 if ((ehci->usbsts & USBINTR_MASK) & ehci->usbintr) {
2324                     break;
2325                 }
2326             }
2327             if (ehci->periodic_sched_active) {
2328                 ehci->periodic_sched_active--;
2329             }
2330             ehci_update_frindex(ehci, 1);
2331             if ((ehci->frindex & 7) == 0) {
2332                 ehci_advance_periodic_state(ehci);
2333             }
2334             ehci->last_run_ns += UFRAME_TIMER_NS;
2335         }
2336     } else {
2337         ehci->periodic_sched_active = 0;
2338         ehci_update_frindex(ehci, uframes);
2339         ehci->last_run_ns += UFRAME_TIMER_NS * uframes;
2340     }
2341
2342     if (ehci->periodic_sched_active) {
2343         ehci->async_stepdown = 0;
2344     } else if (ehci->async_stepdown < ehci->maxframes / 2) {
2345         ehci->async_stepdown++;
2346     }
2347
2348     /*  Async is not inside loop since it executes everything it can once
2349      *  called
2350      */
2351     if (ehci_async_enabled(ehci) || ehci->astate != EST_INACTIVE) {
2352         need_timer++;
2353         ehci_advance_async_state(ehci);
2354     }
2355
2356     ehci_commit_irq(ehci);
2357     if (ehci->usbsts_pending) {
2358         need_timer++;
2359         ehci->async_stepdown = 0;
2360     }
2361
2362     if (ehci_enabled(ehci) && (ehci->usbintr & USBSTS_FLR)) {
2363         need_timer++;
2364     }
2365
2366     if (need_timer) {
2367         /* If we've raised int, we speed up the timer, so that we quickly
2368          * notice any new packets queued up in response */
2369         if (ehci->int_req_by_async && (ehci->usbsts & USBSTS_INT)) {
2370             expire_time = t_now + get_ticks_per_sec() / (FRAME_TIMER_FREQ * 4);
2371             ehci->int_req_by_async = false;
2372         } else {
2373             expire_time = t_now + (get_ticks_per_sec()
2374                                * (ehci->async_stepdown+1) / FRAME_TIMER_FREQ);
2375         }
2376         timer_mod(ehci->frame_timer, expire_time);
2377     }
2378 }
2379
2380 static const MemoryRegionOps ehci_mmio_caps_ops = {
2381     .read = ehci_caps_read,
2382     .valid.min_access_size = 1,
2383     .valid.max_access_size = 4,
2384     .impl.min_access_size = 1,
2385     .impl.max_access_size = 1,
2386     .endianness = DEVICE_LITTLE_ENDIAN,
2387 };
2388
2389 static const MemoryRegionOps ehci_mmio_opreg_ops = {
2390     .read = ehci_opreg_read,
2391     .write = ehci_opreg_write,
2392     .valid.min_access_size = 4,
2393     .valid.max_access_size = 4,
2394     .endianness = DEVICE_LITTLE_ENDIAN,
2395 };
2396
2397 static const MemoryRegionOps ehci_mmio_port_ops = {
2398     .read = ehci_port_read,
2399     .write = ehci_port_write,
2400     .valid.min_access_size = 4,
2401     .valid.max_access_size = 4,
2402     .endianness = DEVICE_LITTLE_ENDIAN,
2403 };
2404
2405 static USBPortOps ehci_port_ops = {
2406     .attach = ehci_attach,
2407     .detach = ehci_detach,
2408     .child_detach = ehci_child_detach,
2409     .wakeup = ehci_wakeup,
2410     .complete = ehci_async_complete_packet,
2411 };
2412
2413 static USBBusOps ehci_bus_ops = {
2414     .register_companion = ehci_register_companion,
2415     .wakeup_endpoint = ehci_wakeup_endpoint,
2416 };
2417
2418 static void usb_ehci_pre_save(void *opaque)
2419 {
2420     EHCIState *ehci = opaque;
2421     uint32_t new_frindex;
2422
2423     /* Round down frindex to a multiple of 8 for migration compatibility */
2424     new_frindex = ehci->frindex & ~7;
2425     ehci->last_run_ns -= (ehci->frindex - new_frindex) * UFRAME_TIMER_NS;
2426     ehci->frindex = new_frindex;
2427 }
2428
2429 static int usb_ehci_post_load(void *opaque, int version_id)
2430 {
2431     EHCIState *s = opaque;
2432     int i;
2433
2434     for (i = 0; i < NB_PORTS; i++) {
2435         USBPort *companion = s->companion_ports[i];
2436         if (companion == NULL) {
2437             continue;
2438         }
2439         if (s->portsc[i] & PORTSC_POWNER) {
2440             companion->dev = s->ports[i].dev;
2441         } else {
2442             companion->dev = NULL;
2443         }
2444     }
2445
2446     return 0;
2447 }
2448
2449 static void usb_ehci_vm_state_change(void *opaque, int running, RunState state)
2450 {
2451     EHCIState *ehci = opaque;
2452
2453     /*
2454      * We don't migrate the EHCIQueue-s, instead we rebuild them for the
2455      * schedule in guest memory. We must do the rebuilt ASAP, so that
2456      * USB-devices which have async handled packages have a packet in the
2457      * ep queue to match the completion with.
2458      */
2459     if (state == RUN_STATE_RUNNING) {
2460         ehci_advance_async_state(ehci);
2461     }
2462
2463     /*
2464      * The schedule rebuilt from guest memory could cause the migration dest
2465      * to miss a QH unlink, and fail to cancel packets, since the unlinked QH
2466      * will never have existed on the destination. Therefor we must flush the
2467      * async schedule on savevm to catch any not yet noticed unlinks.
2468      */
2469     if (state == RUN_STATE_SAVE_VM) {
2470         ehci_advance_async_state(ehci);
2471         ehci_queues_rip_unseen(ehci, 1);
2472     }
2473 }
2474
2475 const VMStateDescription vmstate_ehci = {
2476     .name        = "ehci-core",
2477     .version_id  = 2,
2478     .minimum_version_id  = 1,
2479     .pre_save    = usb_ehci_pre_save,
2480     .post_load   = usb_ehci_post_load,
2481     .fields      = (VMStateField[]) {
2482         /* mmio registers */
2483         VMSTATE_UINT32(usbcmd, EHCIState),
2484         VMSTATE_UINT32(usbsts, EHCIState),
2485         VMSTATE_UINT32_V(usbsts_pending, EHCIState, 2),
2486         VMSTATE_UINT32_V(usbsts_frindex, EHCIState, 2),
2487         VMSTATE_UINT32(usbintr, EHCIState),
2488         VMSTATE_UINT32(frindex, EHCIState),
2489         VMSTATE_UINT32(ctrldssegment, EHCIState),
2490         VMSTATE_UINT32(periodiclistbase, EHCIState),
2491         VMSTATE_UINT32(asynclistaddr, EHCIState),
2492         VMSTATE_UINT32(configflag, EHCIState),
2493         VMSTATE_UINT32(portsc[0], EHCIState),
2494         VMSTATE_UINT32(portsc[1], EHCIState),
2495         VMSTATE_UINT32(portsc[2], EHCIState),
2496         VMSTATE_UINT32(portsc[3], EHCIState),
2497         VMSTATE_UINT32(portsc[4], EHCIState),
2498         VMSTATE_UINT32(portsc[5], EHCIState),
2499         /* frame timer */
2500         VMSTATE_TIMER(frame_timer, EHCIState),
2501         VMSTATE_UINT64(last_run_ns, EHCIState),
2502         VMSTATE_UINT32(async_stepdown, EHCIState),
2503         /* schedule state */
2504         VMSTATE_UINT32(astate, EHCIState),
2505         VMSTATE_UINT32(pstate, EHCIState),
2506         VMSTATE_UINT32(a_fetch_addr, EHCIState),
2507         VMSTATE_UINT32(p_fetch_addr, EHCIState),
2508         VMSTATE_END_OF_LIST()
2509     }
2510 };
2511
2512 void usb_ehci_realize(EHCIState *s, DeviceState *dev, Error **errp)
2513 {
2514     int i;
2515
2516     if (s->portnr > NB_PORTS) {
2517         error_setg(errp, "Too many ports! Max. port number is %d.",
2518                    NB_PORTS);
2519         return;
2520     }
2521
2522     usb_bus_new(&s->bus, sizeof(s->bus), &ehci_bus_ops, dev);
2523     for (i = 0; i < s->portnr; i++) {
2524         usb_register_port(&s->bus, &s->ports[i], s, i, &ehci_port_ops,
2525                           USB_SPEED_MASK_HIGH);
2526         s->ports[i].dev = 0;
2527     }
2528
2529     s->frame_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, ehci_frame_timer, s);
2530     s->async_bh = qemu_bh_new(ehci_frame_timer, s);
2531     s->device = dev;
2532
2533     qemu_register_reset(ehci_reset, s);
2534     qemu_add_vm_change_state_handler(usb_ehci_vm_state_change, s);
2535 }
2536
2537 void usb_ehci_init(EHCIState *s, DeviceState *dev)
2538 {
2539     /* 2.2 host controller interface version */
2540     s->caps[0x00] = (uint8_t)(s->opregbase - s->capsbase);
2541     s->caps[0x01] = 0x00;
2542     s->caps[0x02] = 0x00;
2543     s->caps[0x03] = 0x01;        /* HC version */
2544     s->caps[0x04] = s->portnr;   /* Number of downstream ports */
2545     s->caps[0x05] = 0x00;        /* No companion ports at present */
2546     s->caps[0x06] = 0x00;
2547     s->caps[0x07] = 0x00;
2548     s->caps[0x08] = 0x80;        /* We can cache whole frame, no 64-bit */
2549     s->caps[0x0a] = 0x00;
2550     s->caps[0x0b] = 0x00;
2551
2552     QTAILQ_INIT(&s->aqueues);
2553     QTAILQ_INIT(&s->pqueues);
2554     usb_packet_init(&s->ipacket);
2555
2556     memory_region_init(&s->mem, OBJECT(dev), "ehci", MMIO_SIZE);
2557     memory_region_init_io(&s->mem_caps, OBJECT(dev), &ehci_mmio_caps_ops, s,
2558                           "capabilities", CAPA_SIZE);
2559     memory_region_init_io(&s->mem_opreg, OBJECT(dev), &ehci_mmio_opreg_ops, s,
2560                           "operational", s->portscbase);
2561     memory_region_init_io(&s->mem_ports, OBJECT(dev), &ehci_mmio_port_ops, s,
2562                           "ports", 4 * s->portnr);
2563
2564     memory_region_add_subregion(&s->mem, s->capsbase, &s->mem_caps);
2565     memory_region_add_subregion(&s->mem, s->opregbase, &s->mem_opreg);
2566     memory_region_add_subregion(&s->mem, s->opregbase + s->portscbase,
2567                                 &s->mem_ports);
2568 }
2569
2570 /*
2571  * vim: expandtab ts=4
2572  */
This page took 0.169908 seconds and 4 git commands to generate.