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