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