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