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