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