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