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