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