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