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