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