xref: /openbmc/qemu/hw/usb/hcd-xhci.c (revision 7acd279f)
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         DPRINTF("xhci: TRB fetched [" DMA_ADDR_FMT "]: "
705                 "%016" PRIx64 " %08x %08x %s\n",
706                 ring->dequeue, trb->parameter, trb->status, trb->control,
707                 trb_name(trb));
708 
709         if ((trb->control & TRB_C) != ring->ccs) {
710             return 0;
711         }
712 
713         type = TRB_TYPE(*trb);
714 
715         if (type != TR_LINK) {
716             if (addr) {
717                 *addr = ring->dequeue;
718             }
719             ring->dequeue += TRB_SIZE;
720             return type;
721         } else {
722             ring->dequeue = xhci_mask64(trb->parameter);
723             if (trb->control & TRB_LK_TC) {
724                 ring->ccs = !ring->ccs;
725             }
726         }
727     }
728 }
729 
730 static int xhci_ring_chain_length(XHCIState *xhci, const XHCIRing *ring)
731 {
732     XHCITRB trb;
733     int length = 0;
734     dma_addr_t dequeue = ring->dequeue;
735     bool ccs = ring->ccs;
736     /* hack to bundle together the two/three TDs that make a setup transfer */
737     bool control_td_set = 0;
738 
739     while (1) {
740         TRBType type;
741         pci_dma_read(&xhci->pci_dev, dequeue, &trb, TRB_SIZE);
742         le64_to_cpus(&trb.parameter);
743         le32_to_cpus(&trb.status);
744         le32_to_cpus(&trb.control);
745 
746         DPRINTF("xhci: TRB peeked [" DMA_ADDR_FMT "]: "
747                 "%016" PRIx64 " %08x %08x\n",
748                 dequeue, trb.parameter, trb.status, trb.control);
749 
750         if ((trb.control & TRB_C) != ccs) {
751             return -length;
752         }
753 
754         type = TRB_TYPE(trb);
755 
756         if (type == TR_LINK) {
757             dequeue = xhci_mask64(trb.parameter);
758             if (trb.control & TRB_LK_TC) {
759                 ccs = !ccs;
760             }
761             continue;
762         }
763 
764         length += 1;
765         dequeue += TRB_SIZE;
766 
767         if (type == TR_SETUP) {
768             control_td_set = 1;
769         } else if (type == TR_STATUS) {
770             control_td_set = 0;
771         }
772 
773         if (!control_td_set && !(trb.control & TRB_TR_CH)) {
774             return length;
775         }
776     }
777 }
778 
779 static void xhci_er_reset(XHCIState *xhci)
780 {
781     XHCIEvRingSeg seg;
782 
783     /* cache the (sole) event ring segment location */
784     if (xhci->erstsz != 1) {
785         fprintf(stderr, "xhci: invalid value for ERSTSZ: %d\n", xhci->erstsz);
786         xhci_die(xhci);
787         return;
788     }
789     dma_addr_t erstba = xhci_addr64(xhci->erstba_low, xhci->erstba_high);
790     pci_dma_read(&xhci->pci_dev, erstba, &seg, sizeof(seg));
791     le32_to_cpus(&seg.addr_low);
792     le32_to_cpus(&seg.addr_high);
793     le32_to_cpus(&seg.size);
794     if (seg.size < 16 || seg.size > 4096) {
795         fprintf(stderr, "xhci: invalid value for segment size: %d\n", seg.size);
796         xhci_die(xhci);
797         return;
798     }
799     xhci->er_start = xhci_addr64(seg.addr_low, seg.addr_high);
800     xhci->er_size = seg.size;
801 
802     xhci->er_ep_idx = 0;
803     xhci->er_pcs = 1;
804     xhci->er_full = 0;
805 
806     DPRINTF("xhci: event ring:" DMA_ADDR_FMT " [%d]\n",
807             xhci->er_start, xhci->er_size);
808 }
809 
810 static void xhci_run(XHCIState *xhci)
811 {
812     trace_usb_xhci_run();
813     xhci->usbsts &= ~USBSTS_HCH;
814 }
815 
816 static void xhci_stop(XHCIState *xhci)
817 {
818     trace_usb_xhci_stop();
819     xhci->usbsts |= USBSTS_HCH;
820     xhci->crcr_low &= ~CRCR_CRR;
821 }
822 
823 static void xhci_set_ep_state(XHCIState *xhci, XHCIEPContext *epctx,
824                               uint32_t state)
825 {
826     uint32_t ctx[5];
827     if (epctx->state == state) {
828         return;
829     }
830 
831     pci_dma_read(&xhci->pci_dev, epctx->pctx, ctx, sizeof(ctx));
832     ctx[0] &= ~EP_STATE_MASK;
833     ctx[0] |= state;
834     ctx[2] = epctx->ring.dequeue | epctx->ring.ccs;
835     ctx[3] = (epctx->ring.dequeue >> 16) >> 16;
836     DPRINTF("xhci: set epctx: " DMA_ADDR_FMT " state=%d dequeue=%08x%08x\n",
837             epctx->pctx, state, ctx[3], ctx[2]);
838     pci_dma_write(&xhci->pci_dev, epctx->pctx, ctx, sizeof(ctx));
839     epctx->state = state;
840 }
841 
842 static TRBCCode xhci_enable_ep(XHCIState *xhci, unsigned int slotid,
843                                unsigned int epid, dma_addr_t pctx,
844                                uint32_t *ctx)
845 {
846     XHCISlot *slot;
847     XHCIEPContext *epctx;
848     dma_addr_t dequeue;
849     int i;
850 
851     assert(slotid >= 1 && slotid <= MAXSLOTS);
852     assert(epid >= 1 && epid <= 31);
853 
854     DPRINTF("xhci_enable_ep(%d, %d)\n", slotid, epid);
855 
856     slot = &xhci->slots[slotid-1];
857     if (slot->eps[epid-1]) {
858         fprintf(stderr, "xhci: slot %d ep %d already enabled!\n", slotid, epid);
859         return CC_TRB_ERROR;
860     }
861 
862     epctx = g_malloc(sizeof(XHCIEPContext));
863     memset(epctx, 0, sizeof(XHCIEPContext));
864 
865     slot->eps[epid-1] = epctx;
866 
867     dequeue = xhci_addr64(ctx[2] & ~0xf, ctx[3]);
868     xhci_ring_init(xhci, &epctx->ring, dequeue);
869     epctx->ring.ccs = ctx[2] & 1;
870 
871     epctx->type = (ctx[1] >> EP_TYPE_SHIFT) & EP_TYPE_MASK;
872     DPRINTF("xhci: endpoint %d.%d type is %d\n", epid/2, epid%2, epctx->type);
873     epctx->pctx = pctx;
874     epctx->max_psize = ctx[1]>>16;
875     epctx->max_psize *= 1+((ctx[1]>>8)&0xff);
876     epctx->has_bg = false;
877     if (epctx->type == ET_ISO_IN) {
878         epctx->has_bg = true;
879     }
880     DPRINTF("xhci: endpoint %d.%d max transaction (burst) size is %d\n",
881             epid/2, epid%2, epctx->max_psize);
882     for (i = 0; i < ARRAY_SIZE(epctx->transfers); i++) {
883         usb_packet_init(&epctx->transfers[i].packet);
884     }
885 
886     epctx->state = EP_RUNNING;
887     ctx[0] &= ~EP_STATE_MASK;
888     ctx[0] |= EP_RUNNING;
889 
890     return CC_SUCCESS;
891 }
892 
893 static int xhci_ep_nuke_xfers(XHCIState *xhci, unsigned int slotid,
894                                unsigned int epid)
895 {
896     XHCISlot *slot;
897     XHCIEPContext *epctx;
898     int i, xferi, killed = 0;
899     assert(slotid >= 1 && slotid <= MAXSLOTS);
900     assert(epid >= 1 && epid <= 31);
901 
902     DPRINTF("xhci_ep_nuke_xfers(%d, %d)\n", slotid, epid);
903 
904     slot = &xhci->slots[slotid-1];
905 
906     if (!slot->eps[epid-1]) {
907         return 0;
908     }
909 
910     epctx = slot->eps[epid-1];
911 
912     xferi = epctx->next_xfer;
913     for (i = 0; i < TD_QUEUE; i++) {
914         XHCITransfer *t = &epctx->transfers[xferi];
915         if (t->running_async) {
916             usb_cancel_packet(&t->packet);
917             t->running_async = 0;
918             t->cancelled = 1;
919             DPRINTF("xhci: cancelling transfer %d, waiting for it to complete...\n", i);
920             killed++;
921         }
922         if (t->running_retry) {
923             t->running_retry = 0;
924             epctx->retry = NULL;
925         }
926         if (t->backgrounded) {
927             t->backgrounded = 0;
928         }
929         if (t->trbs) {
930             g_free(t->trbs);
931         }
932         if (t->data) {
933             g_free(t->data);
934         }
935 
936         t->trbs = NULL;
937         t->data = NULL;
938         t->trb_count = t->trb_alloced = 0;
939         t->data_length = t->data_alloced = 0;
940         xferi = (xferi + 1) % TD_QUEUE;
941     }
942     if (epctx->has_bg) {
943         xferi = epctx->next_bg;
944         for (i = 0; i < BG_XFERS; i++) {
945             XHCITransfer *t = &epctx->bg_transfers[xferi];
946             if (t->running_async) {
947                 usb_cancel_packet(&t->packet);
948                 t->running_async = 0;
949                 t->cancelled = 1;
950                 DPRINTF("xhci: cancelling bg transfer %d, waiting for it to complete...\n", i);
951                 killed++;
952             }
953             if (t->data) {
954                 g_free(t->data);
955             }
956 
957             t->data = NULL;
958             xferi = (xferi + 1) % BG_XFERS;
959         }
960     }
961     return killed;
962 }
963 
964 static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,
965                                unsigned int epid)
966 {
967     XHCISlot *slot;
968     XHCIEPContext *epctx;
969 
970     assert(slotid >= 1 && slotid <= MAXSLOTS);
971     assert(epid >= 1 && epid <= 31);
972 
973     DPRINTF("xhci_disable_ep(%d, %d)\n", slotid, epid);
974 
975     slot = &xhci->slots[slotid-1];
976 
977     if (!slot->eps[epid-1]) {
978         DPRINTF("xhci: slot %d ep %d already disabled\n", slotid, epid);
979         return CC_SUCCESS;
980     }
981 
982     xhci_ep_nuke_xfers(xhci, slotid, epid);
983 
984     epctx = slot->eps[epid-1];
985 
986     xhci_set_ep_state(xhci, epctx, EP_DISABLED);
987 
988     g_free(epctx);
989     slot->eps[epid-1] = NULL;
990 
991     return CC_SUCCESS;
992 }
993 
994 static TRBCCode xhci_stop_ep(XHCIState *xhci, unsigned int slotid,
995                              unsigned int epid)
996 {
997     XHCISlot *slot;
998     XHCIEPContext *epctx;
999 
1000     DPRINTF("xhci_stop_ep(%d, %d)\n", slotid, epid);
1001 
1002     assert(slotid >= 1 && slotid <= MAXSLOTS);
1003 
1004     if (epid < 1 || epid > 31) {
1005         fprintf(stderr, "xhci: bad ep %d\n", epid);
1006         return CC_TRB_ERROR;
1007     }
1008 
1009     slot = &xhci->slots[slotid-1];
1010 
1011     if (!slot->eps[epid-1]) {
1012         DPRINTF("xhci: slot %d ep %d not enabled\n", slotid, epid);
1013         return CC_EP_NOT_ENABLED_ERROR;
1014     }
1015 
1016     if (xhci_ep_nuke_xfers(xhci, slotid, epid) > 0) {
1017         fprintf(stderr, "xhci: FIXME: endpoint stopped w/ xfers running, "
1018                 "data might be lost\n");
1019     }
1020 
1021     epctx = slot->eps[epid-1];
1022 
1023     xhci_set_ep_state(xhci, epctx, EP_STOPPED);
1024 
1025     return CC_SUCCESS;
1026 }
1027 
1028 static TRBCCode xhci_reset_ep(XHCIState *xhci, unsigned int slotid,
1029                               unsigned int epid)
1030 {
1031     XHCISlot *slot;
1032     XHCIEPContext *epctx;
1033     USBDevice *dev;
1034 
1035     assert(slotid >= 1 && slotid <= MAXSLOTS);
1036 
1037     DPRINTF("xhci_reset_ep(%d, %d)\n", slotid, epid);
1038 
1039     if (epid < 1 || epid > 31) {
1040         fprintf(stderr, "xhci: bad ep %d\n", epid);
1041         return CC_TRB_ERROR;
1042     }
1043 
1044     slot = &xhci->slots[slotid-1];
1045 
1046     if (!slot->eps[epid-1]) {
1047         DPRINTF("xhci: slot %d ep %d not enabled\n", slotid, epid);
1048         return CC_EP_NOT_ENABLED_ERROR;
1049     }
1050 
1051     epctx = slot->eps[epid-1];
1052 
1053     if (epctx->state != EP_HALTED) {
1054         fprintf(stderr, "xhci: reset EP while EP %d not halted (%d)\n",
1055                 epid, epctx->state);
1056         return CC_CONTEXT_STATE_ERROR;
1057     }
1058 
1059     if (xhci_ep_nuke_xfers(xhci, slotid, epid) > 0) {
1060         fprintf(stderr, "xhci: FIXME: endpoint reset w/ xfers running, "
1061                 "data might be lost\n");
1062     }
1063 
1064     uint8_t ep = epid>>1;
1065 
1066     if (epid & 1) {
1067         ep |= 0x80;
1068     }
1069 
1070     dev = xhci->ports[xhci->slots[slotid-1].port-1].port.dev;
1071     if (!dev) {
1072         return CC_USB_TRANSACTION_ERROR;
1073     }
1074 
1075     xhci_set_ep_state(xhci, epctx, EP_STOPPED);
1076 
1077     return CC_SUCCESS;
1078 }
1079 
1080 static TRBCCode xhci_set_ep_dequeue(XHCIState *xhci, unsigned int slotid,
1081                                     unsigned int epid, uint64_t pdequeue)
1082 {
1083     XHCISlot *slot;
1084     XHCIEPContext *epctx;
1085     dma_addr_t dequeue;
1086 
1087     assert(slotid >= 1 && slotid <= MAXSLOTS);
1088 
1089     if (epid < 1 || epid > 31) {
1090         fprintf(stderr, "xhci: bad ep %d\n", epid);
1091         return CC_TRB_ERROR;
1092     }
1093 
1094     DPRINTF("xhci_set_ep_dequeue(%d, %d, %016"PRIx64")\n", slotid, epid, pdequeue);
1095     dequeue = xhci_mask64(pdequeue);
1096 
1097     slot = &xhci->slots[slotid-1];
1098 
1099     if (!slot->eps[epid-1]) {
1100         DPRINTF("xhci: slot %d ep %d not enabled\n", slotid, epid);
1101         return CC_EP_NOT_ENABLED_ERROR;
1102     }
1103 
1104     epctx = slot->eps[epid-1];
1105 
1106 
1107     if (epctx->state != EP_STOPPED) {
1108         fprintf(stderr, "xhci: set EP dequeue pointer while EP %d not stopped\n", epid);
1109         return CC_CONTEXT_STATE_ERROR;
1110     }
1111 
1112     xhci_ring_init(xhci, &epctx->ring, dequeue & ~0xF);
1113     epctx->ring.ccs = dequeue & 1;
1114 
1115     xhci_set_ep_state(xhci, epctx, EP_STOPPED);
1116 
1117     return CC_SUCCESS;
1118 }
1119 
1120 static int xhci_xfer_data(XHCITransfer *xfer, uint8_t *data,
1121                           unsigned int length, bool in_xfer, bool out_xfer,
1122                           bool report)
1123 {
1124     int i;
1125     uint32_t edtla = 0;
1126     unsigned int transferred = 0;
1127     unsigned int left = length;
1128     bool reported = 0;
1129     bool shortpkt = 0;
1130     XHCIEvent event = {ER_TRANSFER, CC_SUCCESS};
1131     XHCIState *xhci = xfer->xhci;
1132 
1133     DPRINTF("xhci_xfer_data(len=%d, in_xfer=%d, out_xfer=%d, report=%d)\n",
1134             length, in_xfer, out_xfer, report);
1135 
1136     assert(!(in_xfer && out_xfer));
1137 
1138     for (i = 0; i < xfer->trb_count; i++) {
1139         XHCITRB *trb = &xfer->trbs[i];
1140         dma_addr_t addr;
1141         unsigned int chunk = 0;
1142 
1143         switch (TRB_TYPE(*trb)) {
1144         case TR_DATA:
1145             if ((!(trb->control & TRB_TR_DIR)) != (!in_xfer)) {
1146                 fprintf(stderr, "xhci: data direction mismatch for TR_DATA\n");
1147                 xhci_die(xhci);
1148                 return transferred;
1149             }
1150             /* fallthrough */
1151         case TR_NORMAL:
1152         case TR_ISOCH:
1153             addr = xhci_mask64(trb->parameter);
1154             chunk = trb->status & 0x1ffff;
1155             if (chunk > left) {
1156                 chunk = left;
1157                 shortpkt = 1;
1158             }
1159             if (in_xfer || out_xfer) {
1160                 if (trb->control & TRB_TR_IDT) {
1161                     uint64_t idata;
1162                     if (chunk > 8 || in_xfer) {
1163                         fprintf(stderr, "xhci: invalid immediate data TRB\n");
1164                         xhci_die(xhci);
1165                         return transferred;
1166                     }
1167                     idata = le64_to_cpu(trb->parameter);
1168                     memcpy(data, &idata, chunk);
1169                 } else {
1170                     DPRINTF("xhci_xfer_data: r/w(%d) %d bytes at "
1171                             DMA_ADDR_FMT "\n", in_xfer, chunk, addr);
1172                     if (in_xfer) {
1173                         pci_dma_write(&xhci->pci_dev, addr, data, chunk);
1174                     } else {
1175                         pci_dma_read(&xhci->pci_dev, addr, data, chunk);
1176                     }
1177 #ifdef DEBUG_DATA
1178                     unsigned int count = chunk;
1179                     int i;
1180                     if (count > 16) {
1181                         count = 16;
1182                     }
1183                     DPRINTF(" ::");
1184                     for (i = 0; i < count; i++) {
1185                         DPRINTF(" %02x", data[i]);
1186                     }
1187                     DPRINTF("\n");
1188 #endif
1189                 }
1190             }
1191             left -= chunk;
1192             data += chunk;
1193             edtla += chunk;
1194             transferred += chunk;
1195             break;
1196         case TR_STATUS:
1197             reported = 0;
1198             shortpkt = 0;
1199             break;
1200         }
1201 
1202         if (report && !reported && (trb->control & TRB_TR_IOC ||
1203             (shortpkt && (trb->control & TRB_TR_ISP)))) {
1204             event.slotid = xfer->slotid;
1205             event.epid = xfer->epid;
1206             event.length = (trb->status & 0x1ffff) - chunk;
1207             event.flags = 0;
1208             event.ptr = trb->addr;
1209             if (xfer->status == CC_SUCCESS) {
1210                 event.ccode = shortpkt ? CC_SHORT_PACKET : CC_SUCCESS;
1211             } else {
1212                 event.ccode = xfer->status;
1213             }
1214             if (TRB_TYPE(*trb) == TR_EVDATA) {
1215                 event.ptr = trb->parameter;
1216                 event.flags |= TRB_EV_ED;
1217                 event.length = edtla & 0xffffff;
1218                 DPRINTF("xhci_xfer_data: EDTLA=%d\n", event.length);
1219                 edtla = 0;
1220             }
1221             xhci_event(xhci, &event);
1222             reported = 1;
1223         }
1224     }
1225     return transferred;
1226 }
1227 
1228 static void xhci_stall_ep(XHCITransfer *xfer)
1229 {
1230     XHCIState *xhci = xfer->xhci;
1231     XHCISlot *slot = &xhci->slots[xfer->slotid-1];
1232     XHCIEPContext *epctx = slot->eps[xfer->epid-1];
1233 
1234     epctx->ring.dequeue = xfer->trbs[0].addr;
1235     epctx->ring.ccs = xfer->trbs[0].ccs;
1236     xhci_set_ep_state(xhci, epctx, EP_HALTED);
1237     DPRINTF("xhci: stalled slot %d ep %d\n", xfer->slotid, xfer->epid);
1238     DPRINTF("xhci: will continue at "DMA_ADDR_FMT"\n", epctx->ring.dequeue);
1239 }
1240 
1241 static int xhci_submit(XHCIState *xhci, XHCITransfer *xfer,
1242                        XHCIEPContext *epctx);
1243 
1244 static void xhci_bg_update(XHCIState *xhci, XHCIEPContext *epctx)
1245 {
1246     if (epctx->bg_updating) {
1247         return;
1248     }
1249     DPRINTF("xhci_bg_update(%p, %p)\n", xhci, epctx);
1250     assert(epctx->has_bg);
1251     DPRINTF("xhci: fg=%d bg=%d\n", epctx->comp_xfer, epctx->next_bg);
1252     epctx->bg_updating = 1;
1253     while (epctx->transfers[epctx->comp_xfer].backgrounded &&
1254            epctx->bg_transfers[epctx->next_bg].complete) {
1255         XHCITransfer *fg = &epctx->transfers[epctx->comp_xfer];
1256         XHCITransfer *bg = &epctx->bg_transfers[epctx->next_bg];
1257 #if 0
1258         DPRINTF("xhci: completing fg %d from bg %d.%d (stat: %d)\n",
1259                 epctx->comp_xfer, epctx->next_bg, bg->cur_pkt,
1260                 bg->usbxfer->iso_packet_desc[bg->cur_pkt].status
1261                );
1262 #endif
1263         assert(epctx->type == ET_ISO_IN);
1264         assert(bg->iso_xfer);
1265         assert(bg->in_xfer);
1266         uint8_t *p = bg->data + bg->cur_pkt * bg->pktsize;
1267 #if 0
1268         int len = bg->usbxfer->iso_packet_desc[bg->cur_pkt].actual_length;
1269         fg->status = libusb_to_ccode(bg->usbxfer->iso_packet_desc[bg->cur_pkt].status);
1270 #else
1271         int len = 0;
1272         FIXME();
1273 #endif
1274         fg->complete = 1;
1275         fg->backgrounded = 0;
1276 
1277         if (fg->status == CC_STALL_ERROR) {
1278             xhci_stall_ep(fg);
1279         }
1280 
1281         xhci_xfer_data(fg, p, len, 1, 0, 1);
1282 
1283         epctx->comp_xfer++;
1284         if (epctx->comp_xfer == TD_QUEUE) {
1285             epctx->comp_xfer = 0;
1286         }
1287         DPRINTF("next fg xfer: %d\n", epctx->comp_xfer);
1288         bg->cur_pkt++;
1289         if (bg->cur_pkt == bg->pkts) {
1290             bg->complete = 0;
1291             if (xhci_submit(xhci, bg, epctx) < 0) {
1292                 fprintf(stderr, "xhci: bg resubmit failed\n");
1293             }
1294             epctx->next_bg++;
1295             if (epctx->next_bg == BG_XFERS) {
1296                 epctx->next_bg = 0;
1297             }
1298             DPRINTF("next bg xfer: %d\n", epctx->next_bg);
1299 
1300         xhci_kick_ep(xhci, fg->slotid, fg->epid);
1301         }
1302     }
1303     epctx->bg_updating = 0;
1304 }
1305 
1306 #if 0
1307 static void xhci_xfer_cb(struct libusb_transfer *transfer)
1308 {
1309     XHCIState *xhci;
1310     XHCITransfer *xfer;
1311 
1312     xfer = (XHCITransfer *)transfer->user_data;
1313     xhci = xfer->xhci;
1314 
1315     DPRINTF("xhci_xfer_cb(slot=%d, ep=%d, status=%d)\n", xfer->slotid,
1316             xfer->epid, transfer->status);
1317 
1318     assert(xfer->slotid >= 1 && xfer->slotid <= MAXSLOTS);
1319     assert(xfer->epid >= 1 && xfer->epid <= 31);
1320 
1321     if (xfer->cancelled) {
1322         DPRINTF("xhci: transfer cancelled, not reporting anything\n");
1323         xfer->running = 0;
1324         return;
1325     }
1326 
1327     XHCIEPContext *epctx;
1328     XHCISlot *slot;
1329     slot = &xhci->slots[xfer->slotid-1];
1330     assert(slot->eps[xfer->epid-1]);
1331     epctx = slot->eps[xfer->epid-1];
1332 
1333     if (xfer->bg_xfer) {
1334         DPRINTF("xhci: background transfer, updating\n");
1335         xfer->complete = 1;
1336         xfer->running = 0;
1337         xhci_bg_update(xhci, epctx);
1338         return;
1339     }
1340 
1341     if (xfer->iso_xfer) {
1342         transfer->status = transfer->iso_packet_desc[0].status;
1343         transfer->actual_length = transfer->iso_packet_desc[0].actual_length;
1344     }
1345 
1346     xfer->status = libusb_to_ccode(transfer->status);
1347 
1348     xfer->complete = 1;
1349     xfer->running = 0;
1350 
1351     if (transfer->status == LIBUSB_TRANSFER_STALL)
1352         xhci_stall_ep(xhci, epctx, xfer);
1353 
1354     DPRINTF("xhci: transfer actual length = %d\n", transfer->actual_length);
1355 
1356     if (xfer->in_xfer) {
1357         if (xfer->epid == 1) {
1358             xhci_xfer_data(xhci, xfer, xfer->data + 8,
1359                            transfer->actual_length, 1, 0, 1);
1360         } else {
1361             xhci_xfer_data(xhci, xfer, xfer->data,
1362                            transfer->actual_length, 1, 0, 1);
1363         }
1364     } else {
1365         xhci_xfer_data(xhci, xfer, NULL, transfer->actual_length, 0, 0, 1);
1366     }
1367 
1368     xhci_kick_ep(xhci, xfer->slotid, xfer->epid);
1369 }
1370 
1371 static int xhci_hle_control(XHCIState *xhci, XHCITransfer *xfer,
1372                             uint8_t bmRequestType, uint8_t bRequest,
1373                             uint16_t wValue, uint16_t wIndex, uint16_t wLength)
1374 {
1375     uint16_t type_req = (bmRequestType << 8) | bRequest;
1376 
1377     switch (type_req) {
1378         case 0x0000 | USB_REQ_SET_CONFIGURATION:
1379             DPRINTF("xhci: HLE switch configuration\n");
1380             return xhci_switch_config(xhci, xfer->slotid, wValue) == 0;
1381         case 0x0100 | USB_REQ_SET_INTERFACE:
1382             DPRINTF("xhci: HLE set interface altsetting\n");
1383             return xhci_set_iface_alt(xhci, xfer->slotid, wIndex, wValue) == 0;
1384         case 0x0200 | USB_REQ_CLEAR_FEATURE:
1385             if (wValue == 0) { // endpoint halt
1386                 DPRINTF("xhci: HLE clear halt\n");
1387                 return xhci_clear_halt(xhci, xfer->slotid, wIndex);
1388             }
1389         case 0x0000 | USB_REQ_SET_ADDRESS:
1390             fprintf(stderr, "xhci: warn: illegal SET_ADDRESS request\n");
1391             return 0;
1392         default:
1393             return 0;
1394     }
1395 }
1396 #endif
1397 
1398 static int xhci_setup_packet(XHCITransfer *xfer, USBDevice *dev)
1399 {
1400     USBEndpoint *ep;
1401     int dir;
1402 
1403     dir = xfer->in_xfer ? USB_TOKEN_IN : USB_TOKEN_OUT;
1404     ep = usb_ep_get(dev, dir, xfer->epid >> 1);
1405     usb_packet_setup(&xfer->packet, dir, ep);
1406     usb_packet_addbuf(&xfer->packet, xfer->data, xfer->data_length);
1407     DPRINTF("xhci: setup packet pid 0x%x addr %d ep %d\n",
1408             xfer->packet.pid, dev->addr, ep->nr);
1409     return 0;
1410 }
1411 
1412 static int xhci_complete_packet(XHCITransfer *xfer, int ret)
1413 {
1414     if (ret == USB_RET_ASYNC) {
1415         xfer->running_async = 1;
1416         xfer->running_retry = 0;
1417         xfer->complete = 0;
1418         xfer->cancelled = 0;
1419         return 0;
1420     } else if (ret == USB_RET_NAK) {
1421         xfer->running_async = 0;
1422         xfer->running_retry = 1;
1423         xfer->complete = 0;
1424         xfer->cancelled = 0;
1425         return 0;
1426     } else {
1427         xfer->running_async = 0;
1428         xfer->running_retry = 0;
1429         xfer->complete = 1;
1430     }
1431 
1432     if (ret >= 0) {
1433         xfer->status = CC_SUCCESS;
1434         xhci_xfer_data(xfer, xfer->data, ret, xfer->in_xfer, 0, 1);
1435         return 0;
1436     }
1437 
1438     /* error */
1439     switch (ret) {
1440     case USB_RET_NODEV:
1441         xfer->status = CC_USB_TRANSACTION_ERROR;
1442         xhci_xfer_data(xfer, xfer->data, 0, xfer->in_xfer, 0, 1);
1443         xhci_stall_ep(xfer);
1444         break;
1445     case USB_RET_STALL:
1446         xfer->status = CC_STALL_ERROR;
1447         xhci_xfer_data(xfer, xfer->data, 0, xfer->in_xfer, 0, 1);
1448         xhci_stall_ep(xfer);
1449         break;
1450     default:
1451         fprintf(stderr, "%s: FIXME: ret = %d\n", __FUNCTION__, ret);
1452         FIXME();
1453     }
1454     return 0;
1455 }
1456 
1457 static USBDevice *xhci_find_device(XHCIPort *port, uint8_t addr)
1458 {
1459     if (!(port->portsc & PORTSC_PED)) {
1460         return NULL;
1461     }
1462     return usb_find_device(&port->port, addr);
1463 }
1464 
1465 static int xhci_fire_ctl_transfer(XHCIState *xhci, XHCITransfer *xfer)
1466 {
1467     XHCITRB *trb_setup, *trb_status;
1468     uint8_t bmRequestType;
1469     uint16_t wLength;
1470     XHCIPort *port;
1471     USBDevice *dev;
1472     int ret;
1473 
1474     DPRINTF("xhci_fire_ctl_transfer(slot=%d)\n", xfer->slotid);
1475 
1476     trb_setup = &xfer->trbs[0];
1477     trb_status = &xfer->trbs[xfer->trb_count-1];
1478 
1479     /* at most one Event Data TRB allowed after STATUS */
1480     if (TRB_TYPE(*trb_status) == TR_EVDATA && xfer->trb_count > 2) {
1481         trb_status--;
1482     }
1483 
1484     /* do some sanity checks */
1485     if (TRB_TYPE(*trb_setup) != TR_SETUP) {
1486         fprintf(stderr, "xhci: ep0 first TD not SETUP: %d\n",
1487                 TRB_TYPE(*trb_setup));
1488         return -1;
1489     }
1490     if (TRB_TYPE(*trb_status) != TR_STATUS) {
1491         fprintf(stderr, "xhci: ep0 last TD not STATUS: %d\n",
1492                 TRB_TYPE(*trb_status));
1493         return -1;
1494     }
1495     if (!(trb_setup->control & TRB_TR_IDT)) {
1496         fprintf(stderr, "xhci: Setup TRB doesn't have IDT set\n");
1497         return -1;
1498     }
1499     if ((trb_setup->status & 0x1ffff) != 8) {
1500         fprintf(stderr, "xhci: Setup TRB has bad length (%d)\n",
1501                 (trb_setup->status & 0x1ffff));
1502         return -1;
1503     }
1504 
1505     bmRequestType = trb_setup->parameter;
1506     wLength = trb_setup->parameter >> 48;
1507 
1508     if (xfer->data && xfer->data_alloced < wLength) {
1509         xfer->data_alloced = 0;
1510         g_free(xfer->data);
1511         xfer->data = NULL;
1512     }
1513     if (!xfer->data) {
1514         DPRINTF("xhci: alloc %d bytes data\n", wLength);
1515         xfer->data = g_malloc(wLength+1);
1516         xfer->data_alloced = wLength;
1517     }
1518     xfer->data_length = wLength;
1519 
1520     port = &xhci->ports[xhci->slots[xfer->slotid-1].port-1];
1521     dev = xhci_find_device(port, xhci->slots[xfer->slotid-1].devaddr);
1522     if (!dev) {
1523         fprintf(stderr, "xhci: slot %d port %d has no device\n", xfer->slotid,
1524                 xhci->slots[xfer->slotid-1].port);
1525         return -1;
1526     }
1527 
1528     xfer->in_xfer = bmRequestType & USB_DIR_IN;
1529     xfer->iso_xfer = false;
1530 
1531     xhci_setup_packet(xfer, dev);
1532     xfer->packet.parameter = trb_setup->parameter;
1533     if (!xfer->in_xfer) {
1534         xhci_xfer_data(xfer, xfer->data, wLength, 0, 1, 0);
1535     }
1536 
1537     ret = usb_handle_packet(dev, &xfer->packet);
1538 
1539     xhci_complete_packet(xfer, ret);
1540     if (!xfer->running_async && !xfer->running_retry) {
1541         xhci_kick_ep(xhci, xfer->slotid, xfer->epid);
1542     }
1543     return 0;
1544 }
1545 
1546 static int xhci_submit(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)
1547 {
1548     XHCIPort *port;
1549     USBDevice *dev;
1550     int ret;
1551 
1552     DPRINTF("xhci_submit(slotid=%d,epid=%d)\n", xfer->slotid, xfer->epid);
1553 
1554     xfer->in_xfer = epctx->type>>2;
1555 
1556     if (xfer->data && xfer->data_alloced < xfer->data_length) {
1557         xfer->data_alloced = 0;
1558         g_free(xfer->data);
1559         xfer->data = NULL;
1560     }
1561     if (!xfer->data && xfer->data_length) {
1562         DPRINTF("xhci: alloc %d bytes data\n", xfer->data_length);
1563         xfer->data = g_malloc(xfer->data_length);
1564         xfer->data_alloced = xfer->data_length;
1565     }
1566     if (epctx->type == ET_ISO_IN || epctx->type == ET_ISO_OUT) {
1567         if (!xfer->bg_xfer) {
1568             xfer->pkts = 1;
1569         }
1570     } else {
1571         xfer->pkts = 0;
1572     }
1573 
1574     port = &xhci->ports[xhci->slots[xfer->slotid-1].port-1];
1575     dev = xhci_find_device(port, xhci->slots[xfer->slotid-1].devaddr);
1576     if (!dev) {
1577         fprintf(stderr, "xhci: slot %d port %d has no device\n", xfer->slotid,
1578                 xhci->slots[xfer->slotid-1].port);
1579         return -1;
1580     }
1581 
1582     xhci_setup_packet(xfer, dev);
1583 
1584     switch(epctx->type) {
1585     case ET_INTR_OUT:
1586     case ET_INTR_IN:
1587     case ET_BULK_OUT:
1588     case ET_BULK_IN:
1589         break;
1590     case ET_ISO_OUT:
1591     case ET_ISO_IN:
1592         FIXME();
1593         break;
1594     default:
1595         fprintf(stderr, "xhci: unknown or unhandled EP "
1596                 "(type %d, in %d, ep %02x)\n",
1597                 epctx->type, xfer->in_xfer, xfer->epid);
1598         return -1;
1599     }
1600 
1601     if (!xfer->in_xfer) {
1602         xhci_xfer_data(xfer, xfer->data, xfer->data_length, 0, 1, 0);
1603     }
1604     ret = usb_handle_packet(dev, &xfer->packet);
1605 
1606     xhci_complete_packet(xfer, ret);
1607     if (!xfer->running_async && !xfer->running_retry) {
1608         xhci_kick_ep(xhci, xfer->slotid, xfer->epid);
1609     }
1610     return 0;
1611 }
1612 
1613 static int xhci_fire_transfer(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)
1614 {
1615     int i;
1616     unsigned int length = 0;
1617     XHCITRB *trb;
1618 
1619     DPRINTF("xhci_fire_transfer(slotid=%d,epid=%d)\n", xfer->slotid, xfer->epid);
1620 
1621     for (i = 0; i < xfer->trb_count; i++) {
1622         trb = &xfer->trbs[i];
1623         if (TRB_TYPE(*trb) == TR_NORMAL || TRB_TYPE(*trb) == TR_ISOCH) {
1624             length += trb->status & 0x1ffff;
1625         }
1626     }
1627     DPRINTF("xhci: total TD length=%d\n", length);
1628 
1629     if (!epctx->has_bg) {
1630         xfer->data_length = length;
1631         xfer->backgrounded = 0;
1632         return xhci_submit(xhci, xfer, epctx);
1633     } else {
1634         if (!epctx->bg_running) {
1635             for (i = 0; i < BG_XFERS; i++) {
1636                 XHCITransfer *t = &epctx->bg_transfers[i];
1637                 t->xhci = xhci;
1638                 t->epid = xfer->epid;
1639                 t->slotid = xfer->slotid;
1640                 t->pkts = BG_PKTS;
1641                 t->pktsize = epctx->max_psize;
1642                 t->data_length = t->pkts * t->pktsize;
1643                 t->bg_xfer = 1;
1644                 if (xhci_submit(xhci, t, epctx) < 0) {
1645                     fprintf(stderr, "xhci: bg submit failed\n");
1646                     return -1;
1647                 }
1648             }
1649             epctx->bg_running = 1;
1650         }
1651         xfer->backgrounded = 1;
1652         xhci_bg_update(xhci, epctx);
1653         return 0;
1654     }
1655 }
1656 
1657 static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid, unsigned int epid)
1658 {
1659     XHCIEPContext *epctx;
1660     int length;
1661     int i;
1662 
1663     assert(slotid >= 1 && slotid <= MAXSLOTS);
1664     assert(epid >= 1 && epid <= 31);
1665     DPRINTF("xhci_kick_ep(%d, %d)\n", slotid, epid);
1666 
1667     if (!xhci->slots[slotid-1].enabled) {
1668         fprintf(stderr, "xhci: xhci_kick_ep for disabled slot %d\n", slotid);
1669         return;
1670     }
1671     epctx = xhci->slots[slotid-1].eps[epid-1];
1672     if (!epctx) {
1673         fprintf(stderr, "xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
1674                 epid, slotid);
1675         return;
1676     }
1677 
1678     if (epctx->retry) {
1679         /* retry nak'ed transfer */
1680         XHCITransfer *xfer = epctx->retry;
1681         int result;
1682 
1683         DPRINTF("xhci: retry nack'ed transfer ...\n");
1684         assert(xfer->running_retry);
1685         xhci_setup_packet(xfer, xfer->packet.ep->dev);
1686         result = usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
1687         if (result == USB_RET_NAK) {
1688             DPRINTF("xhci: ... xfer still nacked\n");
1689             return;
1690         }
1691         DPRINTF("xhci: ... result %d\n", result);
1692         xhci_complete_packet(xfer, result);
1693         assert(!xfer->running_retry);
1694         epctx->retry = NULL;
1695     }
1696 
1697     if (epctx->state == EP_HALTED) {
1698         DPRINTF("xhci: ep halted, not running schedule\n");
1699         return;
1700     }
1701 
1702     xhci_set_ep_state(xhci, epctx, EP_RUNNING);
1703 
1704     while (1) {
1705         XHCITransfer *xfer = &epctx->transfers[epctx->next_xfer];
1706         if (xfer->running_async || xfer->running_retry || xfer->backgrounded) {
1707             DPRINTF("xhci: ep is busy (#%d,%d,%d,%d)\n",
1708                     epctx->next_xfer, xfer->running_async,
1709                     xfer->running_retry, xfer->backgrounded);
1710             break;
1711         } else {
1712             DPRINTF("xhci: ep: using #%d\n", epctx->next_xfer);
1713         }
1714         length = xhci_ring_chain_length(xhci, &epctx->ring);
1715         if (length < 0) {
1716             DPRINTF("xhci: incomplete TD (%d TRBs)\n", -length);
1717             break;
1718         } else if (length == 0) {
1719             break;
1720         }
1721         DPRINTF("xhci: fetching %d-TRB TD\n", length);
1722         if (xfer->trbs && xfer->trb_alloced < length) {
1723             xfer->trb_count = 0;
1724             xfer->trb_alloced = 0;
1725             g_free(xfer->trbs);
1726             xfer->trbs = NULL;
1727         }
1728         if (!xfer->trbs) {
1729             xfer->trbs = g_malloc(sizeof(XHCITRB) * length);
1730             xfer->trb_alloced = length;
1731         }
1732         xfer->trb_count = length;
1733 
1734         for (i = 0; i < length; i++) {
1735             assert(xhci_ring_fetch(xhci, &epctx->ring, &xfer->trbs[i], NULL));
1736         }
1737         xfer->xhci = xhci;
1738         xfer->epid = epid;
1739         xfer->slotid = slotid;
1740 
1741         if (epid == 1) {
1742             if (xhci_fire_ctl_transfer(xhci, xfer) >= 0) {
1743                 epctx->next_xfer = (epctx->next_xfer + 1) % TD_QUEUE;
1744             } else {
1745                 fprintf(stderr, "xhci: error firing CTL transfer\n");
1746             }
1747         } else {
1748             if (xhci_fire_transfer(xhci, xfer, epctx) >= 0) {
1749                 epctx->next_xfer = (epctx->next_xfer + 1) % TD_QUEUE;
1750             } else {
1751                 fprintf(stderr, "xhci: error firing data transfer\n");
1752             }
1753         }
1754 
1755         if (epctx->state == EP_HALTED) {
1756             DPRINTF("xhci: ep halted, stopping schedule\n");
1757             break;
1758         }
1759         if (xfer->running_retry) {
1760             DPRINTF("xhci: xfer nacked, stopping schedule\n");
1761             epctx->retry = xfer;
1762             break;
1763         }
1764     }
1765 }
1766 
1767 static TRBCCode xhci_enable_slot(XHCIState *xhci, unsigned int slotid)
1768 {
1769     assert(slotid >= 1 && slotid <= MAXSLOTS);
1770     DPRINTF("xhci_enable_slot(%d)\n", slotid);
1771     xhci->slots[slotid-1].enabled = 1;
1772     xhci->slots[slotid-1].port = 0;
1773     memset(xhci->slots[slotid-1].eps, 0, sizeof(XHCIEPContext*)*31);
1774 
1775     return CC_SUCCESS;
1776 }
1777 
1778 static TRBCCode xhci_disable_slot(XHCIState *xhci, unsigned int slotid)
1779 {
1780     int i;
1781 
1782     assert(slotid >= 1 && slotid <= MAXSLOTS);
1783     DPRINTF("xhci_disable_slot(%d)\n", slotid);
1784 
1785     for (i = 1; i <= 31; i++) {
1786         if (xhci->slots[slotid-1].eps[i-1]) {
1787             xhci_disable_ep(xhci, slotid, i);
1788         }
1789     }
1790 
1791     xhci->slots[slotid-1].enabled = 0;
1792     return CC_SUCCESS;
1793 }
1794 
1795 static TRBCCode xhci_address_slot(XHCIState *xhci, unsigned int slotid,
1796                                   uint64_t pictx, bool bsr)
1797 {
1798     XHCISlot *slot;
1799     USBDevice *dev;
1800     dma_addr_t ictx, octx, dcbaap;
1801     uint64_t poctx;
1802     uint32_t ictl_ctx[2];
1803     uint32_t slot_ctx[4];
1804     uint32_t ep0_ctx[5];
1805     unsigned int port;
1806     int i;
1807     TRBCCode res;
1808 
1809     assert(slotid >= 1 && slotid <= MAXSLOTS);
1810     DPRINTF("xhci_address_slot(%d)\n", slotid);
1811 
1812     dcbaap = xhci_addr64(xhci->dcbaap_low, xhci->dcbaap_high);
1813     pci_dma_read(&xhci->pci_dev, dcbaap + 8*slotid, &poctx, sizeof(poctx));
1814     ictx = xhci_mask64(pictx);
1815     octx = xhci_mask64(le64_to_cpu(poctx));
1816 
1817     DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
1818     DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
1819 
1820     pci_dma_read(&xhci->pci_dev, ictx, ictl_ctx, sizeof(ictl_ctx));
1821 
1822     if (ictl_ctx[0] != 0x0 || ictl_ctx[1] != 0x3) {
1823         fprintf(stderr, "xhci: invalid input context control %08x %08x\n",
1824                 ictl_ctx[0], ictl_ctx[1]);
1825         return CC_TRB_ERROR;
1826     }
1827 
1828     pci_dma_read(&xhci->pci_dev, ictx+32, slot_ctx, sizeof(slot_ctx));
1829     pci_dma_read(&xhci->pci_dev, ictx+64, ep0_ctx, sizeof(ep0_ctx));
1830 
1831     DPRINTF("xhci: input slot context: %08x %08x %08x %08x\n",
1832             slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
1833 
1834     DPRINTF("xhci: input ep0 context: %08x %08x %08x %08x %08x\n",
1835             ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);
1836 
1837     port = (slot_ctx[1]>>16) & 0xFF;
1838     dev = xhci->ports[port-1].port.dev;
1839 
1840     if (port < 1 || port > MAXPORTS) {
1841         fprintf(stderr, "xhci: bad port %d\n", port);
1842         return CC_TRB_ERROR;
1843     } else if (!dev) {
1844         fprintf(stderr, "xhci: port %d not connected\n", port);
1845         return CC_USB_TRANSACTION_ERROR;
1846     }
1847 
1848     for (i = 0; i < MAXSLOTS; i++) {
1849         if (xhci->slots[i].port == port) {
1850             fprintf(stderr, "xhci: port %d already assigned to slot %d\n",
1851                     port, i+1);
1852             return CC_TRB_ERROR;
1853         }
1854     }
1855 
1856     slot = &xhci->slots[slotid-1];
1857     slot->port = port;
1858     slot->ctx = octx;
1859 
1860     if (bsr) {
1861         slot_ctx[3] = SLOT_DEFAULT << SLOT_STATE_SHIFT;
1862     } else {
1863         slot->devaddr = xhci->devaddr++;
1864         slot_ctx[3] = (SLOT_ADDRESSED << SLOT_STATE_SHIFT) | slot->devaddr;
1865         DPRINTF("xhci: device address is %d\n", slot->devaddr);
1866         usb_device_handle_control(dev, NULL,
1867                                   DeviceOutRequest | USB_REQ_SET_ADDRESS,
1868                                   slot->devaddr, 0, 0, NULL);
1869     }
1870 
1871     res = xhci_enable_ep(xhci, slotid, 1, octx+32, ep0_ctx);
1872 
1873     DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
1874             slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
1875     DPRINTF("xhci: output ep0 context: %08x %08x %08x %08x %08x\n",
1876             ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);
1877 
1878     pci_dma_write(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
1879     pci_dma_write(&xhci->pci_dev, octx+32, ep0_ctx, sizeof(ep0_ctx));
1880 
1881     return res;
1882 }
1883 
1884 
1885 static TRBCCode xhci_configure_slot(XHCIState *xhci, unsigned int slotid,
1886                                   uint64_t pictx, bool dc)
1887 {
1888     dma_addr_t ictx, octx;
1889     uint32_t ictl_ctx[2];
1890     uint32_t slot_ctx[4];
1891     uint32_t islot_ctx[4];
1892     uint32_t ep_ctx[5];
1893     int i;
1894     TRBCCode res;
1895 
1896     assert(slotid >= 1 && slotid <= MAXSLOTS);
1897     DPRINTF("xhci_configure_slot(%d)\n", slotid);
1898 
1899     ictx = xhci_mask64(pictx);
1900     octx = xhci->slots[slotid-1].ctx;
1901 
1902     DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
1903     DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
1904 
1905     if (dc) {
1906         for (i = 2; i <= 31; i++) {
1907             if (xhci->slots[slotid-1].eps[i-1]) {
1908                 xhci_disable_ep(xhci, slotid, i);
1909             }
1910         }
1911 
1912         pci_dma_read(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
1913         slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
1914         slot_ctx[3] |= SLOT_ADDRESSED << SLOT_STATE_SHIFT;
1915         DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
1916                 slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
1917         pci_dma_write(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
1918 
1919         return CC_SUCCESS;
1920     }
1921 
1922     pci_dma_read(&xhci->pci_dev, ictx, ictl_ctx, sizeof(ictl_ctx));
1923 
1924     if ((ictl_ctx[0] & 0x3) != 0x0 || (ictl_ctx[1] & 0x3) != 0x1) {
1925         fprintf(stderr, "xhci: invalid input context control %08x %08x\n",
1926                 ictl_ctx[0], ictl_ctx[1]);
1927         return CC_TRB_ERROR;
1928     }
1929 
1930     pci_dma_read(&xhci->pci_dev, ictx+32, islot_ctx, sizeof(islot_ctx));
1931     pci_dma_read(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
1932 
1933     if (SLOT_STATE(slot_ctx[3]) < SLOT_ADDRESSED) {
1934         fprintf(stderr, "xhci: invalid slot state %08x\n", slot_ctx[3]);
1935         return CC_CONTEXT_STATE_ERROR;
1936     }
1937 
1938     for (i = 2; i <= 31; i++) {
1939         if (ictl_ctx[0] & (1<<i)) {
1940             xhci_disable_ep(xhci, slotid, i);
1941         }
1942         if (ictl_ctx[1] & (1<<i)) {
1943             pci_dma_read(&xhci->pci_dev, ictx+32+(32*i), ep_ctx,
1944                          sizeof(ep_ctx));
1945             DPRINTF("xhci: input ep%d.%d context: %08x %08x %08x %08x %08x\n",
1946                     i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2],
1947                     ep_ctx[3], ep_ctx[4]);
1948             xhci_disable_ep(xhci, slotid, i);
1949             res = xhci_enable_ep(xhci, slotid, i, octx+(32*i), ep_ctx);
1950             if (res != CC_SUCCESS) {
1951                 return res;
1952             }
1953             DPRINTF("xhci: output ep%d.%d context: %08x %08x %08x %08x %08x\n",
1954                     i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2],
1955                     ep_ctx[3], ep_ctx[4]);
1956             pci_dma_write(&xhci->pci_dev, octx+(32*i), ep_ctx, sizeof(ep_ctx));
1957         }
1958     }
1959 
1960     slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
1961     slot_ctx[3] |= SLOT_CONFIGURED << SLOT_STATE_SHIFT;
1962     slot_ctx[0] &= ~(SLOT_CONTEXT_ENTRIES_MASK << SLOT_CONTEXT_ENTRIES_SHIFT);
1963     slot_ctx[0] |= islot_ctx[0] & (SLOT_CONTEXT_ENTRIES_MASK <<
1964                                    SLOT_CONTEXT_ENTRIES_SHIFT);
1965     DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
1966             slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
1967 
1968     pci_dma_write(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
1969 
1970     return CC_SUCCESS;
1971 }
1972 
1973 
1974 static TRBCCode xhci_evaluate_slot(XHCIState *xhci, unsigned int slotid,
1975                                    uint64_t pictx)
1976 {
1977     dma_addr_t ictx, octx;
1978     uint32_t ictl_ctx[2];
1979     uint32_t iep0_ctx[5];
1980     uint32_t ep0_ctx[5];
1981     uint32_t islot_ctx[4];
1982     uint32_t slot_ctx[4];
1983 
1984     assert(slotid >= 1 && slotid <= MAXSLOTS);
1985     DPRINTF("xhci_evaluate_slot(%d)\n", slotid);
1986 
1987     ictx = xhci_mask64(pictx);
1988     octx = xhci->slots[slotid-1].ctx;
1989 
1990     DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
1991     DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
1992 
1993     pci_dma_read(&xhci->pci_dev, ictx, ictl_ctx, sizeof(ictl_ctx));
1994 
1995     if (ictl_ctx[0] != 0x0 || ictl_ctx[1] & ~0x3) {
1996         fprintf(stderr, "xhci: invalid input context control %08x %08x\n",
1997                 ictl_ctx[0], ictl_ctx[1]);
1998         return CC_TRB_ERROR;
1999     }
2000 
2001     if (ictl_ctx[1] & 0x1) {
2002         pci_dma_read(&xhci->pci_dev, ictx+32, islot_ctx, sizeof(islot_ctx));
2003 
2004         DPRINTF("xhci: input slot context: %08x %08x %08x %08x\n",
2005                 islot_ctx[0], islot_ctx[1], islot_ctx[2], islot_ctx[3]);
2006 
2007         pci_dma_read(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
2008 
2009         slot_ctx[1] &= ~0xFFFF; /* max exit latency */
2010         slot_ctx[1] |= islot_ctx[1] & 0xFFFF;
2011         slot_ctx[2] &= ~0xFF00000; /* interrupter target */
2012         slot_ctx[2] |= islot_ctx[2] & 0xFF000000;
2013 
2014         DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
2015                 slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
2016 
2017         pci_dma_write(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
2018     }
2019 
2020     if (ictl_ctx[1] & 0x2) {
2021         pci_dma_read(&xhci->pci_dev, ictx+64, iep0_ctx, sizeof(iep0_ctx));
2022 
2023         DPRINTF("xhci: input ep0 context: %08x %08x %08x %08x %08x\n",
2024                 iep0_ctx[0], iep0_ctx[1], iep0_ctx[2],
2025                 iep0_ctx[3], iep0_ctx[4]);
2026 
2027         pci_dma_read(&xhci->pci_dev, octx+32, ep0_ctx, sizeof(ep0_ctx));
2028 
2029         ep0_ctx[1] &= ~0xFFFF0000; /* max packet size*/
2030         ep0_ctx[1] |= iep0_ctx[1] & 0xFFFF0000;
2031 
2032         DPRINTF("xhci: output ep0 context: %08x %08x %08x %08x %08x\n",
2033                 ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);
2034 
2035         pci_dma_write(&xhci->pci_dev, octx+32, ep0_ctx, sizeof(ep0_ctx));
2036     }
2037 
2038     return CC_SUCCESS;
2039 }
2040 
2041 static TRBCCode xhci_reset_slot(XHCIState *xhci, unsigned int slotid)
2042 {
2043     uint32_t slot_ctx[4];
2044     dma_addr_t octx;
2045     int i;
2046 
2047     assert(slotid >= 1 && slotid <= MAXSLOTS);
2048     DPRINTF("xhci_reset_slot(%d)\n", slotid);
2049 
2050     octx = xhci->slots[slotid-1].ctx;
2051 
2052     DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
2053 
2054     for (i = 2; i <= 31; i++) {
2055         if (xhci->slots[slotid-1].eps[i-1]) {
2056             xhci_disable_ep(xhci, slotid, i);
2057         }
2058     }
2059 
2060     pci_dma_read(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
2061     slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
2062     slot_ctx[3] |= SLOT_DEFAULT << SLOT_STATE_SHIFT;
2063     DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
2064             slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
2065     pci_dma_write(&xhci->pci_dev, octx, slot_ctx, sizeof(slot_ctx));
2066 
2067     return CC_SUCCESS;
2068 }
2069 
2070 static unsigned int xhci_get_slot(XHCIState *xhci, XHCIEvent *event, XHCITRB *trb)
2071 {
2072     unsigned int slotid;
2073     slotid = (trb->control >> TRB_CR_SLOTID_SHIFT) & TRB_CR_SLOTID_MASK;
2074     if (slotid < 1 || slotid > MAXSLOTS) {
2075         fprintf(stderr, "xhci: bad slot id %d\n", slotid);
2076         event->ccode = CC_TRB_ERROR;
2077         return 0;
2078     } else if (!xhci->slots[slotid-1].enabled) {
2079         fprintf(stderr, "xhci: slot id %d not enabled\n", slotid);
2080         event->ccode = CC_SLOT_NOT_ENABLED_ERROR;
2081         return 0;
2082     }
2083     return slotid;
2084 }
2085 
2086 static TRBCCode xhci_get_port_bandwidth(XHCIState *xhci, uint64_t pctx)
2087 {
2088     dma_addr_t ctx;
2089     uint8_t bw_ctx[MAXPORTS+1];
2090 
2091     DPRINTF("xhci_get_port_bandwidth()\n");
2092 
2093     ctx = xhci_mask64(pctx);
2094 
2095     DPRINTF("xhci: bandwidth context at "DMA_ADDR_FMT"\n", ctx);
2096 
2097     /* TODO: actually implement real values here */
2098     bw_ctx[0] = 0;
2099     memset(&bw_ctx[1], 80, MAXPORTS); /* 80% */
2100     pci_dma_write(&xhci->pci_dev, ctx, bw_ctx, sizeof(bw_ctx));
2101 
2102     return CC_SUCCESS;
2103 }
2104 
2105 static uint32_t rotl(uint32_t v, unsigned count)
2106 {
2107     count &= 31;
2108     return (v << count) | (v >> (32 - count));
2109 }
2110 
2111 
2112 static uint32_t xhci_nec_challenge(uint32_t hi, uint32_t lo)
2113 {
2114     uint32_t val;
2115     val = rotl(lo - 0x49434878, 32 - ((hi>>8) & 0x1F));
2116     val += rotl(lo + 0x49434878, hi & 0x1F);
2117     val -= rotl(hi ^ 0x49434878, (lo >> 16) & 0x1F);
2118     return ~val;
2119 }
2120 
2121 static void xhci_via_challenge(XHCIState *xhci, uint64_t addr)
2122 {
2123     uint32_t buf[8];
2124     uint32_t obuf[8];
2125     dma_addr_t paddr = xhci_mask64(addr);
2126 
2127     pci_dma_read(&xhci->pci_dev, paddr, &buf, 32);
2128 
2129     memcpy(obuf, buf, sizeof(obuf));
2130 
2131     if ((buf[0] & 0xff) == 2) {
2132         obuf[0] = 0x49932000 + 0x54dc200 * buf[2] + 0x7429b578 * buf[3];
2133         obuf[0] |=  (buf[2] * buf[3]) & 0xff;
2134         obuf[1] = 0x0132bb37 + 0xe89 * buf[2] + 0xf09 * buf[3];
2135         obuf[2] = 0x0066c2e9 + 0x2091 * buf[2] + 0x19bd * buf[3];
2136         obuf[3] = 0xd5281342 + 0x2cc9691 * buf[2] + 0x2367662 * buf[3];
2137         obuf[4] = 0x0123c75c + 0x1595 * buf[2] + 0x19ec * buf[3];
2138         obuf[5] = 0x00f695de + 0x26fd * buf[2] + 0x3e9 * buf[3];
2139         obuf[6] = obuf[2] ^ obuf[3] ^ 0x29472956;
2140         obuf[7] = obuf[2] ^ obuf[3] ^ 0x65866593;
2141     }
2142 
2143     pci_dma_write(&xhci->pci_dev, paddr, &obuf, 32);
2144 }
2145 
2146 static void xhci_process_commands(XHCIState *xhci)
2147 {
2148     XHCITRB trb;
2149     TRBType type;
2150     XHCIEvent event = {ER_COMMAND_COMPLETE, CC_SUCCESS};
2151     dma_addr_t addr;
2152     unsigned int i, slotid = 0;
2153 
2154     DPRINTF("xhci_process_commands()\n");
2155     if (!xhci_running(xhci)) {
2156         DPRINTF("xhci_process_commands() called while xHC stopped or paused\n");
2157         return;
2158     }
2159 
2160     xhci->crcr_low |= CRCR_CRR;
2161 
2162     while ((type = xhci_ring_fetch(xhci, &xhci->cmd_ring, &trb, &addr))) {
2163         event.ptr = addr;
2164         switch (type) {
2165         case CR_ENABLE_SLOT:
2166             for (i = 0; i < MAXSLOTS; i++) {
2167                 if (!xhci->slots[i].enabled) {
2168                     break;
2169                 }
2170             }
2171             if (i >= MAXSLOTS) {
2172                 fprintf(stderr, "xhci: no device slots available\n");
2173                 event.ccode = CC_NO_SLOTS_ERROR;
2174             } else {
2175                 slotid = i+1;
2176                 event.ccode = xhci_enable_slot(xhci, slotid);
2177             }
2178             break;
2179         case CR_DISABLE_SLOT:
2180             slotid = xhci_get_slot(xhci, &event, &trb);
2181             if (slotid) {
2182                 event.ccode = xhci_disable_slot(xhci, slotid);
2183             }
2184             break;
2185         case CR_ADDRESS_DEVICE:
2186             slotid = xhci_get_slot(xhci, &event, &trb);
2187             if (slotid) {
2188                 event.ccode = xhci_address_slot(xhci, slotid, trb.parameter,
2189                                                 trb.control & TRB_CR_BSR);
2190             }
2191             break;
2192         case CR_CONFIGURE_ENDPOINT:
2193             slotid = xhci_get_slot(xhci, &event, &trb);
2194             if (slotid) {
2195                 event.ccode = xhci_configure_slot(xhci, slotid, trb.parameter,
2196                                                   trb.control & TRB_CR_DC);
2197             }
2198             break;
2199         case CR_EVALUATE_CONTEXT:
2200             slotid = xhci_get_slot(xhci, &event, &trb);
2201             if (slotid) {
2202                 event.ccode = xhci_evaluate_slot(xhci, slotid, trb.parameter);
2203             }
2204             break;
2205         case CR_STOP_ENDPOINT:
2206             slotid = xhci_get_slot(xhci, &event, &trb);
2207             if (slotid) {
2208                 unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2209                     & TRB_CR_EPID_MASK;
2210                 event.ccode = xhci_stop_ep(xhci, slotid, epid);
2211             }
2212             break;
2213         case CR_RESET_ENDPOINT:
2214             slotid = xhci_get_slot(xhci, &event, &trb);
2215             if (slotid) {
2216                 unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2217                     & TRB_CR_EPID_MASK;
2218                 event.ccode = xhci_reset_ep(xhci, slotid, epid);
2219             }
2220             break;
2221         case CR_SET_TR_DEQUEUE:
2222             slotid = xhci_get_slot(xhci, &event, &trb);
2223             if (slotid) {
2224                 unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2225                     & TRB_CR_EPID_MASK;
2226                 event.ccode = xhci_set_ep_dequeue(xhci, slotid, epid,
2227                                                   trb.parameter);
2228             }
2229             break;
2230         case CR_RESET_DEVICE:
2231             slotid = xhci_get_slot(xhci, &event, &trb);
2232             if (slotid) {
2233                 event.ccode = xhci_reset_slot(xhci, slotid);
2234             }
2235             break;
2236         case CR_GET_PORT_BANDWIDTH:
2237             event.ccode = xhci_get_port_bandwidth(xhci, trb.parameter);
2238             break;
2239         case CR_VENDOR_VIA_CHALLENGE_RESPONSE:
2240             xhci_via_challenge(xhci, trb.parameter);
2241             break;
2242         case CR_VENDOR_NEC_FIRMWARE_REVISION:
2243             event.type = 48; /* NEC reply */
2244             event.length = 0x3025;
2245             break;
2246         case CR_VENDOR_NEC_CHALLENGE_RESPONSE:
2247         {
2248             uint32_t chi = trb.parameter >> 32;
2249             uint32_t clo = trb.parameter;
2250             uint32_t val = xhci_nec_challenge(chi, clo);
2251             event.length = val & 0xFFFF;
2252             event.epid = val >> 16;
2253             slotid = val >> 24;
2254             event.type = 48; /* NEC reply */
2255         }
2256         break;
2257         default:
2258             fprintf(stderr, "xhci: unimplemented command %d\n", type);
2259             event.ccode = CC_TRB_ERROR;
2260             break;
2261         }
2262         event.slotid = slotid;
2263         xhci_event(xhci, &event);
2264     }
2265 }
2266 
2267 static void xhci_update_port(XHCIState *xhci, XHCIPort *port, int is_detach)
2268 {
2269     int nr = port->port.index + 1;
2270 
2271     port->portsc = PORTSC_PP;
2272     if (port->port.dev && port->port.dev->attached && !is_detach) {
2273         port->portsc |= PORTSC_CCS;
2274         switch (port->port.dev->speed) {
2275         case USB_SPEED_LOW:
2276             port->portsc |= PORTSC_SPEED_LOW;
2277             break;
2278         case USB_SPEED_FULL:
2279             port->portsc |= PORTSC_SPEED_FULL;
2280             break;
2281         case USB_SPEED_HIGH:
2282             port->portsc |= PORTSC_SPEED_HIGH;
2283             break;
2284         }
2285     }
2286 
2287     if (xhci_running(xhci)) {
2288         port->portsc |= PORTSC_CSC;
2289         XHCIEvent ev = { ER_PORT_STATUS_CHANGE, CC_SUCCESS, nr << 24};
2290         xhci_event(xhci, &ev);
2291         DPRINTF("xhci: port change event for port %d\n", nr);
2292     }
2293 }
2294 
2295 static void xhci_reset(DeviceState *dev)
2296 {
2297     XHCIState *xhci = DO_UPCAST(XHCIState, pci_dev.qdev, dev);
2298     int i;
2299 
2300     trace_usb_xhci_reset();
2301     if (!(xhci->usbsts & USBSTS_HCH)) {
2302         fprintf(stderr, "xhci: reset while running!\n");
2303     }
2304 
2305     xhci->usbcmd = 0;
2306     xhci->usbsts = USBSTS_HCH;
2307     xhci->dnctrl = 0;
2308     xhci->crcr_low = 0;
2309     xhci->crcr_high = 0;
2310     xhci->dcbaap_low = 0;
2311     xhci->dcbaap_high = 0;
2312     xhci->config = 0;
2313     xhci->devaddr = 2;
2314 
2315     for (i = 0; i < MAXSLOTS; i++) {
2316         xhci_disable_slot(xhci, i+1);
2317     }
2318 
2319     for (i = 0; i < MAXPORTS; i++) {
2320         xhci_update_port(xhci, xhci->ports + i, 0);
2321     }
2322 
2323     xhci->mfindex = 0;
2324     xhci->iman = 0;
2325     xhci->imod = 0;
2326     xhci->erstsz = 0;
2327     xhci->erstba_low = 0;
2328     xhci->erstba_high = 0;
2329     xhci->erdp_low = 0;
2330     xhci->erdp_high = 0;
2331 
2332     xhci->er_ep_idx = 0;
2333     xhci->er_pcs = 1;
2334     xhci->er_full = 0;
2335     xhci->ev_buffer_put = 0;
2336     xhci->ev_buffer_get = 0;
2337 }
2338 
2339 static uint32_t xhci_cap_read(XHCIState *xhci, uint32_t reg)
2340 {
2341     uint32_t ret;
2342 
2343     switch (reg) {
2344     case 0x00: /* HCIVERSION, CAPLENGTH */
2345         ret = 0x01000000 | LEN_CAP;
2346         break;
2347     case 0x04: /* HCSPARAMS 1 */
2348         ret = (MAXPORTS<<24) | (MAXINTRS<<8) | MAXSLOTS;
2349         break;
2350     case 0x08: /* HCSPARAMS 2 */
2351         ret = 0x0000000f;
2352         break;
2353     case 0x0c: /* HCSPARAMS 3 */
2354         ret = 0x00000000;
2355         break;
2356     case 0x10: /* HCCPARAMS */
2357         if (sizeof(dma_addr_t) == 4) {
2358             ret = 0x00081000;
2359         } else {
2360             ret = 0x00081001;
2361         }
2362         break;
2363     case 0x14: /* DBOFF */
2364         ret = OFF_DOORBELL;
2365         break;
2366     case 0x18: /* RTSOFF */
2367         ret = OFF_RUNTIME;
2368         break;
2369 
2370     /* extended capabilities */
2371     case 0x20: /* Supported Protocol:00 */
2372         ret = 0x02000402; /* USB 2.0 */
2373         break;
2374     case 0x24: /* Supported Protocol:04 */
2375         ret = 0x20425455; /* "USB " */
2376         break;
2377     case 0x28: /* Supported Protocol:08 */
2378         ret = 0x00000001 | (USB2_PORTS<<8);
2379         break;
2380     case 0x2c: /* Supported Protocol:0c */
2381         ret = 0x00000000; /* reserved */
2382         break;
2383     case 0x30: /* Supported Protocol:00 */
2384         ret = 0x03000002; /* USB 3.0 */
2385         break;
2386     case 0x34: /* Supported Protocol:04 */
2387         ret = 0x20425455; /* "USB " */
2388         break;
2389     case 0x38: /* Supported Protocol:08 */
2390         ret = 0x00000000 | (USB2_PORTS+1) | (USB3_PORTS<<8);
2391         break;
2392     case 0x3c: /* Supported Protocol:0c */
2393         ret = 0x00000000; /* reserved */
2394         break;
2395     default:
2396         fprintf(stderr, "xhci_cap_read: reg %d unimplemented\n", reg);
2397         ret = 0;
2398     }
2399 
2400     trace_usb_xhci_cap_read(reg, ret);
2401     return ret;
2402 }
2403 
2404 static uint32_t xhci_port_read(XHCIState *xhci, uint32_t reg)
2405 {
2406     uint32_t port = reg >> 4;
2407     uint32_t ret;
2408 
2409     if (port >= MAXPORTS) {
2410         fprintf(stderr, "xhci_port_read: port %d out of bounds\n", port);
2411         ret = 0;
2412         goto out;
2413     }
2414 
2415     switch (reg & 0xf) {
2416     case 0x00: /* PORTSC */
2417         ret = xhci->ports[port].portsc;
2418         break;
2419     case 0x04: /* PORTPMSC */
2420     case 0x08: /* PORTLI */
2421         ret = 0;
2422         break;
2423     case 0x0c: /* reserved */
2424     default:
2425         fprintf(stderr, "xhci_port_read (port %d): reg 0x%x unimplemented\n",
2426                 port, reg);
2427         ret = 0;
2428     }
2429 
2430 out:
2431     trace_usb_xhci_port_read(port, reg & 0x0f, ret);
2432     return ret;
2433 }
2434 
2435 static void xhci_port_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2436 {
2437     uint32_t port = reg >> 4;
2438     uint32_t portsc;
2439 
2440     trace_usb_xhci_port_write(port, reg & 0x0f, val);
2441 
2442     if (port >= MAXPORTS) {
2443         fprintf(stderr, "xhci_port_read: port %d out of bounds\n", port);
2444         return;
2445     }
2446 
2447     switch (reg & 0xf) {
2448     case 0x00: /* PORTSC */
2449         portsc = xhci->ports[port].portsc;
2450         /* write-1-to-clear bits*/
2451         portsc &= ~(val & (PORTSC_CSC|PORTSC_PEC|PORTSC_WRC|PORTSC_OCC|
2452                            PORTSC_PRC|PORTSC_PLC|PORTSC_CEC));
2453         if (val & PORTSC_LWS) {
2454             /* overwrite PLS only when LWS=1 */
2455             portsc &= ~(PORTSC_PLS_MASK << PORTSC_PLS_SHIFT);
2456             portsc |= val & (PORTSC_PLS_MASK << PORTSC_PLS_SHIFT);
2457         }
2458         /* read/write bits */
2459         portsc &= ~(PORTSC_PP|PORTSC_WCE|PORTSC_WDE|PORTSC_WOE);
2460         portsc |= (val & (PORTSC_PP|PORTSC_WCE|PORTSC_WDE|PORTSC_WOE));
2461         /* write-1-to-start bits */
2462         if (val & PORTSC_PR) {
2463             DPRINTF("xhci: port %d reset\n", port);
2464             usb_device_reset(xhci->ports[port].port.dev);
2465             portsc |= PORTSC_PRC | PORTSC_PED;
2466         }
2467         xhci->ports[port].portsc = portsc;
2468         break;
2469     case 0x04: /* PORTPMSC */
2470     case 0x08: /* PORTLI */
2471     default:
2472         fprintf(stderr, "xhci_port_write (port %d): reg 0x%x unimplemented\n",
2473                 port, reg);
2474     }
2475 }
2476 
2477 static uint32_t xhci_oper_read(XHCIState *xhci, uint32_t reg)
2478 {
2479     uint32_t ret;
2480 
2481     if (reg >= 0x400) {
2482         return xhci_port_read(xhci, reg - 0x400);
2483     }
2484 
2485     switch (reg) {
2486     case 0x00: /* USBCMD */
2487         ret = xhci->usbcmd;
2488         break;
2489     case 0x04: /* USBSTS */
2490         ret = xhci->usbsts;
2491         break;
2492     case 0x08: /* PAGESIZE */
2493         ret = 1; /* 4KiB */
2494         break;
2495     case 0x14: /* DNCTRL */
2496         ret = xhci->dnctrl;
2497         break;
2498     case 0x18: /* CRCR low */
2499         ret = xhci->crcr_low & ~0xe;
2500         break;
2501     case 0x1c: /* CRCR high */
2502         ret = xhci->crcr_high;
2503         break;
2504     case 0x30: /* DCBAAP low */
2505         ret = xhci->dcbaap_low;
2506         break;
2507     case 0x34: /* DCBAAP high */
2508         ret = xhci->dcbaap_high;
2509         break;
2510     case 0x38: /* CONFIG */
2511         ret = xhci->config;
2512         break;
2513     default:
2514         fprintf(stderr, "xhci_oper_read: reg 0x%x unimplemented\n", reg);
2515         ret = 0;
2516     }
2517 
2518     trace_usb_xhci_oper_read(reg, ret);
2519     return ret;
2520 }
2521 
2522 static void xhci_oper_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2523 {
2524     if (reg >= 0x400) {
2525         xhci_port_write(xhci, reg - 0x400, val);
2526         return;
2527     }
2528 
2529     trace_usb_xhci_oper_write(reg, val);
2530 
2531     switch (reg) {
2532     case 0x00: /* USBCMD */
2533         if ((val & USBCMD_RS) && !(xhci->usbcmd & USBCMD_RS)) {
2534             xhci_run(xhci);
2535         } else if (!(val & USBCMD_RS) && (xhci->usbcmd & USBCMD_RS)) {
2536             xhci_stop(xhci);
2537         }
2538         xhci->usbcmd = val & 0xc0f;
2539         if (val & USBCMD_HCRST) {
2540             xhci_reset(&xhci->pci_dev.qdev);
2541         }
2542         xhci_irq_update(xhci);
2543         break;
2544 
2545     case 0x04: /* USBSTS */
2546         /* these bits are write-1-to-clear */
2547         xhci->usbsts &= ~(val & (USBSTS_HSE|USBSTS_EINT|USBSTS_PCD|USBSTS_SRE));
2548         xhci_irq_update(xhci);
2549         break;
2550 
2551     case 0x14: /* DNCTRL */
2552         xhci->dnctrl = val & 0xffff;
2553         break;
2554     case 0x18: /* CRCR low */
2555         xhci->crcr_low = (val & 0xffffffcf) | (xhci->crcr_low & CRCR_CRR);
2556         break;
2557     case 0x1c: /* CRCR high */
2558         xhci->crcr_high = val;
2559         if (xhci->crcr_low & (CRCR_CA|CRCR_CS) && (xhci->crcr_low & CRCR_CRR)) {
2560             XHCIEvent event = {ER_COMMAND_COMPLETE, CC_COMMAND_RING_STOPPED};
2561             xhci->crcr_low &= ~CRCR_CRR;
2562             xhci_event(xhci, &event);
2563             DPRINTF("xhci: command ring stopped (CRCR=%08x)\n", xhci->crcr_low);
2564         } else {
2565             dma_addr_t base = xhci_addr64(xhci->crcr_low & ~0x3f, val);
2566             xhci_ring_init(xhci, &xhci->cmd_ring, base);
2567         }
2568         xhci->crcr_low &= ~(CRCR_CA | CRCR_CS);
2569         break;
2570     case 0x30: /* DCBAAP low */
2571         xhci->dcbaap_low = val & 0xffffffc0;
2572         break;
2573     case 0x34: /* DCBAAP high */
2574         xhci->dcbaap_high = val;
2575         break;
2576     case 0x38: /* CONFIG */
2577         xhci->config = val & 0xff;
2578         break;
2579     default:
2580         fprintf(stderr, "xhci_oper_write: reg 0x%x unimplemented\n", reg);
2581     }
2582 }
2583 
2584 static uint32_t xhci_runtime_read(XHCIState *xhci, uint32_t reg)
2585 {
2586     uint32_t ret;
2587 
2588     switch (reg) {
2589     case 0x00: /* MFINDEX */
2590         fprintf(stderr, "xhci_runtime_read: MFINDEX not yet implemented\n");
2591         ret = xhci->mfindex;
2592         break;
2593     case 0x20: /* IMAN */
2594         ret = xhci->iman;
2595         break;
2596     case 0x24: /* IMOD */
2597         ret = xhci->imod;
2598         break;
2599     case 0x28: /* ERSTSZ */
2600         ret = xhci->erstsz;
2601         break;
2602     case 0x30: /* ERSTBA low */
2603         ret = xhci->erstba_low;
2604         break;
2605     case 0x34: /* ERSTBA high */
2606         ret = xhci->erstba_high;
2607         break;
2608     case 0x38: /* ERDP low */
2609         ret = xhci->erdp_low;
2610         break;
2611     case 0x3c: /* ERDP high */
2612         ret = xhci->erdp_high;
2613         break;
2614     default:
2615         fprintf(stderr, "xhci_runtime_read: reg 0x%x unimplemented\n", reg);
2616         ret = 0;
2617     }
2618 
2619     trace_usb_xhci_runtime_read(reg, ret);
2620     return ret;
2621 }
2622 
2623 static void xhci_runtime_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2624 {
2625     trace_usb_xhci_runtime_read(reg, val);
2626 
2627     switch (reg) {
2628     case 0x20: /* IMAN */
2629         if (val & IMAN_IP) {
2630             xhci->iman &= ~IMAN_IP;
2631         }
2632         xhci->iman &= ~IMAN_IE;
2633         xhci->iman |= val & IMAN_IE;
2634         xhci_irq_update(xhci);
2635         break;
2636     case 0x24: /* IMOD */
2637         xhci->imod = val;
2638         break;
2639     case 0x28: /* ERSTSZ */
2640         xhci->erstsz = val & 0xffff;
2641         break;
2642     case 0x30: /* ERSTBA low */
2643         /* XXX NEC driver bug: it doesn't align this to 64 bytes
2644         xhci->erstba_low = val & 0xffffffc0; */
2645         xhci->erstba_low = val & 0xfffffff0;
2646         break;
2647     case 0x34: /* ERSTBA high */
2648         xhci->erstba_high = val;
2649         xhci_er_reset(xhci);
2650         break;
2651     case 0x38: /* ERDP low */
2652         if (val & ERDP_EHB) {
2653             xhci->erdp_low &= ~ERDP_EHB;
2654         }
2655         xhci->erdp_low = (val & ~ERDP_EHB) | (xhci->erdp_low & ERDP_EHB);
2656         break;
2657     case 0x3c: /* ERDP high */
2658         xhci->erdp_high = val;
2659         xhci_events_update(xhci);
2660         break;
2661     default:
2662         fprintf(stderr, "xhci_oper_write: reg 0x%x unimplemented\n", reg);
2663     }
2664 }
2665 
2666 static uint32_t xhci_doorbell_read(XHCIState *xhci, uint32_t reg)
2667 {
2668     /* doorbells always read as 0 */
2669     trace_usb_xhci_doorbell_read(reg, 0);
2670     return 0;
2671 }
2672 
2673 static void xhci_doorbell_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2674 {
2675     trace_usb_xhci_doorbell_write(reg, val);
2676 
2677     if (!xhci_running(xhci)) {
2678         fprintf(stderr, "xhci: wrote doorbell while xHC stopped or paused\n");
2679         return;
2680     }
2681 
2682     reg >>= 2;
2683 
2684     if (reg == 0) {
2685         if (val == 0) {
2686             xhci_process_commands(xhci);
2687         } else {
2688             fprintf(stderr, "xhci: bad doorbell 0 write: 0x%x\n", val);
2689         }
2690     } else {
2691         if (reg > MAXSLOTS) {
2692             fprintf(stderr, "xhci: bad doorbell %d\n", reg);
2693         } else if (val > 31) {
2694             fprintf(stderr, "xhci: bad doorbell %d write: 0x%x\n", reg, val);
2695         } else {
2696             xhci_kick_ep(xhci, reg, val);
2697         }
2698     }
2699 }
2700 
2701 static uint64_t xhci_mem_read(void *ptr, target_phys_addr_t addr,
2702                               unsigned size)
2703 {
2704     XHCIState *xhci = ptr;
2705 
2706     /* Only aligned reads are allowed on xHCI */
2707     if (addr & 3) {
2708         fprintf(stderr, "xhci_mem_read: Mis-aligned read\n");
2709         return 0;
2710     }
2711 
2712     if (addr < LEN_CAP) {
2713         return xhci_cap_read(xhci, addr);
2714     } else if (addr >= OFF_OPER && addr < (OFF_OPER + LEN_OPER)) {
2715         return xhci_oper_read(xhci, addr - OFF_OPER);
2716     } else if (addr >= OFF_RUNTIME && addr < (OFF_RUNTIME + LEN_RUNTIME)) {
2717         return xhci_runtime_read(xhci, addr - OFF_RUNTIME);
2718     } else if (addr >= OFF_DOORBELL && addr < (OFF_DOORBELL + LEN_DOORBELL)) {
2719         return xhci_doorbell_read(xhci, addr - OFF_DOORBELL);
2720     } else {
2721         fprintf(stderr, "xhci_mem_read: Bad offset %x\n", (int)addr);
2722         return 0;
2723     }
2724 }
2725 
2726 static void xhci_mem_write(void *ptr, target_phys_addr_t addr,
2727                            uint64_t val, unsigned size)
2728 {
2729     XHCIState *xhci = ptr;
2730 
2731     /* Only aligned writes are allowed on xHCI */
2732     if (addr & 3) {
2733         fprintf(stderr, "xhci_mem_write: Mis-aligned write\n");
2734         return;
2735     }
2736 
2737     if (addr >= OFF_OPER && addr < (OFF_OPER + LEN_OPER)) {
2738         xhci_oper_write(xhci, addr - OFF_OPER, val);
2739     } else if (addr >= OFF_RUNTIME && addr < (OFF_RUNTIME + LEN_RUNTIME)) {
2740         xhci_runtime_write(xhci, addr - OFF_RUNTIME, val);
2741     } else if (addr >= OFF_DOORBELL && addr < (OFF_DOORBELL + LEN_DOORBELL)) {
2742         xhci_doorbell_write(xhci, addr - OFF_DOORBELL, val);
2743     } else {
2744         fprintf(stderr, "xhci_mem_write: Bad offset %x\n", (int)addr);
2745     }
2746 }
2747 
2748 static const MemoryRegionOps xhci_mem_ops = {
2749     .read = xhci_mem_read,
2750     .write = xhci_mem_write,
2751     .valid.min_access_size = 4,
2752     .valid.max_access_size = 4,
2753     .endianness = DEVICE_LITTLE_ENDIAN,
2754 };
2755 
2756 static void xhci_attach(USBPort *usbport)
2757 {
2758     XHCIState *xhci = usbport->opaque;
2759     XHCIPort *port = &xhci->ports[usbport->index];
2760 
2761     xhci_update_port(xhci, port, 0);
2762 }
2763 
2764 static void xhci_detach(USBPort *usbport)
2765 {
2766     XHCIState *xhci = usbport->opaque;
2767     XHCIPort *port = &xhci->ports[usbport->index];
2768 
2769     xhci_update_port(xhci, port, 1);
2770 }
2771 
2772 static void xhci_wakeup(USBPort *usbport)
2773 {
2774     XHCIState *xhci = usbport->opaque;
2775     XHCIPort *port = &xhci->ports[usbport->index];
2776     int nr = port->port.index + 1;
2777     XHCIEvent ev = { ER_PORT_STATUS_CHANGE, CC_SUCCESS, nr << 24};
2778     uint32_t pls;
2779 
2780     pls = (port->portsc >> PORTSC_PLS_SHIFT) & PORTSC_PLS_MASK;
2781     if (pls != 3) {
2782         return;
2783     }
2784     port->portsc |= 0xf << PORTSC_PLS_SHIFT;
2785     if (port->portsc & PORTSC_PLC) {
2786         return;
2787     }
2788     port->portsc |= PORTSC_PLC;
2789     xhci_event(xhci, &ev);
2790 }
2791 
2792 static void xhci_complete(USBPort *port, USBPacket *packet)
2793 {
2794     XHCITransfer *xfer = container_of(packet, XHCITransfer, packet);
2795 
2796     xhci_complete_packet(xfer, packet->result);
2797     xhci_kick_ep(xfer->xhci, xfer->slotid, xfer->epid);
2798 }
2799 
2800 static void xhci_child_detach(USBPort *port, USBDevice *child)
2801 {
2802     FIXME();
2803 }
2804 
2805 static USBPortOps xhci_port_ops = {
2806     .attach   = xhci_attach,
2807     .detach   = xhci_detach,
2808     .wakeup   = xhci_wakeup,
2809     .complete = xhci_complete,
2810     .child_detach = xhci_child_detach,
2811 };
2812 
2813 static int xhci_find_slotid(XHCIState *xhci, USBDevice *dev)
2814 {
2815     XHCISlot *slot;
2816     int slotid;
2817 
2818     for (slotid = 1; slotid <= MAXSLOTS; slotid++) {
2819         slot = &xhci->slots[slotid-1];
2820         if (slot->devaddr == dev->addr) {
2821             return slotid;
2822         }
2823     }
2824     return 0;
2825 }
2826 
2827 static int xhci_find_epid(USBEndpoint *ep)
2828 {
2829     if (ep->nr == 0) {
2830         return 1;
2831     }
2832     if (ep->pid == USB_TOKEN_IN) {
2833         return ep->nr * 2 + 1;
2834     } else {
2835         return ep->nr * 2;
2836     }
2837 }
2838 
2839 static void xhci_wakeup_endpoint(USBBus *bus, USBEndpoint *ep)
2840 {
2841     XHCIState *xhci = container_of(bus, XHCIState, bus);
2842     int slotid;
2843 
2844     DPRINTF("%s\n", __func__);
2845     slotid = xhci_find_slotid(xhci, ep->dev);
2846     if (slotid == 0 || !xhci->slots[slotid-1].enabled) {
2847         DPRINTF("%s: oops, no slot for dev %d\n", __func__, ep->dev->addr);
2848         return;
2849     }
2850     xhci_kick_ep(xhci, slotid, xhci_find_epid(ep));
2851 }
2852 
2853 static USBBusOps xhci_bus_ops = {
2854     .wakeup_endpoint = xhci_wakeup_endpoint,
2855 };
2856 
2857 static void usb_xhci_init(XHCIState *xhci, DeviceState *dev)
2858 {
2859     int i;
2860 
2861     xhci->usbsts = USBSTS_HCH;
2862 
2863     usb_bus_new(&xhci->bus, &xhci_bus_ops, &xhci->pci_dev.qdev);
2864 
2865     for (i = 0; i < MAXPORTS; i++) {
2866         memset(&xhci->ports[i], 0, sizeof(xhci->ports[i]));
2867         usb_register_port(&xhci->bus, &xhci->ports[i].port, xhci, i,
2868                           &xhci_port_ops,
2869                           USB_SPEED_MASK_LOW  |
2870                           USB_SPEED_MASK_FULL |
2871                           USB_SPEED_MASK_HIGH);
2872     }
2873     for (i = 0; i < MAXSLOTS; i++) {
2874         xhci->slots[i].enabled = 0;
2875     }
2876 }
2877 
2878 static int usb_xhci_initfn(struct PCIDevice *dev)
2879 {
2880     int ret;
2881 
2882     XHCIState *xhci = DO_UPCAST(XHCIState, pci_dev, dev);
2883 
2884     xhci->pci_dev.config[PCI_CLASS_PROG] = 0x30;    /* xHCI */
2885     xhci->pci_dev.config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin 1 */
2886     xhci->pci_dev.config[PCI_CACHE_LINE_SIZE] = 0x10;
2887     xhci->pci_dev.config[0x60] = 0x30; /* release number */
2888 
2889     usb_xhci_init(xhci, &dev->qdev);
2890 
2891     xhci->irq = xhci->pci_dev.irq[0];
2892 
2893     memory_region_init_io(&xhci->mem, &xhci_mem_ops, xhci,
2894                           "xhci", LEN_REGS);
2895     pci_register_bar(&xhci->pci_dev, 0,
2896                      PCI_BASE_ADDRESS_SPACE_MEMORY|PCI_BASE_ADDRESS_MEM_TYPE_64,
2897                      &xhci->mem);
2898 
2899     ret = pcie_cap_init(&xhci->pci_dev, 0xa0, PCI_EXP_TYPE_ENDPOINT, 0);
2900     assert(ret >= 0);
2901 
2902     if (xhci->msi) {
2903         ret = msi_init(&xhci->pci_dev, 0x70, 1, true, false);
2904         assert(ret >= 0);
2905     }
2906 
2907     return 0;
2908 }
2909 
2910 static void xhci_write_config(PCIDevice *dev, uint32_t addr, uint32_t val,
2911                               int len)
2912 {
2913     XHCIState *xhci = DO_UPCAST(XHCIState, pci_dev, dev);
2914 
2915     pci_default_write_config(dev, addr, val, len);
2916     if (xhci->msi) {
2917         msi_write_config(dev, addr, val, len);
2918     }
2919 }
2920 
2921 static const VMStateDescription vmstate_xhci = {
2922     .name = "xhci",
2923     .unmigratable = 1,
2924 };
2925 
2926 static Property xhci_properties[] = {
2927     DEFINE_PROP_UINT32("msi", XHCIState, msi, 0),
2928     DEFINE_PROP_END_OF_LIST(),
2929 };
2930 
2931 static void xhci_class_init(ObjectClass *klass, void *data)
2932 {
2933     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
2934     DeviceClass *dc = DEVICE_CLASS(klass);
2935 
2936     dc->vmsd    = &vmstate_xhci;
2937     dc->props   = xhci_properties;
2938     dc->reset   = xhci_reset;
2939     k->init         = usb_xhci_initfn;
2940     k->vendor_id    = PCI_VENDOR_ID_NEC;
2941     k->device_id    = PCI_DEVICE_ID_NEC_UPD720200;
2942     k->class_id     = PCI_CLASS_SERIAL_USB;
2943     k->revision     = 0x03;
2944     k->is_express   = 1;
2945     k->config_write = xhci_write_config;
2946 }
2947 
2948 static TypeInfo xhci_info = {
2949     .name          = "nec-usb-xhci",
2950     .parent        = TYPE_PCI_DEVICE,
2951     .instance_size = sizeof(XHCIState),
2952     .class_init    = xhci_class_init,
2953 };
2954 
2955 static void xhci_register_types(void)
2956 {
2957     type_register_static(&xhci_info);
2958 }
2959 
2960 type_init(xhci_register_types)
2961