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