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