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