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