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