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