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