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