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