hcd-xhci.c 96.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * USB xHCI controller emulation
 *
 * Copyright (c) 2011 Securiforest
 * Date: 2011-05-11 ;  Author: Hector Martin <hector@marcansoft.com>
 * Based on usb-ohci.c, emulates Renesas NEC USB 3.0
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
 */
G
Gerd Hoffmann 已提交
21
#include "hw/hw.h"
22
#include "qemu/timer.h"
G
Gerd Hoffmann 已提交
23
#include "hw/usb.h"
24 25 26
#include "hw/pci/pci.h"
#include "hw/pci/msi.h"
#include "hw/pci/msix.h"
G
Gerd Hoffmann 已提交
27
#include "trace.h"
28 29 30 31 32 33 34 35 36

//#define DEBUG_XHCI
//#define DEBUG_DATA

#ifdef DEBUG_XHCI
#define DPRINTF(...) fprintf(stderr, __VA_ARGS__)
#else
#define DPRINTF(...) do {} while (0)
#endif
G
Gerd Hoffmann 已提交
37 38
#define FIXME(_msg) do { fprintf(stderr, "FIXME %s:%d %s\n", \
                                 __func__, __LINE__, _msg); abort(); } while (0)
39

G
Gerd Hoffmann 已提交
40 41
#define MAXPORTS_2 15
#define MAXPORTS_3 15
42

G
Gerd Hoffmann 已提交
43
#define MAXPORTS (MAXPORTS_2+MAXPORTS_3)
G
Gerd Hoffmann 已提交
44 45
#define MAXSLOTS 64
#define MAXINTRS 16
46 47 48 49 50 51 52 53 54 55 56

#define TD_QUEUE 24

/* Very pessimistic, let's hope it's enough for all cases */
#define EV_QUEUE (((3*TD_QUEUE)+16)*MAXSLOTS)
/* Do not deliver ER Full events. NEC's driver does some things not bound
 * to the specs when it gets them */
#define ER_FULL_HACK

#define LEN_CAP         0x40
#define LEN_OPER        (0x400 + 0x10 * MAXPORTS)
G
Gerd Hoffmann 已提交
57
#define LEN_RUNTIME     ((MAXINTRS + 1) * 0x20)
58 59
#define LEN_DOORBELL    ((MAXSLOTS + 1) * 0x20)

G
Gerd Hoffmann 已提交
60 61 62
#define OFF_OPER        LEN_CAP
#define OFF_RUNTIME     0x1000
#define OFF_DOORBELL    0x2000
G
Gerd Hoffmann 已提交
63 64
#define OFF_MSIX_TABLE  0x3000
#define OFF_MSIX_PBA    0x3800
65
/* must be power of 2 */
G
Gerd Hoffmann 已提交
66
#define LEN_REGS        0x4000
67

G
Gerd Hoffmann 已提交
68 69 70 71 72 73
#if (OFF_OPER + LEN_OPER) > OFF_RUNTIME
#error Increase OFF_RUNTIME
#endif
#if (OFF_RUNTIME + LEN_RUNTIME) > OFF_DOORBELL
#error Increase OFF_DOORBELL
#endif
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
#if (OFF_DOORBELL + LEN_DOORBELL) > LEN_REGS
# error Increase LEN_REGS
#endif

/* bit definitions */
#define USBCMD_RS       (1<<0)
#define USBCMD_HCRST    (1<<1)
#define USBCMD_INTE     (1<<2)
#define USBCMD_HSEE     (1<<3)
#define USBCMD_LHCRST   (1<<7)
#define USBCMD_CSS      (1<<8)
#define USBCMD_CRS      (1<<9)
#define USBCMD_EWE      (1<<10)
#define USBCMD_EU3S     (1<<11)

#define USBSTS_HCH      (1<<0)
#define USBSTS_HSE      (1<<2)
#define USBSTS_EINT     (1<<3)
#define USBSTS_PCD      (1<<4)
#define USBSTS_SSS      (1<<8)
#define USBSTS_RSS      (1<<9)
#define USBSTS_SRE      (1<<10)
#define USBSTS_CNR      (1<<11)
#define USBSTS_HCE      (1<<12)


#define PORTSC_CCS          (1<<0)
#define PORTSC_PED          (1<<1)
#define PORTSC_OCA          (1<<3)
#define PORTSC_PR           (1<<4)
#define PORTSC_PLS_SHIFT        5
#define PORTSC_PLS_MASK     0xf
#define PORTSC_PP           (1<<9)
#define PORTSC_SPEED_SHIFT      10
#define PORTSC_SPEED_MASK   0xf
#define PORTSC_SPEED_FULL   (1<<10)
#define PORTSC_SPEED_LOW    (2<<10)
#define PORTSC_SPEED_HIGH   (3<<10)
#define PORTSC_SPEED_SUPER  (4<<10)
#define PORTSC_PIC_SHIFT        14
#define PORTSC_PIC_MASK     0x3
#define PORTSC_LWS          (1<<16)
#define PORTSC_CSC          (1<<17)
#define PORTSC_PEC          (1<<18)
#define PORTSC_WRC          (1<<19)
#define PORTSC_OCC          (1<<20)
#define PORTSC_PRC          (1<<21)
#define PORTSC_PLC          (1<<22)
#define PORTSC_CEC          (1<<23)
#define PORTSC_CAS          (1<<24)
#define PORTSC_WCE          (1<<25)
#define PORTSC_WDE          (1<<26)
#define PORTSC_WOE          (1<<27)
#define PORTSC_DR           (1<<30)
#define PORTSC_WPR          (1<<31)

#define CRCR_RCS        (1<<0)
#define CRCR_CS         (1<<1)
#define CRCR_CA         (1<<2)
#define CRCR_CRR        (1<<3)

#define IMAN_IP         (1<<0)
#define IMAN_IE         (1<<1)

#define ERDP_EHB        (1<<3)

#define TRB_SIZE 16
typedef struct XHCITRB {
    uint64_t parameter;
    uint32_t status;
    uint32_t control;
145
    dma_addr_t addr;
146 147 148
    bool ccs;
} XHCITRB;

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
enum {
    PLS_U0              =  0,
    PLS_U1              =  1,
    PLS_U2              =  2,
    PLS_U3              =  3,
    PLS_DISABLED        =  4,
    PLS_RX_DETECT       =  5,
    PLS_INACTIVE        =  6,
    PLS_POLLING         =  7,
    PLS_RECOVERY        =  8,
    PLS_HOT_RESET       =  9,
    PLS_COMPILANCE_MODE = 10,
    PLS_TEST_MODE       = 11,
    PLS_RESUME          = 15,
};
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277

typedef enum TRBType {
    TRB_RESERVED = 0,
    TR_NORMAL,
    TR_SETUP,
    TR_DATA,
    TR_STATUS,
    TR_ISOCH,
    TR_LINK,
    TR_EVDATA,
    TR_NOOP,
    CR_ENABLE_SLOT,
    CR_DISABLE_SLOT,
    CR_ADDRESS_DEVICE,
    CR_CONFIGURE_ENDPOINT,
    CR_EVALUATE_CONTEXT,
    CR_RESET_ENDPOINT,
    CR_STOP_ENDPOINT,
    CR_SET_TR_DEQUEUE,
    CR_RESET_DEVICE,
    CR_FORCE_EVENT,
    CR_NEGOTIATE_BW,
    CR_SET_LATENCY_TOLERANCE,
    CR_GET_PORT_BANDWIDTH,
    CR_FORCE_HEADER,
    CR_NOOP,
    ER_TRANSFER = 32,
    ER_COMMAND_COMPLETE,
    ER_PORT_STATUS_CHANGE,
    ER_BANDWIDTH_REQUEST,
    ER_DOORBELL,
    ER_HOST_CONTROLLER,
    ER_DEVICE_NOTIFICATION,
    ER_MFINDEX_WRAP,
    /* vendor specific bits */
    CR_VENDOR_VIA_CHALLENGE_RESPONSE = 48,
    CR_VENDOR_NEC_FIRMWARE_REVISION  = 49,
    CR_VENDOR_NEC_CHALLENGE_RESPONSE = 50,
} TRBType;

#define CR_LINK TR_LINK

typedef enum TRBCCode {
    CC_INVALID = 0,
    CC_SUCCESS,
    CC_DATA_BUFFER_ERROR,
    CC_BABBLE_DETECTED,
    CC_USB_TRANSACTION_ERROR,
    CC_TRB_ERROR,
    CC_STALL_ERROR,
    CC_RESOURCE_ERROR,
    CC_BANDWIDTH_ERROR,
    CC_NO_SLOTS_ERROR,
    CC_INVALID_STREAM_TYPE_ERROR,
    CC_SLOT_NOT_ENABLED_ERROR,
    CC_EP_NOT_ENABLED_ERROR,
    CC_SHORT_PACKET,
    CC_RING_UNDERRUN,
    CC_RING_OVERRUN,
    CC_VF_ER_FULL,
    CC_PARAMETER_ERROR,
    CC_BANDWIDTH_OVERRUN,
    CC_CONTEXT_STATE_ERROR,
    CC_NO_PING_RESPONSE_ERROR,
    CC_EVENT_RING_FULL_ERROR,
    CC_INCOMPATIBLE_DEVICE_ERROR,
    CC_MISSED_SERVICE_ERROR,
    CC_COMMAND_RING_STOPPED,
    CC_COMMAND_ABORTED,
    CC_STOPPED,
    CC_STOPPED_LENGTH_INVALID,
    CC_MAX_EXIT_LATENCY_TOO_LARGE_ERROR = 29,
    CC_ISOCH_BUFFER_OVERRUN = 31,
    CC_EVENT_LOST_ERROR,
    CC_UNDEFINED_ERROR,
    CC_INVALID_STREAM_ID_ERROR,
    CC_SECONDARY_BANDWIDTH_ERROR,
    CC_SPLIT_TRANSACTION_ERROR
} TRBCCode;

#define TRB_C               (1<<0)
#define TRB_TYPE_SHIFT          10
#define TRB_TYPE_MASK       0x3f
#define TRB_TYPE(t)         (((t).control >> TRB_TYPE_SHIFT) & TRB_TYPE_MASK)

#define TRB_EV_ED           (1<<2)

#define TRB_TR_ENT          (1<<1)
#define TRB_TR_ISP          (1<<2)
#define TRB_TR_NS           (1<<3)
#define TRB_TR_CH           (1<<4)
#define TRB_TR_IOC          (1<<5)
#define TRB_TR_IDT          (1<<6)
#define TRB_TR_TBC_SHIFT        7
#define TRB_TR_TBC_MASK     0x3
#define TRB_TR_BEI          (1<<9)
#define TRB_TR_TLBPC_SHIFT      16
#define TRB_TR_TLBPC_MASK   0xf
#define TRB_TR_FRAMEID_SHIFT    20
#define TRB_TR_FRAMEID_MASK 0x7ff
#define TRB_TR_SIA          (1<<31)

#define TRB_TR_DIR          (1<<16)

#define TRB_CR_SLOTID_SHIFT     24
#define TRB_CR_SLOTID_MASK  0xff
#define TRB_CR_EPID_SHIFT       16
#define TRB_CR_EPID_MASK    0x1f

#define TRB_CR_BSR          (1<<9)
#define TRB_CR_DC           (1<<9)

#define TRB_LK_TC           (1<<1)

G
Gerd Hoffmann 已提交
278 279 280 281
#define TRB_INTR_SHIFT          22
#define TRB_INTR_MASK       0x3ff
#define TRB_INTR(t)         (((t).status >> TRB_INTR_SHIFT) & TRB_INTR_MASK)

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
#define EP_TYPE_MASK        0x7
#define EP_TYPE_SHIFT           3

#define EP_STATE_MASK       0x7
#define EP_DISABLED         (0<<0)
#define EP_RUNNING          (1<<0)
#define EP_HALTED           (2<<0)
#define EP_STOPPED          (3<<0)
#define EP_ERROR            (4<<0)

#define SLOT_STATE_MASK     0x1f
#define SLOT_STATE_SHIFT        27
#define SLOT_STATE(s)       (((s)>>SLOT_STATE_SHIFT)&SLOT_STATE_MASK)
#define SLOT_ENABLED        0
#define SLOT_DEFAULT        1
#define SLOT_ADDRESSED      2
#define SLOT_CONFIGURED     3

#define SLOT_CONTEXT_ENTRIES_MASK 0x1f
#define SLOT_CONTEXT_ENTRIES_SHIFT 27

303
typedef struct XHCIState XHCIState;
G
Gerd Hoffmann 已提交
304 305
typedef struct XHCIStreamContext XHCIStreamContext;
typedef struct XHCIEPContext XHCIEPContext;
306

307 308 309 310 311 312 313 314 315 316
#define get_field(data, field)                  \
    (((data) >> field##_SHIFT) & field##_MASK)

#define set_field(data, newval, field) do {                     \
        uint32_t val = *data;                                   \
        val &= ~(field##_MASK << field##_SHIFT);                \
        val |= ((newval) & field##_MASK) << field##_SHIFT;      \
        *data = val;                                            \
    } while (0)

317 318 319 320 321 322 323 324 325 326 327 328
typedef enum EPType {
    ET_INVALID = 0,
    ET_ISO_OUT,
    ET_BULK_OUT,
    ET_INTR_OUT,
    ET_CONTROL,
    ET_ISO_IN,
    ET_BULK_IN,
    ET_INTR_IN,
} EPType;

typedef struct XHCIRing {
329 330
    dma_addr_t base;
    dma_addr_t dequeue;
331 332 333 334
    bool ccs;
} XHCIRing;

typedef struct XHCIPort {
335
    XHCIState *xhci;
336
    uint32_t portsc;
G
Gerd Hoffmann 已提交
337 338 339
    uint32_t portnr;
    USBPort  *uport;
    uint32_t speedmask;
340 341
    char name[16];
    MemoryRegion mem;
342 343 344 345 346
} XHCIPort;

typedef struct XHCITransfer {
    XHCIState *xhci;
    USBPacket packet;
G
Gerd Hoffmann 已提交
347
    QEMUSGList sgl;
G
Gerd Hoffmann 已提交
348 349
    bool running_async;
    bool running_retry;
350 351
    bool cancelled;
    bool complete;
352
    bool int_req;
353 354 355
    unsigned int iso_pkts;
    unsigned int slotid;
    unsigned int epid;
G
Gerd Hoffmann 已提交
356
    unsigned int streamid;
357 358 359 360 361 362 363 364 365 366 367 368
    bool in_xfer;
    bool iso_xfer;

    unsigned int trb_count;
    unsigned int trb_alloced;
    XHCITRB *trbs;

    TRBCCode status;

    unsigned int pkts;
    unsigned int pktsize;
    unsigned int cur_pkt;
G
Gerd Hoffmann 已提交
369 370

    uint64_t mfindex_kick;
371 372
} XHCITransfer;

G
Gerd Hoffmann 已提交
373 374 375 376 377 378 379 380
struct XHCIStreamContext {
    dma_addr_t pctx;
    unsigned int sct;
    XHCIRing ring;
    XHCIStreamContext *sstreams;
};

struct XHCIEPContext {
G
Gerd Hoffmann 已提交
381 382 383 384
    XHCIState *xhci;
    unsigned int slotid;
    unsigned int epid;

385 386 387 388
    XHCIRing ring;
    unsigned int next_xfer;
    unsigned int comp_xfer;
    XHCITransfer transfers[TD_QUEUE];
G
Gerd Hoffmann 已提交
389
    XHCITransfer *retry;
390
    EPType type;
391
    dma_addr_t pctx;
392 393
    unsigned int max_psize;
    uint32_t state;
G
Gerd Hoffmann 已提交
394

G
Gerd Hoffmann 已提交
395 396 397 398 399 400
    /* streams */
    unsigned int max_pstreams;
    bool         lsa;
    unsigned int nr_pstreams;
    XHCIStreamContext *pstreams;

G
Gerd Hoffmann 已提交
401 402 403 404
    /* iso xfer scheduling */
    unsigned int interval;
    int64_t mfindex_last;
    QEMUTimer *kick_timer;
G
Gerd Hoffmann 已提交
405
};
406 407 408

typedef struct XHCISlot {
    bool enabled;
409
    dma_addr_t ctx;
410
    USBPort *uport;
411 412 413 414 415 416 417 418 419 420 421 422 423 424
    unsigned int devaddr;
    XHCIEPContext * eps[31];
} XHCISlot;

typedef struct XHCIEvent {
    TRBType type;
    TRBCCode ccode;
    uint64_t ptr;
    uint32_t length;
    uint32_t flags;
    uint8_t slotid;
    uint8_t epid;
} XHCIEvent;

G
Gerd Hoffmann 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
typedef struct XHCIInterrupter {
    uint32_t iman;
    uint32_t imod;
    uint32_t erstsz;
    uint32_t erstba_low;
    uint32_t erstba_high;
    uint32_t erdp_low;
    uint32_t erdp_high;

    bool msix_used, er_pcs, er_full;

    dma_addr_t er_start;
    uint32_t er_size;
    unsigned int er_ep_idx;

    XHCIEvent ev_buffer[EV_QUEUE];
    unsigned int ev_buffer_put;
    unsigned int ev_buffer_get;

} XHCIInterrupter;

446 447 448 449 450
struct XHCIState {
    PCIDevice pci_dev;
    USBBus bus;
    qemu_irq irq;
    MemoryRegion mem;
451 452 453 454
    MemoryRegion mem_cap;
    MemoryRegion mem_oper;
    MemoryRegion mem_runtime;
    MemoryRegion mem_doorbell;
455 456
    unsigned int devaddr;

G
Gerd Hoffmann 已提交
457 458 459
    /* properties */
    uint32_t numports_2;
    uint32_t numports_3;
460 461
    uint32_t numintrs;
    uint32_t numslots;
G
Gerd Hoffmann 已提交
462
    uint32_t flags;
G
Gerd Hoffmann 已提交
463

464 465 466 467 468 469 470 471 472 473
    /* Operational Registers */
    uint32_t usbcmd;
    uint32_t usbsts;
    uint32_t dnctrl;
    uint32_t crcr_low;
    uint32_t crcr_high;
    uint32_t dcbaap_low;
    uint32_t dcbaap_high;
    uint32_t config;

G
Gerd Hoffmann 已提交
474
    USBPort  uports[MAX(MAXPORTS_2, MAXPORTS_3)];
475 476
    XHCIPort ports[MAXPORTS];
    XHCISlot slots[MAXSLOTS];
G
Gerd Hoffmann 已提交
477
    uint32_t numports;
478 479

    /* Runtime Registers */
G
Gerd Hoffmann 已提交
480 481
    int64_t mfindex_start;
    QEMUTimer *mfwrap_timer;
G
Gerd Hoffmann 已提交
482
    XHCIInterrupter intr[MAXINTRS];
483 484 485 486 487 488 489 490 491 492 493

    XHCIRing cmd_ring;
};

typedef struct XHCIEvRingSeg {
    uint32_t addr_low;
    uint32_t addr_high;
    uint32_t size;
    uint32_t rsvd;
} XHCIEvRingSeg;

G
Gerd Hoffmann 已提交
494 495
enum xhci_flags {
    XHCI_FLAG_USE_MSI = 1,
G
Gerd Hoffmann 已提交
496
    XHCI_FLAG_USE_MSI_X,
G
Gerd Hoffmann 已提交
497 498
};

G
Gerd Hoffmann 已提交
499
static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
G
Gerd Hoffmann 已提交
500
                         unsigned int epid, unsigned int streamid);
501 502
static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,
                                unsigned int epid);
G
Gerd Hoffmann 已提交
503 504
static void xhci_event(XHCIState *xhci, XHCIEvent *event, int v);
static void xhci_write_event(XHCIState *xhci, XHCIEvent *event, int v);
G
Gerd Hoffmann 已提交
505

506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
static const char *TRBType_names[] = {
    [TRB_RESERVED]                     = "TRB_RESERVED",
    [TR_NORMAL]                        = "TR_NORMAL",
    [TR_SETUP]                         = "TR_SETUP",
    [TR_DATA]                          = "TR_DATA",
    [TR_STATUS]                        = "TR_STATUS",
    [TR_ISOCH]                         = "TR_ISOCH",
    [TR_LINK]                          = "TR_LINK",
    [TR_EVDATA]                        = "TR_EVDATA",
    [TR_NOOP]                          = "TR_NOOP",
    [CR_ENABLE_SLOT]                   = "CR_ENABLE_SLOT",
    [CR_DISABLE_SLOT]                  = "CR_DISABLE_SLOT",
    [CR_ADDRESS_DEVICE]                = "CR_ADDRESS_DEVICE",
    [CR_CONFIGURE_ENDPOINT]            = "CR_CONFIGURE_ENDPOINT",
    [CR_EVALUATE_CONTEXT]              = "CR_EVALUATE_CONTEXT",
    [CR_RESET_ENDPOINT]                = "CR_RESET_ENDPOINT",
    [CR_STOP_ENDPOINT]                 = "CR_STOP_ENDPOINT",
    [CR_SET_TR_DEQUEUE]                = "CR_SET_TR_DEQUEUE",
    [CR_RESET_DEVICE]                  = "CR_RESET_DEVICE",
    [CR_FORCE_EVENT]                   = "CR_FORCE_EVENT",
    [CR_NEGOTIATE_BW]                  = "CR_NEGOTIATE_BW",
    [CR_SET_LATENCY_TOLERANCE]         = "CR_SET_LATENCY_TOLERANCE",
    [CR_GET_PORT_BANDWIDTH]            = "CR_GET_PORT_BANDWIDTH",
    [CR_FORCE_HEADER]                  = "CR_FORCE_HEADER",
    [CR_NOOP]                          = "CR_NOOP",
    [ER_TRANSFER]                      = "ER_TRANSFER",
    [ER_COMMAND_COMPLETE]              = "ER_COMMAND_COMPLETE",
    [ER_PORT_STATUS_CHANGE]            = "ER_PORT_STATUS_CHANGE",
    [ER_BANDWIDTH_REQUEST]             = "ER_BANDWIDTH_REQUEST",
    [ER_DOORBELL]                      = "ER_DOORBELL",
    [ER_HOST_CONTROLLER]               = "ER_HOST_CONTROLLER",
    [ER_DEVICE_NOTIFICATION]           = "ER_DEVICE_NOTIFICATION",
    [ER_MFINDEX_WRAP]                  = "ER_MFINDEX_WRAP",
    [CR_VENDOR_VIA_CHALLENGE_RESPONSE] = "CR_VENDOR_VIA_CHALLENGE_RESPONSE",
    [CR_VENDOR_NEC_FIRMWARE_REVISION]  = "CR_VENDOR_NEC_FIRMWARE_REVISION",
    [CR_VENDOR_NEC_CHALLENGE_RESPONSE] = "CR_VENDOR_NEC_CHALLENGE_RESPONSE",
};

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
static const char *TRBCCode_names[] = {
    [CC_INVALID]                       = "CC_INVALID",
    [CC_SUCCESS]                       = "CC_SUCCESS",
    [CC_DATA_BUFFER_ERROR]             = "CC_DATA_BUFFER_ERROR",
    [CC_BABBLE_DETECTED]               = "CC_BABBLE_DETECTED",
    [CC_USB_TRANSACTION_ERROR]         = "CC_USB_TRANSACTION_ERROR",
    [CC_TRB_ERROR]                     = "CC_TRB_ERROR",
    [CC_STALL_ERROR]                   = "CC_STALL_ERROR",
    [CC_RESOURCE_ERROR]                = "CC_RESOURCE_ERROR",
    [CC_BANDWIDTH_ERROR]               = "CC_BANDWIDTH_ERROR",
    [CC_NO_SLOTS_ERROR]                = "CC_NO_SLOTS_ERROR",
    [CC_INVALID_STREAM_TYPE_ERROR]     = "CC_INVALID_STREAM_TYPE_ERROR",
    [CC_SLOT_NOT_ENABLED_ERROR]        = "CC_SLOT_NOT_ENABLED_ERROR",
    [CC_EP_NOT_ENABLED_ERROR]          = "CC_EP_NOT_ENABLED_ERROR",
    [CC_SHORT_PACKET]                  = "CC_SHORT_PACKET",
    [CC_RING_UNDERRUN]                 = "CC_RING_UNDERRUN",
    [CC_RING_OVERRUN]                  = "CC_RING_OVERRUN",
    [CC_VF_ER_FULL]                    = "CC_VF_ER_FULL",
    [CC_PARAMETER_ERROR]               = "CC_PARAMETER_ERROR",
    [CC_BANDWIDTH_OVERRUN]             = "CC_BANDWIDTH_OVERRUN",
    [CC_CONTEXT_STATE_ERROR]           = "CC_CONTEXT_STATE_ERROR",
    [CC_NO_PING_RESPONSE_ERROR]        = "CC_NO_PING_RESPONSE_ERROR",
    [CC_EVENT_RING_FULL_ERROR]         = "CC_EVENT_RING_FULL_ERROR",
    [CC_INCOMPATIBLE_DEVICE_ERROR]     = "CC_INCOMPATIBLE_DEVICE_ERROR",
    [CC_MISSED_SERVICE_ERROR]          = "CC_MISSED_SERVICE_ERROR",
    [CC_COMMAND_RING_STOPPED]          = "CC_COMMAND_RING_STOPPED",
    [CC_COMMAND_ABORTED]               = "CC_COMMAND_ABORTED",
    [CC_STOPPED]                       = "CC_STOPPED",
    [CC_STOPPED_LENGTH_INVALID]        = "CC_STOPPED_LENGTH_INVALID",
    [CC_MAX_EXIT_LATENCY_TOO_LARGE_ERROR]
    = "CC_MAX_EXIT_LATENCY_TOO_LARGE_ERROR",
    [CC_ISOCH_BUFFER_OVERRUN]          = "CC_ISOCH_BUFFER_OVERRUN",
    [CC_EVENT_LOST_ERROR]              = "CC_EVENT_LOST_ERROR",
    [CC_UNDEFINED_ERROR]               = "CC_UNDEFINED_ERROR",
    [CC_INVALID_STREAM_ID_ERROR]       = "CC_INVALID_STREAM_ID_ERROR",
    [CC_SECONDARY_BANDWIDTH_ERROR]     = "CC_SECONDARY_BANDWIDTH_ERROR",
    [CC_SPLIT_TRANSACTION_ERROR]       = "CC_SPLIT_TRANSACTION_ERROR",
};

583 584 585 586 587 588 589 590 591 592 593 594 595 596
static const char *lookup_name(uint32_t index, const char **list, uint32_t llen)
{
    if (index >= llen || list[index] == NULL) {
        return "???";
    }
    return list[index];
}

static const char *trb_name(XHCITRB *trb)
{
    return lookup_name(TRB_TYPE(*trb), TRBType_names,
                       ARRAY_SIZE(TRBType_names));
}

597 598 599 600 601 602
static const char *event_name(XHCIEvent *event)
{
    return lookup_name(event->ccode, TRBCCode_names,
                       ARRAY_SIZE(TRBCCode_names));
}

G
Gerd Hoffmann 已提交
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
static uint64_t xhci_mfindex_get(XHCIState *xhci)
{
    int64_t now = qemu_get_clock_ns(vm_clock);
    return (now - xhci->mfindex_start) / 125000;
}

static void xhci_mfwrap_update(XHCIState *xhci)
{
    const uint32_t bits = USBCMD_RS | USBCMD_EWE;
    uint32_t mfindex, left;
    int64_t now;

    if ((xhci->usbcmd & bits) == bits) {
        now = qemu_get_clock_ns(vm_clock);
        mfindex = ((now - xhci->mfindex_start) / 125000) & 0x3fff;
        left = 0x4000 - mfindex;
        qemu_mod_timer(xhci->mfwrap_timer, now + left * 125000);
    } else {
        qemu_del_timer(xhci->mfwrap_timer);
    }
}

static void xhci_mfwrap_timer(void *opaque)
{
    XHCIState *xhci = opaque;
    XHCIEvent wrap = { ER_MFINDEX_WRAP, CC_SUCCESS };

G
Gerd Hoffmann 已提交
630
    xhci_event(xhci, &wrap, 0);
G
Gerd Hoffmann 已提交
631 632
    xhci_mfwrap_update(xhci);
}
633

634
static inline dma_addr_t xhci_addr64(uint32_t low, uint32_t high)
635
{
636 637 638 639 640
    if (sizeof(dma_addr_t) == 4) {
        return low;
    } else {
        return low | (((dma_addr_t)high << 16) << 16);
    }
641 642
}

643
static inline dma_addr_t xhci_mask64(uint64_t addr)
644
{
645 646 647 648 649
    if (sizeof(dma_addr_t) == 4) {
        return addr & 0xffffffff;
    } else {
        return addr;
    }
650 651
}

D
David Gibson 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
static inline void xhci_dma_read_u32s(XHCIState *xhci, dma_addr_t addr,
                                      uint32_t *buf, size_t len)
{
    int i;

    assert((len % sizeof(uint32_t)) == 0);

    pci_dma_read(&xhci->pci_dev, addr, buf, len);

    for (i = 0; i < (len / sizeof(uint32_t)); i++) {
        buf[i] = le32_to_cpu(buf[i]);
    }
}

static inline void xhci_dma_write_u32s(XHCIState *xhci, dma_addr_t addr,
                                       uint32_t *buf, size_t len)
{
    int i;
    uint32_t tmp[len / sizeof(uint32_t)];

    assert((len % sizeof(uint32_t)) == 0);

    for (i = 0; i < (len / sizeof(uint32_t)); i++) {
        tmp[i] = cpu_to_le32(buf[i]);
    }
    pci_dma_write(&xhci->pci_dev, addr, tmp, len);
}

G
Gerd Hoffmann 已提交
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
static XHCIPort *xhci_lookup_port(XHCIState *xhci, struct USBPort *uport)
{
    int index;

    if (!uport->dev) {
        return NULL;
    }
    switch (uport->dev->speed) {
    case USB_SPEED_LOW:
    case USB_SPEED_FULL:
    case USB_SPEED_HIGH:
        index = uport->index;
        break;
    case USB_SPEED_SUPER:
        index = uport->index + xhci->numports_2;
        break;
    default:
        return NULL;
    }
    return &xhci->ports[index];
}

G
Gerd Hoffmann 已提交
702
static void xhci_intx_update(XHCIState *xhci)
703 704 705
{
    int level = 0;

G
Gerd Hoffmann 已提交
706 707
    if (msix_enabled(&xhci->pci_dev) ||
        msi_enabled(&xhci->pci_dev)) {
G
Gerd Hoffmann 已提交
708 709 710
        return;
    }

G
Gerd Hoffmann 已提交
711 712
    if (xhci->intr[0].iman & IMAN_IP &&
        xhci->intr[0].iman & IMAN_IE &&
L
Lai Jiangshan 已提交
713
        xhci->usbcmd & USBCMD_INTE) {
714 715 716
        level = 1;
    }

G
Gerd Hoffmann 已提交
717 718 719 720
    trace_usb_xhci_irq_intx(level);
    qemu_set_irq(xhci->irq, level);
}

G
Gerd Hoffmann 已提交
721
static void xhci_msix_update(XHCIState *xhci, int v)
G
Gerd Hoffmann 已提交
722 723 724 725 726 727 728
{
    bool enabled;

    if (!msix_enabled(&xhci->pci_dev)) {
        return;
    }

G
Gerd Hoffmann 已提交
729 730
    enabled = xhci->intr[v].iman & IMAN_IE;
    if (enabled == xhci->intr[v].msix_used) {
G
Gerd Hoffmann 已提交
731 732 733 734
        return;
    }

    if (enabled) {
G
Gerd Hoffmann 已提交
735 736 737
        trace_usb_xhci_irq_msix_use(v);
        msix_vector_use(&xhci->pci_dev, v);
        xhci->intr[v].msix_used = true;
G
Gerd Hoffmann 已提交
738
    } else {
G
Gerd Hoffmann 已提交
739 740 741
        trace_usb_xhci_irq_msix_unuse(v);
        msix_vector_unuse(&xhci->pci_dev, v);
        xhci->intr[v].msix_used = false;
G
Gerd Hoffmann 已提交
742 743 744
    }
}

G
Gerd Hoffmann 已提交
745
static void xhci_intr_raise(XHCIState *xhci, int v)
G
Gerd Hoffmann 已提交
746
{
G
Gerd Hoffmann 已提交
747 748
    xhci->intr[v].erdp_low |= ERDP_EHB;
    xhci->intr[v].iman |= IMAN_IP;
749 750
    xhci->usbsts |= USBSTS_EINT;

G
Gerd Hoffmann 已提交
751
    if (!(xhci->intr[v].iman & IMAN_IE)) {
G
Gerd Hoffmann 已提交
752 753 754 755 756 757 758
        return;
    }

    if (!(xhci->usbcmd & USBCMD_INTE)) {
        return;
    }

G
Gerd Hoffmann 已提交
759
    if (msix_enabled(&xhci->pci_dev)) {
G
Gerd Hoffmann 已提交
760 761
        trace_usb_xhci_irq_msix(v);
        msix_notify(&xhci->pci_dev, v);
G
Gerd Hoffmann 已提交
762 763 764
        return;
    }

G
Gerd Hoffmann 已提交
765
    if (msi_enabled(&xhci->pci_dev)) {
G
Gerd Hoffmann 已提交
766 767
        trace_usb_xhci_irq_msi(v);
        msi_notify(&xhci->pci_dev, v);
G
Gerd Hoffmann 已提交
768
        return;
769
    }
G
Gerd Hoffmann 已提交
770

G
Gerd Hoffmann 已提交
771 772 773 774
    if (v == 0) {
        trace_usb_xhci_irq_intx(1);
        qemu_set_irq(xhci->irq, 1);
    }
775 776 777 778
}

static inline int xhci_running(XHCIState *xhci)
{
G
Gerd Hoffmann 已提交
779
    return !(xhci->usbsts & USBSTS_HCH) && !xhci->intr[0].er_full;
780 781 782 783 784 785 786 787
}

static void xhci_die(XHCIState *xhci)
{
    xhci->usbsts |= USBSTS_HCE;
    fprintf(stderr, "xhci: asserted controller error\n");
}

G
Gerd Hoffmann 已提交
788
static void xhci_write_event(XHCIState *xhci, XHCIEvent *event, int v)
789
{
G
Gerd Hoffmann 已提交
790
    XHCIInterrupter *intr = &xhci->intr[v];
791
    XHCITRB ev_trb;
792
    dma_addr_t addr;
793 794 795 796 797

    ev_trb.parameter = cpu_to_le64(event->ptr);
    ev_trb.status = cpu_to_le32(event->length | (event->ccode << 24));
    ev_trb.control = (event->slotid << 24) | (event->epid << 16) |
                     event->flags | (event->type << TRB_TYPE_SHIFT);
G
Gerd Hoffmann 已提交
798
    if (intr->er_pcs) {
799 800 801 802
        ev_trb.control |= TRB_C;
    }
    ev_trb.control = cpu_to_le32(ev_trb.control);

G
Gerd Hoffmann 已提交
803
    trace_usb_xhci_queue_event(v, intr->er_ep_idx, trb_name(&ev_trb),
804 805
                               event_name(event), ev_trb.parameter,
                               ev_trb.status, ev_trb.control);
806

G
Gerd Hoffmann 已提交
807
    addr = intr->er_start + TRB_SIZE*intr->er_ep_idx;
808
    pci_dma_write(&xhci->pci_dev, addr, &ev_trb, TRB_SIZE);
809

G
Gerd Hoffmann 已提交
810 811 812 813
    intr->er_ep_idx++;
    if (intr->er_ep_idx >= intr->er_size) {
        intr->er_ep_idx = 0;
        intr->er_pcs = !intr->er_pcs;
814 815 816
    }
}

G
Gerd Hoffmann 已提交
817
static void xhci_events_update(XHCIState *xhci, int v)
818
{
G
Gerd Hoffmann 已提交
819
    XHCIInterrupter *intr = &xhci->intr[v];
820
    dma_addr_t erdp;
821 822 823 824 825 826 827
    unsigned int dp_idx;
    bool do_irq = 0;

    if (xhci->usbsts & USBSTS_HCH) {
        return;
    }

G
Gerd Hoffmann 已提交
828 829 830
    erdp = xhci_addr64(intr->erdp_low, intr->erdp_high);
    if (erdp < intr->er_start ||
        erdp >= (intr->er_start + TRB_SIZE*intr->er_size)) {
831
        fprintf(stderr, "xhci: ERDP out of bounds: "DMA_ADDR_FMT"\n", erdp);
G
Gerd Hoffmann 已提交
832 833
        fprintf(stderr, "xhci: ER[%d] at "DMA_ADDR_FMT" len %d\n",
                v, intr->er_start, intr->er_size);
834 835 836
        xhci_die(xhci);
        return;
    }
G
Gerd Hoffmann 已提交
837 838
    dp_idx = (erdp - intr->er_start) / TRB_SIZE;
    assert(dp_idx < intr->er_size);
839 840 841 842

    /* NEC didn't read section 4.9.4 of the spec (v1.0 p139 top Note) and thus
     * deadlocks when the ER is full. Hack it by holding off events until
     * the driver decides to free at least half of the ring */
G
Gerd Hoffmann 已提交
843 844
    if (intr->er_full) {
        int er_free = dp_idx - intr->er_ep_idx;
845
        if (er_free <= 0) {
G
Gerd Hoffmann 已提交
846
            er_free += intr->er_size;
847
        }
G
Gerd Hoffmann 已提交
848
        if (er_free < (intr->er_size/2)) {
849 850 851 852 853 854
            DPRINTF("xhci_events_update(): event ring still "
                    "more than half full (hack)\n");
            return;
        }
    }

G
Gerd Hoffmann 已提交
855 856 857
    while (intr->ev_buffer_put != intr->ev_buffer_get) {
        assert(intr->er_full);
        if (((intr->er_ep_idx+1) % intr->er_size) == dp_idx) {
858 859 860
            DPRINTF("xhci_events_update(): event ring full again\n");
#ifndef ER_FULL_HACK
            XHCIEvent full = {ER_HOST_CONTROLLER, CC_EVENT_RING_FULL_ERROR};
G
Gerd Hoffmann 已提交
861
            xhci_write_event(xhci, &full, v);
862 863 864 865
#endif
            do_irq = 1;
            break;
        }
G
Gerd Hoffmann 已提交
866 867 868
        XHCIEvent *event = &intr->ev_buffer[intr->ev_buffer_get];
        xhci_write_event(xhci, event, v);
        intr->ev_buffer_get++;
869
        do_irq = 1;
G
Gerd Hoffmann 已提交
870 871
        if (intr->ev_buffer_get == EV_QUEUE) {
            intr->ev_buffer_get = 0;
872 873 874 875
        }
    }

    if (do_irq) {
G
Gerd Hoffmann 已提交
876
        xhci_intr_raise(xhci, v);
877 878
    }

G
Gerd Hoffmann 已提交
879
    if (intr->er_full && intr->ev_buffer_put == intr->ev_buffer_get) {
880
        DPRINTF("xhci_events_update(): event ring no longer full\n");
G
Gerd Hoffmann 已提交
881
        intr->er_full = 0;
882 883 884
    }
}

G
Gerd Hoffmann 已提交
885
static void xhci_event(XHCIState *xhci, XHCIEvent *event, int v)
886
{
G
Gerd Hoffmann 已提交
887
    XHCIInterrupter *intr;
888
    dma_addr_t erdp;
889 890
    unsigned int dp_idx;

891 892
    if (v >= xhci->numintrs) {
        DPRINTF("intr nr out of range (%d >= %d)\n", v, xhci->numintrs);
G
Gerd Hoffmann 已提交
893 894 895 896
        return;
    }
    intr = &xhci->intr[v];

G
Gerd Hoffmann 已提交
897
    if (intr->er_full) {
898
        DPRINTF("xhci_event(): ER full, queueing\n");
G
Gerd Hoffmann 已提交
899
        if (((intr->ev_buffer_put+1) % EV_QUEUE) == intr->ev_buffer_get) {
900 901 902
            fprintf(stderr, "xhci: event queue full, dropping event!\n");
            return;
        }
G
Gerd Hoffmann 已提交
903 904 905
        intr->ev_buffer[intr->ev_buffer_put++] = *event;
        if (intr->ev_buffer_put == EV_QUEUE) {
            intr->ev_buffer_put = 0;
906 907 908 909
        }
        return;
    }

G
Gerd Hoffmann 已提交
910 911 912
    erdp = xhci_addr64(intr->erdp_low, intr->erdp_high);
    if (erdp < intr->er_start ||
        erdp >= (intr->er_start + TRB_SIZE*intr->er_size)) {
913
        fprintf(stderr, "xhci: ERDP out of bounds: "DMA_ADDR_FMT"\n", erdp);
G
Gerd Hoffmann 已提交
914 915
        fprintf(stderr, "xhci: ER[%d] at "DMA_ADDR_FMT" len %d\n",
                v, intr->er_start, intr->er_size);
916 917 918 919
        xhci_die(xhci);
        return;
    }

G
Gerd Hoffmann 已提交
920 921
    dp_idx = (erdp - intr->er_start) / TRB_SIZE;
    assert(dp_idx < intr->er_size);
922

G
Gerd Hoffmann 已提交
923
    if ((intr->er_ep_idx+1) % intr->er_size == dp_idx) {
924 925 926 927 928
        DPRINTF("xhci_event(): ER full, queueing\n");
#ifndef ER_FULL_HACK
        XHCIEvent full = {ER_HOST_CONTROLLER, CC_EVENT_RING_FULL_ERROR};
        xhci_write_event(xhci, &full);
#endif
G
Gerd Hoffmann 已提交
929 930
        intr->er_full = 1;
        if (((intr->ev_buffer_put+1) % EV_QUEUE) == intr->ev_buffer_get) {
931 932 933
            fprintf(stderr, "xhci: event queue full, dropping event!\n");
            return;
        }
G
Gerd Hoffmann 已提交
934 935 936
        intr->ev_buffer[intr->ev_buffer_put++] = *event;
        if (intr->ev_buffer_put == EV_QUEUE) {
            intr->ev_buffer_put = 0;
937 938
        }
    } else {
G
Gerd Hoffmann 已提交
939
        xhci_write_event(xhci, event, v);
940 941
    }

G
Gerd Hoffmann 已提交
942
    xhci_intr_raise(xhci, v);
943 944 945
}

static void xhci_ring_init(XHCIState *xhci, XHCIRing *ring,
946
                           dma_addr_t base)
947 948 949 950 951 952 953
{
    ring->base = base;
    ring->dequeue = base;
    ring->ccs = 1;
}

static TRBType xhci_ring_fetch(XHCIState *xhci, XHCIRing *ring, XHCITRB *trb,
954
                               dma_addr_t *addr)
955 956 957
{
    while (1) {
        TRBType type;
958
        pci_dma_read(&xhci->pci_dev, ring->dequeue, trb, TRB_SIZE);
959 960 961 962 963 964
        trb->addr = ring->dequeue;
        trb->ccs = ring->ccs;
        le64_to_cpus(&trb->parameter);
        le32_to_cpus(&trb->status);
        le32_to_cpus(&trb->control);

G
Gerd Hoffmann 已提交
965 966
        trace_usb_xhci_fetch_trb(ring->dequeue, trb_name(trb),
                                 trb->parameter, trb->status, trb->control);
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992

        if ((trb->control & TRB_C) != ring->ccs) {
            return 0;
        }

        type = TRB_TYPE(*trb);

        if (type != TR_LINK) {
            if (addr) {
                *addr = ring->dequeue;
            }
            ring->dequeue += TRB_SIZE;
            return type;
        } else {
            ring->dequeue = xhci_mask64(trb->parameter);
            if (trb->control & TRB_LK_TC) {
                ring->ccs = !ring->ccs;
            }
        }
    }
}

static int xhci_ring_chain_length(XHCIState *xhci, const XHCIRing *ring)
{
    XHCITRB trb;
    int length = 0;
993
    dma_addr_t dequeue = ring->dequeue;
994 995 996 997 998 999
    bool ccs = ring->ccs;
    /* hack to bundle together the two/three TDs that make a setup transfer */
    bool control_td_set = 0;

    while (1) {
        TRBType type;
1000
        pci_dma_read(&xhci->pci_dev, dequeue, &trb, TRB_SIZE);
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
        le64_to_cpus(&trb.parameter);
        le32_to_cpus(&trb.status);
        le32_to_cpus(&trb.control);

        if ((trb.control & TRB_C) != ccs) {
            return -length;
        }

        type = TRB_TYPE(trb);

        if (type == TR_LINK) {
            dequeue = xhci_mask64(trb.parameter);
            if (trb.control & TRB_LK_TC) {
                ccs = !ccs;
            }
            continue;
        }

        length += 1;
        dequeue += TRB_SIZE;

        if (type == TR_SETUP) {
            control_td_set = 1;
        } else if (type == TR_STATUS) {
            control_td_set = 0;
        }

        if (!control_td_set && !(trb.control & TRB_TR_CH)) {
            return length;
        }
    }
}

G
Gerd Hoffmann 已提交
1034
static void xhci_er_reset(XHCIState *xhci, int v)
1035
{
G
Gerd Hoffmann 已提交
1036
    XHCIInterrupter *intr = &xhci->intr[v];
1037 1038
    XHCIEvRingSeg seg;

G
Gerd Hoffmann 已提交
1039 1040 1041 1042 1043 1044
    if (intr->erstsz == 0) {
        /* disabled */
        intr->er_start = 0;
        intr->er_size = 0;
        return;
    }
1045
    /* cache the (sole) event ring segment location */
G
Gerd Hoffmann 已提交
1046 1047
    if (intr->erstsz != 1) {
        fprintf(stderr, "xhci: invalid value for ERSTSZ: %d\n", intr->erstsz);
1048 1049 1050
        xhci_die(xhci);
        return;
    }
G
Gerd Hoffmann 已提交
1051
    dma_addr_t erstba = xhci_addr64(intr->erstba_low, intr->erstba_high);
1052
    pci_dma_read(&xhci->pci_dev, erstba, &seg, sizeof(seg));
1053 1054 1055 1056 1057 1058 1059 1060
    le32_to_cpus(&seg.addr_low);
    le32_to_cpus(&seg.addr_high);
    le32_to_cpus(&seg.size);
    if (seg.size < 16 || seg.size > 4096) {
        fprintf(stderr, "xhci: invalid value for segment size: %d\n", seg.size);
        xhci_die(xhci);
        return;
    }
G
Gerd Hoffmann 已提交
1061 1062
    intr->er_start = xhci_addr64(seg.addr_low, seg.addr_high);
    intr->er_size = seg.size;
1063

G
Gerd Hoffmann 已提交
1064 1065 1066
    intr->er_ep_idx = 0;
    intr->er_pcs = 1;
    intr->er_full = 0;
1067

G
Gerd Hoffmann 已提交
1068 1069
    DPRINTF("xhci: event ring[%d]:" DMA_ADDR_FMT " [%d]\n",
            v, intr->er_start, intr->er_size);
1070 1071 1072 1073
}

static void xhci_run(XHCIState *xhci)
{
G
Gerd Hoffmann 已提交
1074
    trace_usb_xhci_run();
1075
    xhci->usbsts &= ~USBSTS_HCH;
G
Gerd Hoffmann 已提交
1076
    xhci->mfindex_start = qemu_get_clock_ns(vm_clock);
1077 1078 1079 1080
}

static void xhci_stop(XHCIState *xhci)
{
G
Gerd Hoffmann 已提交
1081
    trace_usb_xhci_stop();
1082 1083 1084 1085
    xhci->usbsts |= USBSTS_HCH;
    xhci->crcr_low &= ~CRCR_CRR;
}

G
Gerd Hoffmann 已提交
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
static XHCIStreamContext *xhci_alloc_stream_contexts(unsigned count,
                                                     dma_addr_t base)
{
    XHCIStreamContext *stctx;
    unsigned int i;

    stctx = g_new0(XHCIStreamContext, count);
    for (i = 0; i < count; i++) {
        stctx[i].pctx = base + i * 16;
        stctx[i].sct = -1;
    }
    return stctx;
}

static void xhci_reset_streams(XHCIEPContext *epctx)
{
    unsigned int i;

    for (i = 0; i < epctx->nr_pstreams; i++) {
        epctx->pstreams[i].sct = -1;
        g_free(epctx->pstreams[i].sstreams);
    }
}

static void xhci_alloc_streams(XHCIEPContext *epctx, dma_addr_t base)
{
    assert(epctx->pstreams == NULL);
    epctx->nr_pstreams = 2 << epctx->max_pstreams;
    epctx->pstreams = xhci_alloc_stream_contexts(epctx->nr_pstreams, base);
}

static void xhci_free_streams(XHCIEPContext *epctx)
{
    int i;

    assert(epctx->pstreams != NULL);

    if (!epctx->lsa) {
        for (i = 0; i < epctx->nr_pstreams; i++) {
            g_free(epctx->pstreams[i].sstreams);
        }
    }
    g_free(epctx->pstreams);
    epctx->pstreams = NULL;
    epctx->nr_pstreams = 0;
}

static XHCIStreamContext *xhci_find_stream(XHCIEPContext *epctx,
                                           unsigned int streamid,
                                           uint32_t *cc_error)
{
    XHCIStreamContext *sctx;
    dma_addr_t base;
    uint32_t ctx[2], sct;

    assert(streamid != 0);
    if (epctx->lsa) {
        if (streamid >= epctx->nr_pstreams) {
            *cc_error = CC_INVALID_STREAM_ID_ERROR;
            return NULL;
        }
        sctx = epctx->pstreams + streamid;
    } else {
        FIXME("secondary streams not implemented yet");
    }

    if (sctx->sct == -1) {
        xhci_dma_read_u32s(epctx->xhci, sctx->pctx, ctx, sizeof(ctx));
1154 1155
        fprintf(stderr, "%s: init sctx #%d @ " DMA_ADDR_FMT ": %08x %08x\n",
                __func__, streamid, sctx->pctx, ctx[0], ctx[1]);
G
Gerd Hoffmann 已提交
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
        sct = (ctx[0] >> 1) & 0x07;
        if (epctx->lsa && sct != 1) {
            *cc_error = CC_INVALID_STREAM_TYPE_ERROR;
            return NULL;
        }
        sctx->sct = sct;
        base = xhci_addr64(ctx[0] & ~0xf, ctx[1]);
        xhci_ring_init(epctx->xhci, &sctx->ring, base);
    }
    return sctx;
}

1168
static void xhci_set_ep_state(XHCIState *xhci, XHCIEPContext *epctx,
G
Gerd Hoffmann 已提交
1169
                              XHCIStreamContext *sctx, uint32_t state)
1170 1171
{
    uint32_t ctx[5];
G
Gerd Hoffmann 已提交
1172
    uint32_t ctx2[2];
1173

D
David Gibson 已提交
1174
    xhci_dma_read_u32s(xhci, epctx->pctx, ctx, sizeof(ctx));
1175 1176
    ctx[0] &= ~EP_STATE_MASK;
    ctx[0] |= state;
G
Gerd Hoffmann 已提交
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193

    /* update ring dequeue ptr */
    if (epctx->nr_pstreams) {
        if (sctx != NULL) {
            xhci_dma_read_u32s(xhci, sctx->pctx, ctx2, sizeof(ctx2));
            ctx2[0] &= 0xe;
            ctx2[0] |= sctx->ring.dequeue | sctx->ring.ccs;
            ctx2[1] = (sctx->ring.dequeue >> 16) >> 16;
            xhci_dma_write_u32s(xhci, sctx->pctx, ctx2, sizeof(ctx2));
        }
    } else {
        ctx[2] = epctx->ring.dequeue | epctx->ring.ccs;
        ctx[3] = (epctx->ring.dequeue >> 16) >> 16;
        DPRINTF("xhci: set epctx: " DMA_ADDR_FMT " state=%d dequeue=%08x%08x\n",
                epctx->pctx, state, ctx[3], ctx[2]);
    }

D
David Gibson 已提交
1194
    xhci_dma_write_u32s(xhci, epctx->pctx, ctx, sizeof(ctx));
1195 1196 1197
    epctx->state = state;
}

G
Gerd Hoffmann 已提交
1198 1199 1200
static void xhci_ep_kick_timer(void *opaque)
{
    XHCIEPContext *epctx = opaque;
G
Gerd Hoffmann 已提交
1201
    xhci_kick_ep(epctx->xhci, epctx->slotid, epctx->epid, 0);
G
Gerd Hoffmann 已提交
1202 1203
}

1204
static TRBCCode xhci_enable_ep(XHCIState *xhci, unsigned int slotid,
1205
                               unsigned int epid, dma_addr_t pctx,
1206 1207 1208 1209
                               uint32_t *ctx)
{
    XHCISlot *slot;
    XHCIEPContext *epctx;
1210
    dma_addr_t dequeue;
1211 1212
    int i;

G
Gerd Hoffmann 已提交
1213
    trace_usb_xhci_ep_enable(slotid, epid);
1214
    assert(slotid >= 1 && slotid <= xhci->numslots);
1215 1216 1217 1218
    assert(epid >= 1 && epid <= 31);

    slot = &xhci->slots[slotid-1];
    if (slot->eps[epid-1]) {
1219
        xhci_disable_ep(xhci, slotid, epid);
1220 1221 1222 1223
    }

    epctx = g_malloc(sizeof(XHCIEPContext));
    memset(epctx, 0, sizeof(XHCIEPContext));
G
Gerd Hoffmann 已提交
1224 1225 1226
    epctx->xhci = xhci;
    epctx->slotid = slotid;
    epctx->epid = epid;
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236

    slot->eps[epid-1] = epctx;

    dequeue = xhci_addr64(ctx[2] & ~0xf, ctx[3]);

    epctx->type = (ctx[1] >> EP_TYPE_SHIFT) & EP_TYPE_MASK;
    DPRINTF("xhci: endpoint %d.%d type is %d\n", epid/2, epid%2, epctx->type);
    epctx->pctx = pctx;
    epctx->max_psize = ctx[1]>>16;
    epctx->max_psize *= 1+((ctx[1]>>8)&0xff);
G
Gerd Hoffmann 已提交
1237 1238
    epctx->max_pstreams = (ctx[0] >> 10) & 0xf;
    epctx->lsa = (ctx[0] >> 15) & 1;
1239 1240
    DPRINTF("xhci: endpoint %d.%d max transaction (burst) size is %d\n",
            epid/2, epid%2, epctx->max_psize);
G
Gerd Hoffmann 已提交
1241 1242 1243 1244 1245 1246
    if (epctx->max_pstreams) {
        xhci_alloc_streams(epctx, dequeue);
    } else {
        xhci_ring_init(xhci, &epctx->ring, dequeue);
        epctx->ring.ccs = ctx[2] & 1;
    }
1247 1248 1249 1250
    for (i = 0; i < ARRAY_SIZE(epctx->transfers); i++) {
        usb_packet_init(&epctx->transfers[i].packet);
    }

G
Gerd Hoffmann 已提交
1251 1252 1253 1254
    epctx->interval = 1 << (ctx[0] >> 16) & 0xff;
    epctx->mfindex_last = 0;
    epctx->kick_timer = qemu_new_timer_ns(vm_clock, xhci_ep_kick_timer, epctx);

1255 1256 1257 1258 1259 1260 1261
    epctx->state = EP_RUNNING;
    ctx[0] &= ~EP_STATE_MASK;
    ctx[0] |= EP_RUNNING;

    return CC_SUCCESS;
}

1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
static int xhci_ep_nuke_one_xfer(XHCITransfer *t)
{
    int killed = 0;

    if (t->running_async) {
        usb_cancel_packet(&t->packet);
        t->running_async = 0;
        t->cancelled = 1;
        DPRINTF("xhci: cancelling transfer, waiting for it to complete\n");
        killed = 1;
    }
    if (t->running_retry) {
        XHCIEPContext *epctx = t->xhci->slots[t->slotid-1].eps[t->epid-1];
        if (epctx) {
            epctx->retry = NULL;
            qemu_del_timer(epctx->kick_timer);
        }
        t->running_retry = 0;
    }
    if (t->trbs) {
        g_free(t->trbs);
    }

    t->trbs = NULL;
    t->trb_count = t->trb_alloced = 0;

    return killed;
}

1291 1292 1293 1294 1295 1296
static int xhci_ep_nuke_xfers(XHCIState *xhci, unsigned int slotid,
                               unsigned int epid)
{
    XHCISlot *slot;
    XHCIEPContext *epctx;
    int i, xferi, killed = 0;
1297
    USBEndpoint *ep = NULL;
1298
    assert(slotid >= 1 && slotid <= xhci->numslots);
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
    assert(epid >= 1 && epid <= 31);

    DPRINTF("xhci_ep_nuke_xfers(%d, %d)\n", slotid, epid);

    slot = &xhci->slots[slotid-1];

    if (!slot->eps[epid-1]) {
        return 0;
    }

    epctx = slot->eps[epid-1];

    xferi = epctx->next_xfer;
    for (i = 0; i < TD_QUEUE; i++) {
1313 1314 1315
        if (epctx->transfers[xferi].packet.ep) {
            ep = epctx->transfers[xferi].packet.ep;
        }
1316
        killed += xhci_ep_nuke_one_xfer(&epctx->transfers[xferi]);
G
Gerd Hoffmann 已提交
1317
        epctx->transfers[xferi].packet.ep = NULL;
1318 1319
        xferi = (xferi + 1) % TD_QUEUE;
    }
1320 1321 1322
    if (ep) {
        usb_device_ep_stopped(ep->dev, ep);
    }
1323 1324 1325 1326 1327 1328 1329 1330 1331
    return killed;
}

static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,
                               unsigned int epid)
{
    XHCISlot *slot;
    XHCIEPContext *epctx;

G
Gerd Hoffmann 已提交
1332
    trace_usb_xhci_ep_disable(slotid, epid);
1333
    assert(slotid >= 1 && slotid <= xhci->numslots);
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
    assert(epid >= 1 && epid <= 31);

    slot = &xhci->slots[slotid-1];

    if (!slot->eps[epid-1]) {
        DPRINTF("xhci: slot %d ep %d already disabled\n", slotid, epid);
        return CC_SUCCESS;
    }

    xhci_ep_nuke_xfers(xhci, slotid, epid);

    epctx = slot->eps[epid-1];

G
Gerd Hoffmann 已提交
1347 1348 1349 1350 1351
    if (epctx->nr_pstreams) {
        xhci_free_streams(epctx);
    }

    xhci_set_ep_state(xhci, epctx, NULL, EP_DISABLED);
1352

G
Gerd Hoffmann 已提交
1353
    qemu_free_timer(epctx->kick_timer);
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
    g_free(epctx);
    slot->eps[epid-1] = NULL;

    return CC_SUCCESS;
}

static TRBCCode xhci_stop_ep(XHCIState *xhci, unsigned int slotid,
                             unsigned int epid)
{
    XHCISlot *slot;
    XHCIEPContext *epctx;

G
Gerd Hoffmann 已提交
1366
    trace_usb_xhci_ep_stop(slotid, epid);
1367
    assert(slotid >= 1 && slotid <= xhci->numslots);
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387

    if (epid < 1 || epid > 31) {
        fprintf(stderr, "xhci: bad ep %d\n", epid);
        return CC_TRB_ERROR;
    }

    slot = &xhci->slots[slotid-1];

    if (!slot->eps[epid-1]) {
        DPRINTF("xhci: slot %d ep %d not enabled\n", slotid, epid);
        return CC_EP_NOT_ENABLED_ERROR;
    }

    if (xhci_ep_nuke_xfers(xhci, slotid, epid) > 0) {
        fprintf(stderr, "xhci: FIXME: endpoint stopped w/ xfers running, "
                "data might be lost\n");
    }

    epctx = slot->eps[epid-1];

G
Gerd Hoffmann 已提交
1388 1389 1390 1391 1392
    xhci_set_ep_state(xhci, epctx, NULL, EP_STOPPED);

    if (epctx->nr_pstreams) {
        xhci_reset_streams(epctx);
    }
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403

    return CC_SUCCESS;
}

static TRBCCode xhci_reset_ep(XHCIState *xhci, unsigned int slotid,
                              unsigned int epid)
{
    XHCISlot *slot;
    XHCIEPContext *epctx;
    USBDevice *dev;

G
Gerd Hoffmann 已提交
1404
    trace_usb_xhci_ep_reset(slotid, epid);
1405
    assert(slotid >= 1 && slotid <= xhci->numslots);
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437

    if (epid < 1 || epid > 31) {
        fprintf(stderr, "xhci: bad ep %d\n", epid);
        return CC_TRB_ERROR;
    }

    slot = &xhci->slots[slotid-1];

    if (!slot->eps[epid-1]) {
        DPRINTF("xhci: slot %d ep %d not enabled\n", slotid, epid);
        return CC_EP_NOT_ENABLED_ERROR;
    }

    epctx = slot->eps[epid-1];

    if (epctx->state != EP_HALTED) {
        fprintf(stderr, "xhci: reset EP while EP %d not halted (%d)\n",
                epid, epctx->state);
        return CC_CONTEXT_STATE_ERROR;
    }

    if (xhci_ep_nuke_xfers(xhci, slotid, epid) > 0) {
        fprintf(stderr, "xhci: FIXME: endpoint reset w/ xfers running, "
                "data might be lost\n");
    }

    uint8_t ep = epid>>1;

    if (epid & 1) {
        ep |= 0x80;
    }

1438
    dev = xhci->slots[slotid-1].uport->dev;
1439 1440 1441 1442
    if (!dev) {
        return CC_USB_TRANSACTION_ERROR;
    }

G
Gerd Hoffmann 已提交
1443 1444 1445 1446 1447
    xhci_set_ep_state(xhci, epctx, NULL, EP_STOPPED);

    if (epctx->nr_pstreams) {
        xhci_reset_streams(epctx);
    }
1448 1449 1450 1451 1452

    return CC_SUCCESS;
}

static TRBCCode xhci_set_ep_dequeue(XHCIState *xhci, unsigned int slotid,
G
Gerd Hoffmann 已提交
1453 1454
                                    unsigned int epid, unsigned int streamid,
                                    uint64_t pdequeue)
1455 1456 1457
{
    XHCISlot *slot;
    XHCIEPContext *epctx;
G
Gerd Hoffmann 已提交
1458
    XHCIStreamContext *sctx;
1459
    dma_addr_t dequeue;
1460

1461
    assert(slotid >= 1 && slotid <= xhci->numslots);
1462 1463 1464 1465 1466 1467

    if (epid < 1 || epid > 31) {
        fprintf(stderr, "xhci: bad ep %d\n", epid);
        return CC_TRB_ERROR;
    }

G
Gerd Hoffmann 已提交
1468
    trace_usb_xhci_ep_set_dequeue(slotid, epid, streamid, pdequeue);
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
    dequeue = xhci_mask64(pdequeue);

    slot = &xhci->slots[slotid-1];

    if (!slot->eps[epid-1]) {
        DPRINTF("xhci: slot %d ep %d not enabled\n", slotid, epid);
        return CC_EP_NOT_ENABLED_ERROR;
    }

    epctx = slot->eps[epid-1];

    if (epctx->state != EP_STOPPED) {
        fprintf(stderr, "xhci: set EP dequeue pointer while EP %d not stopped\n", epid);
        return CC_CONTEXT_STATE_ERROR;
    }

G
Gerd Hoffmann 已提交
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
    if (epctx->nr_pstreams) {
        uint32_t err;
        sctx = xhci_find_stream(epctx, streamid, &err);
        if (sctx == NULL) {
            return err;
        }
        xhci_ring_init(xhci, &sctx->ring, dequeue & ~0xf);
        sctx->ring.ccs = dequeue & 1;
    } else {
        sctx = NULL;
        xhci_ring_init(xhci, &epctx->ring, dequeue & ~0xF);
        epctx->ring.ccs = dequeue & 1;
    }
1498

G
Gerd Hoffmann 已提交
1499
    xhci_set_ep_state(xhci, epctx, sctx, EP_STOPPED);
1500 1501 1502 1503

    return CC_SUCCESS;
}

1504
static int xhci_xfer_create_sgl(XHCITransfer *xfer, int in_xfer)
1505 1506
{
    XHCIState *xhci = xfer->xhci;
G
Gerd Hoffmann 已提交
1507
    int i;
1508

1509
    xfer->int_req = false;
G
Gerd Hoffmann 已提交
1510
    pci_dma_sglist_init(&xfer->sgl, &xhci->pci_dev, xfer->trb_count);
1511 1512
    for (i = 0; i < xfer->trb_count; i++) {
        XHCITRB *trb = &xfer->trbs[i];
1513
        dma_addr_t addr;
1514 1515
        unsigned int chunk = 0;

1516 1517 1518 1519
        if (trb->control & TRB_TR_IOC) {
            xfer->int_req = true;
        }

1520 1521 1522 1523
        switch (TRB_TYPE(*trb)) {
        case TR_DATA:
            if ((!(trb->control & TRB_TR_DIR)) != (!in_xfer)) {
                fprintf(stderr, "xhci: data direction mismatch for TR_DATA\n");
G
Gerd Hoffmann 已提交
1524
                goto err;
1525 1526 1527 1528 1529
            }
            /* fallthrough */
        case TR_NORMAL:
        case TR_ISOCH:
            addr = xhci_mask64(trb->parameter);
G
Gerd Hoffmann 已提交
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
            chunk = trb->status & 0x1ffff;
            if (trb->control & TRB_TR_IDT) {
                if (chunk > 8 || in_xfer) {
                    fprintf(stderr, "xhci: invalid immediate data TRB\n");
                    goto err;
                }
                qemu_sglist_add(&xfer->sgl, trb->addr, chunk);
            } else {
                qemu_sglist_add(&xfer->sgl, addr, chunk);
            }
            break;
        }
    }

    return 0;

err:
    qemu_sglist_destroy(&xfer->sgl);
    xhci_die(xhci);
    return -1;
}

static void xhci_xfer_unmap(XHCITransfer *xfer)
{
    usb_packet_unmap(&xfer->packet, &xfer->sgl);
    qemu_sglist_destroy(&xfer->sgl);
}

static void xhci_xfer_report(XHCITransfer *xfer)
{
    uint32_t edtla = 0;
    unsigned int left;
    bool reported = 0;
    bool shortpkt = 0;
    XHCIEvent event = {ER_TRANSFER, CC_SUCCESS};
    XHCIState *xhci = xfer->xhci;
    int i;

1568
    left = xfer->packet.actual_length;
G
Gerd Hoffmann 已提交
1569 1570 1571 1572 1573 1574 1575 1576 1577

    for (i = 0; i < xfer->trb_count; i++) {
        XHCITRB *trb = &xfer->trbs[i];
        unsigned int chunk = 0;

        switch (TRB_TYPE(*trb)) {
        case TR_DATA:
        case TR_NORMAL:
        case TR_ISOCH:
1578 1579 1580
            chunk = trb->status & 0x1ffff;
            if (chunk > left) {
                chunk = left;
G
Gerd Hoffmann 已提交
1581 1582
                if (xfer->status == CC_SUCCESS) {
                    shortpkt = 1;
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
                }
            }
            left -= chunk;
            edtla += chunk;
            break;
        case TR_STATUS:
            reported = 0;
            shortpkt = 0;
            break;
        }

G
Gerd Hoffmann 已提交
1594 1595
        if (!reported && ((trb->control & TRB_TR_IOC) ||
                          (shortpkt && (trb->control & TRB_TR_ISP)) ||
1596
                          (xfer->status != CC_SUCCESS && left == 0))) {
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
            event.slotid = xfer->slotid;
            event.epid = xfer->epid;
            event.length = (trb->status & 0x1ffff) - chunk;
            event.flags = 0;
            event.ptr = trb->addr;
            if (xfer->status == CC_SUCCESS) {
                event.ccode = shortpkt ? CC_SHORT_PACKET : CC_SUCCESS;
            } else {
                event.ccode = xfer->status;
            }
            if (TRB_TYPE(*trb) == TR_EVDATA) {
                event.ptr = trb->parameter;
                event.flags |= TRB_EV_ED;
                event.length = edtla & 0xffffff;
                DPRINTF("xhci_xfer_data: EDTLA=%d\n", event.length);
                edtla = 0;
            }
G
Gerd Hoffmann 已提交
1614
            xhci_event(xhci, &event, TRB_INTR(*trb));
1615
            reported = 1;
G
Gerd Hoffmann 已提交
1616 1617 1618
            if (xfer->status != CC_SUCCESS) {
                return;
            }
1619 1620 1621 1622 1623 1624 1625 1626 1627
        }
    }
}

static void xhci_stall_ep(XHCITransfer *xfer)
{
    XHCIState *xhci = xfer->xhci;
    XHCISlot *slot = &xhci->slots[xfer->slotid-1];
    XHCIEPContext *epctx = slot->eps[xfer->epid-1];
G
Gerd Hoffmann 已提交
1628 1629
    uint32_t err;
    XHCIStreamContext *sctx;
1630

G
Gerd Hoffmann 已提交
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
    if (epctx->nr_pstreams) {
        sctx = xhci_find_stream(epctx, xfer->streamid, &err);
        if (sctx == NULL) {
            return;
        }
        sctx->ring.dequeue = xfer->trbs[0].addr;
        sctx->ring.ccs = xfer->trbs[0].ccs;
        xhci_set_ep_state(xhci, epctx, sctx, EP_HALTED);
    } else {
        epctx->ring.dequeue = xfer->trbs[0].addr;
        epctx->ring.ccs = xfer->trbs[0].ccs;
        xhci_set_ep_state(xhci, epctx, NULL, EP_HALTED);
    }
1644 1645 1646 1647 1648
}

static int xhci_submit(XHCIState *xhci, XHCITransfer *xfer,
                       XHCIEPContext *epctx);

1649 1650 1651 1652
static int xhci_setup_packet(XHCITransfer *xfer)
{
    XHCIState *xhci = xfer->xhci;
    USBDevice *dev;
1653 1654 1655 1656
    USBEndpoint *ep;
    int dir;

    dir = xfer->in_xfer ? USB_TOKEN_IN : USB_TOKEN_OUT;
1657 1658 1659 1660 1661

    if (xfer->packet.ep) {
        ep = xfer->packet.ep;
        dev = ep->dev;
    } else {
1662 1663 1664
        if (!xhci->slots[xfer->slotid-1].uport) {
            fprintf(stderr, "xhci: slot %d has no device\n",
                    xfer->slotid);
1665 1666
            return -1;
        }
1667
        dev = xhci->slots[xfer->slotid-1].uport->dev;
1668 1669 1670
        ep = usb_ep_get(dev, dir, xfer->epid >> 1);
    }

1671
    xhci_xfer_create_sgl(xfer, dir == USB_TOKEN_IN); /* Also sets int_req */
G
Gerd Hoffmann 已提交
1672
    usb_packet_setup(&xfer->packet, dir, ep, xfer->streamid,
G
Gerd Hoffmann 已提交
1673
                     xfer->trbs[0].addr, false, xfer->int_req);
1674
    usb_packet_map(&xfer->packet, &xfer->sgl);
1675
    DPRINTF("xhci: setup packet pid 0x%x addr %d ep %d\n",
1676
            xfer->packet.pid, dev->addr, ep->nr);
1677 1678 1679
    return 0;
}

1680
static int xhci_complete_packet(XHCITransfer *xfer)
1681
{
1682
    if (xfer->packet.status == USB_RET_ASYNC) {
G
Gerd Hoffmann 已提交
1683
        trace_usb_xhci_xfer_async(xfer);
G
Gerd Hoffmann 已提交
1684 1685 1686 1687 1688
        xfer->running_async = 1;
        xfer->running_retry = 0;
        xfer->complete = 0;
        xfer->cancelled = 0;
        return 0;
1689
    } else if (xfer->packet.status == USB_RET_NAK) {
G
Gerd Hoffmann 已提交
1690
        trace_usb_xhci_xfer_nak(xfer);
G
Gerd Hoffmann 已提交
1691 1692
        xfer->running_async = 0;
        xfer->running_retry = 1;
1693 1694 1695 1696
        xfer->complete = 0;
        xfer->cancelled = 0;
        return 0;
    } else {
G
Gerd Hoffmann 已提交
1697 1698
        xfer->running_async = 0;
        xfer->running_retry = 0;
1699
        xfer->complete = 1;
G
Gerd Hoffmann 已提交
1700
        xhci_xfer_unmap(xfer);
1701 1702
    }

1703 1704
    if (xfer->packet.status == USB_RET_SUCCESS) {
        trace_usb_xhci_xfer_success(xfer, xfer->packet.actual_length);
G
Gerd Hoffmann 已提交
1705 1706
        xfer->status = CC_SUCCESS;
        xhci_xfer_report(xfer);
1707 1708 1709 1710
        return 0;
    }

    /* error */
1711 1712
    trace_usb_xhci_xfer_error(xfer, xfer->packet.status);
    switch (xfer->packet.status) {
1713 1714
    case USB_RET_NODEV:
        xfer->status = CC_USB_TRANSACTION_ERROR;
G
Gerd Hoffmann 已提交
1715
        xhci_xfer_report(xfer);
1716 1717 1718 1719
        xhci_stall_ep(xfer);
        break;
    case USB_RET_STALL:
        xfer->status = CC_STALL_ERROR;
G
Gerd Hoffmann 已提交
1720
        xhci_xfer_report(xfer);
1721 1722 1723
        xhci_stall_ep(xfer);
        break;
    default:
1724 1725
        fprintf(stderr, "%s: FIXME: status = %d\n", __func__,
                xfer->packet.status);
G
Gerd Hoffmann 已提交
1726
        FIXME("unhandled USB_RET_*");
1727 1728 1729 1730 1731 1732 1733
    }
    return 0;
}

static int xhci_fire_ctl_transfer(XHCIState *xhci, XHCITransfer *xfer)
{
    XHCITRB *trb_setup, *trb_status;
G
Gerd Hoffmann 已提交
1734
    uint8_t bmRequestType;
1735 1736 1737 1738

    trb_setup = &xfer->trbs[0];
    trb_status = &xfer->trbs[xfer->trb_count-1];

G
Gerd Hoffmann 已提交
1739
    trace_usb_xhci_xfer_start(xfer, xfer->slotid, xfer->epid, xfer->streamid);
G
Gerd Hoffmann 已提交
1740

1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
    /* at most one Event Data TRB allowed after STATUS */
    if (TRB_TYPE(*trb_status) == TR_EVDATA && xfer->trb_count > 2) {
        trb_status--;
    }

    /* do some sanity checks */
    if (TRB_TYPE(*trb_setup) != TR_SETUP) {
        fprintf(stderr, "xhci: ep0 first TD not SETUP: %d\n",
                TRB_TYPE(*trb_setup));
        return -1;
    }
    if (TRB_TYPE(*trb_status) != TR_STATUS) {
        fprintf(stderr, "xhci: ep0 last TD not STATUS: %d\n",
                TRB_TYPE(*trb_status));
        return -1;
    }
    if (!(trb_setup->control & TRB_TR_IDT)) {
        fprintf(stderr, "xhci: Setup TRB doesn't have IDT set\n");
        return -1;
    }
    if ((trb_setup->status & 0x1ffff) != 8) {
        fprintf(stderr, "xhci: Setup TRB has bad length (%d)\n",
                (trb_setup->status & 0x1ffff));
        return -1;
    }

    bmRequestType = trb_setup->parameter;

    xfer->in_xfer = bmRequestType & USB_DIR_IN;
    xfer->iso_xfer = false;

1772 1773 1774
    if (xhci_setup_packet(xfer) < 0) {
        return -1;
    }
G
Gerd Hoffmann 已提交
1775 1776
    xfer->packet.parameter = trb_setup->parameter;

1777
    usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
1778

1779
    xhci_complete_packet(xfer);
G
Gerd Hoffmann 已提交
1780
    if (!xfer->running_async && !xfer->running_retry) {
G
Gerd Hoffmann 已提交
1781
        xhci_kick_ep(xhci, xfer->slotid, xfer->epid, 0);
1782 1783 1784 1785
    }
    return 0;
}

G
Gerd Hoffmann 已提交
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
static void xhci_calc_iso_kick(XHCIState *xhci, XHCITransfer *xfer,
                               XHCIEPContext *epctx, uint64_t mfindex)
{
    if (xfer->trbs[0].control & TRB_TR_SIA) {
        uint64_t asap = ((mfindex + epctx->interval - 1) &
                         ~(epctx->interval-1));
        if (asap >= epctx->mfindex_last &&
            asap <= epctx->mfindex_last + epctx->interval * 4) {
            xfer->mfindex_kick = epctx->mfindex_last + epctx->interval;
        } else {
            xfer->mfindex_kick = asap;
        }
    } else {
        xfer->mfindex_kick = (xfer->trbs[0].control >> TRB_TR_FRAMEID_SHIFT)
            & TRB_TR_FRAMEID_MASK;
        xfer->mfindex_kick |= mfindex & ~0x3fff;
        if (xfer->mfindex_kick < mfindex) {
            xfer->mfindex_kick += 0x4000;
        }
    }
}

static void xhci_check_iso_kick(XHCIState *xhci, XHCITransfer *xfer,
                                XHCIEPContext *epctx, uint64_t mfindex)
{
    if (xfer->mfindex_kick > mfindex) {
        qemu_mod_timer(epctx->kick_timer, qemu_get_clock_ns(vm_clock) +
                       (xfer->mfindex_kick - mfindex) * 125000);
        xfer->running_retry = 1;
    } else {
        epctx->mfindex_last = xfer->mfindex_kick;
        qemu_del_timer(epctx->kick_timer);
        xfer->running_retry = 0;
    }
}


1823 1824
static int xhci_submit(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)
{
G
Gerd Hoffmann 已提交
1825
    uint64_t mfindex;
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835

    DPRINTF("xhci_submit(slotid=%d,epid=%d)\n", xfer->slotid, xfer->epid);

    xfer->in_xfer = epctx->type>>2;

    switch(epctx->type) {
    case ET_INTR_OUT:
    case ET_INTR_IN:
    case ET_BULK_OUT:
    case ET_BULK_IN:
G
Gerd Hoffmann 已提交
1836 1837
        xfer->pkts = 0;
        xfer->iso_xfer = false;
1838 1839 1840
        break;
    case ET_ISO_OUT:
    case ET_ISO_IN:
G
Gerd Hoffmann 已提交
1841 1842 1843 1844 1845 1846 1847 1848
        xfer->pkts = 1;
        xfer->iso_xfer = true;
        mfindex = xhci_mfindex_get(xhci);
        xhci_calc_iso_kick(xhci, xfer, epctx, mfindex);
        xhci_check_iso_kick(xhci, xfer, epctx, mfindex);
        if (xfer->running_retry) {
            return -1;
        }
1849 1850
        break;
    default:
1851 1852 1853
        fprintf(stderr, "xhci: unknown or unhandled EP "
                "(type %d, in %d, ep %02x)\n",
                epctx->type, xfer->in_xfer, xfer->epid);
1854 1855 1856
        return -1;
    }

1857 1858 1859
    if (xhci_setup_packet(xfer) < 0) {
        return -1;
    }
1860
    usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
1861

1862
    xhci_complete_packet(xfer);
G
Gerd Hoffmann 已提交
1863
    if (!xfer->running_async && !xfer->running_retry) {
G
Gerd Hoffmann 已提交
1864
        xhci_kick_ep(xhci, xfer->slotid, xfer->epid, xfer->streamid);
1865 1866 1867 1868 1869 1870
    }
    return 0;
}

static int xhci_fire_transfer(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)
{
G
Gerd Hoffmann 已提交
1871
    trace_usb_xhci_xfer_start(xfer, xfer->slotid, xfer->epid, xfer->streamid);
1872
    return xhci_submit(xhci, xfer, epctx);
1873 1874
}

G
Gerd Hoffmann 已提交
1875 1876
static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
                         unsigned int epid, unsigned int streamid)
1877
{
G
Gerd Hoffmann 已提交
1878
    XHCIStreamContext *stctx;
1879
    XHCIEPContext *epctx;
G
Gerd Hoffmann 已提交
1880
    XHCIRing *ring;
1881
    USBEndpoint *ep = NULL;
G
Gerd Hoffmann 已提交
1882
    uint64_t mfindex;
1883 1884 1885
    int length;
    int i;

G
Gerd Hoffmann 已提交
1886
    trace_usb_xhci_ep_kick(slotid, epid, streamid);
1887
    assert(slotid >= 1 && slotid <= xhci->numslots);
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
    assert(epid >= 1 && epid <= 31);

    if (!xhci->slots[slotid-1].enabled) {
        fprintf(stderr, "xhci: xhci_kick_ep for disabled slot %d\n", slotid);
        return;
    }
    epctx = xhci->slots[slotid-1].eps[epid-1];
    if (!epctx) {
        fprintf(stderr, "xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
                epid, slotid);
        return;
    }

G
Gerd Hoffmann 已提交
1901 1902 1903
    if (epctx->retry) {
        XHCITransfer *xfer = epctx->retry;

G
Gerd Hoffmann 已提交
1904
        trace_usb_xhci_xfer_retry(xfer);
G
Gerd Hoffmann 已提交
1905
        assert(xfer->running_retry);
G
Gerd Hoffmann 已提交
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
        if (xfer->iso_xfer) {
            /* retry delayed iso transfer */
            mfindex = xhci_mfindex_get(xhci);
            xhci_check_iso_kick(xhci, xfer, epctx, mfindex);
            if (xfer->running_retry) {
                return;
            }
            if (xhci_setup_packet(xfer) < 0) {
                return;
            }
1916 1917 1918
            usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
            assert(xfer->packet.status != USB_RET_NAK);
            xhci_complete_packet(xfer);
G
Gerd Hoffmann 已提交
1919 1920 1921 1922 1923
        } else {
            /* retry nak'ed transfer */
            if (xhci_setup_packet(xfer) < 0) {
                return;
            }
1924 1925
            usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
            if (xfer->packet.status == USB_RET_NAK) {
G
Gerd Hoffmann 已提交
1926 1927
                return;
            }
1928
            xhci_complete_packet(xfer);
G
Gerd Hoffmann 已提交
1929 1930 1931 1932 1933
        }
        assert(!xfer->running_retry);
        epctx->retry = NULL;
    }

1934 1935 1936 1937 1938
    if (epctx->state == EP_HALTED) {
        DPRINTF("xhci: ep halted, not running schedule\n");
        return;
    }

G
Gerd Hoffmann 已提交
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953

    if (epctx->nr_pstreams) {
        uint32_t err;
        stctx = xhci_find_stream(epctx, streamid, &err);
        if (stctx == NULL) {
            return;
        }
        ring = &stctx->ring;
        xhci_set_ep_state(xhci, epctx, stctx, EP_RUNNING);
    } else {
        ring = &epctx->ring;
        streamid = 0;
        xhci_set_ep_state(xhci, epctx, NULL, EP_RUNNING);
    }
    assert(ring->base != 0);
1954 1955 1956

    while (1) {
        XHCITransfer *xfer = &epctx->transfers[epctx->next_xfer];
1957
        if (xfer->running_async || xfer->running_retry) {
1958 1959
            break;
        }
G
Gerd Hoffmann 已提交
1960
        length = xhci_ring_chain_length(xhci, ring);
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
        if (length < 0) {
            break;
        } else if (length == 0) {
            break;
        }
        if (xfer->trbs && xfer->trb_alloced < length) {
            xfer->trb_count = 0;
            xfer->trb_alloced = 0;
            g_free(xfer->trbs);
            xfer->trbs = NULL;
        }
        if (!xfer->trbs) {
            xfer->trbs = g_malloc(sizeof(XHCITRB) * length);
            xfer->trb_alloced = length;
        }
        xfer->trb_count = length;

        for (i = 0; i < length; i++) {
G
Gerd Hoffmann 已提交
1979
            assert(xhci_ring_fetch(xhci, ring, &xfer->trbs[i], NULL));
1980 1981 1982 1983
        }
        xfer->xhci = xhci;
        xfer->epid = epid;
        xfer->slotid = slotid;
G
Gerd Hoffmann 已提交
1984
        xfer->streamid = streamid;
1985 1986 1987 1988

        if (epid == 1) {
            if (xhci_fire_ctl_transfer(xhci, xfer) >= 0) {
                epctx->next_xfer = (epctx->next_xfer + 1) % TD_QUEUE;
1989
                ep = xfer->packet.ep;
1990 1991 1992 1993 1994 1995
            } else {
                fprintf(stderr, "xhci: error firing CTL transfer\n");
            }
        } else {
            if (xhci_fire_transfer(xhci, xfer, epctx) >= 0) {
                epctx->next_xfer = (epctx->next_xfer + 1) % TD_QUEUE;
1996
                ep = xfer->packet.ep;
1997
            } else {
G
Gerd Hoffmann 已提交
1998 1999 2000
                if (!xfer->iso_xfer) {
                    fprintf(stderr, "xhci: error firing data transfer\n");
                }
2001 2002 2003
            }
        }

G
Gerd Hoffmann 已提交
2004 2005 2006
        if (epctx->state == EP_HALTED) {
            break;
        }
G
Gerd Hoffmann 已提交
2007 2008 2009 2010 2011
        if (xfer->running_retry) {
            DPRINTF("xhci: xfer nacked, stopping schedule\n");
            epctx->retry = xfer;
            break;
        }
2012
    }
2013 2014 2015
    if (ep) {
        usb_device_flush_ep_queue(ep->dev, ep);
    }
2016 2017 2018 2019
}

static TRBCCode xhci_enable_slot(XHCIState *xhci, unsigned int slotid)
{
G
Gerd Hoffmann 已提交
2020
    trace_usb_xhci_slot_enable(slotid);
2021
    assert(slotid >= 1 && slotid <= xhci->numslots);
2022
    xhci->slots[slotid-1].enabled = 1;
2023
    xhci->slots[slotid-1].uport = NULL;
2024 2025 2026 2027 2028 2029 2030 2031 2032
    memset(xhci->slots[slotid-1].eps, 0, sizeof(XHCIEPContext*)*31);

    return CC_SUCCESS;
}

static TRBCCode xhci_disable_slot(XHCIState *xhci, unsigned int slotid)
{
    int i;

G
Gerd Hoffmann 已提交
2033
    trace_usb_xhci_slot_disable(slotid);
2034
    assert(slotid >= 1 && slotid <= xhci->numslots);
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045

    for (i = 1; i <= 31; i++) {
        if (xhci->slots[slotid-1].eps[i-1]) {
            xhci_disable_ep(xhci, slotid, i);
        }
    }

    xhci->slots[slotid-1].enabled = 0;
    return CC_SUCCESS;
}

2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
static USBPort *xhci_lookup_uport(XHCIState *xhci, uint32_t *slot_ctx)
{
    USBPort *uport;
    char path[32];
    int i, pos, port;

    port = (slot_ctx[1]>>16) & 0xFF;
    port = xhci->ports[port-1].uport->index+1;
    pos = snprintf(path, sizeof(path), "%d", port);
    for (i = 0; i < 5; i++) {
        port = (slot_ctx[0] >> 4*i) & 0x0f;
        if (!port) {
            break;
        }
        pos += snprintf(path + pos, sizeof(path) - pos, ".%d", port);
    }

    QTAILQ_FOREACH(uport, &xhci->bus.used, next) {
        if (strcmp(uport->path, path) == 0) {
            return uport;
        }
    }
    return NULL;
}

2071 2072 2073 2074
static TRBCCode xhci_address_slot(XHCIState *xhci, unsigned int slotid,
                                  uint64_t pictx, bool bsr)
{
    XHCISlot *slot;
2075
    USBPort *uport;
2076
    USBDevice *dev;
2077
    dma_addr_t ictx, octx, dcbaap;
2078 2079 2080 2081 2082 2083 2084
    uint64_t poctx;
    uint32_t ictl_ctx[2];
    uint32_t slot_ctx[4];
    uint32_t ep0_ctx[5];
    int i;
    TRBCCode res;

G
Gerd Hoffmann 已提交
2085
    trace_usb_xhci_slot_address(slotid);
2086
    assert(slotid >= 1 && slotid <= xhci->numslots);
2087 2088

    dcbaap = xhci_addr64(xhci->dcbaap_low, xhci->dcbaap_high);
D
David Gibson 已提交
2089
    poctx = ldq_le_pci_dma(&xhci->pci_dev, dcbaap + 8*slotid);
2090
    ictx = xhci_mask64(pictx);
D
David Gibson 已提交
2091
    octx = xhci_mask64(poctx);
2092

2093 2094
    DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
    DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
2095

D
David Gibson 已提交
2096
    xhci_dma_read_u32s(xhci, ictx, ictl_ctx, sizeof(ictl_ctx));
2097 2098 2099 2100 2101 2102 2103

    if (ictl_ctx[0] != 0x0 || ictl_ctx[1] != 0x3) {
        fprintf(stderr, "xhci: invalid input context control %08x %08x\n",
                ictl_ctx[0], ictl_ctx[1]);
        return CC_TRB_ERROR;
    }

D
David Gibson 已提交
2104 2105
    xhci_dma_read_u32s(xhci, ictx+32, slot_ctx, sizeof(slot_ctx));
    xhci_dma_read_u32s(xhci, ictx+64, ep0_ctx, sizeof(ep0_ctx));
2106 2107 2108 2109 2110 2111 2112

    DPRINTF("xhci: input slot context: %08x %08x %08x %08x\n",
            slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);

    DPRINTF("xhci: input ep0 context: %08x %08x %08x %08x %08x\n",
            ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);

2113 2114 2115
    uport = xhci_lookup_uport(xhci, slot_ctx);
    if (uport == NULL) {
        fprintf(stderr, "xhci: port not found\n");
2116
        return CC_TRB_ERROR;
2117 2118 2119 2120 2121
    }

    dev = uport->dev;
    if (!dev) {
        fprintf(stderr, "xhci: port %s not connected\n", uport->path);
2122 2123 2124
        return CC_USB_TRANSACTION_ERROR;
    }

2125
    for (i = 0; i < xhci->numslots; i++) {
2126 2127 2128
        if (i == slotid-1) {
            continue;
        }
2129 2130 2131
        if (xhci->slots[i].uport == uport) {
            fprintf(stderr, "xhci: port %s already assigned to slot %d\n",
                    uport->path, i+1);
2132 2133 2134 2135 2136
            return CC_TRB_ERROR;
        }
    }

    slot = &xhci->slots[slotid-1];
2137
    slot->uport = uport;
2138 2139 2140 2141 2142
    slot->ctx = octx;

    if (bsr) {
        slot_ctx[3] = SLOT_DEFAULT << SLOT_STATE_SHIFT;
    } else {
2143
        USBPacket p;
2144 2145 2146
        slot->devaddr = xhci->devaddr++;
        slot_ctx[3] = (SLOT_ADDRESSED << SLOT_STATE_SHIFT) | slot->devaddr;
        DPRINTF("xhci: device address is %d\n", slot->devaddr);
2147
        usb_device_reset(dev);
2148
        usb_packet_setup(&p, USB_TOKEN_OUT,
G
Gerd Hoffmann 已提交
2149
                         usb_ep_get(dev, USB_TOKEN_OUT, 0), 0,
2150 2151
                         0, false, false);
        usb_device_handle_control(dev, &p,
2152 2153
                                  DeviceOutRequest | USB_REQ_SET_ADDRESS,
                                  slot->devaddr, 0, 0, NULL);
2154
        assert(p.status != USB_RET_ASYNC);
2155 2156 2157 2158 2159 2160 2161 2162 2163
    }

    res = xhci_enable_ep(xhci, slotid, 1, octx+32, ep0_ctx);

    DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
            slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
    DPRINTF("xhci: output ep0 context: %08x %08x %08x %08x %08x\n",
            ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);

D
David Gibson 已提交
2164 2165
    xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
    xhci_dma_write_u32s(xhci, octx+32, ep0_ctx, sizeof(ep0_ctx));
2166 2167 2168 2169 2170 2171 2172 2173

    return res;
}


static TRBCCode xhci_configure_slot(XHCIState *xhci, unsigned int slotid,
                                  uint64_t pictx, bool dc)
{
2174
    dma_addr_t ictx, octx;
2175 2176 2177 2178 2179 2180 2181
    uint32_t ictl_ctx[2];
    uint32_t slot_ctx[4];
    uint32_t islot_ctx[4];
    uint32_t ep_ctx[5];
    int i;
    TRBCCode res;

G
Gerd Hoffmann 已提交
2182
    trace_usb_xhci_slot_configure(slotid);
2183
    assert(slotid >= 1 && slotid <= xhci->numslots);
2184 2185 2186 2187

    ictx = xhci_mask64(pictx);
    octx = xhci->slots[slotid-1].ctx;

2188 2189
    DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
    DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
2190 2191 2192 2193 2194 2195 2196 2197

    if (dc) {
        for (i = 2; i <= 31; i++) {
            if (xhci->slots[slotid-1].eps[i-1]) {
                xhci_disable_ep(xhci, slotid, i);
            }
        }

D
David Gibson 已提交
2198
        xhci_dma_read_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2199 2200 2201 2202
        slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
        slot_ctx[3] |= SLOT_ADDRESSED << SLOT_STATE_SHIFT;
        DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
                slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
D
David Gibson 已提交
2203
        xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2204 2205 2206 2207

        return CC_SUCCESS;
    }

D
David Gibson 已提交
2208
    xhci_dma_read_u32s(xhci, ictx, ictl_ctx, sizeof(ictl_ctx));
2209 2210 2211 2212 2213 2214 2215

    if ((ictl_ctx[0] & 0x3) != 0x0 || (ictl_ctx[1] & 0x3) != 0x1) {
        fprintf(stderr, "xhci: invalid input context control %08x %08x\n",
                ictl_ctx[0], ictl_ctx[1]);
        return CC_TRB_ERROR;
    }

D
David Gibson 已提交
2216 2217
    xhci_dma_read_u32s(xhci, ictx+32, islot_ctx, sizeof(islot_ctx));
    xhci_dma_read_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228

    if (SLOT_STATE(slot_ctx[3]) < SLOT_ADDRESSED) {
        fprintf(stderr, "xhci: invalid slot state %08x\n", slot_ctx[3]);
        return CC_CONTEXT_STATE_ERROR;
    }

    for (i = 2; i <= 31; i++) {
        if (ictl_ctx[0] & (1<<i)) {
            xhci_disable_ep(xhci, slotid, i);
        }
        if (ictl_ctx[1] & (1<<i)) {
D
David Gibson 已提交
2229
            xhci_dma_read_u32s(xhci, ictx+32+(32*i), ep_ctx, sizeof(ep_ctx));
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
            DPRINTF("xhci: input ep%d.%d context: %08x %08x %08x %08x %08x\n",
                    i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2],
                    ep_ctx[3], ep_ctx[4]);
            xhci_disable_ep(xhci, slotid, i);
            res = xhci_enable_ep(xhci, slotid, i, octx+(32*i), ep_ctx);
            if (res != CC_SUCCESS) {
                return res;
            }
            DPRINTF("xhci: output ep%d.%d context: %08x %08x %08x %08x %08x\n",
                    i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2],
                    ep_ctx[3], ep_ctx[4]);
D
David Gibson 已提交
2241
            xhci_dma_write_u32s(xhci, octx+(32*i), ep_ctx, sizeof(ep_ctx));
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
        }
    }

    slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
    slot_ctx[3] |= SLOT_CONFIGURED << SLOT_STATE_SHIFT;
    slot_ctx[0] &= ~(SLOT_CONTEXT_ENTRIES_MASK << SLOT_CONTEXT_ENTRIES_SHIFT);
    slot_ctx[0] |= islot_ctx[0] & (SLOT_CONTEXT_ENTRIES_MASK <<
                                   SLOT_CONTEXT_ENTRIES_SHIFT);
    DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
            slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);

D
David Gibson 已提交
2253
    xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2254 2255 2256 2257 2258 2259 2260 2261

    return CC_SUCCESS;
}


static TRBCCode xhci_evaluate_slot(XHCIState *xhci, unsigned int slotid,
                                   uint64_t pictx)
{
2262
    dma_addr_t ictx, octx;
2263 2264 2265 2266 2267 2268
    uint32_t ictl_ctx[2];
    uint32_t iep0_ctx[5];
    uint32_t ep0_ctx[5];
    uint32_t islot_ctx[4];
    uint32_t slot_ctx[4];

G
Gerd Hoffmann 已提交
2269
    trace_usb_xhci_slot_evaluate(slotid);
2270
    assert(slotid >= 1 && slotid <= xhci->numslots);
2271 2272 2273 2274

    ictx = xhci_mask64(pictx);
    octx = xhci->slots[slotid-1].ctx;

2275 2276
    DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx);
    DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
2277

D
David Gibson 已提交
2278
    xhci_dma_read_u32s(xhci, ictx, ictl_ctx, sizeof(ictl_ctx));
2279 2280 2281 2282 2283 2284 2285 2286

    if (ictl_ctx[0] != 0x0 || ictl_ctx[1] & ~0x3) {
        fprintf(stderr, "xhci: invalid input context control %08x %08x\n",
                ictl_ctx[0], ictl_ctx[1]);
        return CC_TRB_ERROR;
    }

    if (ictl_ctx[1] & 0x1) {
D
David Gibson 已提交
2287
        xhci_dma_read_u32s(xhci, ictx+32, islot_ctx, sizeof(islot_ctx));
2288 2289 2290 2291

        DPRINTF("xhci: input slot context: %08x %08x %08x %08x\n",
                islot_ctx[0], islot_ctx[1], islot_ctx[2], islot_ctx[3]);

D
David Gibson 已提交
2292
        xhci_dma_read_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2293 2294 2295 2296 2297 2298 2299 2300 2301

        slot_ctx[1] &= ~0xFFFF; /* max exit latency */
        slot_ctx[1] |= islot_ctx[1] & 0xFFFF;
        slot_ctx[2] &= ~0xFF00000; /* interrupter target */
        slot_ctx[2] |= islot_ctx[2] & 0xFF000000;

        DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
                slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);

D
David Gibson 已提交
2302
        xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2303 2304 2305
    }

    if (ictl_ctx[1] & 0x2) {
D
David Gibson 已提交
2306
        xhci_dma_read_u32s(xhci, ictx+64, iep0_ctx, sizeof(iep0_ctx));
2307 2308 2309 2310 2311

        DPRINTF("xhci: input ep0 context: %08x %08x %08x %08x %08x\n",
                iep0_ctx[0], iep0_ctx[1], iep0_ctx[2],
                iep0_ctx[3], iep0_ctx[4]);

D
David Gibson 已提交
2312
        xhci_dma_read_u32s(xhci, octx+32, ep0_ctx, sizeof(ep0_ctx));
2313 2314 2315 2316 2317 2318 2319

        ep0_ctx[1] &= ~0xFFFF0000; /* max packet size*/
        ep0_ctx[1] |= iep0_ctx[1] & 0xFFFF0000;

        DPRINTF("xhci: output ep0 context: %08x %08x %08x %08x %08x\n",
                ep0_ctx[0], ep0_ctx[1], ep0_ctx[2], ep0_ctx[3], ep0_ctx[4]);

D
David Gibson 已提交
2320
        xhci_dma_write_u32s(xhci, octx+32, ep0_ctx, sizeof(ep0_ctx));
2321 2322 2323 2324 2325 2326 2327 2328
    }

    return CC_SUCCESS;
}

static TRBCCode xhci_reset_slot(XHCIState *xhci, unsigned int slotid)
{
    uint32_t slot_ctx[4];
2329
    dma_addr_t octx;
2330 2331
    int i;

G
Gerd Hoffmann 已提交
2332
    trace_usb_xhci_slot_reset(slotid);
2333
    assert(slotid >= 1 && slotid <= xhci->numslots);
2334 2335 2336

    octx = xhci->slots[slotid-1].ctx;

2337
    DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx);
2338 2339 2340 2341 2342 2343 2344

    for (i = 2; i <= 31; i++) {
        if (xhci->slots[slotid-1].eps[i-1]) {
            xhci_disable_ep(xhci, slotid, i);
        }
    }

D
David Gibson 已提交
2345
    xhci_dma_read_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2346 2347 2348 2349
    slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
    slot_ctx[3] |= SLOT_DEFAULT << SLOT_STATE_SHIFT;
    DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
            slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
D
David Gibson 已提交
2350
    xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx));
2351 2352 2353 2354 2355 2356 2357 2358

    return CC_SUCCESS;
}

static unsigned int xhci_get_slot(XHCIState *xhci, XHCIEvent *event, XHCITRB *trb)
{
    unsigned int slotid;
    slotid = (trb->control >> TRB_CR_SLOTID_SHIFT) & TRB_CR_SLOTID_MASK;
2359
    if (slotid < 1 || slotid > xhci->numslots) {
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
        fprintf(stderr, "xhci: bad slot id %d\n", slotid);
        event->ccode = CC_TRB_ERROR;
        return 0;
    } else if (!xhci->slots[slotid-1].enabled) {
        fprintf(stderr, "xhci: slot id %d not enabled\n", slotid);
        event->ccode = CC_SLOT_NOT_ENABLED_ERROR;
        return 0;
    }
    return slotid;
}

2371 2372 2373
/* cleanup slot state on usb device detach */
static void xhci_detach_slot(XHCIState *xhci, USBPort *uport)
{
G
Gerd Hoffmann 已提交
2374
    int slot, ep;
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384

    for (slot = 0; slot < xhci->numslots; slot++) {
        if (xhci->slots[slot].uport == uport) {
            break;
        }
    }
    if (slot == xhci->numslots) {
        return;
    }

G
Gerd Hoffmann 已提交
2385 2386 2387 2388 2389
    for (ep = 0; ep < 31; ep++) {
        if (xhci->slots[slot].eps[ep]) {
            xhci_ep_nuke_xfers(xhci, slot+1, ep+1);
        }
    }
2390 2391 2392
    xhci->slots[slot].uport = NULL;
}

2393 2394
static TRBCCode xhci_get_port_bandwidth(XHCIState *xhci, uint64_t pctx)
{
2395
    dma_addr_t ctx;
G
Gerd Hoffmann 已提交
2396
    uint8_t bw_ctx[xhci->numports+1];
2397 2398 2399 2400 2401

    DPRINTF("xhci_get_port_bandwidth()\n");

    ctx = xhci_mask64(pctx);

2402
    DPRINTF("xhci: bandwidth context at "DMA_ADDR_FMT"\n", ctx);
2403 2404 2405

    /* TODO: actually implement real values here */
    bw_ctx[0] = 0;
G
Gerd Hoffmann 已提交
2406
    memset(&bw_ctx[1], 80, xhci->numports); /* 80% */
2407
    pci_dma_write(&xhci->pci_dev, ctx, bw_ctx, sizeof(bw_ctx));
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427

    return CC_SUCCESS;
}

static uint32_t rotl(uint32_t v, unsigned count)
{
    count &= 31;
    return (v << count) | (v >> (32 - count));
}


static uint32_t xhci_nec_challenge(uint32_t hi, uint32_t lo)
{
    uint32_t val;
    val = rotl(lo - 0x49434878, 32 - ((hi>>8) & 0x1F));
    val += rotl(lo + 0x49434878, hi & 0x1F);
    val -= rotl(hi ^ 0x49434878, (lo >> 16) & 0x1F);
    return ~val;
}

2428
static void xhci_via_challenge(XHCIState *xhci, uint64_t addr)
2429 2430 2431
{
    uint32_t buf[8];
    uint32_t obuf[8];
2432
    dma_addr_t paddr = xhci_mask64(addr);
2433

2434
    pci_dma_read(&xhci->pci_dev, paddr, &buf, 32);
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449

    memcpy(obuf, buf, sizeof(obuf));

    if ((buf[0] & 0xff) == 2) {
        obuf[0] = 0x49932000 + 0x54dc200 * buf[2] + 0x7429b578 * buf[3];
        obuf[0] |=  (buf[2] * buf[3]) & 0xff;
        obuf[1] = 0x0132bb37 + 0xe89 * buf[2] + 0xf09 * buf[3];
        obuf[2] = 0x0066c2e9 + 0x2091 * buf[2] + 0x19bd * buf[3];
        obuf[3] = 0xd5281342 + 0x2cc9691 * buf[2] + 0x2367662 * buf[3];
        obuf[4] = 0x0123c75c + 0x1595 * buf[2] + 0x19ec * buf[3];
        obuf[5] = 0x00f695de + 0x26fd * buf[2] + 0x3e9 * buf[3];
        obuf[6] = obuf[2] ^ obuf[3] ^ 0x29472956;
        obuf[7] = obuf[2] ^ obuf[3] ^ 0x65866593;
    }

2450
    pci_dma_write(&xhci->pci_dev, paddr, &obuf, 32);
2451 2452 2453 2454 2455 2456 2457
}

static void xhci_process_commands(XHCIState *xhci)
{
    XHCITRB trb;
    TRBType type;
    XHCIEvent event = {ER_COMMAND_COMPLETE, CC_SUCCESS};
2458
    dma_addr_t addr;
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
    unsigned int i, slotid = 0;

    DPRINTF("xhci_process_commands()\n");
    if (!xhci_running(xhci)) {
        DPRINTF("xhci_process_commands() called while xHC stopped or paused\n");
        return;
    }

    xhci->crcr_low |= CRCR_CRR;

    while ((type = xhci_ring_fetch(xhci, &xhci->cmd_ring, &trb, &addr))) {
        event.ptr = addr;
        switch (type) {
        case CR_ENABLE_SLOT:
2473
            for (i = 0; i < xhci->numslots; i++) {
2474 2475 2476 2477
                if (!xhci->slots[i].enabled) {
                    break;
                }
            }
2478
            if (i >= xhci->numslots) {
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
                fprintf(stderr, "xhci: no device slots available\n");
                event.ccode = CC_NO_SLOTS_ERROR;
            } else {
                slotid = i+1;
                event.ccode = xhci_enable_slot(xhci, slotid);
            }
            break;
        case CR_DISABLE_SLOT:
            slotid = xhci_get_slot(xhci, &event, &trb);
            if (slotid) {
                event.ccode = xhci_disable_slot(xhci, slotid);
            }
            break;
        case CR_ADDRESS_DEVICE:
            slotid = xhci_get_slot(xhci, &event, &trb);
            if (slotid) {
                event.ccode = xhci_address_slot(xhci, slotid, trb.parameter,
                                                trb.control & TRB_CR_BSR);
            }
            break;
        case CR_CONFIGURE_ENDPOINT:
            slotid = xhci_get_slot(xhci, &event, &trb);
            if (slotid) {
                event.ccode = xhci_configure_slot(xhci, slotid, trb.parameter,
                                                  trb.control & TRB_CR_DC);
            }
            break;
        case CR_EVALUATE_CONTEXT:
            slotid = xhci_get_slot(xhci, &event, &trb);
            if (slotid) {
                event.ccode = xhci_evaluate_slot(xhci, slotid, trb.parameter);
            }
            break;
        case CR_STOP_ENDPOINT:
            slotid = xhci_get_slot(xhci, &event, &trb);
            if (slotid) {
                unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
                    & TRB_CR_EPID_MASK;
                event.ccode = xhci_stop_ep(xhci, slotid, epid);
            }
            break;
        case CR_RESET_ENDPOINT:
            slotid = xhci_get_slot(xhci, &event, &trb);
            if (slotid) {
                unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
                    & TRB_CR_EPID_MASK;
                event.ccode = xhci_reset_ep(xhci, slotid, epid);
            }
            break;
        case CR_SET_TR_DEQUEUE:
G
Gerd Hoffmann 已提交
2529
            fprintf(stderr, "%s: CR_SET_TR_DEQUEUE\n", __func__);
2530 2531 2532 2533
            slotid = xhci_get_slot(xhci, &event, &trb);
            if (slotid) {
                unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
                    & TRB_CR_EPID_MASK;
G
Gerd Hoffmann 已提交
2534 2535 2536
                unsigned int streamid = (trb.status >> 16) & 0xffff;
                event.ccode = xhci_set_ep_dequeue(xhci, slotid,
                                                  epid, streamid,
2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
                                                  trb.parameter);
            }
            break;
        case CR_RESET_DEVICE:
            slotid = xhci_get_slot(xhci, &event, &trb);
            if (slotid) {
                event.ccode = xhci_reset_slot(xhci, slotid);
            }
            break;
        case CR_GET_PORT_BANDWIDTH:
            event.ccode = xhci_get_port_bandwidth(xhci, trb.parameter);
            break;
        case CR_VENDOR_VIA_CHALLENGE_RESPONSE:
2550
            xhci_via_challenge(xhci, trb.parameter);
2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
            break;
        case CR_VENDOR_NEC_FIRMWARE_REVISION:
            event.type = 48; /* NEC reply */
            event.length = 0x3025;
            break;
        case CR_VENDOR_NEC_CHALLENGE_RESPONSE:
        {
            uint32_t chi = trb.parameter >> 32;
            uint32_t clo = trb.parameter;
            uint32_t val = xhci_nec_challenge(chi, clo);
            event.length = val & 0xFFFF;
            event.epid = val >> 16;
            slotid = val >> 24;
            event.type = 48; /* NEC reply */
        }
        break;
        default:
2568
            trace_usb_xhci_unimplemented("command", type);
2569 2570 2571 2572
            event.ccode = CC_TRB_ERROR;
            break;
        }
        event.slotid = slotid;
G
Gerd Hoffmann 已提交
2573
        xhci_event(xhci, &event, 0);
2574 2575 2576
    }
}

G
Gerd Hoffmann 已提交
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
static bool xhci_port_have_device(XHCIPort *port)
{
    if (!port->uport->dev || !port->uport->dev->attached) {
        return false; /* no device present */
    }
    if (!((1 << port->uport->dev->speed) & port->speedmask)) {
        return false; /* speed mismatch */
    }
    return true;
}

G
Gerd Hoffmann 已提交
2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
static void xhci_port_notify(XHCIPort *port, uint32_t bits)
{
    XHCIEvent ev = { ER_PORT_STATUS_CHANGE, CC_SUCCESS,
                     port->portnr << 24 };

    if ((port->portsc & bits) == bits) {
        return;
    }
    port->portsc |= bits;
    if (!xhci_running(port->xhci)) {
        return;
    }
    xhci_event(port->xhci, &ev, 0);
}

2603
static void xhci_port_update(XHCIPort *port, int is_detach)
2604
{
2605 2606
    uint32_t pls = PLS_RX_DETECT;

2607
    port->portsc = PORTSC_PP;
G
Gerd Hoffmann 已提交
2608
    if (!is_detach && xhci_port_have_device(port)) {
2609
        port->portsc |= PORTSC_CCS;
G
Gerd Hoffmann 已提交
2610
        switch (port->uport->dev->speed) {
2611 2612
        case USB_SPEED_LOW:
            port->portsc |= PORTSC_SPEED_LOW;
2613
            pls = PLS_POLLING;
2614 2615 2616
            break;
        case USB_SPEED_FULL:
            port->portsc |= PORTSC_SPEED_FULL;
2617
            pls = PLS_POLLING;
2618 2619 2620
            break;
        case USB_SPEED_HIGH:
            port->portsc |= PORTSC_SPEED_HIGH;
2621
            pls = PLS_POLLING;
2622
            break;
G
Gerd Hoffmann 已提交
2623 2624
        case USB_SPEED_SUPER:
            port->portsc |= PORTSC_SPEED_SUPER;
2625 2626
            port->portsc |= PORTSC_PED;
            pls = PLS_U0;
G
Gerd Hoffmann 已提交
2627
            break;
2628 2629
        }
    }
2630
    set_field(&port->portsc, pls, PORTSC_PLS);
G
Gerd Hoffmann 已提交
2631
    trace_usb_xhci_port_link(port->portnr, pls);
G
Gerd Hoffmann 已提交
2632
    xhci_port_notify(port, PORTSC_CSC);
2633 2634
}

G
Gerd Hoffmann 已提交
2635 2636
static void xhci_port_reset(XHCIPort *port)
{
G
Gerd Hoffmann 已提交
2637 2638
    trace_usb_xhci_port_reset(port->portnr);

2639 2640 2641 2642
    if (!xhci_port_have_device(port)) {
        return;
    }

G
Gerd Hoffmann 已提交
2643
    usb_device_reset(port->uport->dev);
2644 2645 2646 2647 2648 2649

    switch (port->uport->dev->speed) {
    case USB_SPEED_LOW:
    case USB_SPEED_FULL:
    case USB_SPEED_HIGH:
        set_field(&port->portsc, PLS_U0, PORTSC_PLS);
G
Gerd Hoffmann 已提交
2650
        trace_usb_xhci_port_link(port->portnr, PLS_U0);
2651 2652 2653 2654 2655 2656
        port->portsc |= PORTSC_PED;
        break;
    }

    port->portsc &= ~PORTSC_PR;
    xhci_port_notify(port, PORTSC_PRC);
G
Gerd Hoffmann 已提交
2657 2658
}

J
Jan Kiszka 已提交
2659
static void xhci_reset(DeviceState *dev)
2660
{
J
Jan Kiszka 已提交
2661
    XHCIState *xhci = DO_UPCAST(XHCIState, pci_dev.qdev, dev);
2662 2663
    int i;

G
Gerd Hoffmann 已提交
2664
    trace_usb_xhci_reset();
2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678
    if (!(xhci->usbsts & USBSTS_HCH)) {
        fprintf(stderr, "xhci: reset while running!\n");
    }

    xhci->usbcmd = 0;
    xhci->usbsts = USBSTS_HCH;
    xhci->dnctrl = 0;
    xhci->crcr_low = 0;
    xhci->crcr_high = 0;
    xhci->dcbaap_low = 0;
    xhci->dcbaap_high = 0;
    xhci->config = 0;
    xhci->devaddr = 2;

2679
    for (i = 0; i < xhci->numslots; i++) {
2680 2681 2682
        xhci_disable_slot(xhci, i+1);
    }

G
Gerd Hoffmann 已提交
2683
    for (i = 0; i < xhci->numports; i++) {
2684
        xhci_port_update(xhci->ports + i, 0);
2685 2686
    }

2687
    for (i = 0; i < xhci->numintrs; i++) {
G
Gerd Hoffmann 已提交
2688 2689 2690 2691 2692 2693 2694 2695
        xhci->intr[i].iman = 0;
        xhci->intr[i].imod = 0;
        xhci->intr[i].erstsz = 0;
        xhci->intr[i].erstba_low = 0;
        xhci->intr[i].erstba_high = 0;
        xhci->intr[i].erdp_low = 0;
        xhci->intr[i].erdp_high = 0;
        xhci->intr[i].msix_used = 0;
2696

G
Gerd Hoffmann 已提交
2697 2698 2699 2700 2701 2702
        xhci->intr[i].er_ep_idx = 0;
        xhci->intr[i].er_pcs = 1;
        xhci->intr[i].er_full = 0;
        xhci->intr[i].ev_buffer_put = 0;
        xhci->intr[i].ev_buffer_get = 0;
    }
G
Gerd Hoffmann 已提交
2703 2704 2705

    xhci->mfindex_start = qemu_get_clock_ns(vm_clock);
    xhci_mfwrap_update(xhci);
2706 2707
}

A
Avi Kivity 已提交
2708
static uint64_t xhci_cap_read(void *ptr, hwaddr reg, unsigned size)
2709
{
2710
    XHCIState *xhci = ptr;
G
Gerd Hoffmann 已提交
2711
    uint32_t ret;
2712 2713 2714

    switch (reg) {
    case 0x00: /* HCIVERSION, CAPLENGTH */
G
Gerd Hoffmann 已提交
2715 2716
        ret = 0x01000000 | LEN_CAP;
        break;
2717
    case 0x04: /* HCSPARAMS 1 */
G
Gerd Hoffmann 已提交
2718
        ret = ((xhci->numports_2+xhci->numports_3)<<24)
2719
            | (xhci->numintrs<<8) | xhci->numslots;
G
Gerd Hoffmann 已提交
2720
        break;
2721
    case 0x08: /* HCSPARAMS 2 */
G
Gerd Hoffmann 已提交
2722 2723
        ret = 0x0000000f;
        break;
2724
    case 0x0c: /* HCSPARAMS 3 */
G
Gerd Hoffmann 已提交
2725 2726
        ret = 0x00000000;
        break;
2727
    case 0x10: /* HCCPARAMS */
G
Gerd Hoffmann 已提交
2728
        if (sizeof(dma_addr_t) == 4) {
G
Gerd Hoffmann 已提交
2729
            ret = 0x00087000;
G
Gerd Hoffmann 已提交
2730
        } else {
G
Gerd Hoffmann 已提交
2731
            ret = 0x00087001;
G
Gerd Hoffmann 已提交
2732 2733
        }
        break;
2734
    case 0x14: /* DBOFF */
G
Gerd Hoffmann 已提交
2735 2736
        ret = OFF_DOORBELL;
        break;
2737
    case 0x18: /* RTSOFF */
G
Gerd Hoffmann 已提交
2738 2739
        ret = OFF_RUNTIME;
        break;
2740 2741 2742

    /* extended capabilities */
    case 0x20: /* Supported Protocol:00 */
G
Gerd Hoffmann 已提交
2743 2744
        ret = 0x02000402; /* USB 2.0 */
        break;
2745
    case 0x24: /* Supported Protocol:04 */
G
Gerd Hoffmann 已提交
2746
        ret = 0x20425355; /* "USB " */
G
Gerd Hoffmann 已提交
2747
        break;
2748
    case 0x28: /* Supported Protocol:08 */
G
Gerd Hoffmann 已提交
2749
        ret = 0x00000001 | (xhci->numports_2<<8);
G
Gerd Hoffmann 已提交
2750
        break;
2751
    case 0x2c: /* Supported Protocol:0c */
G
Gerd Hoffmann 已提交
2752 2753
        ret = 0x00000000; /* reserved */
        break;
2754
    case 0x30: /* Supported Protocol:00 */
G
Gerd Hoffmann 已提交
2755 2756
        ret = 0x03000002; /* USB 3.0 */
        break;
2757
    case 0x34: /* Supported Protocol:04 */
G
Gerd Hoffmann 已提交
2758
        ret = 0x20425355; /* "USB " */
G
Gerd Hoffmann 已提交
2759
        break;
2760
    case 0x38: /* Supported Protocol:08 */
G
Gerd Hoffmann 已提交
2761
        ret = 0x00000000 | (xhci->numports_2+1) | (xhci->numports_3<<8);
G
Gerd Hoffmann 已提交
2762
        break;
2763
    case 0x3c: /* Supported Protocol:0c */
G
Gerd Hoffmann 已提交
2764 2765
        ret = 0x00000000; /* reserved */
        break;
2766
    default:
2767
        trace_usb_xhci_unimplemented("cap read", reg);
G
Gerd Hoffmann 已提交
2768
        ret = 0;
2769
    }
G
Gerd Hoffmann 已提交
2770 2771 2772

    trace_usb_xhci_cap_read(reg, ret);
    return ret;
2773 2774
}

A
Avi Kivity 已提交
2775
static uint64_t xhci_port_read(void *ptr, hwaddr reg, unsigned size)
2776
{
2777
    XHCIPort *port = ptr;
G
Gerd Hoffmann 已提交
2778 2779
    uint32_t ret;

2780
    switch (reg) {
2781
    case 0x00: /* PORTSC */
2782
        ret = port->portsc;
G
Gerd Hoffmann 已提交
2783
        break;
2784 2785
    case 0x04: /* PORTPMSC */
    case 0x08: /* PORTLI */
G
Gerd Hoffmann 已提交
2786 2787
        ret = 0;
        break;
2788 2789
    case 0x0c: /* reserved */
    default:
2790
        trace_usb_xhci_unimplemented("port read", reg);
G
Gerd Hoffmann 已提交
2791
        ret = 0;
2792
    }
G
Gerd Hoffmann 已提交
2793

2794
    trace_usb_xhci_port_read(port->portnr, reg, ret);
G
Gerd Hoffmann 已提交
2795
    return ret;
2796 2797
}

A
Avi Kivity 已提交
2798
static void xhci_port_write(void *ptr, hwaddr reg,
2799
                            uint64_t val, unsigned size)
2800
{
2801
    XHCIPort *port = ptr;
2802 2803
    uint32_t portsc;

2804
    trace_usb_xhci_port_write(port->portnr, reg, val);
G
Gerd Hoffmann 已提交
2805

2806
    switch (reg) {
2807
    case 0x00: /* PORTSC */
2808
        portsc = port->portsc;
2809 2810 2811 2812 2813
        /* write-1-to-clear bits*/
        portsc &= ~(val & (PORTSC_CSC|PORTSC_PEC|PORTSC_WRC|PORTSC_OCC|
                           PORTSC_PRC|PORTSC_PLC|PORTSC_CEC));
        if (val & PORTSC_LWS) {
            /* overwrite PLS only when LWS=1 */
2814 2815
            uint32_t pls = get_field(val, PORTSC_PLS);
            set_field(&portsc, pls, PORTSC_PLS);
G
Gerd Hoffmann 已提交
2816
            trace_usb_xhci_port_link(port->portnr, pls);
2817 2818 2819 2820
        }
        /* read/write bits */
        portsc &= ~(PORTSC_PP|PORTSC_WCE|PORTSC_WDE|PORTSC_WOE);
        portsc |= (val & (PORTSC_PP|PORTSC_WCE|PORTSC_WDE|PORTSC_WOE));
G
Gerd Hoffmann 已提交
2821
        port->portsc = portsc;
2822 2823
        /* write-1-to-start bits */
        if (val & PORTSC_PR) {
G
Gerd Hoffmann 已提交
2824
            xhci_port_reset(port);
2825 2826 2827 2828 2829
        }
        break;
    case 0x04: /* PORTPMSC */
    case 0x08: /* PORTLI */
    default:
2830
        trace_usb_xhci_unimplemented("port write", reg);
2831 2832 2833
    }
}

A
Avi Kivity 已提交
2834
static uint64_t xhci_oper_read(void *ptr, hwaddr reg, unsigned size)
2835
{
2836
    XHCIState *xhci = ptr;
G
Gerd Hoffmann 已提交
2837
    uint32_t ret;
2838 2839 2840

    switch (reg) {
    case 0x00: /* USBCMD */
G
Gerd Hoffmann 已提交
2841 2842
        ret = xhci->usbcmd;
        break;
2843
    case 0x04: /* USBSTS */
G
Gerd Hoffmann 已提交
2844 2845
        ret = xhci->usbsts;
        break;
2846
    case 0x08: /* PAGESIZE */
G
Gerd Hoffmann 已提交
2847 2848
        ret = 1; /* 4KiB */
        break;
2849
    case 0x14: /* DNCTRL */
G
Gerd Hoffmann 已提交
2850 2851
        ret = xhci->dnctrl;
        break;
2852
    case 0x18: /* CRCR low */
G
Gerd Hoffmann 已提交
2853 2854
        ret = xhci->crcr_low & ~0xe;
        break;
2855
    case 0x1c: /* CRCR high */
G
Gerd Hoffmann 已提交
2856 2857
        ret = xhci->crcr_high;
        break;
2858
    case 0x30: /* DCBAAP low */
G
Gerd Hoffmann 已提交
2859 2860
        ret = xhci->dcbaap_low;
        break;
2861
    case 0x34: /* DCBAAP high */
G
Gerd Hoffmann 已提交
2862 2863
        ret = xhci->dcbaap_high;
        break;
2864
    case 0x38: /* CONFIG */
G
Gerd Hoffmann 已提交
2865 2866
        ret = xhci->config;
        break;
2867
    default:
2868
        trace_usb_xhci_unimplemented("oper read", reg);
G
Gerd Hoffmann 已提交
2869
        ret = 0;
2870
    }
G
Gerd Hoffmann 已提交
2871 2872 2873

    trace_usb_xhci_oper_read(reg, ret);
    return ret;
2874 2875
}

A
Avi Kivity 已提交
2876
static void xhci_oper_write(void *ptr, hwaddr reg,
2877
                            uint64_t val, unsigned size)
2878
{
2879 2880
    XHCIState *xhci = ptr;

G
Gerd Hoffmann 已提交
2881 2882
    trace_usb_xhci_oper_write(reg, val);

2883 2884 2885 2886 2887 2888 2889 2890
    switch (reg) {
    case 0x00: /* USBCMD */
        if ((val & USBCMD_RS) && !(xhci->usbcmd & USBCMD_RS)) {
            xhci_run(xhci);
        } else if (!(val & USBCMD_RS) && (xhci->usbcmd & USBCMD_RS)) {
            xhci_stop(xhci);
        }
        xhci->usbcmd = val & 0xc0f;
G
Gerd Hoffmann 已提交
2891
        xhci_mfwrap_update(xhci);
2892
        if (val & USBCMD_HCRST) {
J
Jan Kiszka 已提交
2893
            xhci_reset(&xhci->pci_dev.qdev);
2894
        }
G
Gerd Hoffmann 已提交
2895
        xhci_intx_update(xhci);
2896 2897 2898 2899 2900
        break;

    case 0x04: /* USBSTS */
        /* these bits are write-1-to-clear */
        xhci->usbsts &= ~(val & (USBSTS_HSE|USBSTS_EINT|USBSTS_PCD|USBSTS_SRE));
G
Gerd Hoffmann 已提交
2901
        xhci_intx_update(xhci);
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914
        break;

    case 0x14: /* DNCTRL */
        xhci->dnctrl = val & 0xffff;
        break;
    case 0x18: /* CRCR low */
        xhci->crcr_low = (val & 0xffffffcf) | (xhci->crcr_low & CRCR_CRR);
        break;
    case 0x1c: /* CRCR high */
        xhci->crcr_high = val;
        if (xhci->crcr_low & (CRCR_CA|CRCR_CS) && (xhci->crcr_low & CRCR_CRR)) {
            XHCIEvent event = {ER_COMMAND_COMPLETE, CC_COMMAND_RING_STOPPED};
            xhci->crcr_low &= ~CRCR_CRR;
G
Gerd Hoffmann 已提交
2915
            xhci_event(xhci, &event, 0);
2916 2917
            DPRINTF("xhci: command ring stopped (CRCR=%08x)\n", xhci->crcr_low);
        } else {
2918
            dma_addr_t base = xhci_addr64(xhci->crcr_low & ~0x3f, val);
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932
            xhci_ring_init(xhci, &xhci->cmd_ring, base);
        }
        xhci->crcr_low &= ~(CRCR_CA | CRCR_CS);
        break;
    case 0x30: /* DCBAAP low */
        xhci->dcbaap_low = val & 0xffffffc0;
        break;
    case 0x34: /* DCBAAP high */
        xhci->dcbaap_high = val;
        break;
    case 0x38: /* CONFIG */
        xhci->config = val & 0xff;
        break;
    default:
2933
        trace_usb_xhci_unimplemented("oper write", reg);
2934 2935 2936
    }
}

A
Avi Kivity 已提交
2937
static uint64_t xhci_runtime_read(void *ptr, hwaddr reg,
2938
                                  unsigned size)
2939
{
2940
    XHCIState *xhci = ptr;
2941
    uint32_t ret = 0;
2942

2943 2944 2945 2946 2947 2948
    if (reg < 0x20) {
        switch (reg) {
        case 0x00: /* MFINDEX */
            ret = xhci_mfindex_get(xhci) & 0x3fff;
            break;
        default:
2949
            trace_usb_xhci_unimplemented("runtime read", reg);
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977
            break;
        }
    } else {
        int v = (reg - 0x20) / 0x20;
        XHCIInterrupter *intr = &xhci->intr[v];
        switch (reg & 0x1f) {
        case 0x00: /* IMAN */
            ret = intr->iman;
            break;
        case 0x04: /* IMOD */
            ret = intr->imod;
            break;
        case 0x08: /* ERSTSZ */
            ret = intr->erstsz;
            break;
        case 0x10: /* ERSTBA low */
            ret = intr->erstba_low;
            break;
        case 0x14: /* ERSTBA high */
            ret = intr->erstba_high;
            break;
        case 0x18: /* ERDP low */
            ret = intr->erdp_low;
            break;
        case 0x1c: /* ERDP high */
            ret = intr->erdp_high;
            break;
        }
2978
    }
G
Gerd Hoffmann 已提交
2979 2980 2981

    trace_usb_xhci_runtime_read(reg, ret);
    return ret;
2982 2983
}

A
Avi Kivity 已提交
2984
static void xhci_runtime_write(void *ptr, hwaddr reg,
2985
                               uint64_t val, unsigned size)
2986
{
2987
    XHCIState *xhci = ptr;
2988 2989
    int v = (reg - 0x20) / 0x20;
    XHCIInterrupter *intr = &xhci->intr[v];
2990
    trace_usb_xhci_runtime_write(reg, val);
2991

2992
    if (reg < 0x20) {
2993
        trace_usb_xhci_unimplemented("runtime write", reg);
2994 2995 2996 2997 2998
        return;
    }

    switch (reg & 0x1f) {
    case 0x00: /* IMAN */
2999
        if (val & IMAN_IP) {
G
Gerd Hoffmann 已提交
3000
            intr->iman &= ~IMAN_IP;
3001
        }
G
Gerd Hoffmann 已提交
3002 3003
        intr->iman &= ~IMAN_IE;
        intr->iman |= val & IMAN_IE;
3004 3005 3006 3007
        if (v == 0) {
            xhci_intx_update(xhci);
        }
        xhci_msix_update(xhci, v);
3008
        break;
3009
    case 0x04: /* IMOD */
G
Gerd Hoffmann 已提交
3010
        intr->imod = val;
3011
        break;
3012
    case 0x08: /* ERSTSZ */
G
Gerd Hoffmann 已提交
3013
        intr->erstsz = val & 0xffff;
3014
        break;
3015
    case 0x10: /* ERSTBA low */
3016
        /* XXX NEC driver bug: it doesn't align this to 64 bytes
G
Gerd Hoffmann 已提交
3017 3018
        intr->erstba_low = val & 0xffffffc0; */
        intr->erstba_low = val & 0xfffffff0;
3019
        break;
3020
    case 0x14: /* ERSTBA high */
G
Gerd Hoffmann 已提交
3021
        intr->erstba_high = val;
3022
        xhci_er_reset(xhci, v);
3023
        break;
3024
    case 0x18: /* ERDP low */
3025
        if (val & ERDP_EHB) {
G
Gerd Hoffmann 已提交
3026
            intr->erdp_low &= ~ERDP_EHB;
3027
        }
G
Gerd Hoffmann 已提交
3028
        intr->erdp_low = (val & ~ERDP_EHB) | (intr->erdp_low & ERDP_EHB);
3029
        break;
3030
    case 0x1c: /* ERDP high */
G
Gerd Hoffmann 已提交
3031
        intr->erdp_high = val;
3032
        xhci_events_update(xhci, v);
3033 3034
        break;
    default:
3035
        trace_usb_xhci_unimplemented("oper write", reg);
3036 3037 3038
    }
}

A
Avi Kivity 已提交
3039
static uint64_t xhci_doorbell_read(void *ptr, hwaddr reg,
3040
                                   unsigned size)
3041 3042
{
    /* doorbells always read as 0 */
G
Gerd Hoffmann 已提交
3043
    trace_usb_xhci_doorbell_read(reg, 0);
3044 3045 3046
    return 0;
}

A
Avi Kivity 已提交
3047
static void xhci_doorbell_write(void *ptr, hwaddr reg,
3048
                                uint64_t val, unsigned size)
3049
{
3050
    XHCIState *xhci = ptr;
G
Gerd Hoffmann 已提交
3051
    unsigned int epid, streamid;
3052

G
Gerd Hoffmann 已提交
3053
    trace_usb_xhci_doorbell_write(reg, val);
3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065

    if (!xhci_running(xhci)) {
        fprintf(stderr, "xhci: wrote doorbell while xHC stopped or paused\n");
        return;
    }

    reg >>= 2;

    if (reg == 0) {
        if (val == 0) {
            xhci_process_commands(xhci);
        } else {
3066 3067
            fprintf(stderr, "xhci: bad doorbell 0 write: 0x%x\n",
                    (uint32_t)val);
3068 3069
        }
    } else {
G
Gerd Hoffmann 已提交
3070 3071
        epid = val & 0xff;
        streamid = (val >> 16) & 0xffff;
3072
        if (reg > xhci->numslots) {
3073
            fprintf(stderr, "xhci: bad doorbell %d\n", (int)reg);
G
Gerd Hoffmann 已提交
3074
        } else if (epid > 31) {
3075 3076
            fprintf(stderr, "xhci: bad doorbell %d write: 0x%x\n",
                    (int)reg, (uint32_t)val);
3077
        } else {
G
Gerd Hoffmann 已提交
3078
            xhci_kick_ep(xhci, reg, epid, streamid);
3079 3080 3081 3082
        }
    }
}

3083 3084
static const MemoryRegionOps xhci_cap_ops = {
    .read = xhci_cap_read,
3085
    .valid.min_access_size = 1,
3086
    .valid.max_access_size = 4,
3087 3088
    .impl.min_access_size = 4,
    .impl.max_access_size = 4,
3089 3090
    .endianness = DEVICE_LITTLE_ENDIAN,
};
3091

3092 3093 3094 3095 3096 3097 3098
static const MemoryRegionOps xhci_oper_ops = {
    .read = xhci_oper_read,
    .write = xhci_oper_write,
    .valid.min_access_size = 4,
    .valid.max_access_size = 4,
    .endianness = DEVICE_LITTLE_ENDIAN,
};
3099

3100 3101 3102 3103 3104 3105 3106 3107
static const MemoryRegionOps xhci_port_ops = {
    .read = xhci_port_read,
    .write = xhci_port_write,
    .valid.min_access_size = 4,
    .valid.max_access_size = 4,
    .endianness = DEVICE_LITTLE_ENDIAN,
};

3108 3109 3110 3111 3112 3113 3114
static const MemoryRegionOps xhci_runtime_ops = {
    .read = xhci_runtime_read,
    .write = xhci_runtime_write,
    .valid.min_access_size = 4,
    .valid.max_access_size = 4,
    .endianness = DEVICE_LITTLE_ENDIAN,
};
3115

3116 3117 3118
static const MemoryRegionOps xhci_doorbell_ops = {
    .read = xhci_doorbell_read,
    .write = xhci_doorbell_write,
3119 3120 3121 3122 3123 3124 3125 3126
    .valid.min_access_size = 4,
    .valid.max_access_size = 4,
    .endianness = DEVICE_LITTLE_ENDIAN,
};

static void xhci_attach(USBPort *usbport)
{
    XHCIState *xhci = usbport->opaque;
G
Gerd Hoffmann 已提交
3127
    XHCIPort *port = xhci_lookup_port(xhci, usbport);
3128

3129
    xhci_port_update(port, 0);
3130 3131 3132 3133 3134
}

static void xhci_detach(USBPort *usbport)
{
    XHCIState *xhci = usbport->opaque;
G
Gerd Hoffmann 已提交
3135
    XHCIPort *port = xhci_lookup_port(xhci, usbport);
3136

3137
    xhci_detach_slot(xhci, usbport);
3138
    xhci_port_update(port, 1);
3139 3140
}

G
Gerd Hoffmann 已提交
3141 3142 3143
static void xhci_wakeup(USBPort *usbport)
{
    XHCIState *xhci = usbport->opaque;
G
Gerd Hoffmann 已提交
3144
    XHCIPort *port = xhci_lookup_port(xhci, usbport);
G
Gerd Hoffmann 已提交
3145

3146
    if (get_field(port->portsc, PORTSC_PLS) != PLS_U3) {
G
Gerd Hoffmann 已提交
3147 3148
        return;
    }
3149
    set_field(&port->portsc, PLS_RESUME, PORTSC_PLS);
G
Gerd Hoffmann 已提交
3150
    xhci_port_notify(port, PORTSC_PLC);
G
Gerd Hoffmann 已提交
3151 3152
}

3153 3154 3155 3156
static void xhci_complete(USBPort *port, USBPacket *packet)
{
    XHCITransfer *xfer = container_of(packet, XHCITransfer, packet);

3157
    if (packet->status == USB_RET_REMOVE_FROM_QUEUE) {
3158 3159 3160
        xhci_ep_nuke_one_xfer(xfer);
        return;
    }
3161
    xhci_complete_packet(xfer);
G
Gerd Hoffmann 已提交
3162
    xhci_kick_ep(xfer->xhci, xfer->slotid, xfer->epid, xfer->streamid);
3163 3164
}

3165
static void xhci_child_detach(USBPort *uport, USBDevice *child)
3166
{
3167 3168 3169
    USBBus *bus = usb_bus_from_device(child);
    XHCIState *xhci = container_of(bus, XHCIState, bus);

3170
    xhci_detach_slot(xhci, uport);
3171 3172
}

3173
static USBPortOps xhci_uport_ops = {
3174 3175
    .attach   = xhci_attach,
    .detach   = xhci_detach,
G
Gerd Hoffmann 已提交
3176
    .wakeup   = xhci_wakeup,
3177 3178 3179 3180
    .complete = xhci_complete,
    .child_detach = xhci_child_detach,
};

G
Gerd Hoffmann 已提交
3181 3182 3183 3184 3185
static int xhci_find_slotid(XHCIState *xhci, USBDevice *dev)
{
    XHCISlot *slot;
    int slotid;

3186
    for (slotid = 1; slotid <= xhci->numslots; slotid++) {
G
Gerd Hoffmann 已提交
3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
        slot = &xhci->slots[slotid-1];
        if (slot->devaddr == dev->addr) {
            return slotid;
        }
    }
    return 0;
}

static int xhci_find_epid(USBEndpoint *ep)
{
    if (ep->nr == 0) {
        return 1;
    }
    if (ep->pid == USB_TOKEN_IN) {
        return ep->nr * 2 + 1;
    } else {
        return ep->nr * 2;
    }
}

G
Gerd Hoffmann 已提交
3207 3208
static void xhci_wakeup_endpoint(USBBus *bus, USBEndpoint *ep,
                                 unsigned int stream)
G
Gerd Hoffmann 已提交
3209 3210 3211 3212 3213 3214 3215 3216 3217 3218
{
    XHCIState *xhci = container_of(bus, XHCIState, bus);
    int slotid;

    DPRINTF("%s\n", __func__);
    slotid = xhci_find_slotid(xhci, ep->dev);
    if (slotid == 0 || !xhci->slots[slotid-1].enabled) {
        DPRINTF("%s: oops, no slot for dev %d\n", __func__, ep->dev->addr);
        return;
    }
G
Gerd Hoffmann 已提交
3219
    xhci_kick_ep(xhci, slotid, xhci_find_epid(ep), stream);
G
Gerd Hoffmann 已提交
3220 3221
}

3222
static USBBusOps xhci_bus_ops = {
G
Gerd Hoffmann 已提交
3223
    .wakeup_endpoint = xhci_wakeup_endpoint,
3224 3225 3226 3227
};

static void usb_xhci_init(XHCIState *xhci, DeviceState *dev)
{
G
Gerd Hoffmann 已提交
3228 3229
    XHCIPort *port;
    int i, usbports, speedmask;
3230 3231 3232

    xhci->usbsts = USBSTS_HCH;

G
Gerd Hoffmann 已提交
3233 3234 3235 3236 3237 3238 3239 3240 3241
    if (xhci->numports_2 > MAXPORTS_2) {
        xhci->numports_2 = MAXPORTS_2;
    }
    if (xhci->numports_3 > MAXPORTS_3) {
        xhci->numports_3 = MAXPORTS_3;
    }
    usbports = MAX(xhci->numports_2, xhci->numports_3);
    xhci->numports = xhci->numports_2 + xhci->numports_3;

3242 3243
    usb_bus_new(&xhci->bus, &xhci_bus_ops, &xhci->pci_dev.qdev);

G
Gerd Hoffmann 已提交
3244 3245 3246 3247 3248 3249 3250 3251 3252 3253
    for (i = 0; i < usbports; i++) {
        speedmask = 0;
        if (i < xhci->numports_2) {
            port = &xhci->ports[i];
            port->portnr = i + 1;
            port->uport = &xhci->uports[i];
            port->speedmask =
                USB_SPEED_MASK_LOW  |
                USB_SPEED_MASK_FULL |
                USB_SPEED_MASK_HIGH;
3254
            snprintf(port->name, sizeof(port->name), "usb2 port #%d", i+1);
G
Gerd Hoffmann 已提交
3255 3256 3257 3258 3259 3260 3261
            speedmask |= port->speedmask;
        }
        if (i < xhci->numports_3) {
            port = &xhci->ports[i + xhci->numports_2];
            port->portnr = i + 1 + xhci->numports_2;
            port->uport = &xhci->uports[i];
            port->speedmask = USB_SPEED_MASK_SUPER;
3262
            snprintf(port->name, sizeof(port->name), "usb3 port #%d", i+1);
G
Gerd Hoffmann 已提交
3263 3264 3265
            speedmask |= port->speedmask;
        }
        usb_register_port(&xhci->bus, &xhci->uports[i], xhci, i,
3266
                          &xhci_uport_ops, speedmask);
3267 3268 3269 3270 3271
    }
}

static int usb_xhci_initfn(struct PCIDevice *dev)
{
3272
    int i, ret;
3273 3274 3275 3276 3277 3278 3279 3280 3281 3282

    XHCIState *xhci = DO_UPCAST(XHCIState, pci_dev, dev);

    xhci->pci_dev.config[PCI_CLASS_PROG] = 0x30;    /* xHCI */
    xhci->pci_dev.config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin 1 */
    xhci->pci_dev.config[PCI_CACHE_LINE_SIZE] = 0x10;
    xhci->pci_dev.config[0x60] = 0x30; /* release number */

    usb_xhci_init(xhci, &dev->qdev);

3283 3284 3285
    if (xhci->numintrs > MAXINTRS) {
        xhci->numintrs = MAXINTRS;
    }
G
Gerd Hoffmann 已提交
3286 3287 3288
    while (xhci->numintrs & (xhci->numintrs - 1)) {   /* ! power of 2 */
        xhci->numintrs++;
    }
3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
    if (xhci->numintrs < 1) {
        xhci->numintrs = 1;
    }
    if (xhci->numslots > MAXSLOTS) {
        xhci->numslots = MAXSLOTS;
    }
    if (xhci->numslots < 1) {
        xhci->numslots = 1;
    }

G
Gerd Hoffmann 已提交
3299 3300
    xhci->mfwrap_timer = qemu_new_timer_ns(vm_clock, xhci_mfwrap_timer, xhci);

3301 3302
    xhci->irq = xhci->pci_dev.irq[0];

3303 3304 3305 3306
    memory_region_init(&xhci->mem, "xhci", LEN_REGS);
    memory_region_init_io(&xhci->mem_cap, &xhci_cap_ops, xhci,
                          "capabilities", LEN_CAP);
    memory_region_init_io(&xhci->mem_oper, &xhci_oper_ops, xhci,
3307
                          "operational", 0x400);
3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
    memory_region_init_io(&xhci->mem_runtime, &xhci_runtime_ops, xhci,
                          "runtime", LEN_RUNTIME);
    memory_region_init_io(&xhci->mem_doorbell, &xhci_doorbell_ops, xhci,
                          "doorbell", LEN_DOORBELL);

    memory_region_add_subregion(&xhci->mem, 0,            &xhci->mem_cap);
    memory_region_add_subregion(&xhci->mem, OFF_OPER,     &xhci->mem_oper);
    memory_region_add_subregion(&xhci->mem, OFF_RUNTIME,  &xhci->mem_runtime);
    memory_region_add_subregion(&xhci->mem, OFF_DOORBELL, &xhci->mem_doorbell);

3318 3319 3320 3321 3322 3323 3324 3325 3326
    for (i = 0; i < xhci->numports; i++) {
        XHCIPort *port = &xhci->ports[i];
        uint32_t offset = OFF_OPER + 0x400 + 0x10 * i;
        port->xhci = xhci;
        memory_region_init_io(&port->mem, &xhci_port_ops, port,
                              port->name, 0x10);
        memory_region_add_subregion(&xhci->mem, offset, &port->mem);
    }

3327 3328 3329 3330
    pci_register_bar(&xhci->pci_dev, 0,
                     PCI_BASE_ADDRESS_SPACE_MEMORY|PCI_BASE_ADDRESS_MEM_TYPE_64,
                     &xhci->mem);

3331
    ret = pcie_endpoint_cap_init(&xhci->pci_dev, 0xa0);
3332 3333
    assert(ret >= 0);

G
Gerd Hoffmann 已提交
3334
    if (xhci->flags & (1 << XHCI_FLAG_USE_MSI)) {
3335
        msi_init(&xhci->pci_dev, 0x70, xhci->numintrs, true, false);
3336
    }
G
Gerd Hoffmann 已提交
3337
    if (xhci->flags & (1 << XHCI_FLAG_USE_MSI_X)) {
3338
        msix_init(&xhci->pci_dev, xhci->numintrs,
G
Gerd Hoffmann 已提交
3339 3340 3341 3342
                  &xhci->mem, 0, OFF_MSIX_TABLE,
                  &xhci->mem, 0, OFF_MSIX_PBA,
                  0x90);
    }
3343 3344 3345 3346 3347 3348 3349 3350 3351

    return 0;
}

static const VMStateDescription vmstate_xhci = {
    .name = "xhci",
    .unmigratable = 1,
};

3352
static Property xhci_properties[] = {
3353 3354 3355 3356 3357 3358
    DEFINE_PROP_BIT("msi",      XHCIState, flags, XHCI_FLAG_USE_MSI, true),
    DEFINE_PROP_BIT("msix",     XHCIState, flags, XHCI_FLAG_USE_MSI_X, true),
    DEFINE_PROP_UINT32("intrs", XHCIState, numintrs, MAXINTRS),
    DEFINE_PROP_UINT32("slots", XHCIState, numslots, MAXSLOTS),
    DEFINE_PROP_UINT32("p2",    XHCIState, numports_2, 4),
    DEFINE_PROP_UINT32("p3",    XHCIState, numports_3, 4),
3359 3360 3361
    DEFINE_PROP_END_OF_LIST(),
};

3362 3363 3364
static void xhci_class_init(ObjectClass *klass, void *data)
{
    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
3365
    DeviceClass *dc = DEVICE_CLASS(klass);
3366

3367 3368
    dc->vmsd    = &vmstate_xhci;
    dc->props   = xhci_properties;
J
Jan Kiszka 已提交
3369
    dc->reset   = xhci_reset;
3370 3371 3372 3373 3374 3375
    k->init         = usb_xhci_initfn;
    k->vendor_id    = PCI_VENDOR_ID_NEC;
    k->device_id    = PCI_DEVICE_ID_NEC_UPD720200;
    k->class_id     = PCI_CLASS_SERIAL_USB;
    k->revision     = 0x03;
    k->is_express   = 1;
3376
    k->no_hotplug   = 1;
3377 3378
}

3379
static const TypeInfo xhci_info = {
3380 3381 3382 3383
    .name          = "nec-usb-xhci",
    .parent        = TYPE_PCI_DEVICE,
    .instance_size = sizeof(XHCIState),
    .class_init    = xhci_class_init,
3384 3385
};

A
Andreas Färber 已提交
3386
static void xhci_register_types(void)
3387
{
3388
    type_register_static(&xhci_info);
3389
}
A
Andreas Färber 已提交
3390 3391

type_init(xhci_register_types)