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