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