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