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