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