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