xref: /openbmc/qemu/hw/usb/hcd-xhci.c (revision 0b33bb39)
1 /*
2  * USB xHCI controller emulation
3  *
4  * Copyright (c) 2011 Securiforest
5  * Date: 2011-05-11 ;  Author: Hector Martin <hector@marcansoft.com>
6  * Based on usb-ohci.c, emulates Renesas NEC USB 3.0
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20  */
21 
22 #include "qemu/osdep.h"
23 #include "qemu/timer.h"
24 #include "qemu/log.h"
25 #include "qemu/module.h"
26 #include "qemu/queue.h"
27 #include "migration/vmstate.h"
28 #include "hw/qdev-properties.h"
29 #include "trace.h"
30 #include "qapi/error.h"
31 
32 #include "hcd-xhci.h"
33 
34 //#define DEBUG_XHCI
35 //#define DEBUG_DATA
36 
37 #ifdef DEBUG_XHCI
38 #define DPRINTF(...) fprintf(stderr, __VA_ARGS__)
39 #else
40 #define DPRINTF(...) do {} while (0)
41 #endif
42 #define FIXME(_msg) do { fprintf(stderr, "FIXME %s:%d %s\n", \
43                                  __func__, __LINE__, _msg); abort(); } while (0)
44 
45 #define TRB_LINK_LIMIT  32
46 #define COMMAND_LIMIT   256
47 #define TRANSFER_LIMIT  256
48 
49 #define LEN_CAP         0x40
50 #define LEN_OPER        (0x400 + 0x10 * XHCI_MAXPORTS)
51 #define LEN_RUNTIME     ((XHCI_MAXINTRS + 1) * 0x20)
52 #define LEN_DOORBELL    ((XHCI_MAXSLOTS + 1) * 0x20)
53 
54 #define OFF_OPER        LEN_CAP
55 #define OFF_RUNTIME     0x1000
56 #define OFF_DOORBELL    0x2000
57 
58 #if (OFF_OPER + LEN_OPER) > OFF_RUNTIME
59 #error Increase OFF_RUNTIME
60 #endif
61 #if (OFF_RUNTIME + LEN_RUNTIME) > OFF_DOORBELL
62 #error Increase OFF_DOORBELL
63 #endif
64 #if (OFF_DOORBELL + LEN_DOORBELL) > XHCI_LEN_REGS
65 # error Increase XHCI_LEN_REGS
66 #endif
67 
68 /* bit definitions */
69 #define USBCMD_RS       (1<<0)
70 #define USBCMD_HCRST    (1<<1)
71 #define USBCMD_INTE     (1<<2)
72 #define USBCMD_HSEE     (1<<3)
73 #define USBCMD_LHCRST   (1<<7)
74 #define USBCMD_CSS      (1<<8)
75 #define USBCMD_CRS      (1<<9)
76 #define USBCMD_EWE      (1<<10)
77 #define USBCMD_EU3S     (1<<11)
78 
79 #define USBSTS_HCH      (1<<0)
80 #define USBSTS_HSE      (1<<2)
81 #define USBSTS_EINT     (1<<3)
82 #define USBSTS_PCD      (1<<4)
83 #define USBSTS_SSS      (1<<8)
84 #define USBSTS_RSS      (1<<9)
85 #define USBSTS_SRE      (1<<10)
86 #define USBSTS_CNR      (1<<11)
87 #define USBSTS_HCE      (1<<12)
88 
89 
90 #define PORTSC_CCS          (1<<0)
91 #define PORTSC_PED          (1<<1)
92 #define PORTSC_OCA          (1<<3)
93 #define PORTSC_PR           (1<<4)
94 #define PORTSC_PLS_SHIFT        5
95 #define PORTSC_PLS_MASK     0xf
96 #define PORTSC_PP           (1<<9)
97 #define PORTSC_SPEED_SHIFT      10
98 #define PORTSC_SPEED_MASK   0xf
99 #define PORTSC_SPEED_FULL   (1<<10)
100 #define PORTSC_SPEED_LOW    (2<<10)
101 #define PORTSC_SPEED_HIGH   (3<<10)
102 #define PORTSC_SPEED_SUPER  (4<<10)
103 #define PORTSC_PIC_SHIFT        14
104 #define PORTSC_PIC_MASK     0x3
105 #define PORTSC_LWS          (1<<16)
106 #define PORTSC_CSC          (1<<17)
107 #define PORTSC_PEC          (1<<18)
108 #define PORTSC_WRC          (1<<19)
109 #define PORTSC_OCC          (1<<20)
110 #define PORTSC_PRC          (1<<21)
111 #define PORTSC_PLC          (1<<22)
112 #define PORTSC_CEC          (1<<23)
113 #define PORTSC_CAS          (1<<24)
114 #define PORTSC_WCE          (1<<25)
115 #define PORTSC_WDE          (1<<26)
116 #define PORTSC_WOE          (1<<27)
117 #define PORTSC_DR           (1<<30)
118 #define PORTSC_WPR          (1<<31)
119 
120 #define CRCR_RCS        (1<<0)
121 #define CRCR_CS         (1<<1)
122 #define CRCR_CA         (1<<2)
123 #define CRCR_CRR        (1<<3)
124 
125 #define IMAN_IP         (1<<0)
126 #define IMAN_IE         (1<<1)
127 
128 #define ERDP_EHB        (1<<3)
129 
130 #define TRB_SIZE 16
131 typedef struct XHCITRB {
132     uint64_t parameter;
133     uint32_t status;
134     uint32_t control;
135     dma_addr_t addr;
136     bool ccs;
137 } XHCITRB;
138 
139 enum {
140     PLS_U0              =  0,
141     PLS_U1              =  1,
142     PLS_U2              =  2,
143     PLS_U3              =  3,
144     PLS_DISABLED        =  4,
145     PLS_RX_DETECT       =  5,
146     PLS_INACTIVE        =  6,
147     PLS_POLLING         =  7,
148     PLS_RECOVERY        =  8,
149     PLS_HOT_RESET       =  9,
150     PLS_COMPILANCE_MODE = 10,
151     PLS_TEST_MODE       = 11,
152     PLS_RESUME          = 15,
153 };
154 
155 #define CR_LINK TR_LINK
156 
157 #define TRB_C               (1<<0)
158 #define TRB_TYPE_SHIFT          10
159 #define TRB_TYPE_MASK       0x3f
160 #define TRB_TYPE(t)         (((t).control >> TRB_TYPE_SHIFT) & TRB_TYPE_MASK)
161 
162 #define TRB_EV_ED           (1<<2)
163 
164 #define TRB_TR_ENT          (1<<1)
165 #define TRB_TR_ISP          (1<<2)
166 #define TRB_TR_NS           (1<<3)
167 #define TRB_TR_CH           (1<<4)
168 #define TRB_TR_IOC          (1<<5)
169 #define TRB_TR_IDT          (1<<6)
170 #define TRB_TR_TBC_SHIFT        7
171 #define TRB_TR_TBC_MASK     0x3
172 #define TRB_TR_BEI          (1<<9)
173 #define TRB_TR_TLBPC_SHIFT      16
174 #define TRB_TR_TLBPC_MASK   0xf
175 #define TRB_TR_FRAMEID_SHIFT    20
176 #define TRB_TR_FRAMEID_MASK 0x7ff
177 #define TRB_TR_SIA          (1<<31)
178 
179 #define TRB_TR_DIR          (1<<16)
180 
181 #define TRB_CR_SLOTID_SHIFT     24
182 #define TRB_CR_SLOTID_MASK  0xff
183 #define TRB_CR_EPID_SHIFT       16
184 #define TRB_CR_EPID_MASK    0x1f
185 
186 #define TRB_CR_BSR          (1<<9)
187 #define TRB_CR_DC           (1<<9)
188 
189 #define TRB_LK_TC           (1<<1)
190 
191 #define TRB_INTR_SHIFT          22
192 #define TRB_INTR_MASK       0x3ff
193 #define TRB_INTR(t)         (((t).status >> TRB_INTR_SHIFT) & TRB_INTR_MASK)
194 
195 #define EP_TYPE_MASK        0x7
196 #define EP_TYPE_SHIFT           3
197 
198 #define EP_STATE_MASK       0x7
199 #define EP_DISABLED         (0<<0)
200 #define EP_RUNNING          (1<<0)
201 #define EP_HALTED           (2<<0)
202 #define EP_STOPPED          (3<<0)
203 #define EP_ERROR            (4<<0)
204 
205 #define SLOT_STATE_MASK     0x1f
206 #define SLOT_STATE_SHIFT        27
207 #define SLOT_STATE(s)       (((s)>>SLOT_STATE_SHIFT)&SLOT_STATE_MASK)
208 #define SLOT_ENABLED        0
209 #define SLOT_DEFAULT        1
210 #define SLOT_ADDRESSED      2
211 #define SLOT_CONFIGURED     3
212 
213 #define SLOT_CONTEXT_ENTRIES_MASK 0x1f
214 #define SLOT_CONTEXT_ENTRIES_SHIFT 27
215 
216 #define get_field(data, field)                  \
217     (((data) >> field##_SHIFT) & field##_MASK)
218 
219 #define set_field(data, newval, field) do {                     \
220         uint32_t val = *data;                                   \
221         val &= ~(field##_MASK << field##_SHIFT);                \
222         val |= ((newval) & field##_MASK) << field##_SHIFT;      \
223         *data = val;                                            \
224     } while (0)
225 
226 typedef enum EPType {
227     ET_INVALID = 0,
228     ET_ISO_OUT,
229     ET_BULK_OUT,
230     ET_INTR_OUT,
231     ET_CONTROL,
232     ET_ISO_IN,
233     ET_BULK_IN,
234     ET_INTR_IN,
235 } EPType;
236 
237 typedef struct XHCITransfer {
238     XHCIEPContext *epctx;
239     USBPacket packet;
240     QEMUSGList sgl;
241     bool running_async;
242     bool running_retry;
243     bool complete;
244     bool int_req;
245     unsigned int iso_pkts;
246     unsigned int streamid;
247     bool in_xfer;
248     bool iso_xfer;
249     bool timed_xfer;
250 
251     unsigned int trb_count;
252     XHCITRB *trbs;
253 
254     TRBCCode status;
255 
256     unsigned int pkts;
257     unsigned int pktsize;
258     unsigned int cur_pkt;
259 
260     uint64_t mfindex_kick;
261 
262     QTAILQ_ENTRY(XHCITransfer) next;
263 } XHCITransfer;
264 
265 struct XHCIStreamContext {
266     dma_addr_t pctx;
267     unsigned int sct;
268     XHCIRing ring;
269 };
270 
271 struct XHCIEPContext {
272     XHCIState *xhci;
273     unsigned int slotid;
274     unsigned int epid;
275 
276     XHCIRing ring;
277     uint32_t xfer_count;
278     QTAILQ_HEAD(, XHCITransfer) transfers;
279     XHCITransfer *retry;
280     EPType type;
281     dma_addr_t pctx;
282     unsigned int max_psize;
283     uint32_t state;
284     uint32_t kick_active;
285 
286     /* streams */
287     unsigned int max_pstreams;
288     bool         lsa;
289     unsigned int nr_pstreams;
290     XHCIStreamContext *pstreams;
291 
292     /* iso xfer scheduling */
293     unsigned int interval;
294     int64_t mfindex_last;
295     QEMUTimer *kick_timer;
296 };
297 
298 typedef struct XHCIEvRingSeg {
299     uint32_t addr_low;
300     uint32_t addr_high;
301     uint32_t size;
302     uint32_t rsvd;
303 } XHCIEvRingSeg;
304 
305 static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
306                          unsigned int epid, unsigned int streamid);
307 static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid);
308 static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,
309                                 unsigned int epid);
310 static void xhci_xfer_report(XHCITransfer *xfer);
311 static void xhci_event(XHCIState *xhci, XHCIEvent *event, int v);
312 static void xhci_write_event(XHCIState *xhci, XHCIEvent *event, int v);
313 static USBEndpoint *xhci_epid_to_usbep(XHCIEPContext *epctx);
314 
315 static const char *TRBType_names[] = {
316     [TRB_RESERVED]                     = "TRB_RESERVED",
317     [TR_NORMAL]                        = "TR_NORMAL",
318     [TR_SETUP]                         = "TR_SETUP",
319     [TR_DATA]                          = "TR_DATA",
320     [TR_STATUS]                        = "TR_STATUS",
321     [TR_ISOCH]                         = "TR_ISOCH",
322     [TR_LINK]                          = "TR_LINK",
323     [TR_EVDATA]                        = "TR_EVDATA",
324     [TR_NOOP]                          = "TR_NOOP",
325     [CR_ENABLE_SLOT]                   = "CR_ENABLE_SLOT",
326     [CR_DISABLE_SLOT]                  = "CR_DISABLE_SLOT",
327     [CR_ADDRESS_DEVICE]                = "CR_ADDRESS_DEVICE",
328     [CR_CONFIGURE_ENDPOINT]            = "CR_CONFIGURE_ENDPOINT",
329     [CR_EVALUATE_CONTEXT]              = "CR_EVALUATE_CONTEXT",
330     [CR_RESET_ENDPOINT]                = "CR_RESET_ENDPOINT",
331     [CR_STOP_ENDPOINT]                 = "CR_STOP_ENDPOINT",
332     [CR_SET_TR_DEQUEUE]                = "CR_SET_TR_DEQUEUE",
333     [CR_RESET_DEVICE]                  = "CR_RESET_DEVICE",
334     [CR_FORCE_EVENT]                   = "CR_FORCE_EVENT",
335     [CR_NEGOTIATE_BW]                  = "CR_NEGOTIATE_BW",
336     [CR_SET_LATENCY_TOLERANCE]         = "CR_SET_LATENCY_TOLERANCE",
337     [CR_GET_PORT_BANDWIDTH]            = "CR_GET_PORT_BANDWIDTH",
338     [CR_FORCE_HEADER]                  = "CR_FORCE_HEADER",
339     [CR_NOOP]                          = "CR_NOOP",
340     [ER_TRANSFER]                      = "ER_TRANSFER",
341     [ER_COMMAND_COMPLETE]              = "ER_COMMAND_COMPLETE",
342     [ER_PORT_STATUS_CHANGE]            = "ER_PORT_STATUS_CHANGE",
343     [ER_BANDWIDTH_REQUEST]             = "ER_BANDWIDTH_REQUEST",
344     [ER_DOORBELL]                      = "ER_DOORBELL",
345     [ER_HOST_CONTROLLER]               = "ER_HOST_CONTROLLER",
346     [ER_DEVICE_NOTIFICATION]           = "ER_DEVICE_NOTIFICATION",
347     [ER_MFINDEX_WRAP]                  = "ER_MFINDEX_WRAP",
348     [CR_VENDOR_NEC_FIRMWARE_REVISION]  = "CR_VENDOR_NEC_FIRMWARE_REVISION",
349     [CR_VENDOR_NEC_CHALLENGE_RESPONSE] = "CR_VENDOR_NEC_CHALLENGE_RESPONSE",
350 };
351 
352 static const char *TRBCCode_names[] = {
353     [CC_INVALID]                       = "CC_INVALID",
354     [CC_SUCCESS]                       = "CC_SUCCESS",
355     [CC_DATA_BUFFER_ERROR]             = "CC_DATA_BUFFER_ERROR",
356     [CC_BABBLE_DETECTED]               = "CC_BABBLE_DETECTED",
357     [CC_USB_TRANSACTION_ERROR]         = "CC_USB_TRANSACTION_ERROR",
358     [CC_TRB_ERROR]                     = "CC_TRB_ERROR",
359     [CC_STALL_ERROR]                   = "CC_STALL_ERROR",
360     [CC_RESOURCE_ERROR]                = "CC_RESOURCE_ERROR",
361     [CC_BANDWIDTH_ERROR]               = "CC_BANDWIDTH_ERROR",
362     [CC_NO_SLOTS_ERROR]                = "CC_NO_SLOTS_ERROR",
363     [CC_INVALID_STREAM_TYPE_ERROR]     = "CC_INVALID_STREAM_TYPE_ERROR",
364     [CC_SLOT_NOT_ENABLED_ERROR]        = "CC_SLOT_NOT_ENABLED_ERROR",
365     [CC_EP_NOT_ENABLED_ERROR]          = "CC_EP_NOT_ENABLED_ERROR",
366     [CC_SHORT_PACKET]                  = "CC_SHORT_PACKET",
367     [CC_RING_UNDERRUN]                 = "CC_RING_UNDERRUN",
368     [CC_RING_OVERRUN]                  = "CC_RING_OVERRUN",
369     [CC_VF_ER_FULL]                    = "CC_VF_ER_FULL",
370     [CC_PARAMETER_ERROR]               = "CC_PARAMETER_ERROR",
371     [CC_BANDWIDTH_OVERRUN]             = "CC_BANDWIDTH_OVERRUN",
372     [CC_CONTEXT_STATE_ERROR]           = "CC_CONTEXT_STATE_ERROR",
373     [CC_NO_PING_RESPONSE_ERROR]        = "CC_NO_PING_RESPONSE_ERROR",
374     [CC_EVENT_RING_FULL_ERROR]         = "CC_EVENT_RING_FULL_ERROR",
375     [CC_INCOMPATIBLE_DEVICE_ERROR]     = "CC_INCOMPATIBLE_DEVICE_ERROR",
376     [CC_MISSED_SERVICE_ERROR]          = "CC_MISSED_SERVICE_ERROR",
377     [CC_COMMAND_RING_STOPPED]          = "CC_COMMAND_RING_STOPPED",
378     [CC_COMMAND_ABORTED]               = "CC_COMMAND_ABORTED",
379     [CC_STOPPED]                       = "CC_STOPPED",
380     [CC_STOPPED_LENGTH_INVALID]        = "CC_STOPPED_LENGTH_INVALID",
381     [CC_MAX_EXIT_LATENCY_TOO_LARGE_ERROR]
382     = "CC_MAX_EXIT_LATENCY_TOO_LARGE_ERROR",
383     [CC_ISOCH_BUFFER_OVERRUN]          = "CC_ISOCH_BUFFER_OVERRUN",
384     [CC_EVENT_LOST_ERROR]              = "CC_EVENT_LOST_ERROR",
385     [CC_UNDEFINED_ERROR]               = "CC_UNDEFINED_ERROR",
386     [CC_INVALID_STREAM_ID_ERROR]       = "CC_INVALID_STREAM_ID_ERROR",
387     [CC_SECONDARY_BANDWIDTH_ERROR]     = "CC_SECONDARY_BANDWIDTH_ERROR",
388     [CC_SPLIT_TRANSACTION_ERROR]       = "CC_SPLIT_TRANSACTION_ERROR",
389 };
390 
391 static const char *ep_state_names[] = {
392     [EP_DISABLED] = "disabled",
393     [EP_RUNNING]  = "running",
394     [EP_HALTED]   = "halted",
395     [EP_STOPPED]  = "stopped",
396     [EP_ERROR]    = "error",
397 };
398 
399 static const char *lookup_name(uint32_t index, const char **list, uint32_t llen)
400 {
401     if (index >= llen || list[index] == NULL) {
402         return "???";
403     }
404     return list[index];
405 }
406 
407 static const char *trb_name(XHCITRB *trb)
408 {
409     return lookup_name(TRB_TYPE(*trb), TRBType_names,
410                        ARRAY_SIZE(TRBType_names));
411 }
412 
413 static const char *event_name(XHCIEvent *event)
414 {
415     return lookup_name(event->ccode, TRBCCode_names,
416                        ARRAY_SIZE(TRBCCode_names));
417 }
418 
419 static const char *ep_state_name(uint32_t state)
420 {
421     return lookup_name(state, ep_state_names,
422                        ARRAY_SIZE(ep_state_names));
423 }
424 
425 bool xhci_get_flag(XHCIState *xhci, enum xhci_flags bit)
426 {
427     return xhci->flags & (1 << bit);
428 }
429 
430 void xhci_set_flag(XHCIState *xhci, enum xhci_flags bit)
431 {
432     xhci->flags |= (1 << bit);
433 }
434 
435 static uint64_t xhci_mfindex_get(XHCIState *xhci)
436 {
437     int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
438     return (now - xhci->mfindex_start) / 125000;
439 }
440 
441 static void xhci_mfwrap_update(XHCIState *xhci)
442 {
443     const uint32_t bits = USBCMD_RS | USBCMD_EWE;
444     uint32_t mfindex, left;
445     int64_t now;
446 
447     if ((xhci->usbcmd & bits) == bits) {
448         now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
449         mfindex = ((now - xhci->mfindex_start) / 125000) & 0x3fff;
450         left = 0x4000 - mfindex;
451         timer_mod(xhci->mfwrap_timer, now + left * 125000);
452     } else {
453         timer_del(xhci->mfwrap_timer);
454     }
455 }
456 
457 static void xhci_mfwrap_timer(void *opaque)
458 {
459     XHCIState *xhci = opaque;
460     XHCIEvent wrap = { ER_MFINDEX_WRAP, CC_SUCCESS };
461 
462     xhci_event(xhci, &wrap, 0);
463     xhci_mfwrap_update(xhci);
464 }
465 
466 static void xhci_die(XHCIState *xhci)
467 {
468     xhci->usbsts |= USBSTS_HCE;
469     DPRINTF("xhci: asserted controller error\n");
470 }
471 
472 static inline dma_addr_t xhci_addr64(uint32_t low, uint32_t high)
473 {
474     if (sizeof(dma_addr_t) == 4) {
475         return low;
476     } else {
477         return low | (((dma_addr_t)high << 16) << 16);
478     }
479 }
480 
481 static inline dma_addr_t xhci_mask64(uint64_t addr)
482 {
483     if (sizeof(dma_addr_t) == 4) {
484         return addr & 0xffffffff;
485     } else {
486         return addr;
487     }
488 }
489 
490 static inline void xhci_dma_read_u32s(XHCIState *xhci, dma_addr_t addr,
491                                       uint32_t *buf, size_t len)
492 {
493     int i;
494 
495     assert((len % sizeof(uint32_t)) == 0);
496 
497     if (dma_memory_read(xhci->as, addr, buf, len,
498                         MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
499         qemu_log_mask(LOG_GUEST_ERROR, "%s: DMA memory access failed!\n",
500                       __func__);
501         memset(buf, 0xff, len);
502         xhci_die(xhci);
503         return;
504     }
505 
506     for (i = 0; i < (len / sizeof(uint32_t)); i++) {
507         buf[i] = le32_to_cpu(buf[i]);
508     }
509 }
510 
511 static inline void xhci_dma_write_u32s(XHCIState *xhci, dma_addr_t addr,
512                                        const uint32_t *buf, size_t len)
513 {
514     int i;
515     uint32_t tmp[5];
516     uint32_t n = len / sizeof(uint32_t);
517 
518     assert((len % sizeof(uint32_t)) == 0);
519     assert(n <= ARRAY_SIZE(tmp));
520 
521     for (i = 0; i < n; i++) {
522         tmp[i] = cpu_to_le32(buf[i]);
523     }
524     if (dma_memory_write(xhci->as, addr, tmp, len,
525                          MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
526         qemu_log_mask(LOG_GUEST_ERROR, "%s: DMA memory access failed!\n",
527                       __func__);
528         xhci_die(xhci);
529         return;
530     }
531 }
532 
533 static XHCIPort *xhci_lookup_port(XHCIState *xhci, struct USBPort *uport)
534 {
535     int index;
536 
537     if (!uport->dev) {
538         return NULL;
539     }
540     switch (uport->dev->speed) {
541     case USB_SPEED_LOW:
542     case USB_SPEED_FULL:
543     case USB_SPEED_HIGH:
544         if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) {
545             index = uport->index + xhci->numports_3;
546         } else {
547             index = uport->index;
548         }
549         break;
550     case USB_SPEED_SUPER:
551         if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) {
552             index = uport->index;
553         } else {
554             index = uport->index + xhci->numports_2;
555         }
556         break;
557     default:
558         return NULL;
559     }
560     return &xhci->ports[index];
561 }
562 
563 static void xhci_intr_update(XHCIState *xhci, int v)
564 {
565     int level = 0;
566 
567     if (v == 0) {
568         if (xhci->intr[0].iman & IMAN_IP &&
569             xhci->intr[0].iman & IMAN_IE &&
570             xhci->usbcmd & USBCMD_INTE) {
571             level = 1;
572         }
573         if (xhci->intr_raise) {
574             if (xhci->intr_raise(xhci, 0, level)) {
575                 xhci->intr[0].iman &= ~IMAN_IP;
576             }
577         }
578     }
579     if (xhci->intr_update) {
580         xhci->intr_update(xhci, v,
581                      xhci->intr[v].iman & IMAN_IE);
582     }
583 }
584 
585 static void xhci_intr_raise(XHCIState *xhci, int v)
586 {
587     bool pending = (xhci->intr[v].erdp_low & ERDP_EHB);
588 
589     xhci->intr[v].erdp_low |= ERDP_EHB;
590     xhci->intr[v].iman |= IMAN_IP;
591     xhci->usbsts |= USBSTS_EINT;
592 
593     if (pending) {
594         return;
595     }
596     if (!(xhci->intr[v].iman & IMAN_IE)) {
597         return;
598     }
599 
600     if (!(xhci->usbcmd & USBCMD_INTE)) {
601         return;
602     }
603     if (xhci->intr_raise) {
604         if (xhci->intr_raise(xhci, v, true)) {
605             xhci->intr[v].iman &= ~IMAN_IP;
606         }
607     }
608 }
609 
610 static inline int xhci_running(XHCIState *xhci)
611 {
612     return !(xhci->usbsts & USBSTS_HCH);
613 }
614 
615 static void xhci_write_event(XHCIState *xhci, XHCIEvent *event, int v)
616 {
617     XHCIInterrupter *intr = &xhci->intr[v];
618     XHCITRB ev_trb;
619     dma_addr_t addr;
620 
621     ev_trb.parameter = cpu_to_le64(event->ptr);
622     ev_trb.status = cpu_to_le32(event->length | (event->ccode << 24));
623     ev_trb.control = (event->slotid << 24) | (event->epid << 16) |
624                      event->flags | (event->type << TRB_TYPE_SHIFT);
625     if (intr->er_pcs) {
626         ev_trb.control |= TRB_C;
627     }
628     ev_trb.control = cpu_to_le32(ev_trb.control);
629 
630     trace_usb_xhci_queue_event(v, intr->er_ep_idx, trb_name(&ev_trb),
631                                event_name(event), ev_trb.parameter,
632                                ev_trb.status, ev_trb.control);
633 
634     addr = intr->er_start + TRB_SIZE*intr->er_ep_idx;
635     if (dma_memory_write(xhci->as, addr, &ev_trb, TRB_SIZE,
636                          MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
637         qemu_log_mask(LOG_GUEST_ERROR, "%s: DMA memory access failed!\n",
638                       __func__);
639         xhci_die(xhci);
640     }
641 
642     intr->er_ep_idx++;
643     if (intr->er_ep_idx >= intr->er_size) {
644         intr->er_ep_idx = 0;
645         intr->er_pcs = !intr->er_pcs;
646     }
647 }
648 
649 static void xhci_event(XHCIState *xhci, XHCIEvent *event, int v)
650 {
651     XHCIInterrupter *intr;
652     dma_addr_t erdp;
653     unsigned int dp_idx;
654 
655     if (v >= xhci->numintrs) {
656         DPRINTF("intr nr out of range (%d >= %d)\n", v, xhci->numintrs);
657         return;
658     }
659     intr = &xhci->intr[v];
660 
661     erdp = xhci_addr64(intr->erdp_low, intr->erdp_high);
662     if (erdp < intr->er_start ||
663         erdp >= (intr->er_start + TRB_SIZE*intr->er_size)) {
664         DPRINTF("xhci: ERDP out of bounds: "DMA_ADDR_FMT"\n", erdp);
665         DPRINTF("xhci: ER[%d] at "DMA_ADDR_FMT" len %d\n",
666                 v, intr->er_start, intr->er_size);
667         xhci_die(xhci);
668         return;
669     }
670 
671     dp_idx = (erdp - intr->er_start) / TRB_SIZE;
672     assert(dp_idx < intr->er_size);
673 
674     if ((intr->er_ep_idx + 2) % intr->er_size == dp_idx) {
675         DPRINTF("xhci: ER %d full, send ring full error\n", v);
676         XHCIEvent full = {ER_HOST_CONTROLLER, CC_EVENT_RING_FULL_ERROR};
677         xhci_write_event(xhci, &full, v);
678     } else if ((intr->er_ep_idx + 1) % intr->er_size == dp_idx) {
679         DPRINTF("xhci: ER %d full, drop event\n", v);
680     } else {
681         xhci_write_event(xhci, event, v);
682     }
683 
684     xhci_intr_raise(xhci, v);
685 }
686 
687 static void xhci_ring_init(XHCIState *xhci, XHCIRing *ring,
688                            dma_addr_t base)
689 {
690     ring->dequeue = base;
691     ring->ccs = 1;
692 }
693 
694 static TRBType xhci_ring_fetch(XHCIState *xhci, XHCIRing *ring, XHCITRB *trb,
695                                dma_addr_t *addr)
696 {
697     uint32_t link_cnt = 0;
698 
699     while (1) {
700         TRBType type;
701         if (dma_memory_read(xhci->as, ring->dequeue, trb, TRB_SIZE,
702                             MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
703             qemu_log_mask(LOG_GUEST_ERROR, "%s: DMA memory access failed!\n",
704                           __func__);
705             return 0;
706         }
707         trb->addr = ring->dequeue;
708         trb->ccs = ring->ccs;
709         le64_to_cpus(&trb->parameter);
710         le32_to_cpus(&trb->status);
711         le32_to_cpus(&trb->control);
712 
713         trace_usb_xhci_fetch_trb(ring->dequeue, trb_name(trb),
714                                  trb->parameter, trb->status, trb->control);
715 
716         if ((trb->control & TRB_C) != ring->ccs) {
717             return 0;
718         }
719 
720         type = TRB_TYPE(*trb);
721 
722         if (type != TR_LINK) {
723             if (addr) {
724                 *addr = ring->dequeue;
725             }
726             ring->dequeue += TRB_SIZE;
727             return type;
728         } else {
729             if (++link_cnt > TRB_LINK_LIMIT) {
730                 trace_usb_xhci_enforced_limit("trb-link");
731                 return 0;
732             }
733             ring->dequeue = xhci_mask64(trb->parameter);
734             if (trb->control & TRB_LK_TC) {
735                 ring->ccs = !ring->ccs;
736             }
737         }
738     }
739 }
740 
741 static int xhci_ring_chain_length(XHCIState *xhci, const XHCIRing *ring)
742 {
743     XHCITRB trb;
744     int length = 0;
745     dma_addr_t dequeue = ring->dequeue;
746     bool ccs = ring->ccs;
747     /* hack to bundle together the two/three TDs that make a setup transfer */
748     bool control_td_set = 0;
749     uint32_t link_cnt = 0;
750 
751     do {
752         TRBType type;
753         if (dma_memory_read(xhci->as, dequeue, &trb, TRB_SIZE,
754                         MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
755             qemu_log_mask(LOG_GUEST_ERROR, "%s: DMA memory access failed!\n",
756                           __func__);
757             return -1;
758         }
759         le64_to_cpus(&trb.parameter);
760         le32_to_cpus(&trb.status);
761         le32_to_cpus(&trb.control);
762 
763         if ((trb.control & TRB_C) != ccs) {
764             return -length;
765         }
766 
767         type = TRB_TYPE(trb);
768 
769         if (type == TR_LINK) {
770             if (++link_cnt > TRB_LINK_LIMIT) {
771                 return -length;
772             }
773             dequeue = xhci_mask64(trb.parameter);
774             if (trb.control & TRB_LK_TC) {
775                 ccs = !ccs;
776             }
777             continue;
778         }
779 
780         length += 1;
781         dequeue += TRB_SIZE;
782 
783         if (type == TR_SETUP) {
784             control_td_set = 1;
785         } else if (type == TR_STATUS) {
786             control_td_set = 0;
787         }
788 
789         if (!control_td_set && !(trb.control & TRB_TR_CH)) {
790             return length;
791         }
792 
793         /*
794          * According to the xHCI spec, Transfer Ring segments should have
795          * a maximum size of 64 kB (see chapter "6 Data Structures")
796          */
797     } while (length < TRB_LINK_LIMIT * 65536 / TRB_SIZE);
798 
799     qemu_log_mask(LOG_GUEST_ERROR, "%s: exceeded maximum tranfer ring size!\n",
800                           __func__);
801 
802     return -1;
803 }
804 
805 static void xhci_er_reset(XHCIState *xhci, int v)
806 {
807     XHCIInterrupter *intr = &xhci->intr[v];
808     XHCIEvRingSeg seg;
809     dma_addr_t erstba = xhci_addr64(intr->erstba_low, intr->erstba_high);
810 
811     if (intr->erstsz == 0 || erstba == 0) {
812         /* disabled */
813         intr->er_start = 0;
814         intr->er_size = 0;
815         return;
816     }
817     /* cache the (sole) event ring segment location */
818     if (intr->erstsz != 1) {
819         DPRINTF("xhci: invalid value for ERSTSZ: %d\n", intr->erstsz);
820         xhci_die(xhci);
821         return;
822     }
823     if (dma_memory_read(xhci->as, erstba, &seg, sizeof(seg),
824                     MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
825         qemu_log_mask(LOG_GUEST_ERROR, "%s: DMA memory access failed!\n",
826                       __func__);
827         xhci_die(xhci);
828         return;
829     }
830 
831     le32_to_cpus(&seg.addr_low);
832     le32_to_cpus(&seg.addr_high);
833     le32_to_cpus(&seg.size);
834     if (seg.size < 16 || seg.size > 4096) {
835         DPRINTF("xhci: invalid value for segment size: %d\n", seg.size);
836         xhci_die(xhci);
837         return;
838     }
839     intr->er_start = xhci_addr64(seg.addr_low, seg.addr_high);
840     intr->er_size = seg.size;
841 
842     intr->er_ep_idx = 0;
843     intr->er_pcs = 1;
844 
845     DPRINTF("xhci: event ring[%d]:" DMA_ADDR_FMT " [%d]\n",
846             v, intr->er_start, intr->er_size);
847 }
848 
849 static void xhci_run(XHCIState *xhci)
850 {
851     trace_usb_xhci_run();
852     xhci->usbsts &= ~USBSTS_HCH;
853     xhci->mfindex_start = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
854 }
855 
856 static void xhci_stop(XHCIState *xhci)
857 {
858     trace_usb_xhci_stop();
859     xhci->usbsts |= USBSTS_HCH;
860     xhci->crcr_low &= ~CRCR_CRR;
861 }
862 
863 static XHCIStreamContext *xhci_alloc_stream_contexts(unsigned count,
864                                                      dma_addr_t base)
865 {
866     XHCIStreamContext *stctx;
867     unsigned int i;
868 
869     stctx = g_new0(XHCIStreamContext, count);
870     for (i = 0; i < count; i++) {
871         stctx[i].pctx = base + i * 16;
872         stctx[i].sct = -1;
873     }
874     return stctx;
875 }
876 
877 static void xhci_reset_streams(XHCIEPContext *epctx)
878 {
879     unsigned int i;
880 
881     for (i = 0; i < epctx->nr_pstreams; i++) {
882         epctx->pstreams[i].sct = -1;
883     }
884 }
885 
886 static void xhci_alloc_streams(XHCIEPContext *epctx, dma_addr_t base)
887 {
888     assert(epctx->pstreams == NULL);
889     epctx->nr_pstreams = 2 << epctx->max_pstreams;
890     epctx->pstreams = xhci_alloc_stream_contexts(epctx->nr_pstreams, base);
891 }
892 
893 static void xhci_free_streams(XHCIEPContext *epctx)
894 {
895     assert(epctx->pstreams != NULL);
896 
897     g_free(epctx->pstreams);
898     epctx->pstreams = NULL;
899     epctx->nr_pstreams = 0;
900 }
901 
902 static int xhci_epmask_to_eps_with_streams(XHCIState *xhci,
903                                            unsigned int slotid,
904                                            uint32_t epmask,
905                                            XHCIEPContext **epctxs,
906                                            USBEndpoint **eps)
907 {
908     XHCISlot *slot;
909     XHCIEPContext *epctx;
910     USBEndpoint *ep;
911     int i, j;
912 
913     assert(slotid >= 1 && slotid <= xhci->numslots);
914 
915     slot = &xhci->slots[slotid - 1];
916 
917     for (i = 2, j = 0; i <= 31; i++) {
918         if (!(epmask & (1u << i))) {
919             continue;
920         }
921 
922         epctx = slot->eps[i - 1];
923         ep = xhci_epid_to_usbep(epctx);
924         if (!epctx || !epctx->nr_pstreams || !ep) {
925             continue;
926         }
927 
928         if (epctxs) {
929             epctxs[j] = epctx;
930         }
931         eps[j++] = ep;
932     }
933     return j;
934 }
935 
936 static void xhci_free_device_streams(XHCIState *xhci, unsigned int slotid,
937                                      uint32_t epmask)
938 {
939     USBEndpoint *eps[30];
940     int nr_eps;
941 
942     nr_eps = xhci_epmask_to_eps_with_streams(xhci, slotid, epmask, NULL, eps);
943     if (nr_eps) {
944         usb_device_free_streams(eps[0]->dev, eps, nr_eps);
945     }
946 }
947 
948 static TRBCCode xhci_alloc_device_streams(XHCIState *xhci, unsigned int slotid,
949                                           uint32_t epmask)
950 {
951     XHCIEPContext *epctxs[30];
952     USBEndpoint *eps[30];
953     int i, r, nr_eps, req_nr_streams, dev_max_streams;
954 
955     nr_eps = xhci_epmask_to_eps_with_streams(xhci, slotid, epmask, epctxs,
956                                              eps);
957     if (nr_eps == 0) {
958         return CC_SUCCESS;
959     }
960 
961     req_nr_streams = epctxs[0]->nr_pstreams;
962     dev_max_streams = eps[0]->max_streams;
963 
964     for (i = 1; i < nr_eps; i++) {
965         /*
966          * HdG: I don't expect these to ever trigger, but if they do we need
967          * to come up with another solution, ie group identical endpoints
968          * together and make an usb_device_alloc_streams call per group.
969          */
970         if (epctxs[i]->nr_pstreams != req_nr_streams) {
971             FIXME("guest streams config not identical for all eps");
972             return CC_RESOURCE_ERROR;
973         }
974         if (eps[i]->max_streams != dev_max_streams) {
975             FIXME("device streams config not identical for all eps");
976             return CC_RESOURCE_ERROR;
977         }
978     }
979 
980     /*
981      * max-streams in both the device descriptor and in the controller is a
982      * power of 2. But stream id 0 is reserved, so if a device can do up to 4
983      * streams the guest will ask for 5 rounded up to the next power of 2 which
984      * becomes 8. For emulated devices usb_device_alloc_streams is a nop.
985      *
986      * For redirected devices however this is an issue, as there we must ask
987      * the real xhci controller to alloc streams, and the host driver for the
988      * real xhci controller will likely disallow allocating more streams then
989      * the device can handle.
990      *
991      * So we limit the requested nr_streams to the maximum number the device
992      * can handle.
993      */
994     if (req_nr_streams > dev_max_streams) {
995         req_nr_streams = dev_max_streams;
996     }
997 
998     r = usb_device_alloc_streams(eps[0]->dev, eps, nr_eps, req_nr_streams);
999     if (r != 0) {
1000         DPRINTF("xhci: alloc streams failed\n");
1001         return CC_RESOURCE_ERROR;
1002     }
1003 
1004     return CC_SUCCESS;
1005 }
1006 
1007 static XHCIStreamContext *xhci_find_stream(XHCIEPContext *epctx,
1008                                            unsigned int streamid,
1009                                            uint32_t *cc_error)
1010 {
1011     XHCIStreamContext *sctx;
1012     dma_addr_t base;
1013     uint32_t ctx[2], sct;
1014 
1015     assert(streamid != 0);
1016     if (epctx->lsa) {
1017         if (streamid >= epctx->nr_pstreams) {
1018             *cc_error = CC_INVALID_STREAM_ID_ERROR;
1019             return NULL;
1020         }
1021         sctx = epctx->pstreams + streamid;
1022     } else {
1023         FIXME("secondary streams not implemented yet");
1024     }
1025 
1026     if (sctx->sct == -1) {
1027         xhci_dma_read_u32s(epctx->xhci, sctx->pctx, ctx, sizeof(ctx));
1028         sct = (ctx[0] >> 1) & 0x07;
1029         if (epctx->lsa && sct != 1) {
1030             *cc_error = CC_INVALID_STREAM_TYPE_ERROR;
1031             return NULL;
1032         }
1033         sctx->sct = sct;
1034         base = xhci_addr64(ctx[0] & ~0xf, ctx[1]);
1035         xhci_ring_init(epctx->xhci, &sctx->ring, base);
1036     }
1037     return sctx;
1038 }
1039 
1040 static void xhci_set_ep_state(XHCIState *xhci, XHCIEPContext *epctx,
1041                               XHCIStreamContext *sctx, uint32_t state)
1042 {
1043     XHCIRing *ring = NULL;
1044     uint32_t ctx[5];
1045     uint32_t ctx2[2];
1046 
1047     xhci_dma_read_u32s(xhci, epctx->pctx, ctx, sizeof(ctx));
1048     ctx[0] &= ~EP_STATE_MASK;
1049     ctx[0] |= state;
1050 
1051     /* update ring dequeue ptr */
1052     if (epctx->nr_pstreams) {
1053         if (sctx != NULL) {
1054             ring = &sctx->ring;
1055             xhci_dma_read_u32s(xhci, sctx->pctx, ctx2, sizeof(ctx2));
1056             ctx2[0] &= 0xe;
1057             ctx2[0] |= sctx->ring.dequeue | sctx->ring.ccs;
1058             ctx2[1] = (sctx->ring.dequeue >> 16) >> 16;
1059             xhci_dma_write_u32s(xhci, sctx->pctx, ctx2, sizeof(ctx2));
1060         }
1061     } else {
1062         ring = &epctx->ring;
1063     }
1064     if (ring) {
1065         ctx[2] = ring->dequeue | ring->ccs;
1066         ctx[3] = (ring->dequeue >> 16) >> 16;
1067 
1068         DPRINTF("xhci: set epctx: " DMA_ADDR_FMT " state=%d dequeue=%08x%08x\n",
1069                 epctx->pctx, state, ctx[3], ctx[2]);
1070     }
1071 
1072     xhci_dma_write_u32s(xhci, epctx->pctx, ctx, sizeof(ctx));
1073     if (epctx->state != state) {
1074         trace_usb_xhci_ep_state(epctx->slotid, epctx->epid,
1075                                 ep_state_name(epctx->state),
1076                                 ep_state_name(state));
1077     }
1078     epctx->state = state;
1079 }
1080 
1081 static void xhci_ep_kick_timer(void *opaque)
1082 {
1083     XHCIEPContext *epctx = opaque;
1084     xhci_kick_epctx(epctx, 0);
1085 }
1086 
1087 static XHCIEPContext *xhci_alloc_epctx(XHCIState *xhci,
1088                                        unsigned int slotid,
1089                                        unsigned int epid)
1090 {
1091     XHCIEPContext *epctx;
1092 
1093     epctx = g_new0(XHCIEPContext, 1);
1094     epctx->xhci = xhci;
1095     epctx->slotid = slotid;
1096     epctx->epid = epid;
1097 
1098     QTAILQ_INIT(&epctx->transfers);
1099     epctx->kick_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, xhci_ep_kick_timer, epctx);
1100 
1101     return epctx;
1102 }
1103 
1104 static void xhci_init_epctx(XHCIEPContext *epctx,
1105                             dma_addr_t pctx, uint32_t *ctx)
1106 {
1107     dma_addr_t dequeue;
1108 
1109     dequeue = xhci_addr64(ctx[2] & ~0xf, ctx[3]);
1110 
1111     epctx->type = (ctx[1] >> EP_TYPE_SHIFT) & EP_TYPE_MASK;
1112     epctx->pctx = pctx;
1113     epctx->max_psize = ctx[1]>>16;
1114     epctx->max_psize *= 1+((ctx[1]>>8)&0xff);
1115     epctx->max_pstreams = (ctx[0] >> 10) & epctx->xhci->max_pstreams_mask;
1116     epctx->lsa = (ctx[0] >> 15) & 1;
1117     if (epctx->max_pstreams) {
1118         xhci_alloc_streams(epctx, dequeue);
1119     } else {
1120         xhci_ring_init(epctx->xhci, &epctx->ring, dequeue);
1121         epctx->ring.ccs = ctx[2] & 1;
1122     }
1123 
1124     epctx->interval = 1 << ((ctx[0] >> 16) & 0xff);
1125 }
1126 
1127 static TRBCCode xhci_enable_ep(XHCIState *xhci, unsigned int slotid,
1128                                unsigned int epid, dma_addr_t pctx,
1129                                uint32_t *ctx)
1130 {
1131     XHCISlot *slot;
1132     XHCIEPContext *epctx;
1133 
1134     trace_usb_xhci_ep_enable(slotid, epid);
1135     assert(slotid >= 1 && slotid <= xhci->numslots);
1136     assert(epid >= 1 && epid <= 31);
1137 
1138     slot = &xhci->slots[slotid-1];
1139     if (slot->eps[epid-1]) {
1140         xhci_disable_ep(xhci, slotid, epid);
1141     }
1142 
1143     epctx = xhci_alloc_epctx(xhci, slotid, epid);
1144     slot->eps[epid-1] = epctx;
1145     xhci_init_epctx(epctx, pctx, ctx);
1146 
1147     DPRINTF("xhci: endpoint %d.%d type is %d, max transaction (burst) "
1148             "size is %d\n", epid/2, epid%2, epctx->type, epctx->max_psize);
1149 
1150     epctx->mfindex_last = 0;
1151 
1152     epctx->state = EP_RUNNING;
1153     ctx[0] &= ~EP_STATE_MASK;
1154     ctx[0] |= EP_RUNNING;
1155 
1156     return CC_SUCCESS;
1157 }
1158 
1159 static XHCITransfer *xhci_ep_alloc_xfer(XHCIEPContext *epctx,
1160                                         uint32_t length)
1161 {
1162     uint32_t limit = epctx->nr_pstreams + 16;
1163     XHCITransfer *xfer;
1164 
1165     if (epctx->xfer_count >= limit) {
1166         return NULL;
1167     }
1168 
1169     xfer = g_new0(XHCITransfer, 1);
1170     xfer->epctx = epctx;
1171     xfer->trbs = g_new(XHCITRB, length);
1172     xfer->trb_count = length;
1173     usb_packet_init(&xfer->packet);
1174 
1175     QTAILQ_INSERT_TAIL(&epctx->transfers, xfer, next);
1176     epctx->xfer_count++;
1177 
1178     return xfer;
1179 }
1180 
1181 static void xhci_ep_free_xfer(XHCITransfer *xfer)
1182 {
1183     QTAILQ_REMOVE(&xfer->epctx->transfers, xfer, next);
1184     xfer->epctx->xfer_count--;
1185 
1186     usb_packet_cleanup(&xfer->packet);
1187     g_free(xfer->trbs);
1188     g_free(xfer);
1189 }
1190 
1191 static int xhci_ep_nuke_one_xfer(XHCITransfer *t, TRBCCode report)
1192 {
1193     int killed = 0;
1194 
1195     if (report && (t->running_async || t->running_retry)) {
1196         t->status = report;
1197         xhci_xfer_report(t);
1198     }
1199 
1200     if (t->running_async) {
1201         usb_cancel_packet(&t->packet);
1202         t->running_async = 0;
1203         killed = 1;
1204     }
1205     if (t->running_retry) {
1206         if (t->epctx) {
1207             t->epctx->retry = NULL;
1208             timer_del(t->epctx->kick_timer);
1209         }
1210         t->running_retry = 0;
1211         killed = 1;
1212     }
1213     g_free(t->trbs);
1214 
1215     t->trbs = NULL;
1216     t->trb_count = 0;
1217 
1218     return killed;
1219 }
1220 
1221 static int xhci_ep_nuke_xfers(XHCIState *xhci, unsigned int slotid,
1222                                unsigned int epid, TRBCCode report)
1223 {
1224     XHCISlot *slot;
1225     XHCIEPContext *epctx;
1226     XHCITransfer *xfer;
1227     int killed = 0;
1228     USBEndpoint *ep = NULL;
1229     assert(slotid >= 1 && slotid <= xhci->numslots);
1230     assert(epid >= 1 && epid <= 31);
1231 
1232     DPRINTF("xhci_ep_nuke_xfers(%d, %d)\n", slotid, epid);
1233 
1234     slot = &xhci->slots[slotid-1];
1235 
1236     if (!slot->eps[epid-1]) {
1237         return 0;
1238     }
1239 
1240     epctx = slot->eps[epid-1];
1241 
1242     for (;;) {
1243         xfer = QTAILQ_FIRST(&epctx->transfers);
1244         if (xfer == NULL) {
1245             break;
1246         }
1247         killed += xhci_ep_nuke_one_xfer(xfer, report);
1248         if (killed) {
1249             report = 0; /* Only report once */
1250         }
1251         xhci_ep_free_xfer(xfer);
1252     }
1253 
1254     ep = xhci_epid_to_usbep(epctx);
1255     if (ep) {
1256         usb_device_ep_stopped(ep->dev, ep);
1257     }
1258     return killed;
1259 }
1260 
1261 static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,
1262                                unsigned int epid)
1263 {
1264     XHCISlot *slot;
1265     XHCIEPContext *epctx;
1266 
1267     trace_usb_xhci_ep_disable(slotid, epid);
1268     assert(slotid >= 1 && slotid <= xhci->numslots);
1269     assert(epid >= 1 && epid <= 31);
1270 
1271     slot = &xhci->slots[slotid-1];
1272 
1273     if (!slot->eps[epid-1]) {
1274         DPRINTF("xhci: slot %d ep %d already disabled\n", slotid, epid);
1275         return CC_SUCCESS;
1276     }
1277 
1278     xhci_ep_nuke_xfers(xhci, slotid, epid, 0);
1279 
1280     epctx = slot->eps[epid-1];
1281 
1282     if (epctx->nr_pstreams) {
1283         xhci_free_streams(epctx);
1284     }
1285 
1286     /* only touch guest RAM if we're not resetting the HC */
1287     if (xhci->dcbaap_low || xhci->dcbaap_high) {
1288         xhci_set_ep_state(xhci, epctx, NULL, EP_DISABLED);
1289     }
1290 
1291     timer_free(epctx->kick_timer);
1292     g_free(epctx);
1293     slot->eps[epid-1] = NULL;
1294 
1295     return CC_SUCCESS;
1296 }
1297 
1298 static TRBCCode xhci_stop_ep(XHCIState *xhci, unsigned int slotid,
1299                              unsigned int epid)
1300 {
1301     XHCISlot *slot;
1302     XHCIEPContext *epctx;
1303 
1304     trace_usb_xhci_ep_stop(slotid, epid);
1305     assert(slotid >= 1 && slotid <= xhci->numslots);
1306 
1307     if (epid < 1 || epid > 31) {
1308         DPRINTF("xhci: bad ep %d\n", epid);
1309         return CC_TRB_ERROR;
1310     }
1311 
1312     slot = &xhci->slots[slotid-1];
1313 
1314     if (!slot->eps[epid-1]) {
1315         DPRINTF("xhci: slot %d ep %d not enabled\n", slotid, epid);
1316         return CC_EP_NOT_ENABLED_ERROR;
1317     }
1318 
1319     if (xhci_ep_nuke_xfers(xhci, slotid, epid, CC_STOPPED) > 0) {
1320         DPRINTF("xhci: FIXME: endpoint stopped w/ xfers running, "
1321                 "data might be lost\n");
1322     }
1323 
1324     epctx = slot->eps[epid-1];
1325 
1326     xhci_set_ep_state(xhci, epctx, NULL, EP_STOPPED);
1327 
1328     if (epctx->nr_pstreams) {
1329         xhci_reset_streams(epctx);
1330     }
1331 
1332     return CC_SUCCESS;
1333 }
1334 
1335 static TRBCCode xhci_reset_ep(XHCIState *xhci, unsigned int slotid,
1336                               unsigned int epid)
1337 {
1338     XHCISlot *slot;
1339     XHCIEPContext *epctx;
1340 
1341     trace_usb_xhci_ep_reset(slotid, epid);
1342     assert(slotid >= 1 && slotid <= xhci->numslots);
1343 
1344     if (epid < 1 || epid > 31) {
1345         DPRINTF("xhci: bad ep %d\n", epid);
1346         return CC_TRB_ERROR;
1347     }
1348 
1349     slot = &xhci->slots[slotid-1];
1350 
1351     if (!slot->eps[epid-1]) {
1352         DPRINTF("xhci: slot %d ep %d not enabled\n", slotid, epid);
1353         return CC_EP_NOT_ENABLED_ERROR;
1354     }
1355 
1356     epctx = slot->eps[epid-1];
1357 
1358     if (epctx->state != EP_HALTED) {
1359         DPRINTF("xhci: reset EP while EP %d not halted (%d)\n",
1360                 epid, epctx->state);
1361         return CC_CONTEXT_STATE_ERROR;
1362     }
1363 
1364     if (xhci_ep_nuke_xfers(xhci, slotid, epid, 0) > 0) {
1365         DPRINTF("xhci: FIXME: endpoint reset w/ xfers running, "
1366                 "data might be lost\n");
1367     }
1368 
1369     if (!xhci->slots[slotid-1].uport ||
1370         !xhci->slots[slotid-1].uport->dev ||
1371         !xhci->slots[slotid-1].uport->dev->attached) {
1372         return CC_USB_TRANSACTION_ERROR;
1373     }
1374 
1375     xhci_set_ep_state(xhci, epctx, NULL, EP_STOPPED);
1376 
1377     if (epctx->nr_pstreams) {
1378         xhci_reset_streams(epctx);
1379     }
1380 
1381     return CC_SUCCESS;
1382 }
1383 
1384 static TRBCCode xhci_set_ep_dequeue(XHCIState *xhci, unsigned int slotid,
1385                                     unsigned int epid, unsigned int streamid,
1386                                     uint64_t pdequeue)
1387 {
1388     XHCISlot *slot;
1389     XHCIEPContext *epctx;
1390     XHCIStreamContext *sctx;
1391     dma_addr_t dequeue;
1392 
1393     assert(slotid >= 1 && slotid <= xhci->numslots);
1394 
1395     if (epid < 1 || epid > 31) {
1396         DPRINTF("xhci: bad ep %d\n", epid);
1397         return CC_TRB_ERROR;
1398     }
1399 
1400     trace_usb_xhci_ep_set_dequeue(slotid, epid, streamid, pdequeue);
1401     dequeue = xhci_mask64(pdequeue);
1402 
1403     slot = &xhci->slots[slotid-1];
1404 
1405     if (!slot->eps[epid-1]) {
1406         DPRINTF("xhci: slot %d ep %d not enabled\n", slotid, epid);
1407         return CC_EP_NOT_ENABLED_ERROR;
1408     }
1409 
1410     epctx = slot->eps[epid-1];
1411 
1412     if (epctx->state != EP_STOPPED) {
1413         DPRINTF("xhci: set EP dequeue pointer while EP %d not stopped\n", epid);
1414         return CC_CONTEXT_STATE_ERROR;
1415     }
1416 
1417     if (epctx->nr_pstreams) {
1418         uint32_t err;
1419         sctx = xhci_find_stream(epctx, streamid, &err);
1420         if (sctx == NULL) {
1421             return err;
1422         }
1423         xhci_ring_init(xhci, &sctx->ring, dequeue & ~0xf);
1424         sctx->ring.ccs = dequeue & 1;
1425     } else {
1426         sctx = NULL;
1427         xhci_ring_init(xhci, &epctx->ring, dequeue & ~0xF);
1428         epctx->ring.ccs = dequeue & 1;
1429     }
1430 
1431     xhci_set_ep_state(xhci, epctx, sctx, EP_STOPPED);
1432 
1433     return CC_SUCCESS;
1434 }
1435 
1436 static int xhci_xfer_create_sgl(XHCITransfer *xfer, int in_xfer)
1437 {
1438     XHCIState *xhci = xfer->epctx->xhci;
1439     int i;
1440 
1441     xfer->int_req = false;
1442     qemu_sglist_init(&xfer->sgl, DEVICE(xhci), xfer->trb_count, xhci->as);
1443     for (i = 0; i < xfer->trb_count; i++) {
1444         XHCITRB *trb = &xfer->trbs[i];
1445         dma_addr_t addr;
1446         unsigned int chunk = 0;
1447 
1448         if (trb->control & TRB_TR_IOC) {
1449             xfer->int_req = true;
1450         }
1451 
1452         switch (TRB_TYPE(*trb)) {
1453         case TR_DATA:
1454             if ((!(trb->control & TRB_TR_DIR)) != (!in_xfer)) {
1455                 DPRINTF("xhci: data direction mismatch for TR_DATA\n");
1456                 goto err;
1457             }
1458             /* fallthrough */
1459         case TR_NORMAL:
1460         case TR_ISOCH:
1461             addr = xhci_mask64(trb->parameter);
1462             chunk = trb->status & 0x1ffff;
1463             if (trb->control & TRB_TR_IDT) {
1464                 if (chunk > 8 || in_xfer) {
1465                     DPRINTF("xhci: invalid immediate data TRB\n");
1466                     goto err;
1467                 }
1468                 qemu_sglist_add(&xfer->sgl, trb->addr, chunk);
1469             } else {
1470                 qemu_sglist_add(&xfer->sgl, addr, chunk);
1471             }
1472             break;
1473         }
1474     }
1475 
1476     return 0;
1477 
1478 err:
1479     qemu_sglist_destroy(&xfer->sgl);
1480     xhci_die(xhci);
1481     return -1;
1482 }
1483 
1484 static void xhci_xfer_unmap(XHCITransfer *xfer)
1485 {
1486     usb_packet_unmap(&xfer->packet, &xfer->sgl);
1487     qemu_sglist_destroy(&xfer->sgl);
1488 }
1489 
1490 static void xhci_xfer_report(XHCITransfer *xfer)
1491 {
1492     uint32_t edtla = 0;
1493     unsigned int left;
1494     bool reported = 0;
1495     bool shortpkt = 0;
1496     XHCIEvent event = {ER_TRANSFER, CC_SUCCESS};
1497     XHCIState *xhci = xfer->epctx->xhci;
1498     int i;
1499 
1500     left = xfer->packet.actual_length;
1501 
1502     for (i = 0; i < xfer->trb_count; i++) {
1503         XHCITRB *trb = &xfer->trbs[i];
1504         unsigned int chunk = 0;
1505 
1506         switch (TRB_TYPE(*trb)) {
1507         case TR_SETUP:
1508             chunk = trb->status & 0x1ffff;
1509             if (chunk > 8) {
1510                 chunk = 8;
1511             }
1512             break;
1513         case TR_DATA:
1514         case TR_NORMAL:
1515         case TR_ISOCH:
1516             chunk = trb->status & 0x1ffff;
1517             if (chunk > left) {
1518                 chunk = left;
1519                 if (xfer->status == CC_SUCCESS) {
1520                     shortpkt = 1;
1521                 }
1522             }
1523             left -= chunk;
1524             edtla += chunk;
1525             break;
1526         case TR_STATUS:
1527             reported = 0;
1528             shortpkt = 0;
1529             break;
1530         }
1531 
1532         if (!reported && ((trb->control & TRB_TR_IOC) ||
1533                           (shortpkt && (trb->control & TRB_TR_ISP)) ||
1534                           (xfer->status != CC_SUCCESS && left == 0))) {
1535             event.slotid = xfer->epctx->slotid;
1536             event.epid = xfer->epctx->epid;
1537             event.length = (trb->status & 0x1ffff) - chunk;
1538             event.flags = 0;
1539             event.ptr = trb->addr;
1540             if (xfer->status == CC_SUCCESS) {
1541                 event.ccode = shortpkt ? CC_SHORT_PACKET : CC_SUCCESS;
1542             } else {
1543                 event.ccode = xfer->status;
1544             }
1545             if (TRB_TYPE(*trb) == TR_EVDATA) {
1546                 event.ptr = trb->parameter;
1547                 event.flags |= TRB_EV_ED;
1548                 event.length = edtla & 0xffffff;
1549                 DPRINTF("xhci_xfer_data: EDTLA=%d\n", event.length);
1550                 edtla = 0;
1551             }
1552             xhci_event(xhci, &event, TRB_INTR(*trb));
1553             reported = 1;
1554             if (xfer->status != CC_SUCCESS) {
1555                 return;
1556             }
1557         }
1558 
1559         switch (TRB_TYPE(*trb)) {
1560         case TR_SETUP:
1561             reported = 0;
1562             shortpkt = 0;
1563             break;
1564         }
1565 
1566     }
1567 }
1568 
1569 static void xhci_stall_ep(XHCITransfer *xfer)
1570 {
1571     XHCIEPContext *epctx = xfer->epctx;
1572     XHCIState *xhci = epctx->xhci;
1573     uint32_t err;
1574     XHCIStreamContext *sctx;
1575 
1576     if (epctx->type == ET_ISO_IN || epctx->type == ET_ISO_OUT) {
1577         /* never halt isoch endpoints, 4.10.2 */
1578         return;
1579     }
1580 
1581     if (epctx->nr_pstreams) {
1582         sctx = xhci_find_stream(epctx, xfer->streamid, &err);
1583         if (sctx == NULL) {
1584             return;
1585         }
1586         sctx->ring.dequeue = xfer->trbs[0].addr;
1587         sctx->ring.ccs = xfer->trbs[0].ccs;
1588         xhci_set_ep_state(xhci, epctx, sctx, EP_HALTED);
1589     } else {
1590         epctx->ring.dequeue = xfer->trbs[0].addr;
1591         epctx->ring.ccs = xfer->trbs[0].ccs;
1592         xhci_set_ep_state(xhci, epctx, NULL, EP_HALTED);
1593     }
1594 }
1595 
1596 static int xhci_setup_packet(XHCITransfer *xfer)
1597 {
1598     USBEndpoint *ep;
1599     int dir;
1600 
1601     dir = xfer->in_xfer ? USB_TOKEN_IN : USB_TOKEN_OUT;
1602 
1603     if (xfer->packet.ep) {
1604         ep = xfer->packet.ep;
1605     } else {
1606         ep = xhci_epid_to_usbep(xfer->epctx);
1607         if (!ep) {
1608             DPRINTF("xhci: slot %d has no device\n",
1609                     xfer->epctx->slotid);
1610             return -1;
1611         }
1612     }
1613 
1614     xhci_xfer_create_sgl(xfer, dir == USB_TOKEN_IN); /* Also sets int_req */
1615     usb_packet_setup(&xfer->packet, dir, ep, xfer->streamid,
1616                      xfer->trbs[0].addr, false, xfer->int_req);
1617     if (usb_packet_map(&xfer->packet, &xfer->sgl)) {
1618         qemu_sglist_destroy(&xfer->sgl);
1619         return -1;
1620     }
1621     DPRINTF("xhci: setup packet pid 0x%x addr %d ep %d\n",
1622             xfer->packet.pid, ep->dev->addr, ep->nr);
1623     return 0;
1624 }
1625 
1626 static int xhci_try_complete_packet(XHCITransfer *xfer)
1627 {
1628     if (xfer->packet.status == USB_RET_ASYNC) {
1629         trace_usb_xhci_xfer_async(xfer);
1630         xfer->running_async = 1;
1631         xfer->running_retry = 0;
1632         xfer->complete = 0;
1633         return 0;
1634     } else if (xfer->packet.status == USB_RET_NAK) {
1635         trace_usb_xhci_xfer_nak(xfer);
1636         xfer->running_async = 0;
1637         xfer->running_retry = 1;
1638         xfer->complete = 0;
1639         return 0;
1640     } else {
1641         xfer->running_async = 0;
1642         xfer->running_retry = 0;
1643         xfer->complete = 1;
1644         xhci_xfer_unmap(xfer);
1645     }
1646 
1647     if (xfer->packet.status == USB_RET_SUCCESS) {
1648         trace_usb_xhci_xfer_success(xfer, xfer->packet.actual_length);
1649         xfer->status = CC_SUCCESS;
1650         xhci_xfer_report(xfer);
1651         return 0;
1652     }
1653 
1654     /* error */
1655     trace_usb_xhci_xfer_error(xfer, xfer->packet.status);
1656     switch (xfer->packet.status) {
1657     case USB_RET_NODEV:
1658     case USB_RET_IOERROR:
1659         xfer->status = CC_USB_TRANSACTION_ERROR;
1660         xhci_xfer_report(xfer);
1661         xhci_stall_ep(xfer);
1662         break;
1663     case USB_RET_STALL:
1664         xfer->status = CC_STALL_ERROR;
1665         xhci_xfer_report(xfer);
1666         xhci_stall_ep(xfer);
1667         break;
1668     case USB_RET_BABBLE:
1669         xfer->status = CC_BABBLE_DETECTED;
1670         xhci_xfer_report(xfer);
1671         xhci_stall_ep(xfer);
1672         break;
1673     default:
1674         DPRINTF("%s: FIXME: status = %d\n", __func__,
1675                 xfer->packet.status);
1676         FIXME("unhandled USB_RET_*");
1677     }
1678     return 0;
1679 }
1680 
1681 static int xhci_fire_ctl_transfer(XHCIState *xhci, XHCITransfer *xfer)
1682 {
1683     XHCITRB *trb_setup, *trb_status;
1684     uint8_t bmRequestType;
1685 
1686     trb_setup = &xfer->trbs[0];
1687     trb_status = &xfer->trbs[xfer->trb_count-1];
1688 
1689     trace_usb_xhci_xfer_start(xfer, xfer->epctx->slotid,
1690                               xfer->epctx->epid, xfer->streamid);
1691 
1692     /* at most one Event Data TRB allowed after STATUS */
1693     if (TRB_TYPE(*trb_status) == TR_EVDATA && xfer->trb_count > 2) {
1694         trb_status--;
1695     }
1696 
1697     /* do some sanity checks */
1698     if (TRB_TYPE(*trb_setup) != TR_SETUP) {
1699         DPRINTF("xhci: ep0 first TD not SETUP: %d\n",
1700                 TRB_TYPE(*trb_setup));
1701         return -1;
1702     }
1703     if (TRB_TYPE(*trb_status) != TR_STATUS) {
1704         DPRINTF("xhci: ep0 last TD not STATUS: %d\n",
1705                 TRB_TYPE(*trb_status));
1706         return -1;
1707     }
1708     if (!(trb_setup->control & TRB_TR_IDT)) {
1709         DPRINTF("xhci: Setup TRB doesn't have IDT set\n");
1710         return -1;
1711     }
1712     if ((trb_setup->status & 0x1ffff) != 8) {
1713         DPRINTF("xhci: Setup TRB has bad length (%d)\n",
1714                 (trb_setup->status & 0x1ffff));
1715         return -1;
1716     }
1717 
1718     bmRequestType = trb_setup->parameter;
1719 
1720     xfer->in_xfer = bmRequestType & USB_DIR_IN;
1721     xfer->iso_xfer = false;
1722     xfer->timed_xfer = false;
1723 
1724     if (xhci_setup_packet(xfer) < 0) {
1725         return -1;
1726     }
1727     xfer->packet.parameter = trb_setup->parameter;
1728 
1729     usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
1730     xhci_try_complete_packet(xfer);
1731     return 0;
1732 }
1733 
1734 static void xhci_calc_intr_kick(XHCIState *xhci, XHCITransfer *xfer,
1735                                 XHCIEPContext *epctx, uint64_t mfindex)
1736 {
1737     uint64_t asap = ((mfindex + epctx->interval - 1) &
1738                      ~(epctx->interval-1));
1739     uint64_t kick = epctx->mfindex_last + epctx->interval;
1740 
1741     assert(epctx->interval != 0);
1742     xfer->mfindex_kick = MAX(asap, kick);
1743 }
1744 
1745 static void xhci_calc_iso_kick(XHCIState *xhci, XHCITransfer *xfer,
1746                                XHCIEPContext *epctx, uint64_t mfindex)
1747 {
1748     if (xfer->trbs[0].control & TRB_TR_SIA) {
1749         uint64_t asap = ((mfindex + epctx->interval - 1) &
1750                          ~(epctx->interval-1));
1751         if (asap >= epctx->mfindex_last &&
1752             asap <= epctx->mfindex_last + epctx->interval * 4) {
1753             xfer->mfindex_kick = epctx->mfindex_last + epctx->interval;
1754         } else {
1755             xfer->mfindex_kick = asap;
1756         }
1757     } else {
1758         xfer->mfindex_kick = ((xfer->trbs[0].control >> TRB_TR_FRAMEID_SHIFT)
1759                               & TRB_TR_FRAMEID_MASK) << 3;
1760         xfer->mfindex_kick |= mfindex & ~0x3fff;
1761         if (xfer->mfindex_kick + 0x100 < mfindex) {
1762             xfer->mfindex_kick += 0x4000;
1763         }
1764     }
1765 }
1766 
1767 static void xhci_check_intr_iso_kick(XHCIState *xhci, XHCITransfer *xfer,
1768                                      XHCIEPContext *epctx, uint64_t mfindex)
1769 {
1770     if (xfer->mfindex_kick > mfindex) {
1771         timer_mod(epctx->kick_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1772                        (xfer->mfindex_kick - mfindex) * 125000);
1773         xfer->running_retry = 1;
1774     } else {
1775         epctx->mfindex_last = xfer->mfindex_kick;
1776         timer_del(epctx->kick_timer);
1777         xfer->running_retry = 0;
1778     }
1779 }
1780 
1781 
1782 static int xhci_submit(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)
1783 {
1784     uint64_t mfindex;
1785 
1786     DPRINTF("xhci_submit(slotid=%d,epid=%d)\n", epctx->slotid, epctx->epid);
1787 
1788     xfer->in_xfer = epctx->type>>2;
1789 
1790     switch(epctx->type) {
1791     case ET_INTR_OUT:
1792     case ET_INTR_IN:
1793         xfer->pkts = 0;
1794         xfer->iso_xfer = false;
1795         xfer->timed_xfer = true;
1796         mfindex = xhci_mfindex_get(xhci);
1797         xhci_calc_intr_kick(xhci, xfer, epctx, mfindex);
1798         xhci_check_intr_iso_kick(xhci, xfer, epctx, mfindex);
1799         if (xfer->running_retry) {
1800             return -1;
1801         }
1802         break;
1803     case ET_BULK_OUT:
1804     case ET_BULK_IN:
1805         xfer->pkts = 0;
1806         xfer->iso_xfer = false;
1807         xfer->timed_xfer = false;
1808         break;
1809     case ET_ISO_OUT:
1810     case ET_ISO_IN:
1811         xfer->pkts = 1;
1812         xfer->iso_xfer = true;
1813         xfer->timed_xfer = true;
1814         mfindex = xhci_mfindex_get(xhci);
1815         xhci_calc_iso_kick(xhci, xfer, epctx, mfindex);
1816         xhci_check_intr_iso_kick(xhci, xfer, epctx, mfindex);
1817         if (xfer->running_retry) {
1818             return -1;
1819         }
1820         break;
1821     default:
1822         trace_usb_xhci_unimplemented("endpoint type", epctx->type);
1823         return -1;
1824     }
1825 
1826     if (xhci_setup_packet(xfer) < 0) {
1827         return -1;
1828     }
1829     usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
1830     xhci_try_complete_packet(xfer);
1831     return 0;
1832 }
1833 
1834 static int xhci_fire_transfer(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)
1835 {
1836     trace_usb_xhci_xfer_start(xfer, xfer->epctx->slotid,
1837                               xfer->epctx->epid, xfer->streamid);
1838     return xhci_submit(xhci, xfer, epctx);
1839 }
1840 
1841 static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
1842                          unsigned int epid, unsigned int streamid)
1843 {
1844     XHCIEPContext *epctx;
1845 
1846     assert(slotid >= 1 && slotid <= xhci->numslots);
1847     assert(epid >= 1 && epid <= 31);
1848 
1849     if (!xhci->slots[slotid-1].enabled) {
1850         DPRINTF("xhci: xhci_kick_ep for disabled slot %d\n", slotid);
1851         return;
1852     }
1853     epctx = xhci->slots[slotid-1].eps[epid-1];
1854     if (!epctx) {
1855         DPRINTF("xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
1856                 epid, slotid);
1857         return;
1858     }
1859 
1860     if (epctx->kick_active) {
1861         return;
1862     }
1863     xhci_kick_epctx(epctx, streamid);
1864 }
1865 
1866 static bool xhci_slot_ok(XHCIState *xhci, int slotid)
1867 {
1868     return (xhci->slots[slotid - 1].uport &&
1869             xhci->slots[slotid - 1].uport->dev &&
1870             xhci->slots[slotid - 1].uport->dev->attached);
1871 }
1872 
1873 static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid)
1874 {
1875     XHCIState *xhci = epctx->xhci;
1876     XHCIStreamContext *stctx = NULL;
1877     XHCITransfer *xfer;
1878     XHCIRing *ring;
1879     USBEndpoint *ep = NULL;
1880     uint64_t mfindex;
1881     unsigned int count = 0;
1882     int length;
1883     int i;
1884 
1885     trace_usb_xhci_ep_kick(epctx->slotid, epctx->epid, streamid);
1886     assert(!epctx->kick_active);
1887 
1888     /* If the device has been detached, but the guest has not noticed this
1889        yet the 2 above checks will succeed, but we must NOT continue */
1890     if (!xhci_slot_ok(xhci, epctx->slotid)) {
1891         return;
1892     }
1893 
1894     if (epctx->retry) {
1895         XHCITransfer *xfer = epctx->retry;
1896 
1897         trace_usb_xhci_xfer_retry(xfer);
1898         assert(xfer->running_retry);
1899         if (xfer->timed_xfer) {
1900             /* time to kick the transfer? */
1901             mfindex = xhci_mfindex_get(xhci);
1902             xhci_check_intr_iso_kick(xhci, xfer, epctx, mfindex);
1903             if (xfer->running_retry) {
1904                 return;
1905             }
1906             xfer->timed_xfer = 0;
1907             xfer->running_retry = 1;
1908         }
1909         if (xfer->iso_xfer) {
1910             /* retry iso transfer */
1911             if (xhci_setup_packet(xfer) < 0) {
1912                 return;
1913             }
1914             usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
1915             assert(xfer->packet.status != USB_RET_NAK);
1916             xhci_try_complete_packet(xfer);
1917         } else {
1918             /* retry nak'ed transfer */
1919             if (xhci_setup_packet(xfer) < 0) {
1920                 return;
1921             }
1922             usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
1923             if (xfer->packet.status == USB_RET_NAK) {
1924                 xhci_xfer_unmap(xfer);
1925                 return;
1926             }
1927             xhci_try_complete_packet(xfer);
1928         }
1929         assert(!xfer->running_retry);
1930         if (xfer->complete) {
1931             /* update ring dequeue ptr */
1932             xhci_set_ep_state(xhci, epctx, stctx, epctx->state);
1933             xhci_ep_free_xfer(epctx->retry);
1934         }
1935         epctx->retry = NULL;
1936     }
1937 
1938     if (epctx->state == EP_HALTED) {
1939         DPRINTF("xhci: ep halted, not running schedule\n");
1940         return;
1941     }
1942 
1943 
1944     if (epctx->nr_pstreams) {
1945         uint32_t err;
1946         stctx = xhci_find_stream(epctx, streamid, &err);
1947         if (stctx == NULL) {
1948             return;
1949         }
1950         ring = &stctx->ring;
1951         xhci_set_ep_state(xhci, epctx, stctx, EP_RUNNING);
1952     } else {
1953         ring = &epctx->ring;
1954         streamid = 0;
1955         xhci_set_ep_state(xhci, epctx, NULL, EP_RUNNING);
1956     }
1957     if (!ring->dequeue) {
1958         return;
1959     }
1960 
1961     epctx->kick_active++;
1962     while (1) {
1963         length = xhci_ring_chain_length(xhci, ring);
1964         if (length <= 0) {
1965             if (epctx->type == ET_ISO_OUT || epctx->type == ET_ISO_IN) {
1966                 /* 4.10.3.1 */
1967                 XHCIEvent ev = { ER_TRANSFER };
1968                 ev.ccode  = epctx->type == ET_ISO_IN ?
1969                     CC_RING_OVERRUN : CC_RING_UNDERRUN;
1970                 ev.slotid = epctx->slotid;
1971                 ev.epid   = epctx->epid;
1972                 ev.ptr    = epctx->ring.dequeue;
1973                 xhci_event(xhci, &ev, xhci->slots[epctx->slotid-1].intr);
1974             }
1975             break;
1976         }
1977         xfer = xhci_ep_alloc_xfer(epctx, length);
1978         if (xfer == NULL) {
1979             break;
1980         }
1981 
1982         for (i = 0; i < length; i++) {
1983             TRBType type;
1984             type = xhci_ring_fetch(xhci, ring, &xfer->trbs[i], NULL);
1985             if (!type) {
1986                 xhci_die(xhci);
1987                 xhci_ep_free_xfer(xfer);
1988                 epctx->kick_active--;
1989                 return;
1990             }
1991         }
1992         xfer->streamid = streamid;
1993 
1994         if (epctx->epid == 1) {
1995             xhci_fire_ctl_transfer(xhci, xfer);
1996         } else {
1997             xhci_fire_transfer(xhci, xfer, epctx);
1998         }
1999         if (!xhci_slot_ok(xhci, epctx->slotid)) {
2000             /* surprise removal -> stop processing */
2001             break;
2002         }
2003         if (xfer->complete) {
2004             /* update ring dequeue ptr */
2005             xhci_set_ep_state(xhci, epctx, stctx, epctx->state);
2006             xhci_ep_free_xfer(xfer);
2007             xfer = NULL;
2008         }
2009 
2010         if (epctx->state == EP_HALTED) {
2011             break;
2012         }
2013         if (xfer != NULL && xfer->running_retry) {
2014             DPRINTF("xhci: xfer nacked, stopping schedule\n");
2015             epctx->retry = xfer;
2016             xhci_xfer_unmap(xfer);
2017             break;
2018         }
2019         if (count++ > TRANSFER_LIMIT) {
2020             trace_usb_xhci_enforced_limit("transfers");
2021             break;
2022         }
2023     }
2024     epctx->kick_active--;
2025 
2026     ep = xhci_epid_to_usbep(epctx);
2027     if (ep) {
2028         usb_device_flush_ep_queue(ep->dev, ep);
2029     }
2030 }
2031 
2032 static TRBCCode xhci_enable_slot(XHCIState *xhci, unsigned int slotid)
2033 {
2034     trace_usb_xhci_slot_enable(slotid);
2035     assert(slotid >= 1 && slotid <= xhci->numslots);
2036     xhci->slots[slotid-1].enabled = 1;
2037     xhci->slots[slotid-1].uport = NULL;
2038     memset(xhci->slots[slotid-1].eps, 0, sizeof(XHCIEPContext*)*31);
2039 
2040     return CC_SUCCESS;
2041 }
2042 
2043 static TRBCCode xhci_disable_slot(XHCIState *xhci, unsigned int slotid)
2044 {
2045     int i;
2046 
2047     trace_usb_xhci_slot_disable(slotid);
2048     assert(slotid >= 1 && slotid <= xhci->numslots);
2049 
2050     for (i = 1; i <= 31; i++) {
2051         if (xhci->slots[slotid-1].eps[i-1]) {
2052             xhci_disable_ep(xhci, slotid, i);
2053         }
2054     }
2055 
2056     xhci->slots[slotid-1].enabled = 0;
2057     xhci->slots[slotid-1].addressed = 0;
2058     xhci->slots[slotid-1].uport = NULL;
2059     xhci->slots[slotid-1].intr = 0;
2060     return CC_SUCCESS;
2061 }
2062 
2063 static USBPort *xhci_lookup_uport(XHCIState *xhci, uint32_t *slot_ctx)
2064 {
2065     USBPort *uport;
2066     char path[32];
2067     int i, pos, port;
2068 
2069     port = (slot_ctx[1]>>16) & 0xFF;
2070     if (port < 1 || port > xhci->numports) {
2071         return NULL;
2072     }
2073     port = xhci->ports[port-1].uport->index+1;
2074     pos = snprintf(path, sizeof(path), "%d", port);
2075     for (i = 0; i < 5; i++) {
2076         port = (slot_ctx[0] >> 4*i) & 0x0f;
2077         if (!port) {
2078             break;
2079         }
2080         pos += snprintf(path + pos, sizeof(path) - pos, ".%d", port);
2081     }
2082 
2083     QTAILQ_FOREACH(uport, &xhci->bus.used, next) {
2084         if (strcmp(uport->path, path) == 0) {
2085             return uport;
2086         }
2087     }
2088     return NULL;
2089 }
2090 
2091 static TRBCCode xhci_address_slot(XHCIState *xhci, unsigned int slotid,
2092                                   uint64_t pictx, bool bsr)
2093 {
2094     XHCISlot *slot;
2095     USBPort *uport;
2096     USBDevice *dev;
2097     dma_addr_t ictx, octx, dcbaap;
2098     uint64_t poctx;
2099     uint32_t ictl_ctx[2];
2100     uint32_t slot_ctx[4];
2101     uint32_t ep0_ctx[5];
2102     int i;
2103     TRBCCode res;
2104 
2105     assert(slotid >= 1 && slotid <= xhci->numslots);
2106 
2107     dcbaap = xhci_addr64(xhci->dcbaap_low, xhci->dcbaap_high);
2108     ldq_le_dma(xhci->as, dcbaap + 8 * slotid, &poctx, MEMTXATTRS_UNSPECIFIED);
2109     ictx = xhci_mask64(pictx);
2110     octx = xhci_mask64(poctx);
2111 
2112     DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
2113     DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
2114 
2115     xhci_dma_read_u32s(xhci, ictx, ictl_ctx, sizeof(ictl_ctx));
2116 
2117     if (ictl_ctx[0] != 0x0 || ictl_ctx[1] != 0x3) {
2118         DPRINTF("xhci: invalid input context control %08x %08x\n",
2119                 ictl_ctx[0], ictl_ctx[1]);
2120         return CC_TRB_ERROR;
2121     }
2122 
2123     xhci_dma_read_u32s(xhci, ictx+32, slot_ctx, sizeof(slot_ctx));
2124     xhci_dma_read_u32s(xhci, ictx+64, ep0_ctx, sizeof(ep0_ctx));
2125 
2126     DPRINTF("xhci: input slot context: %08x %08x %08x %08x\n",
2127             slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
2128 
2129     DPRINTF("xhci: input ep0 context: %08x %08x %08x %08x %08x\n",
2130             ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);
2131 
2132     uport = xhci_lookup_uport(xhci, slot_ctx);
2133     if (uport == NULL) {
2134         DPRINTF("xhci: port not found\n");
2135         return CC_TRB_ERROR;
2136     }
2137     trace_usb_xhci_slot_address(slotid, uport->path);
2138 
2139     dev = uport->dev;
2140     if (!dev || !dev->attached) {
2141         DPRINTF("xhci: port %s not connected\n", uport->path);
2142         return CC_USB_TRANSACTION_ERROR;
2143     }
2144 
2145     for (i = 0; i < xhci->numslots; i++) {
2146         if (i == slotid-1) {
2147             continue;
2148         }
2149         if (xhci->slots[i].uport == uport) {
2150             DPRINTF("xhci: port %s already assigned to slot %d\n",
2151                     uport->path, i+1);
2152             return CC_TRB_ERROR;
2153         }
2154     }
2155 
2156     slot = &xhci->slots[slotid-1];
2157     slot->uport = uport;
2158     slot->ctx = octx;
2159     slot->intr = get_field(slot_ctx[2], TRB_INTR);
2160 
2161     /* Make sure device is in USB_STATE_DEFAULT state */
2162     usb_device_reset(dev);
2163     if (bsr) {
2164         slot_ctx[3] = SLOT_DEFAULT << SLOT_STATE_SHIFT;
2165     } else {
2166         USBPacket p;
2167         uint8_t buf[1];
2168 
2169         slot_ctx[3] = (SLOT_ADDRESSED << SLOT_STATE_SHIFT) | slotid;
2170         memset(&p, 0, sizeof(p));
2171         usb_packet_addbuf(&p, buf, sizeof(buf));
2172         usb_packet_setup(&p, USB_TOKEN_OUT,
2173                          usb_ep_get(dev, USB_TOKEN_OUT, 0), 0,
2174                          0, false, false);
2175         usb_device_handle_control(dev, &p,
2176                                   DeviceOutRequest | USB_REQ_SET_ADDRESS,
2177                                   slotid, 0, 0, NULL);
2178         assert(p.status != USB_RET_ASYNC);
2179         usb_packet_cleanup(&p);
2180     }
2181 
2182     res = xhci_enable_ep(xhci, slotid, 1, octx+32, ep0_ctx);
2183 
2184     DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
2185             slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
2186     DPRINTF("xhci: output ep0 context: %08x %08x %08x %08x %08x\n",
2187             ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);
2188 
2189     xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2190     xhci_dma_write_u32s(xhci, octx+32, ep0_ctx, sizeof(ep0_ctx));
2191 
2192     xhci->slots[slotid-1].addressed = 1;
2193     return res;
2194 }
2195 
2196 
2197 static TRBCCode xhci_configure_slot(XHCIState *xhci, unsigned int slotid,
2198                                   uint64_t pictx, bool dc)
2199 {
2200     dma_addr_t ictx, octx;
2201     uint32_t ictl_ctx[2];
2202     uint32_t slot_ctx[4];
2203     uint32_t islot_ctx[4];
2204     uint32_t ep_ctx[5];
2205     int i;
2206     TRBCCode res;
2207 
2208     trace_usb_xhci_slot_configure(slotid);
2209     assert(slotid >= 1 && slotid <= xhci->numslots);
2210 
2211     ictx = xhci_mask64(pictx);
2212     octx = xhci->slots[slotid-1].ctx;
2213 
2214     DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
2215     DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
2216 
2217     if (dc) {
2218         for (i = 2; i <= 31; i++) {
2219             if (xhci->slots[slotid-1].eps[i-1]) {
2220                 xhci_disable_ep(xhci, slotid, i);
2221             }
2222         }
2223 
2224         xhci_dma_read_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2225         slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
2226         slot_ctx[3] |= SLOT_ADDRESSED << SLOT_STATE_SHIFT;
2227         DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
2228                 slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
2229         xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2230 
2231         return CC_SUCCESS;
2232     }
2233 
2234     xhci_dma_read_u32s(xhci, ictx, ictl_ctx, sizeof(ictl_ctx));
2235 
2236     if ((ictl_ctx[0] & 0x3) != 0x0 || (ictl_ctx[1] & 0x3) != 0x1) {
2237         DPRINTF("xhci: invalid input context control %08x %08x\n",
2238                 ictl_ctx[0], ictl_ctx[1]);
2239         return CC_TRB_ERROR;
2240     }
2241 
2242     xhci_dma_read_u32s(xhci, ictx+32, islot_ctx, sizeof(islot_ctx));
2243     xhci_dma_read_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2244 
2245     if (SLOT_STATE(slot_ctx[3]) < SLOT_ADDRESSED) {
2246         DPRINTF("xhci: invalid slot state %08x\n", slot_ctx[3]);
2247         return CC_CONTEXT_STATE_ERROR;
2248     }
2249 
2250     xhci_free_device_streams(xhci, slotid, ictl_ctx[0] | ictl_ctx[1]);
2251 
2252     for (i = 2; i <= 31; i++) {
2253         if (ictl_ctx[0] & (1<<i)) {
2254             xhci_disable_ep(xhci, slotid, i);
2255         }
2256         if (ictl_ctx[1] & (1<<i)) {
2257             xhci_dma_read_u32s(xhci, ictx+32+(32*i), ep_ctx, sizeof(ep_ctx));
2258             DPRINTF("xhci: input ep%d.%d context: %08x %08x %08x %08x %08x\n",
2259                     i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2],
2260                     ep_ctx[3], ep_ctx[4]);
2261             xhci_disable_ep(xhci, slotid, i);
2262             res = xhci_enable_ep(xhci, slotid, i, octx+(32*i), ep_ctx);
2263             if (res != CC_SUCCESS) {
2264                 return res;
2265             }
2266             DPRINTF("xhci: output ep%d.%d context: %08x %08x %08x %08x %08x\n",
2267                     i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2],
2268                     ep_ctx[3], ep_ctx[4]);
2269             xhci_dma_write_u32s(xhci, octx+(32*i), ep_ctx, sizeof(ep_ctx));
2270         }
2271     }
2272 
2273     res = xhci_alloc_device_streams(xhci, slotid, ictl_ctx[1]);
2274     if (res != CC_SUCCESS) {
2275         for (i = 2; i <= 31; i++) {
2276             if (ictl_ctx[1] & (1u << i)) {
2277                 xhci_disable_ep(xhci, slotid, i);
2278             }
2279         }
2280         return res;
2281     }
2282 
2283     slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
2284     slot_ctx[3] |= SLOT_CONFIGURED << SLOT_STATE_SHIFT;
2285     slot_ctx[0] &= ~(SLOT_CONTEXT_ENTRIES_MASK << SLOT_CONTEXT_ENTRIES_SHIFT);
2286     slot_ctx[0] |= islot_ctx[0] & (SLOT_CONTEXT_ENTRIES_MASK <<
2287                                    SLOT_CONTEXT_ENTRIES_SHIFT);
2288     DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
2289             slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
2290 
2291     xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2292 
2293     return CC_SUCCESS;
2294 }
2295 
2296 
2297 static TRBCCode xhci_evaluate_slot(XHCIState *xhci, unsigned int slotid,
2298                                    uint64_t pictx)
2299 {
2300     dma_addr_t ictx, octx;
2301     uint32_t ictl_ctx[2];
2302     uint32_t iep0_ctx[5];
2303     uint32_t ep0_ctx[5];
2304     uint32_t islot_ctx[4];
2305     uint32_t slot_ctx[4];
2306 
2307     trace_usb_xhci_slot_evaluate(slotid);
2308     assert(slotid >= 1 && slotid <= xhci->numslots);
2309 
2310     ictx = xhci_mask64(pictx);
2311     octx = xhci->slots[slotid-1].ctx;
2312 
2313     DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
2314     DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
2315 
2316     xhci_dma_read_u32s(xhci, ictx, ictl_ctx, sizeof(ictl_ctx));
2317 
2318     if (ictl_ctx[0] != 0x0 || ictl_ctx[1] & ~0x3) {
2319         DPRINTF("xhci: invalid input context control %08x %08x\n",
2320                 ictl_ctx[0], ictl_ctx[1]);
2321         return CC_TRB_ERROR;
2322     }
2323 
2324     if (ictl_ctx[1] & 0x1) {
2325         xhci_dma_read_u32s(xhci, ictx+32, islot_ctx, sizeof(islot_ctx));
2326 
2327         DPRINTF("xhci: input slot context: %08x %08x %08x %08x\n",
2328                 islot_ctx[0], islot_ctx[1], islot_ctx[2], islot_ctx[3]);
2329 
2330         xhci_dma_read_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2331 
2332         slot_ctx[1] &= ~0xFFFF; /* max exit latency */
2333         slot_ctx[1] |= islot_ctx[1] & 0xFFFF;
2334         /* update interrupter target field */
2335         xhci->slots[slotid-1].intr = get_field(islot_ctx[2], TRB_INTR);
2336         set_field(&slot_ctx[2], xhci->slots[slotid-1].intr, TRB_INTR);
2337 
2338         DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
2339                 slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
2340 
2341         xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2342     }
2343 
2344     if (ictl_ctx[1] & 0x2) {
2345         xhci_dma_read_u32s(xhci, ictx+64, iep0_ctx, sizeof(iep0_ctx));
2346 
2347         DPRINTF("xhci: input ep0 context: %08x %08x %08x %08x %08x\n",
2348                 iep0_ctx[0], iep0_ctx[1], iep0_ctx[2],
2349                 iep0_ctx[3], iep0_ctx[4]);
2350 
2351         xhci_dma_read_u32s(xhci, octx+32, ep0_ctx, sizeof(ep0_ctx));
2352 
2353         ep0_ctx[1] &= ~0xFFFF0000; /* max packet size*/
2354         ep0_ctx[1] |= iep0_ctx[1] & 0xFFFF0000;
2355 
2356         DPRINTF("xhci: output ep0 context: %08x %08x %08x %08x %08x\n",
2357                 ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);
2358 
2359         xhci_dma_write_u32s(xhci, octx+32, ep0_ctx, sizeof(ep0_ctx));
2360     }
2361 
2362     return CC_SUCCESS;
2363 }
2364 
2365 static TRBCCode xhci_reset_slot(XHCIState *xhci, unsigned int slotid)
2366 {
2367     uint32_t slot_ctx[4];
2368     dma_addr_t octx;
2369     int i;
2370 
2371     trace_usb_xhci_slot_reset(slotid);
2372     assert(slotid >= 1 && slotid <= xhci->numslots);
2373 
2374     octx = xhci->slots[slotid-1].ctx;
2375 
2376     DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
2377 
2378     for (i = 2; i <= 31; i++) {
2379         if (xhci->slots[slotid-1].eps[i-1]) {
2380             xhci_disable_ep(xhci, slotid, i);
2381         }
2382     }
2383 
2384     xhci_dma_read_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2385     slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
2386     slot_ctx[3] |= SLOT_DEFAULT << SLOT_STATE_SHIFT;
2387     DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
2388             slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
2389     xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2390 
2391     return CC_SUCCESS;
2392 }
2393 
2394 static unsigned int xhci_get_slot(XHCIState *xhci, XHCIEvent *event, XHCITRB *trb)
2395 {
2396     unsigned int slotid;
2397     slotid = (trb->control >> TRB_CR_SLOTID_SHIFT) & TRB_CR_SLOTID_MASK;
2398     if (slotid < 1 || slotid > xhci->numslots) {
2399         DPRINTF("xhci: bad slot id %d\n", slotid);
2400         event->ccode = CC_TRB_ERROR;
2401         return 0;
2402     } else if (!xhci->slots[slotid-1].enabled) {
2403         DPRINTF("xhci: slot id %d not enabled\n", slotid);
2404         event->ccode = CC_SLOT_NOT_ENABLED_ERROR;
2405         return 0;
2406     }
2407     return slotid;
2408 }
2409 
2410 /* cleanup slot state on usb device detach */
2411 static void xhci_detach_slot(XHCIState *xhci, USBPort *uport)
2412 {
2413     int slot, ep;
2414 
2415     for (slot = 0; slot < xhci->numslots; slot++) {
2416         if (xhci->slots[slot].uport == uport) {
2417             break;
2418         }
2419     }
2420     if (slot == xhci->numslots) {
2421         return;
2422     }
2423 
2424     for (ep = 0; ep < 31; ep++) {
2425         if (xhci->slots[slot].eps[ep]) {
2426             xhci_ep_nuke_xfers(xhci, slot + 1, ep + 1, 0);
2427         }
2428     }
2429     xhci->slots[slot].uport = NULL;
2430 }
2431 
2432 static TRBCCode xhci_get_port_bandwidth(XHCIState *xhci, uint64_t pctx)
2433 {
2434     dma_addr_t ctx;
2435     uint8_t bw_ctx[xhci->numports+1];
2436 
2437     DPRINTF("xhci_get_port_bandwidth()\n");
2438 
2439     ctx = xhci_mask64(pctx);
2440 
2441     DPRINTF("xhci: bandwidth context at "DMA_ADDR_FMT"\n", ctx);
2442 
2443     /* TODO: actually implement real values here */
2444     bw_ctx[0] = 0;
2445     memset(&bw_ctx[1], 80, xhci->numports); /* 80% */
2446     if (dma_memory_write(xhci->as, ctx, bw_ctx, sizeof(bw_ctx),
2447                      MEMTXATTRS_UNSPECIFIED) != MEMTX_OK) {
2448         qemu_log_mask(LOG_GUEST_ERROR, "%s: DMA memory write failed!\n",
2449                       __func__);
2450         return CC_TRB_ERROR;
2451     }
2452 
2453     return CC_SUCCESS;
2454 }
2455 
2456 static uint32_t rotl(uint32_t v, unsigned count)
2457 {
2458     count &= 31;
2459     return (v << count) | (v >> (32 - count));
2460 }
2461 
2462 
2463 static uint32_t xhci_nec_challenge(uint32_t hi, uint32_t lo)
2464 {
2465     uint32_t val;
2466     val = rotl(lo - 0x49434878, 32 - ((hi>>8) & 0x1F));
2467     val += rotl(lo + 0x49434878, hi & 0x1F);
2468     val -= rotl(hi ^ 0x49434878, (lo >> 16) & 0x1F);
2469     return ~val;
2470 }
2471 
2472 static void xhci_process_commands(XHCIState *xhci)
2473 {
2474     XHCITRB trb;
2475     TRBType type;
2476     XHCIEvent event = {ER_COMMAND_COMPLETE, CC_SUCCESS};
2477     dma_addr_t addr;
2478     unsigned int i, slotid = 0, count = 0;
2479 
2480     DPRINTF("xhci_process_commands()\n");
2481     if (!xhci_running(xhci)) {
2482         DPRINTF("xhci_process_commands() called while xHC stopped or paused\n");
2483         return;
2484     }
2485 
2486     xhci->crcr_low |= CRCR_CRR;
2487 
2488     while ((type = xhci_ring_fetch(xhci, &xhci->cmd_ring, &trb, &addr))) {
2489         event.ptr = addr;
2490         switch (type) {
2491         case CR_ENABLE_SLOT:
2492             for (i = 0; i < xhci->numslots; i++) {
2493                 if (!xhci->slots[i].enabled) {
2494                     break;
2495                 }
2496             }
2497             if (i >= xhci->numslots) {
2498                 DPRINTF("xhci: no device slots available\n");
2499                 event.ccode = CC_NO_SLOTS_ERROR;
2500             } else {
2501                 slotid = i+1;
2502                 event.ccode = xhci_enable_slot(xhci, slotid);
2503             }
2504             break;
2505         case CR_DISABLE_SLOT:
2506             slotid = xhci_get_slot(xhci, &event, &trb);
2507             if (slotid) {
2508                 event.ccode = xhci_disable_slot(xhci, slotid);
2509             }
2510             break;
2511         case CR_ADDRESS_DEVICE:
2512             slotid = xhci_get_slot(xhci, &event, &trb);
2513             if (slotid) {
2514                 event.ccode = xhci_address_slot(xhci, slotid, trb.parameter,
2515                                                 trb.control & TRB_CR_BSR);
2516             }
2517             break;
2518         case CR_CONFIGURE_ENDPOINT:
2519             slotid = xhci_get_slot(xhci, &event, &trb);
2520             if (slotid) {
2521                 event.ccode = xhci_configure_slot(xhci, slotid, trb.parameter,
2522                                                   trb.control & TRB_CR_DC);
2523             }
2524             break;
2525         case CR_EVALUATE_CONTEXT:
2526             slotid = xhci_get_slot(xhci, &event, &trb);
2527             if (slotid) {
2528                 event.ccode = xhci_evaluate_slot(xhci, slotid, trb.parameter);
2529             }
2530             break;
2531         case CR_STOP_ENDPOINT:
2532             slotid = xhci_get_slot(xhci, &event, &trb);
2533             if (slotid) {
2534                 unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2535                     & TRB_CR_EPID_MASK;
2536                 event.ccode = xhci_stop_ep(xhci, slotid, epid);
2537             }
2538             break;
2539         case CR_RESET_ENDPOINT:
2540             slotid = xhci_get_slot(xhci, &event, &trb);
2541             if (slotid) {
2542                 unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2543                     & TRB_CR_EPID_MASK;
2544                 event.ccode = xhci_reset_ep(xhci, slotid, epid);
2545             }
2546             break;
2547         case CR_SET_TR_DEQUEUE:
2548             slotid = xhci_get_slot(xhci, &event, &trb);
2549             if (slotid) {
2550                 unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2551                     & TRB_CR_EPID_MASK;
2552                 unsigned int streamid = (trb.status >> 16) & 0xffff;
2553                 event.ccode = xhci_set_ep_dequeue(xhci, slotid,
2554                                                   epid, streamid,
2555                                                   trb.parameter);
2556             }
2557             break;
2558         case CR_RESET_DEVICE:
2559             slotid = xhci_get_slot(xhci, &event, &trb);
2560             if (slotid) {
2561                 event.ccode = xhci_reset_slot(xhci, slotid);
2562             }
2563             break;
2564         case CR_GET_PORT_BANDWIDTH:
2565             event.ccode = xhci_get_port_bandwidth(xhci, trb.parameter);
2566             break;
2567         case CR_NOOP:
2568             event.ccode = CC_SUCCESS;
2569             break;
2570         case CR_VENDOR_NEC_FIRMWARE_REVISION:
2571             if (xhci->nec_quirks) {
2572                 event.type = 48; /* NEC reply */
2573                 event.length = 0x3034;
2574             } else {
2575                 event.ccode = CC_TRB_ERROR;
2576             }
2577             break;
2578         case CR_VENDOR_NEC_CHALLENGE_RESPONSE:
2579             if (xhci->nec_quirks) {
2580                 uint32_t chi = trb.parameter >> 32;
2581                 uint32_t clo = trb.parameter;
2582                 uint32_t val = xhci_nec_challenge(chi, clo);
2583                 event.length = val & 0xFFFF;
2584                 event.epid = val >> 16;
2585                 slotid = val >> 24;
2586                 event.type = 48; /* NEC reply */
2587             } else {
2588                 event.ccode = CC_TRB_ERROR;
2589             }
2590             break;
2591         default:
2592             trace_usb_xhci_unimplemented("command", type);
2593             event.ccode = CC_TRB_ERROR;
2594             break;
2595         }
2596         event.slotid = slotid;
2597         xhci_event(xhci, &event, 0);
2598 
2599         if (count++ > COMMAND_LIMIT) {
2600             trace_usb_xhci_enforced_limit("commands");
2601             return;
2602         }
2603     }
2604 }
2605 
2606 static bool xhci_port_have_device(XHCIPort *port)
2607 {
2608     if (!port->uport->dev || !port->uport->dev->attached) {
2609         return false; /* no device present */
2610     }
2611     if (!((1 << port->uport->dev->speed) & port->speedmask)) {
2612         return false; /* speed mismatch */
2613     }
2614     return true;
2615 }
2616 
2617 static void xhci_port_notify(XHCIPort *port, uint32_t bits)
2618 {
2619     XHCIEvent ev = { ER_PORT_STATUS_CHANGE, CC_SUCCESS,
2620                      port->portnr << 24 };
2621 
2622     if ((port->portsc & bits) == bits) {
2623         return;
2624     }
2625     trace_usb_xhci_port_notify(port->portnr, bits);
2626     port->portsc |= bits;
2627     if (!xhci_running(port->xhci)) {
2628         return;
2629     }
2630     xhci_event(port->xhci, &ev, 0);
2631 }
2632 
2633 static void xhci_port_update(XHCIPort *port, int is_detach)
2634 {
2635     uint32_t pls = PLS_RX_DETECT;
2636 
2637     assert(port);
2638     port->portsc = PORTSC_PP;
2639     if (!is_detach && xhci_port_have_device(port)) {
2640         port->portsc |= PORTSC_CCS;
2641         switch (port->uport->dev->speed) {
2642         case USB_SPEED_LOW:
2643             port->portsc |= PORTSC_SPEED_LOW;
2644             pls = PLS_POLLING;
2645             break;
2646         case USB_SPEED_FULL:
2647             port->portsc |= PORTSC_SPEED_FULL;
2648             pls = PLS_POLLING;
2649             break;
2650         case USB_SPEED_HIGH:
2651             port->portsc |= PORTSC_SPEED_HIGH;
2652             pls = PLS_POLLING;
2653             break;
2654         case USB_SPEED_SUPER:
2655             port->portsc |= PORTSC_SPEED_SUPER;
2656             port->portsc |= PORTSC_PED;
2657             pls = PLS_U0;
2658             break;
2659         }
2660     }
2661     set_field(&port->portsc, pls, PORTSC_PLS);
2662     trace_usb_xhci_port_link(port->portnr, pls);
2663     xhci_port_notify(port, PORTSC_CSC);
2664 }
2665 
2666 static void xhci_port_reset(XHCIPort *port, bool warm_reset)
2667 {
2668     trace_usb_xhci_port_reset(port->portnr, warm_reset);
2669 
2670     if (!xhci_port_have_device(port)) {
2671         return;
2672     }
2673 
2674     usb_device_reset(port->uport->dev);
2675 
2676     switch (port->uport->dev->speed) {
2677     case USB_SPEED_SUPER:
2678         if (warm_reset) {
2679             port->portsc |= PORTSC_WRC;
2680         }
2681         /* fall through */
2682     case USB_SPEED_LOW:
2683     case USB_SPEED_FULL:
2684     case USB_SPEED_HIGH:
2685         set_field(&port->portsc, PLS_U0, PORTSC_PLS);
2686         trace_usb_xhci_port_link(port->portnr, PLS_U0);
2687         port->portsc |= PORTSC_PED;
2688         break;
2689     }
2690 
2691     port->portsc &= ~PORTSC_PR;
2692     xhci_port_notify(port, PORTSC_PRC);
2693 }
2694 
2695 static void xhci_reset(DeviceState *dev)
2696 {
2697     XHCIState *xhci = XHCI(dev);
2698     int i;
2699 
2700     trace_usb_xhci_reset();
2701     if (!(xhci->usbsts & USBSTS_HCH)) {
2702         DPRINTF("xhci: reset while running!\n");
2703     }
2704 
2705     xhci->usbcmd = 0;
2706     xhci->usbsts = USBSTS_HCH;
2707     xhci->dnctrl = 0;
2708     xhci->crcr_low = 0;
2709     xhci->crcr_high = 0;
2710     xhci->dcbaap_low = 0;
2711     xhci->dcbaap_high = 0;
2712     xhci->config = 0;
2713 
2714     for (i = 0; i < xhci->numslots; i++) {
2715         xhci_disable_slot(xhci, i+1);
2716     }
2717 
2718     for (i = 0; i < xhci->numports; i++) {
2719         xhci_port_update(xhci->ports + i, 0);
2720     }
2721 
2722     for (i = 0; i < xhci->numintrs; i++) {
2723         xhci->intr[i].iman = 0;
2724         xhci->intr[i].imod = 0;
2725         xhci->intr[i].erstsz = 0;
2726         xhci->intr[i].erstba_low = 0;
2727         xhci->intr[i].erstba_high = 0;
2728         xhci->intr[i].erdp_low = 0;
2729         xhci->intr[i].erdp_high = 0;
2730 
2731         xhci->intr[i].er_ep_idx = 0;
2732         xhci->intr[i].er_pcs = 1;
2733         xhci->intr[i].ev_buffer_put = 0;
2734         xhci->intr[i].ev_buffer_get = 0;
2735     }
2736 
2737     xhci->mfindex_start = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2738     xhci_mfwrap_update(xhci);
2739 }
2740 
2741 static uint64_t xhci_cap_read(void *ptr, hwaddr reg, unsigned size)
2742 {
2743     XHCIState *xhci = ptr;
2744     uint32_t ret;
2745 
2746     switch (reg) {
2747     case 0x00: /* HCIVERSION, CAPLENGTH */
2748         ret = 0x01000000 | LEN_CAP;
2749         break;
2750     case 0x04: /* HCSPARAMS 1 */
2751         ret = ((xhci->numports_2+xhci->numports_3)<<24)
2752             | (xhci->numintrs<<8) | xhci->numslots;
2753         break;
2754     case 0x08: /* HCSPARAMS 2 */
2755         ret = 0x0000000f;
2756         break;
2757     case 0x0c: /* HCSPARAMS 3 */
2758         ret = 0x00000000;
2759         break;
2760     case 0x10: /* HCCPARAMS */
2761         if (sizeof(dma_addr_t) == 4) {
2762             ret = 0x00080000 | (xhci->max_pstreams_mask << 12);
2763         } else {
2764             ret = 0x00080001 | (xhci->max_pstreams_mask << 12);
2765         }
2766         break;
2767     case 0x14: /* DBOFF */
2768         ret = OFF_DOORBELL;
2769         break;
2770     case 0x18: /* RTSOFF */
2771         ret = OFF_RUNTIME;
2772         break;
2773 
2774     /* extended capabilities */
2775     case 0x20: /* Supported Protocol:00 */
2776         ret = 0x02000402; /* USB 2.0 */
2777         break;
2778     case 0x24: /* Supported Protocol:04 */
2779         ret = 0x20425355; /* "USB " */
2780         break;
2781     case 0x28: /* Supported Protocol:08 */
2782         if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) {
2783             ret = (xhci->numports_2<<8) | (xhci->numports_3+1);
2784         } else {
2785             ret = (xhci->numports_2<<8) | 1;
2786         }
2787         break;
2788     case 0x2c: /* Supported Protocol:0c */
2789         ret = 0x00000000; /* reserved */
2790         break;
2791     case 0x30: /* Supported Protocol:00 */
2792         ret = 0x03000002; /* USB 3.0 */
2793         break;
2794     case 0x34: /* Supported Protocol:04 */
2795         ret = 0x20425355; /* "USB " */
2796         break;
2797     case 0x38: /* Supported Protocol:08 */
2798         if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) {
2799             ret = (xhci->numports_3<<8) | 1;
2800         } else {
2801             ret = (xhci->numports_3<<8) | (xhci->numports_2+1);
2802         }
2803         break;
2804     case 0x3c: /* Supported Protocol:0c */
2805         ret = 0x00000000; /* reserved */
2806         break;
2807     default:
2808         trace_usb_xhci_unimplemented("cap read", reg);
2809         ret = 0;
2810     }
2811 
2812     trace_usb_xhci_cap_read(reg, ret);
2813     return ret;
2814 }
2815 
2816 static uint64_t xhci_port_read(void *ptr, hwaddr reg, unsigned size)
2817 {
2818     XHCIPort *port = ptr;
2819     uint32_t ret;
2820 
2821     switch (reg) {
2822     case 0x00: /* PORTSC */
2823         ret = port->portsc;
2824         break;
2825     case 0x04: /* PORTPMSC */
2826     case 0x08: /* PORTLI */
2827         ret = 0;
2828         break;
2829     case 0x0c: /* reserved */
2830     default:
2831         trace_usb_xhci_unimplemented("port read", reg);
2832         ret = 0;
2833     }
2834 
2835     trace_usb_xhci_port_read(port->portnr, reg, ret);
2836     return ret;
2837 }
2838 
2839 static void xhci_port_write(void *ptr, hwaddr reg,
2840                             uint64_t val, unsigned size)
2841 {
2842     XHCIPort *port = ptr;
2843     uint32_t portsc, notify;
2844 
2845     trace_usb_xhci_port_write(port->portnr, reg, val);
2846 
2847     switch (reg) {
2848     case 0x00: /* PORTSC */
2849         /* write-1-to-start bits */
2850         if (val & PORTSC_WPR) {
2851             xhci_port_reset(port, true);
2852             break;
2853         }
2854         if (val & PORTSC_PR) {
2855             xhci_port_reset(port, false);
2856             break;
2857         }
2858 
2859         portsc = port->portsc;
2860         notify = 0;
2861         /* write-1-to-clear bits*/
2862         portsc &= ~(val & (PORTSC_CSC|PORTSC_PEC|PORTSC_WRC|PORTSC_OCC|
2863                            PORTSC_PRC|PORTSC_PLC|PORTSC_CEC));
2864         if (val & PORTSC_LWS) {
2865             /* overwrite PLS only when LWS=1 */
2866             uint32_t old_pls = get_field(port->portsc, PORTSC_PLS);
2867             uint32_t new_pls = get_field(val, PORTSC_PLS);
2868             switch (new_pls) {
2869             case PLS_U0:
2870                 if (old_pls != PLS_U0) {
2871                     set_field(&portsc, new_pls, PORTSC_PLS);
2872                     trace_usb_xhci_port_link(port->portnr, new_pls);
2873                     notify = PORTSC_PLC;
2874                 }
2875                 break;
2876             case PLS_U3:
2877                 if (old_pls < PLS_U3) {
2878                     set_field(&portsc, new_pls, PORTSC_PLS);
2879                     trace_usb_xhci_port_link(port->portnr, new_pls);
2880                 }
2881                 break;
2882             case PLS_RESUME:
2883                 /* windows does this for some reason, don't spam stderr */
2884                 break;
2885             default:
2886                 DPRINTF("%s: ignore pls write (old %d, new %d)\n",
2887                         __func__, old_pls, new_pls);
2888                 break;
2889             }
2890         }
2891         /* read/write bits */
2892         portsc &= ~(PORTSC_PP|PORTSC_WCE|PORTSC_WDE|PORTSC_WOE);
2893         portsc |= (val & (PORTSC_PP|PORTSC_WCE|PORTSC_WDE|PORTSC_WOE));
2894         port->portsc = portsc;
2895         if (notify) {
2896             xhci_port_notify(port, notify);
2897         }
2898         break;
2899     case 0x04: /* PORTPMSC */
2900     case 0x08: /* PORTLI */
2901     default:
2902         trace_usb_xhci_unimplemented("port write", reg);
2903     }
2904 }
2905 
2906 static uint64_t xhci_oper_read(void *ptr, hwaddr reg, unsigned size)
2907 {
2908     XHCIState *xhci = ptr;
2909     uint32_t ret;
2910 
2911     switch (reg) {
2912     case 0x00: /* USBCMD */
2913         ret = xhci->usbcmd;
2914         break;
2915     case 0x04: /* USBSTS */
2916         ret = xhci->usbsts;
2917         break;
2918     case 0x08: /* PAGESIZE */
2919         ret = 1; /* 4KiB */
2920         break;
2921     case 0x14: /* DNCTRL */
2922         ret = xhci->dnctrl;
2923         break;
2924     case 0x18: /* CRCR low */
2925         ret = xhci->crcr_low & ~0xe;
2926         break;
2927     case 0x1c: /* CRCR high */
2928         ret = xhci->crcr_high;
2929         break;
2930     case 0x30: /* DCBAAP low */
2931         ret = xhci->dcbaap_low;
2932         break;
2933     case 0x34: /* DCBAAP high */
2934         ret = xhci->dcbaap_high;
2935         break;
2936     case 0x38: /* CONFIG */
2937         ret = xhci->config;
2938         break;
2939     default:
2940         trace_usb_xhci_unimplemented("oper read", reg);
2941         ret = 0;
2942     }
2943 
2944     trace_usb_xhci_oper_read(reg, ret);
2945     return ret;
2946 }
2947 
2948 static void xhci_oper_write(void *ptr, hwaddr reg,
2949                             uint64_t val, unsigned size)
2950 {
2951     XHCIState *xhci = XHCI(ptr);
2952 
2953     trace_usb_xhci_oper_write(reg, val);
2954 
2955     switch (reg) {
2956     case 0x00: /* USBCMD */
2957         if ((val & USBCMD_RS) && !(xhci->usbcmd & USBCMD_RS)) {
2958             xhci_run(xhci);
2959         } else if (!(val & USBCMD_RS) && (xhci->usbcmd & USBCMD_RS)) {
2960             xhci_stop(xhci);
2961         }
2962         if (val & USBCMD_CSS) {
2963             /* save state */
2964             xhci->usbsts &= ~USBSTS_SRE;
2965         }
2966         if (val & USBCMD_CRS) {
2967             /* restore state */
2968             xhci->usbsts |= USBSTS_SRE;
2969         }
2970         xhci->usbcmd = val & 0xc0f;
2971         xhci_mfwrap_update(xhci);
2972         if (val & USBCMD_HCRST) {
2973             xhci_reset(DEVICE(xhci));
2974         }
2975         xhci_intr_update(xhci, 0);
2976         break;
2977 
2978     case 0x04: /* USBSTS */
2979         /* these bits are write-1-to-clear */
2980         xhci->usbsts &= ~(val & (USBSTS_HSE|USBSTS_EINT|USBSTS_PCD|USBSTS_SRE));
2981         xhci_intr_update(xhci, 0);
2982         break;
2983 
2984     case 0x14: /* DNCTRL */
2985         xhci->dnctrl = val & 0xffff;
2986         break;
2987     case 0x18: /* CRCR low */
2988         xhci->crcr_low = (val & 0xffffffcf) | (xhci->crcr_low & CRCR_CRR);
2989         break;
2990     case 0x1c: /* CRCR high */
2991         xhci->crcr_high = val;
2992         if (xhci->crcr_low & (CRCR_CA|CRCR_CS) && (xhci->crcr_low & CRCR_CRR)) {
2993             XHCIEvent event = {ER_COMMAND_COMPLETE, CC_COMMAND_RING_STOPPED};
2994             xhci->crcr_low &= ~CRCR_CRR;
2995             xhci_event(xhci, &event, 0);
2996             DPRINTF("xhci: command ring stopped (CRCR=%08x)\n", xhci->crcr_low);
2997         } else {
2998             dma_addr_t base = xhci_addr64(xhci->crcr_low & ~0x3f, val);
2999             xhci_ring_init(xhci, &xhci->cmd_ring, base);
3000         }
3001         xhci->crcr_low &= ~(CRCR_CA | CRCR_CS);
3002         break;
3003     case 0x30: /* DCBAAP low */
3004         xhci->dcbaap_low = val & 0xffffffc0;
3005         break;
3006     case 0x34: /* DCBAAP high */
3007         xhci->dcbaap_high = val;
3008         break;
3009     case 0x38: /* CONFIG */
3010         xhci->config = val & 0xff;
3011         break;
3012     default:
3013         trace_usb_xhci_unimplemented("oper write", reg);
3014     }
3015 }
3016 
3017 static uint64_t xhci_runtime_read(void *ptr, hwaddr reg,
3018                                   unsigned size)
3019 {
3020     XHCIState *xhci = ptr;
3021     uint32_t ret = 0;
3022 
3023     if (reg < 0x20) {
3024         switch (reg) {
3025         case 0x00: /* MFINDEX */
3026             ret = xhci_mfindex_get(xhci) & 0x3fff;
3027             break;
3028         default:
3029             trace_usb_xhci_unimplemented("runtime read", reg);
3030             break;
3031         }
3032     } else {
3033         int v = (reg - 0x20) / 0x20;
3034         XHCIInterrupter *intr = &xhci->intr[v];
3035         switch (reg & 0x1f) {
3036         case 0x00: /* IMAN */
3037             ret = intr->iman;
3038             break;
3039         case 0x04: /* IMOD */
3040             ret = intr->imod;
3041             break;
3042         case 0x08: /* ERSTSZ */
3043             ret = intr->erstsz;
3044             break;
3045         case 0x10: /* ERSTBA low */
3046             ret = intr->erstba_low;
3047             break;
3048         case 0x14: /* ERSTBA high */
3049             ret = intr->erstba_high;
3050             break;
3051         case 0x18: /* ERDP low */
3052             ret = intr->erdp_low;
3053             break;
3054         case 0x1c: /* ERDP high */
3055             ret = intr->erdp_high;
3056             break;
3057         }
3058     }
3059 
3060     trace_usb_xhci_runtime_read(reg, ret);
3061     return ret;
3062 }
3063 
3064 static void xhci_runtime_write(void *ptr, hwaddr reg,
3065                                uint64_t val, unsigned size)
3066 {
3067     XHCIState *xhci = ptr;
3068     XHCIInterrupter *intr;
3069     int v;
3070 
3071     trace_usb_xhci_runtime_write(reg, val);
3072 
3073     if (reg < 0x20) {
3074         trace_usb_xhci_unimplemented("runtime write", reg);
3075         return;
3076     }
3077     v = (reg - 0x20) / 0x20;
3078     intr = &xhci->intr[v];
3079 
3080     switch (reg & 0x1f) {
3081     case 0x00: /* IMAN */
3082         if (val & IMAN_IP) {
3083             intr->iman &= ~IMAN_IP;
3084         }
3085         intr->iman &= ~IMAN_IE;
3086         intr->iman |= val & IMAN_IE;
3087         xhci_intr_update(xhci, v);
3088         break;
3089     case 0x04: /* IMOD */
3090         intr->imod = val;
3091         break;
3092     case 0x08: /* ERSTSZ */
3093         intr->erstsz = val & 0xffff;
3094         break;
3095     case 0x10: /* ERSTBA low */
3096         if (xhci->nec_quirks) {
3097             /* NEC driver bug: it doesn't align this to 64 bytes */
3098             intr->erstba_low = val & 0xfffffff0;
3099         } else {
3100             intr->erstba_low = val & 0xffffffc0;
3101         }
3102         break;
3103     case 0x14: /* ERSTBA high */
3104         intr->erstba_high = val;
3105         xhci_er_reset(xhci, v);
3106         break;
3107     case 0x18: /* ERDP low */
3108         if (val & ERDP_EHB) {
3109             intr->erdp_low &= ~ERDP_EHB;
3110         }
3111         intr->erdp_low = (val & ~ERDP_EHB) | (intr->erdp_low & ERDP_EHB);
3112         if (val & ERDP_EHB) {
3113             dma_addr_t erdp = xhci_addr64(intr->erdp_low, intr->erdp_high);
3114             unsigned int dp_idx = (erdp - intr->er_start) / TRB_SIZE;
3115             if (erdp >= intr->er_start &&
3116                 erdp < (intr->er_start + TRB_SIZE * intr->er_size) &&
3117                 dp_idx != intr->er_ep_idx) {
3118                 xhci_intr_raise(xhci, v);
3119             }
3120         }
3121         break;
3122     case 0x1c: /* ERDP high */
3123         intr->erdp_high = val;
3124         break;
3125     default:
3126         trace_usb_xhci_unimplemented("oper write", reg);
3127     }
3128 }
3129 
3130 static uint64_t xhci_doorbell_read(void *ptr, hwaddr reg,
3131                                    unsigned size)
3132 {
3133     /* doorbells always read as 0 */
3134     trace_usb_xhci_doorbell_read(reg, 0);
3135     return 0;
3136 }
3137 
3138 static void xhci_doorbell_write(void *ptr, hwaddr reg,
3139                                 uint64_t val, unsigned size)
3140 {
3141     XHCIState *xhci = ptr;
3142     unsigned int epid, streamid;
3143 
3144     trace_usb_xhci_doorbell_write(reg, val);
3145 
3146     if (!xhci_running(xhci)) {
3147         DPRINTF("xhci: wrote doorbell while xHC stopped or paused\n");
3148         return;
3149     }
3150 
3151     reg >>= 2;
3152 
3153     if (reg == 0) {
3154         if (val == 0) {
3155             xhci_process_commands(xhci);
3156         } else {
3157             DPRINTF("xhci: bad doorbell 0 write: 0x%x\n",
3158                     (uint32_t)val);
3159         }
3160     } else {
3161         epid = val & 0xff;
3162         streamid = (val >> 16) & 0xffff;
3163         if (reg > xhci->numslots) {
3164             DPRINTF("xhci: bad doorbell %d\n", (int)reg);
3165         } else if (epid == 0 || epid > 31) {
3166             DPRINTF("xhci: bad doorbell %d write: 0x%x\n",
3167                     (int)reg, (uint32_t)val);
3168         } else {
3169             xhci_kick_ep(xhci, reg, epid, streamid);
3170         }
3171     }
3172 }
3173 
3174 static void xhci_cap_write(void *opaque, hwaddr addr, uint64_t val,
3175                            unsigned width)
3176 {
3177     /* nothing */
3178 }
3179 
3180 static const MemoryRegionOps xhci_cap_ops = {
3181     .read = xhci_cap_read,
3182     .write = xhci_cap_write,
3183     .valid.min_access_size = 1,
3184     .valid.max_access_size = 4,
3185     .impl.min_access_size = 4,
3186     .impl.max_access_size = 4,
3187     .endianness = DEVICE_LITTLE_ENDIAN,
3188 };
3189 
3190 static const MemoryRegionOps xhci_oper_ops = {
3191     .read = xhci_oper_read,
3192     .write = xhci_oper_write,
3193     .valid.min_access_size = 4,
3194     .valid.max_access_size = sizeof(dma_addr_t),
3195     .endianness = DEVICE_LITTLE_ENDIAN,
3196 };
3197 
3198 static const MemoryRegionOps xhci_port_ops = {
3199     .read = xhci_port_read,
3200     .write = xhci_port_write,
3201     .valid.min_access_size = 4,
3202     .valid.max_access_size = 4,
3203     .endianness = DEVICE_LITTLE_ENDIAN,
3204 };
3205 
3206 static const MemoryRegionOps xhci_runtime_ops = {
3207     .read = xhci_runtime_read,
3208     .write = xhci_runtime_write,
3209     .valid.min_access_size = 4,
3210     .valid.max_access_size = sizeof(dma_addr_t),
3211     .endianness = DEVICE_LITTLE_ENDIAN,
3212 };
3213 
3214 static const MemoryRegionOps xhci_doorbell_ops = {
3215     .read = xhci_doorbell_read,
3216     .write = xhci_doorbell_write,
3217     .valid.min_access_size = 4,
3218     .valid.max_access_size = 4,
3219     .endianness = DEVICE_LITTLE_ENDIAN,
3220 };
3221 
3222 static void xhci_attach(USBPort *usbport)
3223 {
3224     XHCIState *xhci = usbport->opaque;
3225     XHCIPort *port = xhci_lookup_port(xhci, usbport);
3226 
3227     xhci_port_update(port, 0);
3228 }
3229 
3230 static void xhci_detach(USBPort *usbport)
3231 {
3232     XHCIState *xhci = usbport->opaque;
3233     XHCIPort *port = xhci_lookup_port(xhci, usbport);
3234 
3235     xhci_detach_slot(xhci, usbport);
3236     xhci_port_update(port, 1);
3237 }
3238 
3239 static void xhci_wakeup(USBPort *usbport)
3240 {
3241     XHCIState *xhci = usbport->opaque;
3242     XHCIPort *port = xhci_lookup_port(xhci, usbport);
3243 
3244     assert(port);
3245     if (get_field(port->portsc, PORTSC_PLS) != PLS_U3) {
3246         return;
3247     }
3248     set_field(&port->portsc, PLS_RESUME, PORTSC_PLS);
3249     xhci_port_notify(port, PORTSC_PLC);
3250 }
3251 
3252 static void xhci_complete(USBPort *port, USBPacket *packet)
3253 {
3254     XHCITransfer *xfer = container_of(packet, XHCITransfer, packet);
3255 
3256     if (packet->status == USB_RET_REMOVE_FROM_QUEUE) {
3257         xhci_ep_nuke_one_xfer(xfer, 0);
3258         return;
3259     }
3260     xhci_try_complete_packet(xfer);
3261     xhci_kick_epctx(xfer->epctx, xfer->streamid);
3262     if (xfer->complete) {
3263         xhci_ep_free_xfer(xfer);
3264     }
3265 }
3266 
3267 static void xhci_child_detach(USBPort *uport, USBDevice *child)
3268 {
3269     USBBus *bus = usb_bus_from_device(child);
3270     XHCIState *xhci = container_of(bus, XHCIState, bus);
3271 
3272     xhci_detach_slot(xhci, child->port);
3273 }
3274 
3275 static USBPortOps xhci_uport_ops = {
3276     .attach   = xhci_attach,
3277     .detach   = xhci_detach,
3278     .wakeup   = xhci_wakeup,
3279     .complete = xhci_complete,
3280     .child_detach = xhci_child_detach,
3281 };
3282 
3283 static int xhci_find_epid(USBEndpoint *ep)
3284 {
3285     if (ep->nr == 0) {
3286         return 1;
3287     }
3288     if (ep->pid == USB_TOKEN_IN) {
3289         return ep->nr * 2 + 1;
3290     } else {
3291         return ep->nr * 2;
3292     }
3293 }
3294 
3295 static USBEndpoint *xhci_epid_to_usbep(XHCIEPContext *epctx)
3296 {
3297     USBPort *uport;
3298     uint32_t token;
3299 
3300     if (!epctx) {
3301         return NULL;
3302     }
3303     uport = epctx->xhci->slots[epctx->slotid - 1].uport;
3304     if (!uport || !uport->dev) {
3305         return NULL;
3306     }
3307     token = (epctx->epid & 1) ? USB_TOKEN_IN : USB_TOKEN_OUT;
3308     return usb_ep_get(uport->dev, token, epctx->epid >> 1);
3309 }
3310 
3311 static void xhci_wakeup_endpoint(USBBus *bus, USBEndpoint *ep,
3312                                  unsigned int stream)
3313 {
3314     XHCIState *xhci = container_of(bus, XHCIState, bus);
3315     int slotid;
3316 
3317     DPRINTF("%s\n", __func__);
3318     slotid = ep->dev->addr;
3319     if (slotid == 0 || slotid > xhci->numslots ||
3320         !xhci->slots[slotid - 1].enabled) {
3321         DPRINTF("%s: oops, no slot for dev %d\n", __func__, ep->dev->addr);
3322         return;
3323     }
3324     xhci_kick_ep(xhci, slotid, xhci_find_epid(ep), stream);
3325 }
3326 
3327 static USBBusOps xhci_bus_ops = {
3328     .wakeup_endpoint = xhci_wakeup_endpoint,
3329 };
3330 
3331 static void usb_xhci_init(XHCIState *xhci)
3332 {
3333     XHCIPort *port;
3334     unsigned int i, usbports, speedmask;
3335 
3336     xhci->usbsts = USBSTS_HCH;
3337 
3338     if (xhci->numports_2 > XHCI_MAXPORTS_2) {
3339         xhci->numports_2 = XHCI_MAXPORTS_2;
3340     }
3341     if (xhci->numports_3 > XHCI_MAXPORTS_3) {
3342         xhci->numports_3 = XHCI_MAXPORTS_3;
3343     }
3344     usbports = MAX(xhci->numports_2, xhci->numports_3);
3345     xhci->numports = xhci->numports_2 + xhci->numports_3;
3346 
3347     usb_bus_new(&xhci->bus, sizeof(xhci->bus), &xhci_bus_ops, xhci->hostOpaque);
3348 
3349     for (i = 0; i < usbports; i++) {
3350         speedmask = 0;
3351         if (i < xhci->numports_2) {
3352             if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) {
3353                 port = &xhci->ports[i + xhci->numports_3];
3354                 port->portnr = i + 1 + xhci->numports_3;
3355             } else {
3356                 port = &xhci->ports[i];
3357                 port->portnr = i + 1;
3358             }
3359             port->uport = &xhci->uports[i];
3360             port->speedmask =
3361                 USB_SPEED_MASK_LOW  |
3362                 USB_SPEED_MASK_FULL |
3363                 USB_SPEED_MASK_HIGH;
3364             assert(i < XHCI_MAXPORTS);
3365             snprintf(port->name, sizeof(port->name), "usb2 port #%d", i+1);
3366             speedmask |= port->speedmask;
3367         }
3368         if (i < xhci->numports_3) {
3369             if (xhci_get_flag(xhci, XHCI_FLAG_SS_FIRST)) {
3370                 port = &xhci->ports[i];
3371                 port->portnr = i + 1;
3372             } else {
3373                 port = &xhci->ports[i + xhci->numports_2];
3374                 port->portnr = i + 1 + xhci->numports_2;
3375             }
3376             port->uport = &xhci->uports[i];
3377             port->speedmask = USB_SPEED_MASK_SUPER;
3378             assert(i < XHCI_MAXPORTS);
3379             snprintf(port->name, sizeof(port->name), "usb3 port #%d", i+1);
3380             speedmask |= port->speedmask;
3381         }
3382         usb_register_port(&xhci->bus, &xhci->uports[i], xhci, i,
3383                           &xhci_uport_ops, speedmask);
3384     }
3385 }
3386 
3387 static void usb_xhci_realize(DeviceState *dev, Error **errp)
3388 {
3389     int i;
3390 
3391     XHCIState *xhci = XHCI(dev);
3392 
3393     if (xhci->numintrs > XHCI_MAXINTRS) {
3394         xhci->numintrs = XHCI_MAXINTRS;
3395     }
3396     while (xhci->numintrs & (xhci->numintrs - 1)) {   /* ! power of 2 */
3397         xhci->numintrs++;
3398     }
3399     if (xhci->numintrs < 1) {
3400         xhci->numintrs = 1;
3401     }
3402     if (xhci->numslots > XHCI_MAXSLOTS) {
3403         xhci->numslots = XHCI_MAXSLOTS;
3404     }
3405     if (xhci->numslots < 1) {
3406         xhci->numslots = 1;
3407     }
3408     if (xhci_get_flag(xhci, XHCI_FLAG_ENABLE_STREAMS)) {
3409         xhci->max_pstreams_mask = 7; /* == 256 primary streams */
3410     } else {
3411         xhci->max_pstreams_mask = 0;
3412     }
3413 
3414     usb_xhci_init(xhci);
3415     xhci->mfwrap_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, xhci_mfwrap_timer, xhci);
3416 
3417     memory_region_init(&xhci->mem, OBJECT(dev), "xhci", XHCI_LEN_REGS);
3418     memory_region_init_io(&xhci->mem_cap, OBJECT(dev), &xhci_cap_ops, xhci,
3419                           "capabilities", LEN_CAP);
3420     memory_region_init_io(&xhci->mem_oper, OBJECT(dev), &xhci_oper_ops, xhci,
3421                           "operational", 0x400);
3422     memory_region_init_io(&xhci->mem_runtime, OBJECT(dev), &xhci_runtime_ops,
3423                            xhci, "runtime", LEN_RUNTIME);
3424     memory_region_init_io(&xhci->mem_doorbell, OBJECT(dev), &xhci_doorbell_ops,
3425                            xhci, "doorbell", LEN_DOORBELL);
3426 
3427     memory_region_add_subregion(&xhci->mem, 0,            &xhci->mem_cap);
3428     memory_region_add_subregion(&xhci->mem, OFF_OPER,     &xhci->mem_oper);
3429     memory_region_add_subregion(&xhci->mem, OFF_RUNTIME,  &xhci->mem_runtime);
3430     memory_region_add_subregion(&xhci->mem, OFF_DOORBELL, &xhci->mem_doorbell);
3431 
3432     for (i = 0; i < xhci->numports; i++) {
3433         XHCIPort *port = &xhci->ports[i];
3434         uint32_t offset = OFF_OPER + 0x400 + 0x10 * i;
3435         port->xhci = xhci;
3436         memory_region_init_io(&port->mem, OBJECT(dev), &xhci_port_ops, port,
3437                               port->name, 0x10);
3438         memory_region_add_subregion(&xhci->mem, offset, &port->mem);
3439     }
3440 }
3441 
3442 static void usb_xhci_unrealize(DeviceState *dev)
3443 {
3444     int i;
3445     XHCIState *xhci = XHCI(dev);
3446 
3447     trace_usb_xhci_exit();
3448 
3449     for (i = 0; i < xhci->numslots; i++) {
3450         xhci_disable_slot(xhci, i + 1);
3451     }
3452 
3453     if (xhci->mfwrap_timer) {
3454         timer_free(xhci->mfwrap_timer);
3455         xhci->mfwrap_timer = NULL;
3456     }
3457 
3458     memory_region_del_subregion(&xhci->mem, &xhci->mem_cap);
3459     memory_region_del_subregion(&xhci->mem, &xhci->mem_oper);
3460     memory_region_del_subregion(&xhci->mem, &xhci->mem_runtime);
3461     memory_region_del_subregion(&xhci->mem, &xhci->mem_doorbell);
3462 
3463     for (i = 0; i < xhci->numports; i++) {
3464         XHCIPort *port = &xhci->ports[i];
3465         memory_region_del_subregion(&xhci->mem, &port->mem);
3466     }
3467 
3468     usb_bus_release(&xhci->bus);
3469 }
3470 
3471 static int usb_xhci_post_load(void *opaque, int version_id)
3472 {
3473     XHCIState *xhci = opaque;
3474     XHCISlot *slot;
3475     XHCIEPContext *epctx;
3476     dma_addr_t dcbaap, pctx;
3477     uint32_t slot_ctx[4];
3478     uint32_t ep_ctx[5];
3479     int slotid, epid, state;
3480     uint64_t addr;
3481 
3482     dcbaap = xhci_addr64(xhci->dcbaap_low, xhci->dcbaap_high);
3483 
3484     for (slotid = 1; slotid <= xhci->numslots; slotid++) {
3485         slot = &xhci->slots[slotid-1];
3486         if (!slot->addressed) {
3487             continue;
3488         }
3489         ldq_le_dma(xhci->as, dcbaap + 8 * slotid, &addr, MEMTXATTRS_UNSPECIFIED);
3490         slot->ctx = xhci_mask64(addr);
3491 
3492         xhci_dma_read_u32s(xhci, slot->ctx, slot_ctx, sizeof(slot_ctx));
3493         slot->uport = xhci_lookup_uport(xhci, slot_ctx);
3494         if (!slot->uport) {
3495             /* should not happen, but may trigger on guest bugs */
3496             slot->enabled = 0;
3497             slot->addressed = 0;
3498             continue;
3499         }
3500         assert(slot->uport && slot->uport->dev);
3501 
3502         for (epid = 1; epid <= 31; epid++) {
3503             pctx = slot->ctx + 32 * epid;
3504             xhci_dma_read_u32s(xhci, pctx, ep_ctx, sizeof(ep_ctx));
3505             state = ep_ctx[0] & EP_STATE_MASK;
3506             if (state == EP_DISABLED) {
3507                 continue;
3508             }
3509             epctx = xhci_alloc_epctx(xhci, slotid, epid);
3510             slot->eps[epid-1] = epctx;
3511             xhci_init_epctx(epctx, pctx, ep_ctx);
3512             epctx->state = state;
3513             if (state == EP_RUNNING) {
3514                 /* kick endpoint after vmload is finished */
3515                 timer_mod(epctx->kick_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));
3516             }
3517         }
3518     }
3519     return 0;
3520 }
3521 
3522 static const VMStateDescription vmstate_xhci_ring = {
3523     .name = "xhci-ring",
3524     .version_id = 1,
3525     .fields = (VMStateField[]) {
3526         VMSTATE_UINT64(dequeue, XHCIRing),
3527         VMSTATE_BOOL(ccs, XHCIRing),
3528         VMSTATE_END_OF_LIST()
3529     }
3530 };
3531 
3532 static const VMStateDescription vmstate_xhci_port = {
3533     .name = "xhci-port",
3534     .version_id = 1,
3535     .fields = (VMStateField[]) {
3536         VMSTATE_UINT32(portsc, XHCIPort),
3537         VMSTATE_END_OF_LIST()
3538     }
3539 };
3540 
3541 static const VMStateDescription vmstate_xhci_slot = {
3542     .name = "xhci-slot",
3543     .version_id = 1,
3544     .fields = (VMStateField[]) {
3545         VMSTATE_BOOL(enabled,   XHCISlot),
3546         VMSTATE_BOOL(addressed, XHCISlot),
3547         VMSTATE_END_OF_LIST()
3548     }
3549 };
3550 
3551 static const VMStateDescription vmstate_xhci_event = {
3552     .name = "xhci-event",
3553     .version_id = 1,
3554     .fields = (VMStateField[]) {
3555         VMSTATE_UINT32(type,   XHCIEvent),
3556         VMSTATE_UINT32(ccode,  XHCIEvent),
3557         VMSTATE_UINT64(ptr,    XHCIEvent),
3558         VMSTATE_UINT32(length, XHCIEvent),
3559         VMSTATE_UINT32(flags,  XHCIEvent),
3560         VMSTATE_UINT8(slotid,  XHCIEvent),
3561         VMSTATE_UINT8(epid,    XHCIEvent),
3562         VMSTATE_END_OF_LIST()
3563     }
3564 };
3565 
3566 static bool xhci_er_full(void *opaque, int version_id)
3567 {
3568     return false;
3569 }
3570 
3571 static const VMStateDescription vmstate_xhci_intr = {
3572     .name = "xhci-intr",
3573     .version_id = 1,
3574     .fields = (VMStateField[]) {
3575         /* registers */
3576         VMSTATE_UINT32(iman,          XHCIInterrupter),
3577         VMSTATE_UINT32(imod,          XHCIInterrupter),
3578         VMSTATE_UINT32(erstsz,        XHCIInterrupter),
3579         VMSTATE_UINT32(erstba_low,    XHCIInterrupter),
3580         VMSTATE_UINT32(erstba_high,   XHCIInterrupter),
3581         VMSTATE_UINT32(erdp_low,      XHCIInterrupter),
3582         VMSTATE_UINT32(erdp_high,     XHCIInterrupter),
3583 
3584         /* state */
3585         VMSTATE_BOOL(msix_used,       XHCIInterrupter),
3586         VMSTATE_BOOL(er_pcs,          XHCIInterrupter),
3587         VMSTATE_UINT64(er_start,      XHCIInterrupter),
3588         VMSTATE_UINT32(er_size,       XHCIInterrupter),
3589         VMSTATE_UINT32(er_ep_idx,     XHCIInterrupter),
3590 
3591         /* event queue (used if ring is full) */
3592         VMSTATE_BOOL(er_full_unused,  XHCIInterrupter),
3593         VMSTATE_UINT32_TEST(ev_buffer_put, XHCIInterrupter, xhci_er_full),
3594         VMSTATE_UINT32_TEST(ev_buffer_get, XHCIInterrupter, xhci_er_full),
3595         VMSTATE_STRUCT_ARRAY_TEST(ev_buffer, XHCIInterrupter, EV_QUEUE,
3596                                   xhci_er_full, 1,
3597                                   vmstate_xhci_event, XHCIEvent),
3598 
3599         VMSTATE_END_OF_LIST()
3600     }
3601 };
3602 
3603 const VMStateDescription vmstate_xhci = {
3604     .name = "xhci-core",
3605     .version_id = 1,
3606     .post_load = usb_xhci_post_load,
3607     .fields = (VMStateField[]) {
3608         VMSTATE_STRUCT_VARRAY_UINT32(ports, XHCIState, numports, 1,
3609                                      vmstate_xhci_port, XHCIPort),
3610         VMSTATE_STRUCT_VARRAY_UINT32(slots, XHCIState, numslots, 1,
3611                                      vmstate_xhci_slot, XHCISlot),
3612         VMSTATE_STRUCT_VARRAY_UINT32(intr, XHCIState, numintrs, 1,
3613                                      vmstate_xhci_intr, XHCIInterrupter),
3614 
3615         /* Operational Registers */
3616         VMSTATE_UINT32(usbcmd,        XHCIState),
3617         VMSTATE_UINT32(usbsts,        XHCIState),
3618         VMSTATE_UINT32(dnctrl,        XHCIState),
3619         VMSTATE_UINT32(crcr_low,      XHCIState),
3620         VMSTATE_UINT32(crcr_high,     XHCIState),
3621         VMSTATE_UINT32(dcbaap_low,    XHCIState),
3622         VMSTATE_UINT32(dcbaap_high,   XHCIState),
3623         VMSTATE_UINT32(config,        XHCIState),
3624 
3625         /* Runtime Registers & state */
3626         VMSTATE_INT64(mfindex_start,  XHCIState),
3627         VMSTATE_TIMER_PTR(mfwrap_timer,   XHCIState),
3628         VMSTATE_STRUCT(cmd_ring, XHCIState, 1, vmstate_xhci_ring, XHCIRing),
3629 
3630         VMSTATE_END_OF_LIST()
3631     }
3632 };
3633 
3634 static Property xhci_properties[] = {
3635     DEFINE_PROP_BIT("streams", XHCIState, flags,
3636                     XHCI_FLAG_ENABLE_STREAMS, true),
3637     DEFINE_PROP_UINT32("p2",    XHCIState, numports_2, 4),
3638     DEFINE_PROP_UINT32("p3",    XHCIState, numports_3, 4),
3639     DEFINE_PROP_LINK("host",    XHCIState, hostOpaque, TYPE_DEVICE,
3640                      DeviceState *),
3641     DEFINE_PROP_END_OF_LIST(),
3642 };
3643 
3644 static void xhci_class_init(ObjectClass *klass, void *data)
3645 {
3646     DeviceClass *dc = DEVICE_CLASS(klass);
3647 
3648     dc->realize = usb_xhci_realize;
3649     dc->unrealize = usb_xhci_unrealize;
3650     dc->reset   = xhci_reset;
3651     device_class_set_props(dc, xhci_properties);
3652     dc->user_creatable = false;
3653 }
3654 
3655 static const TypeInfo xhci_info = {
3656     .name          = TYPE_XHCI,
3657     .parent        = TYPE_DEVICE,
3658     .instance_size = sizeof(XHCIState),
3659     .class_init    = xhci_class_init,
3660 };
3661 
3662 static void xhci_register_types(void)
3663 {
3664     type_register_static(&xhci_info);
3665 }
3666 
3667 type_init(xhci_register_types)
3668