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