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