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