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