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