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