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