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