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