xref: /openbmc/qemu/hw/usb/hcd-xhci.c (revision 4c4abe7c)
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.h"
25 #include "hw/msi.h"
26 #include "trace.h"
27 
28 //#define DEBUG_XHCI
29 //#define DEBUG_DATA
30 
31 #ifdef DEBUG_XHCI
32 #define DPRINTF(...) fprintf(stderr, __VA_ARGS__)
33 #else
34 #define DPRINTF(...) do {} while (0)
35 #endif
36 #define FIXME() do { fprintf(stderr, "FIXME %s:%d\n", \
37                              __func__, __LINE__); abort(); } while (0)
38 
39 #define MAXPORTS_2 8
40 #define MAXPORTS_3 8
41 
42 #define MAXPORTS (MAXPORTS_2+MAXPORTS_3)
43 #define MAXSLOTS MAXPORTS
44 #define MAXINTRS 1 /* MAXPORTS */
45 
46 #define TD_QUEUE 24
47 
48 /* Very pessimistic, let's hope it's enough for all cases */
49 #define EV_QUEUE (((3*TD_QUEUE)+16)*MAXSLOTS)
50 /* Do not deliver ER Full events. NEC's driver does some things not bound
51  * to the specs when it gets them */
52 #define ER_FULL_HACK
53 
54 #define LEN_CAP         0x40
55 #define LEN_OPER        (0x400 + 0x10 * MAXPORTS)
56 #define LEN_RUNTIME     ((MAXINTRS + 1) * 0x20)
57 #define LEN_DOORBELL    ((MAXSLOTS + 1) * 0x20)
58 
59 #define OFF_OPER        LEN_CAP
60 #define OFF_RUNTIME     0x1000
61 #define OFF_DOORBELL    0x2000
62 /* must be power of 2 */
63 #define LEN_REGS        0x4000
64 
65 #if (OFF_OPER + LEN_OPER) > OFF_RUNTIME
66 #error Increase OFF_RUNTIME
67 #endif
68 #if (OFF_RUNTIME + LEN_RUNTIME) > OFF_DOORBELL
69 #error Increase OFF_DOORBELL
70 #endif
71 #if (OFF_DOORBELL + LEN_DOORBELL) > LEN_REGS
72 # error Increase LEN_REGS
73 #endif
74 
75 #if MAXINTRS > 1
76 # error TODO: only one interrupter supported
77 #endif
78 
79 /* bit definitions */
80 #define USBCMD_RS       (1<<0)
81 #define USBCMD_HCRST    (1<<1)
82 #define USBCMD_INTE     (1<<2)
83 #define USBCMD_HSEE     (1<<3)
84 #define USBCMD_LHCRST   (1<<7)
85 #define USBCMD_CSS      (1<<8)
86 #define USBCMD_CRS      (1<<9)
87 #define USBCMD_EWE      (1<<10)
88 #define USBCMD_EU3S     (1<<11)
89 
90 #define USBSTS_HCH      (1<<0)
91 #define USBSTS_HSE      (1<<2)
92 #define USBSTS_EINT     (1<<3)
93 #define USBSTS_PCD      (1<<4)
94 #define USBSTS_SSS      (1<<8)
95 #define USBSTS_RSS      (1<<9)
96 #define USBSTS_SRE      (1<<10)
97 #define USBSTS_CNR      (1<<11)
98 #define USBSTS_HCE      (1<<12)
99 
100 
101 #define PORTSC_CCS          (1<<0)
102 #define PORTSC_PED          (1<<1)
103 #define PORTSC_OCA          (1<<3)
104 #define PORTSC_PR           (1<<4)
105 #define PORTSC_PLS_SHIFT        5
106 #define PORTSC_PLS_MASK     0xf
107 #define PORTSC_PP           (1<<9)
108 #define PORTSC_SPEED_SHIFT      10
109 #define PORTSC_SPEED_MASK   0xf
110 #define PORTSC_SPEED_FULL   (1<<10)
111 #define PORTSC_SPEED_LOW    (2<<10)
112 #define PORTSC_SPEED_HIGH   (3<<10)
113 #define PORTSC_SPEED_SUPER  (4<<10)
114 #define PORTSC_PIC_SHIFT        14
115 #define PORTSC_PIC_MASK     0x3
116 #define PORTSC_LWS          (1<<16)
117 #define PORTSC_CSC          (1<<17)
118 #define PORTSC_PEC          (1<<18)
119 #define PORTSC_WRC          (1<<19)
120 #define PORTSC_OCC          (1<<20)
121 #define PORTSC_PRC          (1<<21)
122 #define PORTSC_PLC          (1<<22)
123 #define PORTSC_CEC          (1<<23)
124 #define PORTSC_CAS          (1<<24)
125 #define PORTSC_WCE          (1<<25)
126 #define PORTSC_WDE          (1<<26)
127 #define PORTSC_WOE          (1<<27)
128 #define PORTSC_DR           (1<<30)
129 #define PORTSC_WPR          (1<<31)
130 
131 #define CRCR_RCS        (1<<0)
132 #define CRCR_CS         (1<<1)
133 #define CRCR_CA         (1<<2)
134 #define CRCR_CRR        (1<<3)
135 
136 #define IMAN_IP         (1<<0)
137 #define IMAN_IE         (1<<1)
138 
139 #define ERDP_EHB        (1<<3)
140 
141 #define TRB_SIZE 16
142 typedef struct XHCITRB {
143     uint64_t parameter;
144     uint32_t status;
145     uint32_t control;
146     dma_addr_t addr;
147     bool ccs;
148 } XHCITRB;
149 
150 
151 typedef enum TRBType {
152     TRB_RESERVED = 0,
153     TR_NORMAL,
154     TR_SETUP,
155     TR_DATA,
156     TR_STATUS,
157     TR_ISOCH,
158     TR_LINK,
159     TR_EVDATA,
160     TR_NOOP,
161     CR_ENABLE_SLOT,
162     CR_DISABLE_SLOT,
163     CR_ADDRESS_DEVICE,
164     CR_CONFIGURE_ENDPOINT,
165     CR_EVALUATE_CONTEXT,
166     CR_RESET_ENDPOINT,
167     CR_STOP_ENDPOINT,
168     CR_SET_TR_DEQUEUE,
169     CR_RESET_DEVICE,
170     CR_FORCE_EVENT,
171     CR_NEGOTIATE_BW,
172     CR_SET_LATENCY_TOLERANCE,
173     CR_GET_PORT_BANDWIDTH,
174     CR_FORCE_HEADER,
175     CR_NOOP,
176     ER_TRANSFER = 32,
177     ER_COMMAND_COMPLETE,
178     ER_PORT_STATUS_CHANGE,
179     ER_BANDWIDTH_REQUEST,
180     ER_DOORBELL,
181     ER_HOST_CONTROLLER,
182     ER_DEVICE_NOTIFICATION,
183     ER_MFINDEX_WRAP,
184     /* vendor specific bits */
185     CR_VENDOR_VIA_CHALLENGE_RESPONSE = 48,
186     CR_VENDOR_NEC_FIRMWARE_REVISION  = 49,
187     CR_VENDOR_NEC_CHALLENGE_RESPONSE = 50,
188 } TRBType;
189 
190 #define CR_LINK TR_LINK
191 
192 typedef enum TRBCCode {
193     CC_INVALID = 0,
194     CC_SUCCESS,
195     CC_DATA_BUFFER_ERROR,
196     CC_BABBLE_DETECTED,
197     CC_USB_TRANSACTION_ERROR,
198     CC_TRB_ERROR,
199     CC_STALL_ERROR,
200     CC_RESOURCE_ERROR,
201     CC_BANDWIDTH_ERROR,
202     CC_NO_SLOTS_ERROR,
203     CC_INVALID_STREAM_TYPE_ERROR,
204     CC_SLOT_NOT_ENABLED_ERROR,
205     CC_EP_NOT_ENABLED_ERROR,
206     CC_SHORT_PACKET,
207     CC_RING_UNDERRUN,
208     CC_RING_OVERRUN,
209     CC_VF_ER_FULL,
210     CC_PARAMETER_ERROR,
211     CC_BANDWIDTH_OVERRUN,
212     CC_CONTEXT_STATE_ERROR,
213     CC_NO_PING_RESPONSE_ERROR,
214     CC_EVENT_RING_FULL_ERROR,
215     CC_INCOMPATIBLE_DEVICE_ERROR,
216     CC_MISSED_SERVICE_ERROR,
217     CC_COMMAND_RING_STOPPED,
218     CC_COMMAND_ABORTED,
219     CC_STOPPED,
220     CC_STOPPED_LENGTH_INVALID,
221     CC_MAX_EXIT_LATENCY_TOO_LARGE_ERROR = 29,
222     CC_ISOCH_BUFFER_OVERRUN = 31,
223     CC_EVENT_LOST_ERROR,
224     CC_UNDEFINED_ERROR,
225     CC_INVALID_STREAM_ID_ERROR,
226     CC_SECONDARY_BANDWIDTH_ERROR,
227     CC_SPLIT_TRANSACTION_ERROR
228 } TRBCCode;
229 
230 #define TRB_C               (1<<0)
231 #define TRB_TYPE_SHIFT          10
232 #define TRB_TYPE_MASK       0x3f
233 #define TRB_TYPE(t)         (((t).control >> TRB_TYPE_SHIFT) & TRB_TYPE_MASK)
234 
235 #define TRB_EV_ED           (1<<2)
236 
237 #define TRB_TR_ENT          (1<<1)
238 #define TRB_TR_ISP          (1<<2)
239 #define TRB_TR_NS           (1<<3)
240 #define TRB_TR_CH           (1<<4)
241 #define TRB_TR_IOC          (1<<5)
242 #define TRB_TR_IDT          (1<<6)
243 #define TRB_TR_TBC_SHIFT        7
244 #define TRB_TR_TBC_MASK     0x3
245 #define TRB_TR_BEI          (1<<9)
246 #define TRB_TR_TLBPC_SHIFT      16
247 #define TRB_TR_TLBPC_MASK   0xf
248 #define TRB_TR_FRAMEID_SHIFT    20
249 #define TRB_TR_FRAMEID_MASK 0x7ff
250 #define TRB_TR_SIA          (1<<31)
251 
252 #define TRB_TR_DIR          (1<<16)
253 
254 #define TRB_CR_SLOTID_SHIFT     24
255 #define TRB_CR_SLOTID_MASK  0xff
256 #define TRB_CR_EPID_SHIFT       16
257 #define TRB_CR_EPID_MASK    0x1f
258 
259 #define TRB_CR_BSR          (1<<9)
260 #define TRB_CR_DC           (1<<9)
261 
262 #define TRB_LK_TC           (1<<1)
263 
264 #define EP_TYPE_MASK        0x7
265 #define EP_TYPE_SHIFT           3
266 
267 #define EP_STATE_MASK       0x7
268 #define EP_DISABLED         (0<<0)
269 #define EP_RUNNING          (1<<0)
270 #define EP_HALTED           (2<<0)
271 #define EP_STOPPED          (3<<0)
272 #define EP_ERROR            (4<<0)
273 
274 #define SLOT_STATE_MASK     0x1f
275 #define SLOT_STATE_SHIFT        27
276 #define SLOT_STATE(s)       (((s)>>SLOT_STATE_SHIFT)&SLOT_STATE_MASK)
277 #define SLOT_ENABLED        0
278 #define SLOT_DEFAULT        1
279 #define SLOT_ADDRESSED      2
280 #define SLOT_CONFIGURED     3
281 
282 #define SLOT_CONTEXT_ENTRIES_MASK 0x1f
283 #define SLOT_CONTEXT_ENTRIES_SHIFT 27
284 
285 typedef enum EPType {
286     ET_INVALID = 0,
287     ET_ISO_OUT,
288     ET_BULK_OUT,
289     ET_INTR_OUT,
290     ET_CONTROL,
291     ET_ISO_IN,
292     ET_BULK_IN,
293     ET_INTR_IN,
294 } EPType;
295 
296 typedef struct XHCIRing {
297     dma_addr_t base;
298     dma_addr_t dequeue;
299     bool ccs;
300 } XHCIRing;
301 
302 typedef struct XHCIPort {
303     uint32_t portsc;
304     uint32_t portnr;
305     USBPort  *uport;
306     uint32_t speedmask;
307 } XHCIPort;
308 
309 struct XHCIState;
310 typedef struct XHCIState XHCIState;
311 
312 typedef struct XHCITransfer {
313     XHCIState *xhci;
314     USBPacket packet;
315     QEMUSGList sgl;
316     bool running_async;
317     bool running_retry;
318     bool cancelled;
319     bool complete;
320     unsigned int iso_pkts;
321     unsigned int slotid;
322     unsigned int epid;
323     bool in_xfer;
324     bool iso_xfer;
325 
326     unsigned int trb_count;
327     unsigned int trb_alloced;
328     XHCITRB *trbs;
329 
330     TRBCCode status;
331 
332     unsigned int pkts;
333     unsigned int pktsize;
334     unsigned int cur_pkt;
335 
336     uint64_t mfindex_kick;
337 } XHCITransfer;
338 
339 typedef struct XHCIEPContext {
340     XHCIState *xhci;
341     unsigned int slotid;
342     unsigned int epid;
343 
344     XHCIRing ring;
345     unsigned int next_xfer;
346     unsigned int comp_xfer;
347     XHCITransfer transfers[TD_QUEUE];
348     XHCITransfer *retry;
349     EPType type;
350     dma_addr_t pctx;
351     unsigned int max_psize;
352     uint32_t state;
353 
354     /* iso xfer scheduling */
355     unsigned int interval;
356     int64_t mfindex_last;
357     QEMUTimer *kick_timer;
358 } XHCIEPContext;
359 
360 typedef struct XHCISlot {
361     bool enabled;
362     dma_addr_t ctx;
363     unsigned int port;
364     unsigned int devaddr;
365     XHCIEPContext * eps[31];
366 } XHCISlot;
367 
368 typedef struct XHCIEvent {
369     TRBType type;
370     TRBCCode ccode;
371     uint64_t ptr;
372     uint32_t length;
373     uint32_t flags;
374     uint8_t slotid;
375     uint8_t epid;
376 } XHCIEvent;
377 
378 struct XHCIState {
379     PCIDevice pci_dev;
380     USBBus bus;
381     qemu_irq irq;
382     MemoryRegion mem;
383     const char *name;
384     unsigned int devaddr;
385 
386     /* properties */
387     uint32_t numports_2;
388     uint32_t numports_3;
389     uint32_t flags;
390 
391     /* Operational Registers */
392     uint32_t usbcmd;
393     uint32_t usbsts;
394     uint32_t dnctrl;
395     uint32_t crcr_low;
396     uint32_t crcr_high;
397     uint32_t dcbaap_low;
398     uint32_t dcbaap_high;
399     uint32_t config;
400 
401     USBPort  uports[MAX(MAXPORTS_2, MAXPORTS_3)];
402     XHCIPort ports[MAXPORTS];
403     XHCISlot slots[MAXSLOTS];
404     uint32_t numports;
405 
406     /* Runtime Registers */
407     uint32_t iman;
408     uint32_t imod;
409     uint32_t erstsz;
410     uint32_t erstba_low;
411     uint32_t erstba_high;
412     uint32_t erdp_low;
413     uint32_t erdp_high;
414 
415     int64_t mfindex_start;
416     QEMUTimer *mfwrap_timer;
417 
418     dma_addr_t er_start;
419     uint32_t er_size;
420     bool er_pcs;
421     unsigned int er_ep_idx;
422     bool er_full;
423 
424     XHCIEvent ev_buffer[EV_QUEUE];
425     unsigned int ev_buffer_put;
426     unsigned int ev_buffer_get;
427 
428     XHCIRing cmd_ring;
429 };
430 
431 typedef struct XHCIEvRingSeg {
432     uint32_t addr_low;
433     uint32_t addr_high;
434     uint32_t size;
435     uint32_t rsvd;
436 } XHCIEvRingSeg;
437 
438 enum xhci_flags {
439     XHCI_FLAG_USE_MSI = 1,
440 };
441 
442 static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
443                          unsigned int epid);
444 static void xhci_event(XHCIState *xhci, XHCIEvent *event);
445 static void xhci_write_event(XHCIState *xhci, XHCIEvent *event);
446 
447 static const char *TRBType_names[] = {
448     [TRB_RESERVED]                     = "TRB_RESERVED",
449     [TR_NORMAL]                        = "TR_NORMAL",
450     [TR_SETUP]                         = "TR_SETUP",
451     [TR_DATA]                          = "TR_DATA",
452     [TR_STATUS]                        = "TR_STATUS",
453     [TR_ISOCH]                         = "TR_ISOCH",
454     [TR_LINK]                          = "TR_LINK",
455     [TR_EVDATA]                        = "TR_EVDATA",
456     [TR_NOOP]                          = "TR_NOOP",
457     [CR_ENABLE_SLOT]                   = "CR_ENABLE_SLOT",
458     [CR_DISABLE_SLOT]                  = "CR_DISABLE_SLOT",
459     [CR_ADDRESS_DEVICE]                = "CR_ADDRESS_DEVICE",
460     [CR_CONFIGURE_ENDPOINT]            = "CR_CONFIGURE_ENDPOINT",
461     [CR_EVALUATE_CONTEXT]              = "CR_EVALUATE_CONTEXT",
462     [CR_RESET_ENDPOINT]                = "CR_RESET_ENDPOINT",
463     [CR_STOP_ENDPOINT]                 = "CR_STOP_ENDPOINT",
464     [CR_SET_TR_DEQUEUE]                = "CR_SET_TR_DEQUEUE",
465     [CR_RESET_DEVICE]                  = "CR_RESET_DEVICE",
466     [CR_FORCE_EVENT]                   = "CR_FORCE_EVENT",
467     [CR_NEGOTIATE_BW]                  = "CR_NEGOTIATE_BW",
468     [CR_SET_LATENCY_TOLERANCE]         = "CR_SET_LATENCY_TOLERANCE",
469     [CR_GET_PORT_BANDWIDTH]            = "CR_GET_PORT_BANDWIDTH",
470     [CR_FORCE_HEADER]                  = "CR_FORCE_HEADER",
471     [CR_NOOP]                          = "CR_NOOP",
472     [ER_TRANSFER]                      = "ER_TRANSFER",
473     [ER_COMMAND_COMPLETE]              = "ER_COMMAND_COMPLETE",
474     [ER_PORT_STATUS_CHANGE]            = "ER_PORT_STATUS_CHANGE",
475     [ER_BANDWIDTH_REQUEST]             = "ER_BANDWIDTH_REQUEST",
476     [ER_DOORBELL]                      = "ER_DOORBELL",
477     [ER_HOST_CONTROLLER]               = "ER_HOST_CONTROLLER",
478     [ER_DEVICE_NOTIFICATION]           = "ER_DEVICE_NOTIFICATION",
479     [ER_MFINDEX_WRAP]                  = "ER_MFINDEX_WRAP",
480     [CR_VENDOR_VIA_CHALLENGE_RESPONSE] = "CR_VENDOR_VIA_CHALLENGE_RESPONSE",
481     [CR_VENDOR_NEC_FIRMWARE_REVISION]  = "CR_VENDOR_NEC_FIRMWARE_REVISION",
482     [CR_VENDOR_NEC_CHALLENGE_RESPONSE] = "CR_VENDOR_NEC_CHALLENGE_RESPONSE",
483 };
484 
485 static const char *TRBCCode_names[] = {
486     [CC_INVALID]                       = "CC_INVALID",
487     [CC_SUCCESS]                       = "CC_SUCCESS",
488     [CC_DATA_BUFFER_ERROR]             = "CC_DATA_BUFFER_ERROR",
489     [CC_BABBLE_DETECTED]               = "CC_BABBLE_DETECTED",
490     [CC_USB_TRANSACTION_ERROR]         = "CC_USB_TRANSACTION_ERROR",
491     [CC_TRB_ERROR]                     = "CC_TRB_ERROR",
492     [CC_STALL_ERROR]                   = "CC_STALL_ERROR",
493     [CC_RESOURCE_ERROR]                = "CC_RESOURCE_ERROR",
494     [CC_BANDWIDTH_ERROR]               = "CC_BANDWIDTH_ERROR",
495     [CC_NO_SLOTS_ERROR]                = "CC_NO_SLOTS_ERROR",
496     [CC_INVALID_STREAM_TYPE_ERROR]     = "CC_INVALID_STREAM_TYPE_ERROR",
497     [CC_SLOT_NOT_ENABLED_ERROR]        = "CC_SLOT_NOT_ENABLED_ERROR",
498     [CC_EP_NOT_ENABLED_ERROR]          = "CC_EP_NOT_ENABLED_ERROR",
499     [CC_SHORT_PACKET]                  = "CC_SHORT_PACKET",
500     [CC_RING_UNDERRUN]                 = "CC_RING_UNDERRUN",
501     [CC_RING_OVERRUN]                  = "CC_RING_OVERRUN",
502     [CC_VF_ER_FULL]                    = "CC_VF_ER_FULL",
503     [CC_PARAMETER_ERROR]               = "CC_PARAMETER_ERROR",
504     [CC_BANDWIDTH_OVERRUN]             = "CC_BANDWIDTH_OVERRUN",
505     [CC_CONTEXT_STATE_ERROR]           = "CC_CONTEXT_STATE_ERROR",
506     [CC_NO_PING_RESPONSE_ERROR]        = "CC_NO_PING_RESPONSE_ERROR",
507     [CC_EVENT_RING_FULL_ERROR]         = "CC_EVENT_RING_FULL_ERROR",
508     [CC_INCOMPATIBLE_DEVICE_ERROR]     = "CC_INCOMPATIBLE_DEVICE_ERROR",
509     [CC_MISSED_SERVICE_ERROR]          = "CC_MISSED_SERVICE_ERROR",
510     [CC_COMMAND_RING_STOPPED]          = "CC_COMMAND_RING_STOPPED",
511     [CC_COMMAND_ABORTED]               = "CC_COMMAND_ABORTED",
512     [CC_STOPPED]                       = "CC_STOPPED",
513     [CC_STOPPED_LENGTH_INVALID]        = "CC_STOPPED_LENGTH_INVALID",
514     [CC_MAX_EXIT_LATENCY_TOO_LARGE_ERROR]
515     = "CC_MAX_EXIT_LATENCY_TOO_LARGE_ERROR",
516     [CC_ISOCH_BUFFER_OVERRUN]          = "CC_ISOCH_BUFFER_OVERRUN",
517     [CC_EVENT_LOST_ERROR]              = "CC_EVENT_LOST_ERROR",
518     [CC_UNDEFINED_ERROR]               = "CC_UNDEFINED_ERROR",
519     [CC_INVALID_STREAM_ID_ERROR]       = "CC_INVALID_STREAM_ID_ERROR",
520     [CC_SECONDARY_BANDWIDTH_ERROR]     = "CC_SECONDARY_BANDWIDTH_ERROR",
521     [CC_SPLIT_TRANSACTION_ERROR]       = "CC_SPLIT_TRANSACTION_ERROR",
522 };
523 
524 static const char *lookup_name(uint32_t index, const char **list, uint32_t llen)
525 {
526     if (index >= llen || list[index] == NULL) {
527         return "???";
528     }
529     return list[index];
530 }
531 
532 static const char *trb_name(XHCITRB *trb)
533 {
534     return lookup_name(TRB_TYPE(*trb), TRBType_names,
535                        ARRAY_SIZE(TRBType_names));
536 }
537 
538 static const char *event_name(XHCIEvent *event)
539 {
540     return lookup_name(event->ccode, TRBCCode_names,
541                        ARRAY_SIZE(TRBCCode_names));
542 }
543 
544 static uint64_t xhci_mfindex_get(XHCIState *xhci)
545 {
546     int64_t now = qemu_get_clock_ns(vm_clock);
547     return (now - xhci->mfindex_start) / 125000;
548 }
549 
550 static void xhci_mfwrap_update(XHCIState *xhci)
551 {
552     const uint32_t bits = USBCMD_RS | USBCMD_EWE;
553     uint32_t mfindex, left;
554     int64_t now;
555 
556     if ((xhci->usbcmd & bits) == bits) {
557         now = qemu_get_clock_ns(vm_clock);
558         mfindex = ((now - xhci->mfindex_start) / 125000) & 0x3fff;
559         left = 0x4000 - mfindex;
560         qemu_mod_timer(xhci->mfwrap_timer, now + left * 125000);
561     } else {
562         qemu_del_timer(xhci->mfwrap_timer);
563     }
564 }
565 
566 static void xhci_mfwrap_timer(void *opaque)
567 {
568     XHCIState *xhci = opaque;
569     XHCIEvent wrap = { ER_MFINDEX_WRAP, CC_SUCCESS };
570 
571     xhci_event(xhci, &wrap);
572     xhci_mfwrap_update(xhci);
573 }
574 
575 static inline dma_addr_t xhci_addr64(uint32_t low, uint32_t high)
576 {
577     if (sizeof(dma_addr_t) == 4) {
578         return low;
579     } else {
580         return low | (((dma_addr_t)high << 16) << 16);
581     }
582 }
583 
584 static inline dma_addr_t xhci_mask64(uint64_t addr)
585 {
586     if (sizeof(dma_addr_t) == 4) {
587         return addr & 0xffffffff;
588     } else {
589         return addr;
590     }
591 }
592 
593 static XHCIPort *xhci_lookup_port(XHCIState *xhci, struct USBPort *uport)
594 {
595     int index;
596 
597     if (!uport->dev) {
598         return NULL;
599     }
600     switch (uport->dev->speed) {
601     case USB_SPEED_LOW:
602     case USB_SPEED_FULL:
603     case USB_SPEED_HIGH:
604         index = uport->index;
605         break;
606     case USB_SPEED_SUPER:
607         index = uport->index + xhci->numports_2;
608         break;
609     default:
610         return NULL;
611     }
612     return &xhci->ports[index];
613 }
614 
615 static void xhci_intx_update(XHCIState *xhci)
616 {
617     int level = 0;
618 
619     if (msi_enabled(&xhci->pci_dev)) {
620         return;
621     }
622 
623     if (xhci->iman & IMAN_IP &&
624         xhci->iman & IMAN_IE &&
625         xhci->usbcmd & USBCMD_INTE) {
626         level = 1;
627     }
628 
629     trace_usb_xhci_irq_intx(level);
630     qemu_set_irq(xhci->irq, level);
631 }
632 
633 static void xhci_intr_raise(XHCIState *xhci)
634 {
635     if (!(xhci->iman & IMAN_IP) ||
636         !(xhci->iman & IMAN_IE)) {
637         return;
638     }
639 
640     if (!(xhci->usbcmd & USBCMD_INTE)) {
641         return;
642     }
643 
644     if (msi_enabled(&xhci->pci_dev)) {
645         trace_usb_xhci_irq_msi(0);
646         msi_notify(&xhci->pci_dev, 0);
647         return;
648     }
649 
650     trace_usb_xhci_irq_intx(1);
651     qemu_set_irq(xhci->irq, 1);
652 }
653 
654 static inline int xhci_running(XHCIState *xhci)
655 {
656     return !(xhci->usbsts & USBSTS_HCH) && !xhci->er_full;
657 }
658 
659 static void xhci_die(XHCIState *xhci)
660 {
661     xhci->usbsts |= USBSTS_HCE;
662     fprintf(stderr, "xhci: asserted controller error\n");
663 }
664 
665 static void xhci_write_event(XHCIState *xhci, XHCIEvent *event)
666 {
667     XHCITRB ev_trb;
668     dma_addr_t addr;
669 
670     ev_trb.parameter = cpu_to_le64(event->ptr);
671     ev_trb.status = cpu_to_le32(event->length | (event->ccode << 24));
672     ev_trb.control = (event->slotid << 24) | (event->epid << 16) |
673                      event->flags | (event->type << TRB_TYPE_SHIFT);
674     if (xhci->er_pcs) {
675         ev_trb.control |= TRB_C;
676     }
677     ev_trb.control = cpu_to_le32(ev_trb.control);
678 
679     trace_usb_xhci_queue_event(xhci->er_ep_idx, trb_name(&ev_trb),
680                                event_name(event), ev_trb.parameter,
681                                ev_trb.status, ev_trb.control);
682 
683     addr = xhci->er_start + TRB_SIZE*xhci->er_ep_idx;
684     pci_dma_write(&xhci->pci_dev, addr, &ev_trb, TRB_SIZE);
685 
686     xhci->er_ep_idx++;
687     if (xhci->er_ep_idx >= xhci->er_size) {
688         xhci->er_ep_idx = 0;
689         xhci->er_pcs = !xhci->er_pcs;
690     }
691 }
692 
693 static void xhci_events_update(XHCIState *xhci)
694 {
695     dma_addr_t erdp;
696     unsigned int dp_idx;
697     bool do_irq = 0;
698 
699     if (xhci->usbsts & USBSTS_HCH) {
700         return;
701     }
702 
703     erdp = xhci_addr64(xhci->erdp_low, xhci->erdp_high);
704     if (erdp < xhci->er_start ||
705         erdp >= (xhci->er_start + TRB_SIZE*xhci->er_size)) {
706         fprintf(stderr, "xhci: ERDP out of bounds: "DMA_ADDR_FMT"\n", erdp);
707         fprintf(stderr, "xhci: ER at "DMA_ADDR_FMT" len %d\n",
708                 xhci->er_start, xhci->er_size);
709         xhci_die(xhci);
710         return;
711     }
712     dp_idx = (erdp - xhci->er_start) / TRB_SIZE;
713     assert(dp_idx < xhci->er_size);
714 
715     /* NEC didn't read section 4.9.4 of the spec (v1.0 p139 top Note) and thus
716      * deadlocks when the ER is full. Hack it by holding off events until
717      * the driver decides to free at least half of the ring */
718     if (xhci->er_full) {
719         int er_free = dp_idx - xhci->er_ep_idx;
720         if (er_free <= 0) {
721             er_free += xhci->er_size;
722         }
723         if (er_free < (xhci->er_size/2)) {
724             DPRINTF("xhci_events_update(): event ring still "
725                     "more than half full (hack)\n");
726             return;
727         }
728     }
729 
730     while (xhci->ev_buffer_put != xhci->ev_buffer_get) {
731         assert(xhci->er_full);
732         if (((xhci->er_ep_idx+1) % xhci->er_size) == dp_idx) {
733             DPRINTF("xhci_events_update(): event ring full again\n");
734 #ifndef ER_FULL_HACK
735             XHCIEvent full = {ER_HOST_CONTROLLER, CC_EVENT_RING_FULL_ERROR};
736             xhci_write_event(xhci, &full);
737 #endif
738             do_irq = 1;
739             break;
740         }
741         XHCIEvent *event = &xhci->ev_buffer[xhci->ev_buffer_get];
742         xhci_write_event(xhci, event);
743         xhci->ev_buffer_get++;
744         do_irq = 1;
745         if (xhci->ev_buffer_get == EV_QUEUE) {
746             xhci->ev_buffer_get = 0;
747         }
748     }
749 
750     if (do_irq) {
751         xhci->erdp_low |= ERDP_EHB;
752         xhci->iman |= IMAN_IP;
753         xhci->usbsts |= USBSTS_EINT;
754         xhci_intr_raise(xhci);
755     }
756 
757     if (xhci->er_full && xhci->ev_buffer_put == xhci->ev_buffer_get) {
758         DPRINTF("xhci_events_update(): event ring no longer full\n");
759         xhci->er_full = 0;
760     }
761     return;
762 }
763 
764 static void xhci_event(XHCIState *xhci, XHCIEvent *event)
765 {
766     dma_addr_t erdp;
767     unsigned int dp_idx;
768 
769     if (xhci->er_full) {
770         DPRINTF("xhci_event(): ER full, queueing\n");
771         if (((xhci->ev_buffer_put+1) % EV_QUEUE) == xhci->ev_buffer_get) {
772             fprintf(stderr, "xhci: event queue full, dropping event!\n");
773             return;
774         }
775         xhci->ev_buffer[xhci->ev_buffer_put++] = *event;
776         if (xhci->ev_buffer_put == EV_QUEUE) {
777             xhci->ev_buffer_put = 0;
778         }
779         return;
780     }
781 
782     erdp = xhci_addr64(xhci->erdp_low, xhci->erdp_high);
783     if (erdp < xhci->er_start ||
784         erdp >= (xhci->er_start + TRB_SIZE*xhci->er_size)) {
785         fprintf(stderr, "xhci: ERDP out of bounds: "DMA_ADDR_FMT"\n", erdp);
786         fprintf(stderr, "xhci: ER at "DMA_ADDR_FMT" len %d\n",
787                 xhci->er_start, xhci->er_size);
788         xhci_die(xhci);
789         return;
790     }
791 
792     dp_idx = (erdp - xhci->er_start) / TRB_SIZE;
793     assert(dp_idx < xhci->er_size);
794 
795     if ((xhci->er_ep_idx+1) % xhci->er_size == dp_idx) {
796         DPRINTF("xhci_event(): ER full, queueing\n");
797 #ifndef ER_FULL_HACK
798         XHCIEvent full = {ER_HOST_CONTROLLER, CC_EVENT_RING_FULL_ERROR};
799         xhci_write_event(xhci, &full);
800 #endif
801         xhci->er_full = 1;
802         if (((xhci->ev_buffer_put+1) % EV_QUEUE) == xhci->ev_buffer_get) {
803             fprintf(stderr, "xhci: event queue full, dropping event!\n");
804             return;
805         }
806         xhci->ev_buffer[xhci->ev_buffer_put++] = *event;
807         if (xhci->ev_buffer_put == EV_QUEUE) {
808             xhci->ev_buffer_put = 0;
809         }
810     } else {
811         xhci_write_event(xhci, event);
812     }
813 
814     xhci->erdp_low |= ERDP_EHB;
815     xhci->iman |= IMAN_IP;
816     xhci->usbsts |= USBSTS_EINT;
817 
818     xhci_intr_raise(xhci);
819 }
820 
821 static void xhci_ring_init(XHCIState *xhci, XHCIRing *ring,
822                            dma_addr_t base)
823 {
824     ring->base = base;
825     ring->dequeue = base;
826     ring->ccs = 1;
827 }
828 
829 static TRBType xhci_ring_fetch(XHCIState *xhci, XHCIRing *ring, XHCITRB *trb,
830                                dma_addr_t *addr)
831 {
832     while (1) {
833         TRBType type;
834         pci_dma_read(&xhci->pci_dev, ring->dequeue, trb, TRB_SIZE);
835         trb->addr = ring->dequeue;
836         trb->ccs = ring->ccs;
837         le64_to_cpus(&trb->parameter);
838         le32_to_cpus(&trb->status);
839         le32_to_cpus(&trb->control);
840 
841         trace_usb_xhci_fetch_trb(ring->dequeue, trb_name(trb),
842                                  trb->parameter, trb->status, trb->control);
843 
844         if ((trb->control & TRB_C) != ring->ccs) {
845             return 0;
846         }
847 
848         type = TRB_TYPE(*trb);
849 
850         if (type != TR_LINK) {
851             if (addr) {
852                 *addr = ring->dequeue;
853             }
854             ring->dequeue += TRB_SIZE;
855             return type;
856         } else {
857             ring->dequeue = xhci_mask64(trb->parameter);
858             if (trb->control & TRB_LK_TC) {
859                 ring->ccs = !ring->ccs;
860             }
861         }
862     }
863 }
864 
865 static int xhci_ring_chain_length(XHCIState *xhci, const XHCIRing *ring)
866 {
867     XHCITRB trb;
868     int length = 0;
869     dma_addr_t dequeue = ring->dequeue;
870     bool ccs = ring->ccs;
871     /* hack to bundle together the two/three TDs that make a setup transfer */
872     bool control_td_set = 0;
873 
874     while (1) {
875         TRBType type;
876         pci_dma_read(&xhci->pci_dev, dequeue, &trb, TRB_SIZE);
877         le64_to_cpus(&trb.parameter);
878         le32_to_cpus(&trb.status);
879         le32_to_cpus(&trb.control);
880 
881         if ((trb.control & TRB_C) != ccs) {
882             return -length;
883         }
884 
885         type = TRB_TYPE(trb);
886 
887         if (type == TR_LINK) {
888             dequeue = xhci_mask64(trb.parameter);
889             if (trb.control & TRB_LK_TC) {
890                 ccs = !ccs;
891             }
892             continue;
893         }
894 
895         length += 1;
896         dequeue += TRB_SIZE;
897 
898         if (type == TR_SETUP) {
899             control_td_set = 1;
900         } else if (type == TR_STATUS) {
901             control_td_set = 0;
902         }
903 
904         if (!control_td_set && !(trb.control & TRB_TR_CH)) {
905             return length;
906         }
907     }
908 }
909 
910 static void xhci_er_reset(XHCIState *xhci)
911 {
912     XHCIEvRingSeg seg;
913 
914     /* cache the (sole) event ring segment location */
915     if (xhci->erstsz != 1) {
916         fprintf(stderr, "xhci: invalid value for ERSTSZ: %d\n", xhci->erstsz);
917         xhci_die(xhci);
918         return;
919     }
920     dma_addr_t erstba = xhci_addr64(xhci->erstba_low, xhci->erstba_high);
921     pci_dma_read(&xhci->pci_dev, erstba, &seg, sizeof(seg));
922     le32_to_cpus(&seg.addr_low);
923     le32_to_cpus(&seg.addr_high);
924     le32_to_cpus(&seg.size);
925     if (seg.size < 16 || seg.size > 4096) {
926         fprintf(stderr, "xhci: invalid value for segment size: %d\n", seg.size);
927         xhci_die(xhci);
928         return;
929     }
930     xhci->er_start = xhci_addr64(seg.addr_low, seg.addr_high);
931     xhci->er_size = seg.size;
932 
933     xhci->er_ep_idx = 0;
934     xhci->er_pcs = 1;
935     xhci->er_full = 0;
936 
937     DPRINTF("xhci: event ring:" DMA_ADDR_FMT " [%d]\n",
938             xhci->er_start, xhci->er_size);
939 }
940 
941 static void xhci_run(XHCIState *xhci)
942 {
943     trace_usb_xhci_run();
944     xhci->usbsts &= ~USBSTS_HCH;
945     xhci->mfindex_start = qemu_get_clock_ns(vm_clock);
946 }
947 
948 static void xhci_stop(XHCIState *xhci)
949 {
950     trace_usb_xhci_stop();
951     xhci->usbsts |= USBSTS_HCH;
952     xhci->crcr_low &= ~CRCR_CRR;
953 }
954 
955 static void xhci_set_ep_state(XHCIState *xhci, XHCIEPContext *epctx,
956                               uint32_t state)
957 {
958     uint32_t ctx[5];
959     if (epctx->state == state) {
960         return;
961     }
962 
963     pci_dma_read(&xhci->pci_dev, epctx->pctx, ctx, sizeof(ctx));
964     ctx[0] &= ~EP_STATE_MASK;
965     ctx[0] |= state;
966     ctx[2] = epctx->ring.dequeue | epctx->ring.ccs;
967     ctx[3] = (epctx->ring.dequeue >> 16) >> 16;
968     DPRINTF("xhci: set epctx: " DMA_ADDR_FMT " state=%d dequeue=%08x%08x\n",
969             epctx->pctx, state, ctx[3], ctx[2]);
970     pci_dma_write(&xhci->pci_dev, epctx->pctx, ctx, sizeof(ctx));
971     epctx->state = state;
972 }
973 
974 static void xhci_ep_kick_timer(void *opaque)
975 {
976     XHCIEPContext *epctx = opaque;
977     xhci_kick_ep(epctx->xhci, epctx->slotid, epctx->epid);
978 }
979 
980 static TRBCCode xhci_enable_ep(XHCIState *xhci, unsigned int slotid,
981                                unsigned int epid, dma_addr_t pctx,
982                                uint32_t *ctx)
983 {
984     XHCISlot *slot;
985     XHCIEPContext *epctx;
986     dma_addr_t dequeue;
987     int i;
988 
989     trace_usb_xhci_ep_enable(slotid, epid);
990     assert(slotid >= 1 && slotid <= MAXSLOTS);
991     assert(epid >= 1 && epid <= 31);
992 
993     slot = &xhci->slots[slotid-1];
994     if (slot->eps[epid-1]) {
995         fprintf(stderr, "xhci: slot %d ep %d already enabled!\n", slotid, epid);
996         return CC_TRB_ERROR;
997     }
998 
999     epctx = g_malloc(sizeof(XHCIEPContext));
1000     memset(epctx, 0, sizeof(XHCIEPContext));
1001     epctx->xhci = xhci;
1002     epctx->slotid = slotid;
1003     epctx->epid = epid;
1004 
1005     slot->eps[epid-1] = epctx;
1006 
1007     dequeue = xhci_addr64(ctx[2] & ~0xf, ctx[3]);
1008     xhci_ring_init(xhci, &epctx->ring, dequeue);
1009     epctx->ring.ccs = ctx[2] & 1;
1010 
1011     epctx->type = (ctx[1] >> EP_TYPE_SHIFT) & EP_TYPE_MASK;
1012     DPRINTF("xhci: endpoint %d.%d type is %d\n", epid/2, epid%2, epctx->type);
1013     epctx->pctx = pctx;
1014     epctx->max_psize = ctx[1]>>16;
1015     epctx->max_psize *= 1+((ctx[1]>>8)&0xff);
1016     DPRINTF("xhci: endpoint %d.%d max transaction (burst) size is %d\n",
1017             epid/2, epid%2, epctx->max_psize);
1018     for (i = 0; i < ARRAY_SIZE(epctx->transfers); i++) {
1019         usb_packet_init(&epctx->transfers[i].packet);
1020     }
1021 
1022     epctx->interval = 1 << (ctx[0] >> 16) & 0xff;
1023     epctx->mfindex_last = 0;
1024     epctx->kick_timer = qemu_new_timer_ns(vm_clock, xhci_ep_kick_timer, epctx);
1025 
1026     epctx->state = EP_RUNNING;
1027     ctx[0] &= ~EP_STATE_MASK;
1028     ctx[0] |= EP_RUNNING;
1029 
1030     return CC_SUCCESS;
1031 }
1032 
1033 static int xhci_ep_nuke_xfers(XHCIState *xhci, unsigned int slotid,
1034                                unsigned int epid)
1035 {
1036     XHCISlot *slot;
1037     XHCIEPContext *epctx;
1038     int i, xferi, killed = 0;
1039     assert(slotid >= 1 && slotid <= MAXSLOTS);
1040     assert(epid >= 1 && epid <= 31);
1041 
1042     DPRINTF("xhci_ep_nuke_xfers(%d, %d)\n", slotid, epid);
1043 
1044     slot = &xhci->slots[slotid-1];
1045 
1046     if (!slot->eps[epid-1]) {
1047         return 0;
1048     }
1049 
1050     epctx = slot->eps[epid-1];
1051 
1052     xferi = epctx->next_xfer;
1053     for (i = 0; i < TD_QUEUE; i++) {
1054         XHCITransfer *t = &epctx->transfers[xferi];
1055         if (t->running_async) {
1056             usb_cancel_packet(&t->packet);
1057             t->running_async = 0;
1058             t->cancelled = 1;
1059             DPRINTF("xhci: cancelling transfer %d, waiting for it to complete...\n", i);
1060             killed++;
1061         }
1062         if (t->running_retry) {
1063             t->running_retry = 0;
1064             epctx->retry = NULL;
1065             qemu_del_timer(epctx->kick_timer);
1066         }
1067         if (t->trbs) {
1068             g_free(t->trbs);
1069         }
1070 
1071         t->trbs = NULL;
1072         t->trb_count = t->trb_alloced = 0;
1073         xferi = (xferi + 1) % TD_QUEUE;
1074     }
1075     return killed;
1076 }
1077 
1078 static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,
1079                                unsigned int epid)
1080 {
1081     XHCISlot *slot;
1082     XHCIEPContext *epctx;
1083 
1084     trace_usb_xhci_ep_disable(slotid, epid);
1085     assert(slotid >= 1 && slotid <= MAXSLOTS);
1086     assert(epid >= 1 && epid <= 31);
1087 
1088     slot = &xhci->slots[slotid-1];
1089 
1090     if (!slot->eps[epid-1]) {
1091         DPRINTF("xhci: slot %d ep %d already disabled\n", slotid, epid);
1092         return CC_SUCCESS;
1093     }
1094 
1095     xhci_ep_nuke_xfers(xhci, slotid, epid);
1096 
1097     epctx = slot->eps[epid-1];
1098 
1099     xhci_set_ep_state(xhci, epctx, EP_DISABLED);
1100 
1101     qemu_free_timer(epctx->kick_timer);
1102     g_free(epctx);
1103     slot->eps[epid-1] = NULL;
1104 
1105     return CC_SUCCESS;
1106 }
1107 
1108 static TRBCCode xhci_stop_ep(XHCIState *xhci, unsigned int slotid,
1109                              unsigned int epid)
1110 {
1111     XHCISlot *slot;
1112     XHCIEPContext *epctx;
1113 
1114     trace_usb_xhci_ep_stop(slotid, epid);
1115     assert(slotid >= 1 && slotid <= MAXSLOTS);
1116 
1117     if (epid < 1 || epid > 31) {
1118         fprintf(stderr, "xhci: bad ep %d\n", epid);
1119         return CC_TRB_ERROR;
1120     }
1121 
1122     slot = &xhci->slots[slotid-1];
1123 
1124     if (!slot->eps[epid-1]) {
1125         DPRINTF("xhci: slot %d ep %d not enabled\n", slotid, epid);
1126         return CC_EP_NOT_ENABLED_ERROR;
1127     }
1128 
1129     if (xhci_ep_nuke_xfers(xhci, slotid, epid) > 0) {
1130         fprintf(stderr, "xhci: FIXME: endpoint stopped w/ xfers running, "
1131                 "data might be lost\n");
1132     }
1133 
1134     epctx = slot->eps[epid-1];
1135 
1136     xhci_set_ep_state(xhci, epctx, EP_STOPPED);
1137 
1138     return CC_SUCCESS;
1139 }
1140 
1141 static TRBCCode xhci_reset_ep(XHCIState *xhci, unsigned int slotid,
1142                               unsigned int epid)
1143 {
1144     XHCISlot *slot;
1145     XHCIEPContext *epctx;
1146     USBDevice *dev;
1147 
1148     trace_usb_xhci_ep_reset(slotid, epid);
1149     assert(slotid >= 1 && slotid <= MAXSLOTS);
1150 
1151     if (epid < 1 || epid > 31) {
1152         fprintf(stderr, "xhci: bad ep %d\n", epid);
1153         return CC_TRB_ERROR;
1154     }
1155 
1156     slot = &xhci->slots[slotid-1];
1157 
1158     if (!slot->eps[epid-1]) {
1159         DPRINTF("xhci: slot %d ep %d not enabled\n", slotid, epid);
1160         return CC_EP_NOT_ENABLED_ERROR;
1161     }
1162 
1163     epctx = slot->eps[epid-1];
1164 
1165     if (epctx->state != EP_HALTED) {
1166         fprintf(stderr, "xhci: reset EP while EP %d not halted (%d)\n",
1167                 epid, epctx->state);
1168         return CC_CONTEXT_STATE_ERROR;
1169     }
1170 
1171     if (xhci_ep_nuke_xfers(xhci, slotid, epid) > 0) {
1172         fprintf(stderr, "xhci: FIXME: endpoint reset w/ xfers running, "
1173                 "data might be lost\n");
1174     }
1175 
1176     uint8_t ep = epid>>1;
1177 
1178     if (epid & 1) {
1179         ep |= 0x80;
1180     }
1181 
1182     dev = xhci->ports[xhci->slots[slotid-1].port-1].uport->dev;
1183     if (!dev) {
1184         return CC_USB_TRANSACTION_ERROR;
1185     }
1186 
1187     xhci_set_ep_state(xhci, epctx, EP_STOPPED);
1188 
1189     return CC_SUCCESS;
1190 }
1191 
1192 static TRBCCode xhci_set_ep_dequeue(XHCIState *xhci, unsigned int slotid,
1193                                     unsigned int epid, uint64_t pdequeue)
1194 {
1195     XHCISlot *slot;
1196     XHCIEPContext *epctx;
1197     dma_addr_t dequeue;
1198 
1199     assert(slotid >= 1 && slotid <= MAXSLOTS);
1200 
1201     if (epid < 1 || epid > 31) {
1202         fprintf(stderr, "xhci: bad ep %d\n", epid);
1203         return CC_TRB_ERROR;
1204     }
1205 
1206     trace_usb_xhci_ep_set_dequeue(slotid, epid, pdequeue);
1207     dequeue = xhci_mask64(pdequeue);
1208 
1209     slot = &xhci->slots[slotid-1];
1210 
1211     if (!slot->eps[epid-1]) {
1212         DPRINTF("xhci: slot %d ep %d not enabled\n", slotid, epid);
1213         return CC_EP_NOT_ENABLED_ERROR;
1214     }
1215 
1216     epctx = slot->eps[epid-1];
1217 
1218 
1219     if (epctx->state != EP_STOPPED) {
1220         fprintf(stderr, "xhci: set EP dequeue pointer while EP %d not stopped\n", epid);
1221         return CC_CONTEXT_STATE_ERROR;
1222     }
1223 
1224     xhci_ring_init(xhci, &epctx->ring, dequeue & ~0xF);
1225     epctx->ring.ccs = dequeue & 1;
1226 
1227     xhci_set_ep_state(xhci, epctx, EP_STOPPED);
1228 
1229     return CC_SUCCESS;
1230 }
1231 
1232 static int xhci_xfer_map(XHCITransfer *xfer)
1233 {
1234     int in_xfer = (xfer->packet.pid == USB_TOKEN_IN);
1235     XHCIState *xhci = xfer->xhci;
1236     int i;
1237 
1238     pci_dma_sglist_init(&xfer->sgl, &xhci->pci_dev, xfer->trb_count);
1239     for (i = 0; i < xfer->trb_count; i++) {
1240         XHCITRB *trb = &xfer->trbs[i];
1241         dma_addr_t addr;
1242         unsigned int chunk = 0;
1243 
1244         switch (TRB_TYPE(*trb)) {
1245         case TR_DATA:
1246             if ((!(trb->control & TRB_TR_DIR)) != (!in_xfer)) {
1247                 fprintf(stderr, "xhci: data direction mismatch for TR_DATA\n");
1248                 goto err;
1249             }
1250             /* fallthrough */
1251         case TR_NORMAL:
1252         case TR_ISOCH:
1253             addr = xhci_mask64(trb->parameter);
1254             chunk = trb->status & 0x1ffff;
1255             if (trb->control & TRB_TR_IDT) {
1256                 if (chunk > 8 || in_xfer) {
1257                     fprintf(stderr, "xhci: invalid immediate data TRB\n");
1258                     goto err;
1259                 }
1260                 qemu_sglist_add(&xfer->sgl, trb->addr, chunk);
1261             } else {
1262                 qemu_sglist_add(&xfer->sgl, addr, chunk);
1263             }
1264             break;
1265         }
1266     }
1267 
1268     usb_packet_map(&xfer->packet, &xfer->sgl);
1269     return 0;
1270 
1271 err:
1272     qemu_sglist_destroy(&xfer->sgl);
1273     xhci_die(xhci);
1274     return -1;
1275 }
1276 
1277 static void xhci_xfer_unmap(XHCITransfer *xfer)
1278 {
1279     usb_packet_unmap(&xfer->packet, &xfer->sgl);
1280     qemu_sglist_destroy(&xfer->sgl);
1281 }
1282 
1283 static void xhci_xfer_report(XHCITransfer *xfer)
1284 {
1285     uint32_t edtla = 0;
1286     unsigned int left;
1287     bool reported = 0;
1288     bool shortpkt = 0;
1289     XHCIEvent event = {ER_TRANSFER, CC_SUCCESS};
1290     XHCIState *xhci = xfer->xhci;
1291     int i;
1292 
1293     left = xfer->packet.result < 0 ? 0 : xfer->packet.result;
1294 
1295     for (i = 0; i < xfer->trb_count; i++) {
1296         XHCITRB *trb = &xfer->trbs[i];
1297         unsigned int chunk = 0;
1298 
1299         switch (TRB_TYPE(*trb)) {
1300         case TR_DATA:
1301         case TR_NORMAL:
1302         case TR_ISOCH:
1303             chunk = trb->status & 0x1ffff;
1304             if (chunk > left) {
1305                 chunk = left;
1306                 if (xfer->status == CC_SUCCESS) {
1307                     shortpkt = 1;
1308                 }
1309             }
1310             left -= chunk;
1311             edtla += chunk;
1312             break;
1313         case TR_STATUS:
1314             reported = 0;
1315             shortpkt = 0;
1316             break;
1317         }
1318 
1319         if (!reported && ((trb->control & TRB_TR_IOC) ||
1320                           (shortpkt && (trb->control & TRB_TR_ISP)) ||
1321                           (xfer->status != CC_SUCCESS))) {
1322             event.slotid = xfer->slotid;
1323             event.epid = xfer->epid;
1324             event.length = (trb->status & 0x1ffff) - chunk;
1325             event.flags = 0;
1326             event.ptr = trb->addr;
1327             if (xfer->status == CC_SUCCESS) {
1328                 event.ccode = shortpkt ? CC_SHORT_PACKET : CC_SUCCESS;
1329             } else {
1330                 event.ccode = xfer->status;
1331             }
1332             if (TRB_TYPE(*trb) == TR_EVDATA) {
1333                 event.ptr = trb->parameter;
1334                 event.flags |= TRB_EV_ED;
1335                 event.length = edtla & 0xffffff;
1336                 DPRINTF("xhci_xfer_data: EDTLA=%d\n", event.length);
1337                 edtla = 0;
1338             }
1339             xhci_event(xhci, &event);
1340             reported = 1;
1341             if (xfer->status != CC_SUCCESS) {
1342                 return;
1343             }
1344         }
1345     }
1346 }
1347 
1348 static void xhci_stall_ep(XHCITransfer *xfer)
1349 {
1350     XHCIState *xhci = xfer->xhci;
1351     XHCISlot *slot = &xhci->slots[xfer->slotid-1];
1352     XHCIEPContext *epctx = slot->eps[xfer->epid-1];
1353 
1354     epctx->ring.dequeue = xfer->trbs[0].addr;
1355     epctx->ring.ccs = xfer->trbs[0].ccs;
1356     xhci_set_ep_state(xhci, epctx, EP_HALTED);
1357     DPRINTF("xhci: stalled slot %d ep %d\n", xfer->slotid, xfer->epid);
1358     DPRINTF("xhci: will continue at "DMA_ADDR_FMT"\n", epctx->ring.dequeue);
1359 }
1360 
1361 static int xhci_submit(XHCIState *xhci, XHCITransfer *xfer,
1362                        XHCIEPContext *epctx);
1363 
1364 static USBDevice *xhci_find_device(XHCIPort *port, uint8_t addr)
1365 {
1366     if (!(port->portsc & PORTSC_PED)) {
1367         return NULL;
1368     }
1369     return usb_find_device(port->uport, addr);
1370 }
1371 
1372 static int xhci_setup_packet(XHCITransfer *xfer)
1373 {
1374     XHCIState *xhci = xfer->xhci;
1375     XHCIPort *port;
1376     USBDevice *dev;
1377     USBEndpoint *ep;
1378     int dir;
1379 
1380     dir = xfer->in_xfer ? USB_TOKEN_IN : USB_TOKEN_OUT;
1381 
1382     if (xfer->packet.ep) {
1383         ep = xfer->packet.ep;
1384         dev = ep->dev;
1385     } else {
1386         port = &xhci->ports[xhci->slots[xfer->slotid-1].port-1];
1387         dev = xhci_find_device(port, xhci->slots[xfer->slotid-1].devaddr);
1388         if (!dev) {
1389             fprintf(stderr, "xhci: slot %d port %d has no device\n",
1390                     xfer->slotid, xhci->slots[xfer->slotid-1].port);
1391             return -1;
1392         }
1393         ep = usb_ep_get(dev, dir, xfer->epid >> 1);
1394     }
1395 
1396     usb_packet_setup(&xfer->packet, dir, ep, xfer->trbs[0].addr);
1397     xhci_xfer_map(xfer);
1398     DPRINTF("xhci: setup packet pid 0x%x addr %d ep %d\n",
1399             xfer->packet.pid, dev->addr, ep->nr);
1400     return 0;
1401 }
1402 
1403 static int xhci_complete_packet(XHCITransfer *xfer, int ret)
1404 {
1405     if (ret == USB_RET_ASYNC) {
1406         trace_usb_xhci_xfer_async(xfer);
1407         xfer->running_async = 1;
1408         xfer->running_retry = 0;
1409         xfer->complete = 0;
1410         xfer->cancelled = 0;
1411         return 0;
1412     } else if (ret == USB_RET_NAK) {
1413         trace_usb_xhci_xfer_nak(xfer);
1414         xfer->running_async = 0;
1415         xfer->running_retry = 1;
1416         xfer->complete = 0;
1417         xfer->cancelled = 0;
1418         return 0;
1419     } else {
1420         xfer->running_async = 0;
1421         xfer->running_retry = 0;
1422         xfer->complete = 1;
1423         xhci_xfer_unmap(xfer);
1424     }
1425 
1426     if (ret >= 0) {
1427         trace_usb_xhci_xfer_success(xfer, ret);
1428         xfer->status = CC_SUCCESS;
1429         xhci_xfer_report(xfer);
1430         return 0;
1431     }
1432 
1433     /* error */
1434     trace_usb_xhci_xfer_error(xfer, ret);
1435     switch (ret) {
1436     case USB_RET_NODEV:
1437         xfer->status = CC_USB_TRANSACTION_ERROR;
1438         xhci_xfer_report(xfer);
1439         xhci_stall_ep(xfer);
1440         break;
1441     case USB_RET_STALL:
1442         xfer->status = CC_STALL_ERROR;
1443         xhci_xfer_report(xfer);
1444         xhci_stall_ep(xfer);
1445         break;
1446     default:
1447         fprintf(stderr, "%s: FIXME: ret = %d\n", __FUNCTION__, ret);
1448         FIXME();
1449     }
1450     return 0;
1451 }
1452 
1453 static int xhci_fire_ctl_transfer(XHCIState *xhci, XHCITransfer *xfer)
1454 {
1455     XHCITRB *trb_setup, *trb_status;
1456     uint8_t bmRequestType;
1457     int ret;
1458 
1459     trb_setup = &xfer->trbs[0];
1460     trb_status = &xfer->trbs[xfer->trb_count-1];
1461 
1462     trace_usb_xhci_xfer_start(xfer, xfer->slotid, xfer->epid);
1463 
1464     /* at most one Event Data TRB allowed after STATUS */
1465     if (TRB_TYPE(*trb_status) == TR_EVDATA && xfer->trb_count > 2) {
1466         trb_status--;
1467     }
1468 
1469     /* do some sanity checks */
1470     if (TRB_TYPE(*trb_setup) != TR_SETUP) {
1471         fprintf(stderr, "xhci: ep0 first TD not SETUP: %d\n",
1472                 TRB_TYPE(*trb_setup));
1473         return -1;
1474     }
1475     if (TRB_TYPE(*trb_status) != TR_STATUS) {
1476         fprintf(stderr, "xhci: ep0 last TD not STATUS: %d\n",
1477                 TRB_TYPE(*trb_status));
1478         return -1;
1479     }
1480     if (!(trb_setup->control & TRB_TR_IDT)) {
1481         fprintf(stderr, "xhci: Setup TRB doesn't have IDT set\n");
1482         return -1;
1483     }
1484     if ((trb_setup->status & 0x1ffff) != 8) {
1485         fprintf(stderr, "xhci: Setup TRB has bad length (%d)\n",
1486                 (trb_setup->status & 0x1ffff));
1487         return -1;
1488     }
1489 
1490     bmRequestType = trb_setup->parameter;
1491 
1492     xfer->in_xfer = bmRequestType & USB_DIR_IN;
1493     xfer->iso_xfer = false;
1494 
1495     if (xhci_setup_packet(xfer) < 0) {
1496         return -1;
1497     }
1498     xfer->packet.parameter = trb_setup->parameter;
1499 
1500     ret = usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
1501 
1502     xhci_complete_packet(xfer, ret);
1503     if (!xfer->running_async && !xfer->running_retry) {
1504         xhci_kick_ep(xhci, xfer->slotid, xfer->epid);
1505     }
1506     return 0;
1507 }
1508 
1509 static void xhci_calc_iso_kick(XHCIState *xhci, XHCITransfer *xfer,
1510                                XHCIEPContext *epctx, uint64_t mfindex)
1511 {
1512     if (xfer->trbs[0].control & TRB_TR_SIA) {
1513         uint64_t asap = ((mfindex + epctx->interval - 1) &
1514                          ~(epctx->interval-1));
1515         if (asap >= epctx->mfindex_last &&
1516             asap <= epctx->mfindex_last + epctx->interval * 4) {
1517             xfer->mfindex_kick = epctx->mfindex_last + epctx->interval;
1518         } else {
1519             xfer->mfindex_kick = asap;
1520         }
1521     } else {
1522         xfer->mfindex_kick = (xfer->trbs[0].control >> TRB_TR_FRAMEID_SHIFT)
1523             & TRB_TR_FRAMEID_MASK;
1524         xfer->mfindex_kick |= mfindex & ~0x3fff;
1525         if (xfer->mfindex_kick < mfindex) {
1526             xfer->mfindex_kick += 0x4000;
1527         }
1528     }
1529 }
1530 
1531 static void xhci_check_iso_kick(XHCIState *xhci, XHCITransfer *xfer,
1532                                 XHCIEPContext *epctx, uint64_t mfindex)
1533 {
1534     if (xfer->mfindex_kick > mfindex) {
1535         qemu_mod_timer(epctx->kick_timer, qemu_get_clock_ns(vm_clock) +
1536                        (xfer->mfindex_kick - mfindex) * 125000);
1537         xfer->running_retry = 1;
1538     } else {
1539         epctx->mfindex_last = xfer->mfindex_kick;
1540         qemu_del_timer(epctx->kick_timer);
1541         xfer->running_retry = 0;
1542     }
1543 }
1544 
1545 
1546 static int xhci_submit(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)
1547 {
1548     uint64_t mfindex;
1549     int ret;
1550 
1551     DPRINTF("xhci_submit(slotid=%d,epid=%d)\n", xfer->slotid, xfer->epid);
1552 
1553     xfer->in_xfer = epctx->type>>2;
1554 
1555     switch(epctx->type) {
1556     case ET_INTR_OUT:
1557     case ET_INTR_IN:
1558     case ET_BULK_OUT:
1559     case ET_BULK_IN:
1560         xfer->pkts = 0;
1561         xfer->iso_xfer = false;
1562         break;
1563     case ET_ISO_OUT:
1564     case ET_ISO_IN:
1565         xfer->pkts = 1;
1566         xfer->iso_xfer = true;
1567         mfindex = xhci_mfindex_get(xhci);
1568         xhci_calc_iso_kick(xhci, xfer, epctx, mfindex);
1569         xhci_check_iso_kick(xhci, xfer, epctx, mfindex);
1570         if (xfer->running_retry) {
1571             return -1;
1572         }
1573         break;
1574     default:
1575         fprintf(stderr, "xhci: unknown or unhandled EP "
1576                 "(type %d, in %d, ep %02x)\n",
1577                 epctx->type, xfer->in_xfer, xfer->epid);
1578         return -1;
1579     }
1580 
1581     if (xhci_setup_packet(xfer) < 0) {
1582         return -1;
1583     }
1584     ret = usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
1585 
1586     xhci_complete_packet(xfer, ret);
1587     if (!xfer->running_async && !xfer->running_retry) {
1588         xhci_kick_ep(xhci, xfer->slotid, xfer->epid);
1589     }
1590     return 0;
1591 }
1592 
1593 static int xhci_fire_transfer(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)
1594 {
1595     trace_usb_xhci_xfer_start(xfer, xfer->slotid, xfer->epid);
1596     return xhci_submit(xhci, xfer, epctx);
1597 }
1598 
1599 static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid, unsigned int epid)
1600 {
1601     XHCIEPContext *epctx;
1602     uint64_t mfindex;
1603     int length;
1604     int i;
1605 
1606     trace_usb_xhci_ep_kick(slotid, epid);
1607     assert(slotid >= 1 && slotid <= MAXSLOTS);
1608     assert(epid >= 1 && epid <= 31);
1609 
1610     if (!xhci->slots[slotid-1].enabled) {
1611         fprintf(stderr, "xhci: xhci_kick_ep for disabled slot %d\n", slotid);
1612         return;
1613     }
1614     epctx = xhci->slots[slotid-1].eps[epid-1];
1615     if (!epctx) {
1616         fprintf(stderr, "xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
1617                 epid, slotid);
1618         return;
1619     }
1620 
1621     if (epctx->retry) {
1622         XHCITransfer *xfer = epctx->retry;
1623         int result;
1624 
1625         trace_usb_xhci_xfer_retry(xfer);
1626         assert(xfer->running_retry);
1627         if (xfer->iso_xfer) {
1628             /* retry delayed iso transfer */
1629             mfindex = xhci_mfindex_get(xhci);
1630             xhci_check_iso_kick(xhci, xfer, epctx, mfindex);
1631             if (xfer->running_retry) {
1632                 return;
1633             }
1634             if (xhci_setup_packet(xfer) < 0) {
1635                 return;
1636             }
1637             result = usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
1638             assert(result != USB_RET_NAK);
1639             xhci_complete_packet(xfer, result);
1640         } else {
1641             /* retry nak'ed transfer */
1642             if (xhci_setup_packet(xfer) < 0) {
1643                 return;
1644             }
1645             result = usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
1646             if (result == USB_RET_NAK) {
1647                 return;
1648             }
1649             xhci_complete_packet(xfer, result);
1650         }
1651         assert(!xfer->running_retry);
1652         epctx->retry = NULL;
1653     }
1654 
1655     if (epctx->state == EP_HALTED) {
1656         DPRINTF("xhci: ep halted, not running schedule\n");
1657         return;
1658     }
1659 
1660     xhci_set_ep_state(xhci, epctx, EP_RUNNING);
1661 
1662     while (1) {
1663         XHCITransfer *xfer = &epctx->transfers[epctx->next_xfer];
1664         if (xfer->running_async || xfer->running_retry) {
1665             break;
1666         }
1667         length = xhci_ring_chain_length(xhci, &epctx->ring);
1668         if (length < 0) {
1669             break;
1670         } else if (length == 0) {
1671             break;
1672         }
1673         if (xfer->trbs && xfer->trb_alloced < length) {
1674             xfer->trb_count = 0;
1675             xfer->trb_alloced = 0;
1676             g_free(xfer->trbs);
1677             xfer->trbs = NULL;
1678         }
1679         if (!xfer->trbs) {
1680             xfer->trbs = g_malloc(sizeof(XHCITRB) * length);
1681             xfer->trb_alloced = length;
1682         }
1683         xfer->trb_count = length;
1684 
1685         for (i = 0; i < length; i++) {
1686             assert(xhci_ring_fetch(xhci, &epctx->ring, &xfer->trbs[i], NULL));
1687         }
1688         xfer->xhci = xhci;
1689         xfer->epid = epid;
1690         xfer->slotid = slotid;
1691 
1692         if (epid == 1) {
1693             if (xhci_fire_ctl_transfer(xhci, xfer) >= 0) {
1694                 epctx->next_xfer = (epctx->next_xfer + 1) % TD_QUEUE;
1695             } else {
1696                 fprintf(stderr, "xhci: error firing CTL transfer\n");
1697             }
1698         } else {
1699             if (xhci_fire_transfer(xhci, xfer, epctx) >= 0) {
1700                 epctx->next_xfer = (epctx->next_xfer + 1) % TD_QUEUE;
1701             } else {
1702                 if (!xfer->iso_xfer) {
1703                     fprintf(stderr, "xhci: error firing data transfer\n");
1704                 }
1705             }
1706         }
1707 
1708         if (epctx->state == EP_HALTED) {
1709             break;
1710         }
1711         if (xfer->running_retry) {
1712             DPRINTF("xhci: xfer nacked, stopping schedule\n");
1713             epctx->retry = xfer;
1714             break;
1715         }
1716     }
1717 }
1718 
1719 static TRBCCode xhci_enable_slot(XHCIState *xhci, unsigned int slotid)
1720 {
1721     trace_usb_xhci_slot_enable(slotid);
1722     assert(slotid >= 1 && slotid <= MAXSLOTS);
1723     xhci->slots[slotid-1].enabled = 1;
1724     xhci->slots[slotid-1].port = 0;
1725     memset(xhci->slots[slotid-1].eps, 0, sizeof(XHCIEPContext*)*31);
1726 
1727     return CC_SUCCESS;
1728 }
1729 
1730 static TRBCCode xhci_disable_slot(XHCIState *xhci, unsigned int slotid)
1731 {
1732     int i;
1733 
1734     trace_usb_xhci_slot_disable(slotid);
1735     assert(slotid >= 1 && slotid <= MAXSLOTS);
1736 
1737     for (i = 1; i <= 31; i++) {
1738         if (xhci->slots[slotid-1].eps[i-1]) {
1739             xhci_disable_ep(xhci, slotid, i);
1740         }
1741     }
1742 
1743     xhci->slots[slotid-1].enabled = 0;
1744     return CC_SUCCESS;
1745 }
1746 
1747 static TRBCCode xhci_address_slot(XHCIState *xhci, unsigned int slotid,
1748                                   uint64_t pictx, bool bsr)
1749 {
1750     XHCISlot *slot;
1751     USBDevice *dev;
1752     dma_addr_t ictx, octx, dcbaap;
1753     uint64_t poctx;
1754     uint32_t ictl_ctx[2];
1755     uint32_t slot_ctx[4];
1756     uint32_t ep0_ctx[5];
1757     unsigned int port;
1758     int i;
1759     TRBCCode res;
1760 
1761     trace_usb_xhci_slot_address(slotid);
1762     assert(slotid >= 1 && slotid <= MAXSLOTS);
1763 
1764     dcbaap = xhci_addr64(xhci->dcbaap_low, xhci->dcbaap_high);
1765     pci_dma_read(&xhci->pci_dev, dcbaap + 8*slotid, &poctx, sizeof(poctx));
1766     ictx = xhci_mask64(pictx);
1767     octx = xhci_mask64(le64_to_cpu(poctx));
1768 
1769     DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
1770     DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
1771 
1772     pci_dma_read(&xhci->pci_dev, ictx, ictl_ctx, sizeof(ictl_ctx));
1773 
1774     if (ictl_ctx[0] != 0x0 || ictl_ctx[1] != 0x3) {
1775         fprintf(stderr, "xhci: invalid input context control %08x %08x\n",
1776                 ictl_ctx[0], ictl_ctx[1]);
1777         return CC_TRB_ERROR;
1778     }
1779 
1780     pci_dma_read(&xhci->pci_dev, ictx+32, slot_ctx, sizeof(slot_ctx));
1781     pci_dma_read(&xhci->pci_dev, ictx+64, ep0_ctx, sizeof(ep0_ctx));
1782 
1783     DPRINTF("xhci: input slot context: %08x %08x %08x %08x\n",
1784             slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
1785 
1786     DPRINTF("xhci: input ep0 context: %08x %08x %08x %08x %08x\n",
1787             ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);
1788 
1789     port = (slot_ctx[1]>>16) & 0xFF;
1790     dev = xhci->ports[port-1].uport->dev;
1791 
1792     if (port < 1 || port > xhci->numports) {
1793         fprintf(stderr, "xhci: bad port %d\n", port);
1794         return CC_TRB_ERROR;
1795     } else if (!dev) {
1796         fprintf(stderr, "xhci: port %d not connected\n", port);
1797         return CC_USB_TRANSACTION_ERROR;
1798     }
1799 
1800     for (i = 0; i < MAXSLOTS; i++) {
1801         if (xhci->slots[i].port == port) {
1802             fprintf(stderr, "xhci: port %d already assigned to slot %d\n",
1803                     port, i+1);
1804             return CC_TRB_ERROR;
1805         }
1806     }
1807 
1808     slot = &xhci->slots[slotid-1];
1809     slot->port = port;
1810     slot->ctx = octx;
1811 
1812     if (bsr) {
1813         slot_ctx[3] = SLOT_DEFAULT << SLOT_STATE_SHIFT;
1814     } else {
1815         slot->devaddr = xhci->devaddr++;
1816         slot_ctx[3] = (SLOT_ADDRESSED << SLOT_STATE_SHIFT) | slot->devaddr;
1817         DPRINTF("xhci: device address is %d\n", slot->devaddr);
1818         usb_device_handle_control(dev, NULL,
1819                                   DeviceOutRequest | USB_REQ_SET_ADDRESS,
1820                                   slot->devaddr, 0, 0, NULL);
1821     }
1822 
1823     res = xhci_enable_ep(xhci, slotid, 1, octx+32, ep0_ctx);
1824 
1825     DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
1826             slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
1827     DPRINTF("xhci: output ep0 context: %08x %08x %08x %08x %08x\n",
1828             ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);
1829 
1830     pci_dma_write(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
1831     pci_dma_write(&xhci->pci_dev, octx+32, ep0_ctx, sizeof(ep0_ctx));
1832 
1833     return res;
1834 }
1835 
1836 
1837 static TRBCCode xhci_configure_slot(XHCIState *xhci, unsigned int slotid,
1838                                   uint64_t pictx, bool dc)
1839 {
1840     dma_addr_t ictx, octx;
1841     uint32_t ictl_ctx[2];
1842     uint32_t slot_ctx[4];
1843     uint32_t islot_ctx[4];
1844     uint32_t ep_ctx[5];
1845     int i;
1846     TRBCCode res;
1847 
1848     trace_usb_xhci_slot_configure(slotid);
1849     assert(slotid >= 1 && slotid <= MAXSLOTS);
1850 
1851     ictx = xhci_mask64(pictx);
1852     octx = xhci->slots[slotid-1].ctx;
1853 
1854     DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
1855     DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
1856 
1857     if (dc) {
1858         for (i = 2; i <= 31; i++) {
1859             if (xhci->slots[slotid-1].eps[i-1]) {
1860                 xhci_disable_ep(xhci, slotid, i);
1861             }
1862         }
1863 
1864         pci_dma_read(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
1865         slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
1866         slot_ctx[3] |= SLOT_ADDRESSED << SLOT_STATE_SHIFT;
1867         DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
1868                 slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
1869         pci_dma_write(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
1870 
1871         return CC_SUCCESS;
1872     }
1873 
1874     pci_dma_read(&xhci->pci_dev, ictx, ictl_ctx, sizeof(ictl_ctx));
1875 
1876     if ((ictl_ctx[0] & 0x3) != 0x0 || (ictl_ctx[1] & 0x3) != 0x1) {
1877         fprintf(stderr, "xhci: invalid input context control %08x %08x\n",
1878                 ictl_ctx[0], ictl_ctx[1]);
1879         return CC_TRB_ERROR;
1880     }
1881 
1882     pci_dma_read(&xhci->pci_dev, ictx+32, islot_ctx, sizeof(islot_ctx));
1883     pci_dma_read(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
1884 
1885     if (SLOT_STATE(slot_ctx[3]) < SLOT_ADDRESSED) {
1886         fprintf(stderr, "xhci: invalid slot state %08x\n", slot_ctx[3]);
1887         return CC_CONTEXT_STATE_ERROR;
1888     }
1889 
1890     for (i = 2; i <= 31; i++) {
1891         if (ictl_ctx[0] & (1<<i)) {
1892             xhci_disable_ep(xhci, slotid, i);
1893         }
1894         if (ictl_ctx[1] & (1<<i)) {
1895             pci_dma_read(&xhci->pci_dev, ictx+32+(32*i), ep_ctx,
1896                          sizeof(ep_ctx));
1897             DPRINTF("xhci: input ep%d.%d context: %08x %08x %08x %08x %08x\n",
1898                     i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2],
1899                     ep_ctx[3], ep_ctx[4]);
1900             xhci_disable_ep(xhci, slotid, i);
1901             res = xhci_enable_ep(xhci, slotid, i, octx+(32*i), ep_ctx);
1902             if (res != CC_SUCCESS) {
1903                 return res;
1904             }
1905             DPRINTF("xhci: output ep%d.%d context: %08x %08x %08x %08x %08x\n",
1906                     i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2],
1907                     ep_ctx[3], ep_ctx[4]);
1908             pci_dma_write(&xhci->pci_dev, octx+(32*i), ep_ctx, sizeof(ep_ctx));
1909         }
1910     }
1911 
1912     slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
1913     slot_ctx[3] |= SLOT_CONFIGURED << SLOT_STATE_SHIFT;
1914     slot_ctx[0] &= ~(SLOT_CONTEXT_ENTRIES_MASK << SLOT_CONTEXT_ENTRIES_SHIFT);
1915     slot_ctx[0] |= islot_ctx[0] & (SLOT_CONTEXT_ENTRIES_MASK <<
1916                                    SLOT_CONTEXT_ENTRIES_SHIFT);
1917     DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
1918             slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
1919 
1920     pci_dma_write(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
1921 
1922     return CC_SUCCESS;
1923 }
1924 
1925 
1926 static TRBCCode xhci_evaluate_slot(XHCIState *xhci, unsigned int slotid,
1927                                    uint64_t pictx)
1928 {
1929     dma_addr_t ictx, octx;
1930     uint32_t ictl_ctx[2];
1931     uint32_t iep0_ctx[5];
1932     uint32_t ep0_ctx[5];
1933     uint32_t islot_ctx[4];
1934     uint32_t slot_ctx[4];
1935 
1936     trace_usb_xhci_slot_evaluate(slotid);
1937     assert(slotid >= 1 && slotid <= MAXSLOTS);
1938 
1939     ictx = xhci_mask64(pictx);
1940     octx = xhci->slots[slotid-1].ctx;
1941 
1942     DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
1943     DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
1944 
1945     pci_dma_read(&xhci->pci_dev, ictx, ictl_ctx, sizeof(ictl_ctx));
1946 
1947     if (ictl_ctx[0] != 0x0 || ictl_ctx[1] & ~0x3) {
1948         fprintf(stderr, "xhci: invalid input context control %08x %08x\n",
1949                 ictl_ctx[0], ictl_ctx[1]);
1950         return CC_TRB_ERROR;
1951     }
1952 
1953     if (ictl_ctx[1] & 0x1) {
1954         pci_dma_read(&xhci->pci_dev, ictx+32, islot_ctx, sizeof(islot_ctx));
1955 
1956         DPRINTF("xhci: input slot context: %08x %08x %08x %08x\n",
1957                 islot_ctx[0], islot_ctx[1], islot_ctx[2], islot_ctx[3]);
1958 
1959         pci_dma_read(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
1960 
1961         slot_ctx[1] &= ~0xFFFF; /* max exit latency */
1962         slot_ctx[1] |= islot_ctx[1] & 0xFFFF;
1963         slot_ctx[2] &= ~0xFF00000; /* interrupter target */
1964         slot_ctx[2] |= islot_ctx[2] & 0xFF000000;
1965 
1966         DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
1967                 slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
1968 
1969         pci_dma_write(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
1970     }
1971 
1972     if (ictl_ctx[1] & 0x2) {
1973         pci_dma_read(&xhci->pci_dev, ictx+64, iep0_ctx, sizeof(iep0_ctx));
1974 
1975         DPRINTF("xhci: input ep0 context: %08x %08x %08x %08x %08x\n",
1976                 iep0_ctx[0], iep0_ctx[1], iep0_ctx[2],
1977                 iep0_ctx[3], iep0_ctx[4]);
1978 
1979         pci_dma_read(&xhci->pci_dev, octx+32, ep0_ctx, sizeof(ep0_ctx));
1980 
1981         ep0_ctx[1] &= ~0xFFFF0000; /* max packet size*/
1982         ep0_ctx[1] |= iep0_ctx[1] & 0xFFFF0000;
1983 
1984         DPRINTF("xhci: output ep0 context: %08x %08x %08x %08x %08x\n",
1985                 ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);
1986 
1987         pci_dma_write(&xhci->pci_dev, octx+32, ep0_ctx, sizeof(ep0_ctx));
1988     }
1989 
1990     return CC_SUCCESS;
1991 }
1992 
1993 static TRBCCode xhci_reset_slot(XHCIState *xhci, unsigned int slotid)
1994 {
1995     uint32_t slot_ctx[4];
1996     dma_addr_t octx;
1997     int i;
1998 
1999     trace_usb_xhci_slot_reset(slotid);
2000     assert(slotid >= 1 && slotid <= MAXSLOTS);
2001 
2002     octx = xhci->slots[slotid-1].ctx;
2003 
2004     DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
2005 
2006     for (i = 2; i <= 31; i++) {
2007         if (xhci->slots[slotid-1].eps[i-1]) {
2008             xhci_disable_ep(xhci, slotid, i);
2009         }
2010     }
2011 
2012     pci_dma_read(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
2013     slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
2014     slot_ctx[3] |= SLOT_DEFAULT << SLOT_STATE_SHIFT;
2015     DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
2016             slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
2017     pci_dma_write(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
2018 
2019     return CC_SUCCESS;
2020 }
2021 
2022 static unsigned int xhci_get_slot(XHCIState *xhci, XHCIEvent *event, XHCITRB *trb)
2023 {
2024     unsigned int slotid;
2025     slotid = (trb->control >> TRB_CR_SLOTID_SHIFT) & TRB_CR_SLOTID_MASK;
2026     if (slotid < 1 || slotid > MAXSLOTS) {
2027         fprintf(stderr, "xhci: bad slot id %d\n", slotid);
2028         event->ccode = CC_TRB_ERROR;
2029         return 0;
2030     } else if (!xhci->slots[slotid-1].enabled) {
2031         fprintf(stderr, "xhci: slot id %d not enabled\n", slotid);
2032         event->ccode = CC_SLOT_NOT_ENABLED_ERROR;
2033         return 0;
2034     }
2035     return slotid;
2036 }
2037 
2038 static TRBCCode xhci_get_port_bandwidth(XHCIState *xhci, uint64_t pctx)
2039 {
2040     dma_addr_t ctx;
2041     uint8_t bw_ctx[xhci->numports+1];
2042 
2043     DPRINTF("xhci_get_port_bandwidth()\n");
2044 
2045     ctx = xhci_mask64(pctx);
2046 
2047     DPRINTF("xhci: bandwidth context at "DMA_ADDR_FMT"\n", ctx);
2048 
2049     /* TODO: actually implement real values here */
2050     bw_ctx[0] = 0;
2051     memset(&bw_ctx[1], 80, xhci->numports); /* 80% */
2052     pci_dma_write(&xhci->pci_dev, ctx, bw_ctx, sizeof(bw_ctx));
2053 
2054     return CC_SUCCESS;
2055 }
2056 
2057 static uint32_t rotl(uint32_t v, unsigned count)
2058 {
2059     count &= 31;
2060     return (v << count) | (v >> (32 - count));
2061 }
2062 
2063 
2064 static uint32_t xhci_nec_challenge(uint32_t hi, uint32_t lo)
2065 {
2066     uint32_t val;
2067     val = rotl(lo - 0x49434878, 32 - ((hi>>8) & 0x1F));
2068     val += rotl(lo + 0x49434878, hi & 0x1F);
2069     val -= rotl(hi ^ 0x49434878, (lo >> 16) & 0x1F);
2070     return ~val;
2071 }
2072 
2073 static void xhci_via_challenge(XHCIState *xhci, uint64_t addr)
2074 {
2075     uint32_t buf[8];
2076     uint32_t obuf[8];
2077     dma_addr_t paddr = xhci_mask64(addr);
2078 
2079     pci_dma_read(&xhci->pci_dev, paddr, &buf, 32);
2080 
2081     memcpy(obuf, buf, sizeof(obuf));
2082 
2083     if ((buf[0] & 0xff) == 2) {
2084         obuf[0] = 0x49932000 + 0x54dc200 * buf[2] + 0x7429b578 * buf[3];
2085         obuf[0] |=  (buf[2] * buf[3]) & 0xff;
2086         obuf[1] = 0x0132bb37 + 0xe89 * buf[2] + 0xf09 * buf[3];
2087         obuf[2] = 0x0066c2e9 + 0x2091 * buf[2] + 0x19bd * buf[3];
2088         obuf[3] = 0xd5281342 + 0x2cc9691 * buf[2] + 0x2367662 * buf[3];
2089         obuf[4] = 0x0123c75c + 0x1595 * buf[2] + 0x19ec * buf[3];
2090         obuf[5] = 0x00f695de + 0x26fd * buf[2] + 0x3e9 * buf[3];
2091         obuf[6] = obuf[2] ^ obuf[3] ^ 0x29472956;
2092         obuf[7] = obuf[2] ^ obuf[3] ^ 0x65866593;
2093     }
2094 
2095     pci_dma_write(&xhci->pci_dev, paddr, &obuf, 32);
2096 }
2097 
2098 static void xhci_process_commands(XHCIState *xhci)
2099 {
2100     XHCITRB trb;
2101     TRBType type;
2102     XHCIEvent event = {ER_COMMAND_COMPLETE, CC_SUCCESS};
2103     dma_addr_t addr;
2104     unsigned int i, slotid = 0;
2105 
2106     DPRINTF("xhci_process_commands()\n");
2107     if (!xhci_running(xhci)) {
2108         DPRINTF("xhci_process_commands() called while xHC stopped or paused\n");
2109         return;
2110     }
2111 
2112     xhci->crcr_low |= CRCR_CRR;
2113 
2114     while ((type = xhci_ring_fetch(xhci, &xhci->cmd_ring, &trb, &addr))) {
2115         event.ptr = addr;
2116         switch (type) {
2117         case CR_ENABLE_SLOT:
2118             for (i = 0; i < MAXSLOTS; i++) {
2119                 if (!xhci->slots[i].enabled) {
2120                     break;
2121                 }
2122             }
2123             if (i >= MAXSLOTS) {
2124                 fprintf(stderr, "xhci: no device slots available\n");
2125                 event.ccode = CC_NO_SLOTS_ERROR;
2126             } else {
2127                 slotid = i+1;
2128                 event.ccode = xhci_enable_slot(xhci, slotid);
2129             }
2130             break;
2131         case CR_DISABLE_SLOT:
2132             slotid = xhci_get_slot(xhci, &event, &trb);
2133             if (slotid) {
2134                 event.ccode = xhci_disable_slot(xhci, slotid);
2135             }
2136             break;
2137         case CR_ADDRESS_DEVICE:
2138             slotid = xhci_get_slot(xhci, &event, &trb);
2139             if (slotid) {
2140                 event.ccode = xhci_address_slot(xhci, slotid, trb.parameter,
2141                                                 trb.control & TRB_CR_BSR);
2142             }
2143             break;
2144         case CR_CONFIGURE_ENDPOINT:
2145             slotid = xhci_get_slot(xhci, &event, &trb);
2146             if (slotid) {
2147                 event.ccode = xhci_configure_slot(xhci, slotid, trb.parameter,
2148                                                   trb.control & TRB_CR_DC);
2149             }
2150             break;
2151         case CR_EVALUATE_CONTEXT:
2152             slotid = xhci_get_slot(xhci, &event, &trb);
2153             if (slotid) {
2154                 event.ccode = xhci_evaluate_slot(xhci, slotid, trb.parameter);
2155             }
2156             break;
2157         case CR_STOP_ENDPOINT:
2158             slotid = xhci_get_slot(xhci, &event, &trb);
2159             if (slotid) {
2160                 unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2161                     & TRB_CR_EPID_MASK;
2162                 event.ccode = xhci_stop_ep(xhci, slotid, epid);
2163             }
2164             break;
2165         case CR_RESET_ENDPOINT:
2166             slotid = xhci_get_slot(xhci, &event, &trb);
2167             if (slotid) {
2168                 unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2169                     & TRB_CR_EPID_MASK;
2170                 event.ccode = xhci_reset_ep(xhci, slotid, epid);
2171             }
2172             break;
2173         case CR_SET_TR_DEQUEUE:
2174             slotid = xhci_get_slot(xhci, &event, &trb);
2175             if (slotid) {
2176                 unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2177                     & TRB_CR_EPID_MASK;
2178                 event.ccode = xhci_set_ep_dequeue(xhci, slotid, epid,
2179                                                   trb.parameter);
2180             }
2181             break;
2182         case CR_RESET_DEVICE:
2183             slotid = xhci_get_slot(xhci, &event, &trb);
2184             if (slotid) {
2185                 event.ccode = xhci_reset_slot(xhci, slotid);
2186             }
2187             break;
2188         case CR_GET_PORT_BANDWIDTH:
2189             event.ccode = xhci_get_port_bandwidth(xhci, trb.parameter);
2190             break;
2191         case CR_VENDOR_VIA_CHALLENGE_RESPONSE:
2192             xhci_via_challenge(xhci, trb.parameter);
2193             break;
2194         case CR_VENDOR_NEC_FIRMWARE_REVISION:
2195             event.type = 48; /* NEC reply */
2196             event.length = 0x3025;
2197             break;
2198         case CR_VENDOR_NEC_CHALLENGE_RESPONSE:
2199         {
2200             uint32_t chi = trb.parameter >> 32;
2201             uint32_t clo = trb.parameter;
2202             uint32_t val = xhci_nec_challenge(chi, clo);
2203             event.length = val & 0xFFFF;
2204             event.epid = val >> 16;
2205             slotid = val >> 24;
2206             event.type = 48; /* NEC reply */
2207         }
2208         break;
2209         default:
2210             fprintf(stderr, "xhci: unimplemented command %d\n", type);
2211             event.ccode = CC_TRB_ERROR;
2212             break;
2213         }
2214         event.slotid = slotid;
2215         xhci_event(xhci, &event);
2216     }
2217 }
2218 
2219 static void xhci_update_port(XHCIState *xhci, XHCIPort *port, int is_detach)
2220 {
2221     port->portsc = PORTSC_PP;
2222     if (port->uport->dev && port->uport->dev->attached && !is_detach &&
2223         (1 << port->uport->dev->speed) & port->speedmask) {
2224         port->portsc |= PORTSC_CCS;
2225         switch (port->uport->dev->speed) {
2226         case USB_SPEED_LOW:
2227             port->portsc |= PORTSC_SPEED_LOW;
2228             break;
2229         case USB_SPEED_FULL:
2230             port->portsc |= PORTSC_SPEED_FULL;
2231             break;
2232         case USB_SPEED_HIGH:
2233             port->portsc |= PORTSC_SPEED_HIGH;
2234             break;
2235         case USB_SPEED_SUPER:
2236             port->portsc |= PORTSC_SPEED_SUPER;
2237             break;
2238         }
2239     }
2240 
2241     if (xhci_running(xhci)) {
2242         port->portsc |= PORTSC_CSC;
2243         XHCIEvent ev = { ER_PORT_STATUS_CHANGE, CC_SUCCESS,
2244                          port->portnr << 24};
2245         xhci_event(xhci, &ev);
2246         DPRINTF("xhci: port change event for port %d\n", port->portnr);
2247     }
2248 }
2249 
2250 static void xhci_reset(DeviceState *dev)
2251 {
2252     XHCIState *xhci = DO_UPCAST(XHCIState, pci_dev.qdev, dev);
2253     int i;
2254 
2255     trace_usb_xhci_reset();
2256     if (!(xhci->usbsts & USBSTS_HCH)) {
2257         fprintf(stderr, "xhci: reset while running!\n");
2258     }
2259 
2260     xhci->usbcmd = 0;
2261     xhci->usbsts = USBSTS_HCH;
2262     xhci->dnctrl = 0;
2263     xhci->crcr_low = 0;
2264     xhci->crcr_high = 0;
2265     xhci->dcbaap_low = 0;
2266     xhci->dcbaap_high = 0;
2267     xhci->config = 0;
2268     xhci->devaddr = 2;
2269 
2270     for (i = 0; i < MAXSLOTS; i++) {
2271         xhci_disable_slot(xhci, i+1);
2272     }
2273 
2274     for (i = 0; i < xhci->numports; i++) {
2275         xhci_update_port(xhci, xhci->ports + i, 0);
2276     }
2277 
2278     xhci->iman = 0;
2279     xhci->imod = 0;
2280     xhci->erstsz = 0;
2281     xhci->erstba_low = 0;
2282     xhci->erstba_high = 0;
2283     xhci->erdp_low = 0;
2284     xhci->erdp_high = 0;
2285 
2286     xhci->er_ep_idx = 0;
2287     xhci->er_pcs = 1;
2288     xhci->er_full = 0;
2289     xhci->ev_buffer_put = 0;
2290     xhci->ev_buffer_get = 0;
2291 
2292     xhci->mfindex_start = qemu_get_clock_ns(vm_clock);
2293     xhci_mfwrap_update(xhci);
2294 }
2295 
2296 static uint32_t xhci_cap_read(XHCIState *xhci, uint32_t reg)
2297 {
2298     uint32_t ret;
2299 
2300     switch (reg) {
2301     case 0x00: /* HCIVERSION, CAPLENGTH */
2302         ret = 0x01000000 | LEN_CAP;
2303         break;
2304     case 0x04: /* HCSPARAMS 1 */
2305         ret = ((xhci->numports_2+xhci->numports_3)<<24)
2306             | (MAXINTRS<<8) | MAXSLOTS;
2307         break;
2308     case 0x08: /* HCSPARAMS 2 */
2309         ret = 0x0000000f;
2310         break;
2311     case 0x0c: /* HCSPARAMS 3 */
2312         ret = 0x00000000;
2313         break;
2314     case 0x10: /* HCCPARAMS */
2315         if (sizeof(dma_addr_t) == 4) {
2316             ret = 0x00081000;
2317         } else {
2318             ret = 0x00081001;
2319         }
2320         break;
2321     case 0x14: /* DBOFF */
2322         ret = OFF_DOORBELL;
2323         break;
2324     case 0x18: /* RTSOFF */
2325         ret = OFF_RUNTIME;
2326         break;
2327 
2328     /* extended capabilities */
2329     case 0x20: /* Supported Protocol:00 */
2330         ret = 0x02000402; /* USB 2.0 */
2331         break;
2332     case 0x24: /* Supported Protocol:04 */
2333         ret = 0x20425455; /* "USB " */
2334         break;
2335     case 0x28: /* Supported Protocol:08 */
2336         ret = 0x00000001 | (xhci->numports_2<<8);
2337         break;
2338     case 0x2c: /* Supported Protocol:0c */
2339         ret = 0x00000000; /* reserved */
2340         break;
2341     case 0x30: /* Supported Protocol:00 */
2342         ret = 0x03000002; /* USB 3.0 */
2343         break;
2344     case 0x34: /* Supported Protocol:04 */
2345         ret = 0x20425455; /* "USB " */
2346         break;
2347     case 0x38: /* Supported Protocol:08 */
2348         ret = 0x00000000 | (xhci->numports_2+1) | (xhci->numports_3<<8);
2349         break;
2350     case 0x3c: /* Supported Protocol:0c */
2351         ret = 0x00000000; /* reserved */
2352         break;
2353     default:
2354         fprintf(stderr, "xhci_cap_read: reg %d unimplemented\n", reg);
2355         ret = 0;
2356     }
2357 
2358     trace_usb_xhci_cap_read(reg, ret);
2359     return ret;
2360 }
2361 
2362 static uint32_t xhci_port_read(XHCIState *xhci, uint32_t reg)
2363 {
2364     uint32_t port = reg >> 4;
2365     uint32_t ret;
2366 
2367     if (port >= xhci->numports) {
2368         fprintf(stderr, "xhci_port_read: port %d out of bounds\n", port);
2369         ret = 0;
2370         goto out;
2371     }
2372 
2373     switch (reg & 0xf) {
2374     case 0x00: /* PORTSC */
2375         ret = xhci->ports[port].portsc;
2376         break;
2377     case 0x04: /* PORTPMSC */
2378     case 0x08: /* PORTLI */
2379         ret = 0;
2380         break;
2381     case 0x0c: /* reserved */
2382     default:
2383         fprintf(stderr, "xhci_port_read (port %d): reg 0x%x unimplemented\n",
2384                 port, reg);
2385         ret = 0;
2386     }
2387 
2388 out:
2389     trace_usb_xhci_port_read(port, reg & 0x0f, ret);
2390     return ret;
2391 }
2392 
2393 static void xhci_port_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2394 {
2395     uint32_t port = reg >> 4;
2396     uint32_t portsc;
2397 
2398     trace_usb_xhci_port_write(port, reg & 0x0f, val);
2399 
2400     if (port >= xhci->numports) {
2401         fprintf(stderr, "xhci_port_read: port %d out of bounds\n", port);
2402         return;
2403     }
2404 
2405     switch (reg & 0xf) {
2406     case 0x00: /* PORTSC */
2407         portsc = xhci->ports[port].portsc;
2408         /* write-1-to-clear bits*/
2409         portsc &= ~(val & (PORTSC_CSC|PORTSC_PEC|PORTSC_WRC|PORTSC_OCC|
2410                            PORTSC_PRC|PORTSC_PLC|PORTSC_CEC));
2411         if (val & PORTSC_LWS) {
2412             /* overwrite PLS only when LWS=1 */
2413             portsc &= ~(PORTSC_PLS_MASK << PORTSC_PLS_SHIFT);
2414             portsc |= val & (PORTSC_PLS_MASK << PORTSC_PLS_SHIFT);
2415         }
2416         /* read/write bits */
2417         portsc &= ~(PORTSC_PP|PORTSC_WCE|PORTSC_WDE|PORTSC_WOE);
2418         portsc |= (val & (PORTSC_PP|PORTSC_WCE|PORTSC_WDE|PORTSC_WOE));
2419         /* write-1-to-start bits */
2420         if (val & PORTSC_PR) {
2421             DPRINTF("xhci: port %d reset\n", port);
2422             usb_device_reset(xhci->ports[port].uport->dev);
2423             portsc |= PORTSC_PRC | PORTSC_PED;
2424         }
2425         xhci->ports[port].portsc = portsc;
2426         break;
2427     case 0x04: /* PORTPMSC */
2428     case 0x08: /* PORTLI */
2429     default:
2430         fprintf(stderr, "xhci_port_write (port %d): reg 0x%x unimplemented\n",
2431                 port, reg);
2432     }
2433 }
2434 
2435 static uint32_t xhci_oper_read(XHCIState *xhci, uint32_t reg)
2436 {
2437     uint32_t ret;
2438 
2439     if (reg >= 0x400) {
2440         return xhci_port_read(xhci, reg - 0x400);
2441     }
2442 
2443     switch (reg) {
2444     case 0x00: /* USBCMD */
2445         ret = xhci->usbcmd;
2446         break;
2447     case 0x04: /* USBSTS */
2448         ret = xhci->usbsts;
2449         break;
2450     case 0x08: /* PAGESIZE */
2451         ret = 1; /* 4KiB */
2452         break;
2453     case 0x14: /* DNCTRL */
2454         ret = xhci->dnctrl;
2455         break;
2456     case 0x18: /* CRCR low */
2457         ret = xhci->crcr_low & ~0xe;
2458         break;
2459     case 0x1c: /* CRCR high */
2460         ret = xhci->crcr_high;
2461         break;
2462     case 0x30: /* DCBAAP low */
2463         ret = xhci->dcbaap_low;
2464         break;
2465     case 0x34: /* DCBAAP high */
2466         ret = xhci->dcbaap_high;
2467         break;
2468     case 0x38: /* CONFIG */
2469         ret = xhci->config;
2470         break;
2471     default:
2472         fprintf(stderr, "xhci_oper_read: reg 0x%x unimplemented\n", reg);
2473         ret = 0;
2474     }
2475 
2476     trace_usb_xhci_oper_read(reg, ret);
2477     return ret;
2478 }
2479 
2480 static void xhci_oper_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2481 {
2482     if (reg >= 0x400) {
2483         xhci_port_write(xhci, reg - 0x400, val);
2484         return;
2485     }
2486 
2487     trace_usb_xhci_oper_write(reg, val);
2488 
2489     switch (reg) {
2490     case 0x00: /* USBCMD */
2491         if ((val & USBCMD_RS) && !(xhci->usbcmd & USBCMD_RS)) {
2492             xhci_run(xhci);
2493         } else if (!(val & USBCMD_RS) && (xhci->usbcmd & USBCMD_RS)) {
2494             xhci_stop(xhci);
2495         }
2496         xhci->usbcmd = val & 0xc0f;
2497         xhci_mfwrap_update(xhci);
2498         if (val & USBCMD_HCRST) {
2499             xhci_reset(&xhci->pci_dev.qdev);
2500         }
2501         xhci_intx_update(xhci);
2502         break;
2503 
2504     case 0x04: /* USBSTS */
2505         /* these bits are write-1-to-clear */
2506         xhci->usbsts &= ~(val & (USBSTS_HSE|USBSTS_EINT|USBSTS_PCD|USBSTS_SRE));
2507         xhci_intx_update(xhci);
2508         break;
2509 
2510     case 0x14: /* DNCTRL */
2511         xhci->dnctrl = val & 0xffff;
2512         break;
2513     case 0x18: /* CRCR low */
2514         xhci->crcr_low = (val & 0xffffffcf) | (xhci->crcr_low & CRCR_CRR);
2515         break;
2516     case 0x1c: /* CRCR high */
2517         xhci->crcr_high = val;
2518         if (xhci->crcr_low & (CRCR_CA|CRCR_CS) && (xhci->crcr_low & CRCR_CRR)) {
2519             XHCIEvent event = {ER_COMMAND_COMPLETE, CC_COMMAND_RING_STOPPED};
2520             xhci->crcr_low &= ~CRCR_CRR;
2521             xhci_event(xhci, &event);
2522             DPRINTF("xhci: command ring stopped (CRCR=%08x)\n", xhci->crcr_low);
2523         } else {
2524             dma_addr_t base = xhci_addr64(xhci->crcr_low & ~0x3f, val);
2525             xhci_ring_init(xhci, &xhci->cmd_ring, base);
2526         }
2527         xhci->crcr_low &= ~(CRCR_CA | CRCR_CS);
2528         break;
2529     case 0x30: /* DCBAAP low */
2530         xhci->dcbaap_low = val & 0xffffffc0;
2531         break;
2532     case 0x34: /* DCBAAP high */
2533         xhci->dcbaap_high = val;
2534         break;
2535     case 0x38: /* CONFIG */
2536         xhci->config = val & 0xff;
2537         break;
2538     default:
2539         fprintf(stderr, "xhci_oper_write: reg 0x%x unimplemented\n", reg);
2540     }
2541 }
2542 
2543 static uint32_t xhci_runtime_read(XHCIState *xhci, uint32_t reg)
2544 {
2545     uint32_t ret;
2546 
2547     switch (reg) {
2548     case 0x00: /* MFINDEX */
2549         ret = xhci_mfindex_get(xhci) & 0x3fff;
2550         break;
2551     case 0x20: /* IMAN */
2552         ret = xhci->iman;
2553         break;
2554     case 0x24: /* IMOD */
2555         ret = xhci->imod;
2556         break;
2557     case 0x28: /* ERSTSZ */
2558         ret = xhci->erstsz;
2559         break;
2560     case 0x30: /* ERSTBA low */
2561         ret = xhci->erstba_low;
2562         break;
2563     case 0x34: /* ERSTBA high */
2564         ret = xhci->erstba_high;
2565         break;
2566     case 0x38: /* ERDP low */
2567         ret = xhci->erdp_low;
2568         break;
2569     case 0x3c: /* ERDP high */
2570         ret = xhci->erdp_high;
2571         break;
2572     default:
2573         fprintf(stderr, "xhci_runtime_read: reg 0x%x unimplemented\n", reg);
2574         ret = 0;
2575     }
2576 
2577     trace_usb_xhci_runtime_read(reg, ret);
2578     return ret;
2579 }
2580 
2581 static void xhci_runtime_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2582 {
2583     trace_usb_xhci_runtime_write(reg, val);
2584 
2585     switch (reg) {
2586     case 0x20: /* IMAN */
2587         if (val & IMAN_IP) {
2588             xhci->iman &= ~IMAN_IP;
2589         }
2590         xhci->iman &= ~IMAN_IE;
2591         xhci->iman |= val & IMAN_IE;
2592         xhci_intx_update(xhci);
2593         break;
2594     case 0x24: /* IMOD */
2595         xhci->imod = val;
2596         break;
2597     case 0x28: /* ERSTSZ */
2598         xhci->erstsz = val & 0xffff;
2599         break;
2600     case 0x30: /* ERSTBA low */
2601         /* XXX NEC driver bug: it doesn't align this to 64 bytes
2602         xhci->erstba_low = val & 0xffffffc0; */
2603         xhci->erstba_low = val & 0xfffffff0;
2604         break;
2605     case 0x34: /* ERSTBA high */
2606         xhci->erstba_high = val;
2607         xhci_er_reset(xhci);
2608         break;
2609     case 0x38: /* ERDP low */
2610         if (val & ERDP_EHB) {
2611             xhci->erdp_low &= ~ERDP_EHB;
2612         }
2613         xhci->erdp_low = (val & ~ERDP_EHB) | (xhci->erdp_low & ERDP_EHB);
2614         break;
2615     case 0x3c: /* ERDP high */
2616         xhci->erdp_high = val;
2617         xhci_events_update(xhci);
2618         break;
2619     default:
2620         fprintf(stderr, "xhci_oper_write: reg 0x%x unimplemented\n", reg);
2621     }
2622 }
2623 
2624 static uint32_t xhci_doorbell_read(XHCIState *xhci, uint32_t reg)
2625 {
2626     /* doorbells always read as 0 */
2627     trace_usb_xhci_doorbell_read(reg, 0);
2628     return 0;
2629 }
2630 
2631 static void xhci_doorbell_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2632 {
2633     trace_usb_xhci_doorbell_write(reg, val);
2634 
2635     if (!xhci_running(xhci)) {
2636         fprintf(stderr, "xhci: wrote doorbell while xHC stopped or paused\n");
2637         return;
2638     }
2639 
2640     reg >>= 2;
2641 
2642     if (reg == 0) {
2643         if (val == 0) {
2644             xhci_process_commands(xhci);
2645         } else {
2646             fprintf(stderr, "xhci: bad doorbell 0 write: 0x%x\n", val);
2647         }
2648     } else {
2649         if (reg > MAXSLOTS) {
2650             fprintf(stderr, "xhci: bad doorbell %d\n", reg);
2651         } else if (val > 31) {
2652             fprintf(stderr, "xhci: bad doorbell %d write: 0x%x\n", reg, val);
2653         } else {
2654             xhci_kick_ep(xhci, reg, val);
2655         }
2656     }
2657 }
2658 
2659 static uint64_t xhci_mem_read(void *ptr, target_phys_addr_t addr,
2660                               unsigned size)
2661 {
2662     XHCIState *xhci = ptr;
2663 
2664     /* Only aligned reads are allowed on xHCI */
2665     if (addr & 3) {
2666         fprintf(stderr, "xhci_mem_read: Mis-aligned read\n");
2667         return 0;
2668     }
2669 
2670     if (addr < LEN_CAP) {
2671         return xhci_cap_read(xhci, addr);
2672     } else if (addr >= OFF_OPER && addr < (OFF_OPER + LEN_OPER)) {
2673         return xhci_oper_read(xhci, addr - OFF_OPER);
2674     } else if (addr >= OFF_RUNTIME && addr < (OFF_RUNTIME + LEN_RUNTIME)) {
2675         return xhci_runtime_read(xhci, addr - OFF_RUNTIME);
2676     } else if (addr >= OFF_DOORBELL && addr < (OFF_DOORBELL + LEN_DOORBELL)) {
2677         return xhci_doorbell_read(xhci, addr - OFF_DOORBELL);
2678     } else {
2679         fprintf(stderr, "xhci_mem_read: Bad offset %x\n", (int)addr);
2680         return 0;
2681     }
2682 }
2683 
2684 static void xhci_mem_write(void *ptr, target_phys_addr_t addr,
2685                            uint64_t val, unsigned size)
2686 {
2687     XHCIState *xhci = ptr;
2688 
2689     /* Only aligned writes are allowed on xHCI */
2690     if (addr & 3) {
2691         fprintf(stderr, "xhci_mem_write: Mis-aligned write\n");
2692         return;
2693     }
2694 
2695     if (addr >= OFF_OPER && addr < (OFF_OPER + LEN_OPER)) {
2696         xhci_oper_write(xhci, addr - OFF_OPER, val);
2697     } else if (addr >= OFF_RUNTIME && addr < (OFF_RUNTIME + LEN_RUNTIME)) {
2698         xhci_runtime_write(xhci, addr - OFF_RUNTIME, val);
2699     } else if (addr >= OFF_DOORBELL && addr < (OFF_DOORBELL + LEN_DOORBELL)) {
2700         xhci_doorbell_write(xhci, addr - OFF_DOORBELL, val);
2701     } else {
2702         fprintf(stderr, "xhci_mem_write: Bad offset %x\n", (int)addr);
2703     }
2704 }
2705 
2706 static const MemoryRegionOps xhci_mem_ops = {
2707     .read = xhci_mem_read,
2708     .write = xhci_mem_write,
2709     .valid.min_access_size = 4,
2710     .valid.max_access_size = 4,
2711     .endianness = DEVICE_LITTLE_ENDIAN,
2712 };
2713 
2714 static void xhci_attach(USBPort *usbport)
2715 {
2716     XHCIState *xhci = usbport->opaque;
2717     XHCIPort *port = xhci_lookup_port(xhci, usbport);
2718 
2719     xhci_update_port(xhci, port, 0);
2720 }
2721 
2722 static void xhci_detach(USBPort *usbport)
2723 {
2724     XHCIState *xhci = usbport->opaque;
2725     XHCIPort *port = xhci_lookup_port(xhci, usbport);
2726 
2727     xhci_update_port(xhci, port, 1);
2728 }
2729 
2730 static void xhci_wakeup(USBPort *usbport)
2731 {
2732     XHCIState *xhci = usbport->opaque;
2733     XHCIPort *port = xhci_lookup_port(xhci, usbport);
2734     XHCIEvent ev = { ER_PORT_STATUS_CHANGE, CC_SUCCESS,
2735                      port->portnr << 24};
2736     uint32_t pls;
2737 
2738     pls = (port->portsc >> PORTSC_PLS_SHIFT) & PORTSC_PLS_MASK;
2739     if (pls != 3) {
2740         return;
2741     }
2742     port->portsc |= 0xf << PORTSC_PLS_SHIFT;
2743     if (port->portsc & PORTSC_PLC) {
2744         return;
2745     }
2746     port->portsc |= PORTSC_PLC;
2747     xhci_event(xhci, &ev);
2748 }
2749 
2750 static void xhci_complete(USBPort *port, USBPacket *packet)
2751 {
2752     XHCITransfer *xfer = container_of(packet, XHCITransfer, packet);
2753 
2754     xhci_complete_packet(xfer, packet->result);
2755     xhci_kick_ep(xfer->xhci, xfer->slotid, xfer->epid);
2756 }
2757 
2758 static void xhci_child_detach(USBPort *port, USBDevice *child)
2759 {
2760     FIXME();
2761 }
2762 
2763 static USBPortOps xhci_port_ops = {
2764     .attach   = xhci_attach,
2765     .detach   = xhci_detach,
2766     .wakeup   = xhci_wakeup,
2767     .complete = xhci_complete,
2768     .child_detach = xhci_child_detach,
2769 };
2770 
2771 static int xhci_find_slotid(XHCIState *xhci, USBDevice *dev)
2772 {
2773     XHCISlot *slot;
2774     int slotid;
2775 
2776     for (slotid = 1; slotid <= MAXSLOTS; slotid++) {
2777         slot = &xhci->slots[slotid-1];
2778         if (slot->devaddr == dev->addr) {
2779             return slotid;
2780         }
2781     }
2782     return 0;
2783 }
2784 
2785 static int xhci_find_epid(USBEndpoint *ep)
2786 {
2787     if (ep->nr == 0) {
2788         return 1;
2789     }
2790     if (ep->pid == USB_TOKEN_IN) {
2791         return ep->nr * 2 + 1;
2792     } else {
2793         return ep->nr * 2;
2794     }
2795 }
2796 
2797 static void xhci_wakeup_endpoint(USBBus *bus, USBEndpoint *ep)
2798 {
2799     XHCIState *xhci = container_of(bus, XHCIState, bus);
2800     int slotid;
2801 
2802     DPRINTF("%s\n", __func__);
2803     slotid = xhci_find_slotid(xhci, ep->dev);
2804     if (slotid == 0 || !xhci->slots[slotid-1].enabled) {
2805         DPRINTF("%s: oops, no slot for dev %d\n", __func__, ep->dev->addr);
2806         return;
2807     }
2808     xhci_kick_ep(xhci, slotid, xhci_find_epid(ep));
2809 }
2810 
2811 static USBBusOps xhci_bus_ops = {
2812     .wakeup_endpoint = xhci_wakeup_endpoint,
2813 };
2814 
2815 static void usb_xhci_init(XHCIState *xhci, DeviceState *dev)
2816 {
2817     XHCIPort *port;
2818     int i, usbports, speedmask;
2819 
2820     xhci->usbsts = USBSTS_HCH;
2821 
2822     if (xhci->numports_2 > MAXPORTS_2) {
2823         xhci->numports_2 = MAXPORTS_2;
2824     }
2825     if (xhci->numports_3 > MAXPORTS_3) {
2826         xhci->numports_3 = MAXPORTS_3;
2827     }
2828     usbports = MAX(xhci->numports_2, xhci->numports_3);
2829     xhci->numports = xhci->numports_2 + xhci->numports_3;
2830 
2831     usb_bus_new(&xhci->bus, &xhci_bus_ops, &xhci->pci_dev.qdev);
2832 
2833     for (i = 0; i < usbports; i++) {
2834         speedmask = 0;
2835         if (i < xhci->numports_2) {
2836             port = &xhci->ports[i];
2837             port->portnr = i + 1;
2838             port->uport = &xhci->uports[i];
2839             port->speedmask =
2840                 USB_SPEED_MASK_LOW  |
2841                 USB_SPEED_MASK_FULL |
2842                 USB_SPEED_MASK_HIGH;
2843             speedmask |= port->speedmask;
2844         }
2845         if (i < xhci->numports_3) {
2846             port = &xhci->ports[i + xhci->numports_2];
2847             port->portnr = i + 1 + xhci->numports_2;
2848             port->uport = &xhci->uports[i];
2849             port->speedmask = USB_SPEED_MASK_SUPER;
2850             speedmask |= port->speedmask;
2851         }
2852         usb_register_port(&xhci->bus, &xhci->uports[i], xhci, i,
2853                           &xhci_port_ops, speedmask);
2854     }
2855 }
2856 
2857 static int usb_xhci_initfn(struct PCIDevice *dev)
2858 {
2859     int ret;
2860 
2861     XHCIState *xhci = DO_UPCAST(XHCIState, pci_dev, dev);
2862 
2863     xhci->pci_dev.config[PCI_CLASS_PROG] = 0x30;    /* xHCI */
2864     xhci->pci_dev.config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin 1 */
2865     xhci->pci_dev.config[PCI_CACHE_LINE_SIZE] = 0x10;
2866     xhci->pci_dev.config[0x60] = 0x30; /* release number */
2867 
2868     usb_xhci_init(xhci, &dev->qdev);
2869 
2870     xhci->mfwrap_timer = qemu_new_timer_ns(vm_clock, xhci_mfwrap_timer, xhci);
2871 
2872     xhci->irq = xhci->pci_dev.irq[0];
2873 
2874     memory_region_init_io(&xhci->mem, &xhci_mem_ops, xhci,
2875                           "xhci", LEN_REGS);
2876     pci_register_bar(&xhci->pci_dev, 0,
2877                      PCI_BASE_ADDRESS_SPACE_MEMORY|PCI_BASE_ADDRESS_MEM_TYPE_64,
2878                      &xhci->mem);
2879 
2880     ret = pcie_cap_init(&xhci->pci_dev, 0xa0, PCI_EXP_TYPE_ENDPOINT, 0);
2881     assert(ret >= 0);
2882 
2883     if (xhci->flags & (1 << XHCI_FLAG_USE_MSI)) {
2884         msi_init(&xhci->pci_dev, 0x70, MAXINTRS, true, false);
2885     }
2886 
2887     return 0;
2888 }
2889 
2890 static const VMStateDescription vmstate_xhci = {
2891     .name = "xhci",
2892     .unmigratable = 1,
2893 };
2894 
2895 static Property xhci_properties[] = {
2896     DEFINE_PROP_BIT("msi",    XHCIState, flags, XHCI_FLAG_USE_MSI, true),
2897     DEFINE_PROP_UINT32("p2",  XHCIState, numports_2, 4),
2898     DEFINE_PROP_UINT32("p3",  XHCIState, numports_3, 4),
2899     DEFINE_PROP_END_OF_LIST(),
2900 };
2901 
2902 static void xhci_class_init(ObjectClass *klass, void *data)
2903 {
2904     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
2905     DeviceClass *dc = DEVICE_CLASS(klass);
2906 
2907     dc->vmsd    = &vmstate_xhci;
2908     dc->props   = xhci_properties;
2909     dc->reset   = xhci_reset;
2910     k->init         = usb_xhci_initfn;
2911     k->vendor_id    = PCI_VENDOR_ID_NEC;
2912     k->device_id    = PCI_DEVICE_ID_NEC_UPD720200;
2913     k->class_id     = PCI_CLASS_SERIAL_USB;
2914     k->revision     = 0x03;
2915     k->is_express   = 1;
2916 }
2917 
2918 static TypeInfo xhci_info = {
2919     .name          = "nec-usb-xhci",
2920     .parent        = TYPE_PCI_DEVICE,
2921     .instance_size = sizeof(XHCIState),
2922     .class_init    = xhci_class_init,
2923 };
2924 
2925 static void xhci_register_types(void)
2926 {
2927     type_register_static(&xhci_info);
2928 }
2929 
2930 type_init(xhci_register_types)
2931