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