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