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