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