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