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