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