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