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