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