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