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