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