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