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