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