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