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