Statistics
| Branch: | Revision:

root / hw / usb-xhci.c @ 1f51470d

History | View | Annotate | Download (85.3 kB)

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

    
28
//#define DEBUG_XHCI
29
//#define DEBUG_DATA
30

    
31
#ifdef DEBUG_XHCI
32
#define DPRINTF(...) fprintf(stderr, __VA_ARGS__)
33
#else
34
#define DPRINTF(...) do {} while (0)
35
#endif
36
#define FIXME() do { fprintf(stderr, "FIXME %s:%d\n", \
37
                             __func__, __LINE__); abort(); } while (0)
38

    
39
#define MAXSLOTS 8
40
#define MAXINTRS 1
41

    
42
#define USB2_PORTS 4
43
#define USB3_PORTS 4
44

    
45
#define MAXPORTS (USB2_PORTS+USB3_PORTS)
46

    
47
#define TD_QUEUE 24
48
#define BG_XFERS 8
49
#define BG_PKTS 8
50

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

    
57
#define LEN_CAP         0x40
58
#define OFF_OPER        LEN_CAP
59
#define LEN_OPER        (0x400 + 0x10 * MAXPORTS)
60
#define OFF_RUNTIME     ((OFF_OPER + LEN_OPER + 0x20) & ~0x1f)
61
#define LEN_RUNTIME     (0x20 + MAXINTRS * 0x20)
62
#define OFF_DOORBELL    (OFF_RUNTIME + LEN_RUNTIME)
63
#define LEN_DOORBELL    ((MAXSLOTS + 1) * 0x20)
64

    
65
/* must be power of 2 */
66
#define LEN_REGS        0x2000
67

    
68
#if (OFF_DOORBELL + LEN_DOORBELL) > LEN_REGS
69
# error Increase LEN_REGS
70
#endif
71

    
72
#if MAXINTRS > 1
73
# error TODO: only one interrupter supported
74
#endif
75

    
76
/* bit definitions */
77
#define USBCMD_RS       (1<<0)
78
#define USBCMD_HCRST    (1<<1)
79
#define USBCMD_INTE     (1<<2)
80
#define USBCMD_HSEE     (1<<3)
81
#define USBCMD_LHCRST   (1<<7)
82
#define USBCMD_CSS      (1<<8)
83
#define USBCMD_CRS      (1<<9)
84
#define USBCMD_EWE      (1<<10)
85
#define USBCMD_EU3S     (1<<11)
86

    
87
#define USBSTS_HCH      (1<<0)
88
#define USBSTS_HSE      (1<<2)
89
#define USBSTS_EINT     (1<<3)
90
#define USBSTS_PCD      (1<<4)
91
#define USBSTS_SSS      (1<<8)
92
#define USBSTS_RSS      (1<<9)
93
#define USBSTS_SRE      (1<<10)
94
#define USBSTS_CNR      (1<<11)
95
#define USBSTS_HCE      (1<<12)
96

    
97

    
98
#define PORTSC_CCS          (1<<0)
99
#define PORTSC_PED          (1<<1)
100
#define PORTSC_OCA          (1<<3)
101
#define PORTSC_PR           (1<<4)
102
#define PORTSC_PLS_SHIFT        5
103
#define PORTSC_PLS_MASK     0xf
104
#define PORTSC_PP           (1<<9)
105
#define PORTSC_SPEED_SHIFT      10
106
#define PORTSC_SPEED_MASK   0xf
107
#define PORTSC_SPEED_FULL   (1<<10)
108
#define PORTSC_SPEED_LOW    (2<<10)
109
#define PORTSC_SPEED_HIGH   (3<<10)
110
#define PORTSC_SPEED_SUPER  (4<<10)
111
#define PORTSC_PIC_SHIFT        14
112
#define PORTSC_PIC_MASK     0x3
113
#define PORTSC_LWS          (1<<16)
114
#define PORTSC_CSC          (1<<17)
115
#define PORTSC_PEC          (1<<18)
116
#define PORTSC_WRC          (1<<19)
117
#define PORTSC_OCC          (1<<20)
118
#define PORTSC_PRC          (1<<21)
119
#define PORTSC_PLC          (1<<22)
120
#define PORTSC_CEC          (1<<23)
121
#define PORTSC_CAS          (1<<24)
122
#define PORTSC_WCE          (1<<25)
123
#define PORTSC_WDE          (1<<26)
124
#define PORTSC_WOE          (1<<27)
125
#define PORTSC_DR           (1<<30)
126
#define PORTSC_WPR          (1<<31)
127

    
128
#define CRCR_RCS        (1<<0)
129
#define CRCR_CS         (1<<1)
130
#define CRCR_CA         (1<<2)
131
#define CRCR_CRR        (1<<3)
132

    
133
#define IMAN_IP         (1<<0)
134
#define IMAN_IE         (1<<1)
135

    
136
#define ERDP_EHB        (1<<3)
137

    
138
#define TRB_SIZE 16
139
typedef struct XHCITRB {
140
    uint64_t parameter;
141
    uint32_t status;
142
    uint32_t control;
143
    target_phys_addr_t addr;
144
    bool ccs;
145
} XHCITRB;
146

    
147

    
148
typedef enum TRBType {
149
    TRB_RESERVED = 0,
150
    TR_NORMAL,
151
    TR_SETUP,
152
    TR_DATA,
153
    TR_STATUS,
154
    TR_ISOCH,
155
    TR_LINK,
156
    TR_EVDATA,
157
    TR_NOOP,
158
    CR_ENABLE_SLOT,
159
    CR_DISABLE_SLOT,
160
    CR_ADDRESS_DEVICE,
161
    CR_CONFIGURE_ENDPOINT,
162
    CR_EVALUATE_CONTEXT,
163
    CR_RESET_ENDPOINT,
164
    CR_STOP_ENDPOINT,
165
    CR_SET_TR_DEQUEUE,
166
    CR_RESET_DEVICE,
167
    CR_FORCE_EVENT,
168
    CR_NEGOTIATE_BW,
169
    CR_SET_LATENCY_TOLERANCE,
170
    CR_GET_PORT_BANDWIDTH,
171
    CR_FORCE_HEADER,
172
    CR_NOOP,
173
    ER_TRANSFER = 32,
174
    ER_COMMAND_COMPLETE,
175
    ER_PORT_STATUS_CHANGE,
176
    ER_BANDWIDTH_REQUEST,
177
    ER_DOORBELL,
178
    ER_HOST_CONTROLLER,
179
    ER_DEVICE_NOTIFICATION,
180
    ER_MFINDEX_WRAP,
181
    /* vendor specific bits */
182
    CR_VENDOR_VIA_CHALLENGE_RESPONSE = 48,
183
    CR_VENDOR_NEC_FIRMWARE_REVISION  = 49,
184
    CR_VENDOR_NEC_CHALLENGE_RESPONSE = 50,
185
} TRBType;
186

    
187
#define CR_LINK TR_LINK
188

    
189
typedef enum TRBCCode {
190
    CC_INVALID = 0,
191
    CC_SUCCESS,
192
    CC_DATA_BUFFER_ERROR,
193
    CC_BABBLE_DETECTED,
194
    CC_USB_TRANSACTION_ERROR,
195
    CC_TRB_ERROR,
196
    CC_STALL_ERROR,
197
    CC_RESOURCE_ERROR,
198
    CC_BANDWIDTH_ERROR,
199
    CC_NO_SLOTS_ERROR,
200
    CC_INVALID_STREAM_TYPE_ERROR,
201
    CC_SLOT_NOT_ENABLED_ERROR,
202
    CC_EP_NOT_ENABLED_ERROR,
203
    CC_SHORT_PACKET,
204
    CC_RING_UNDERRUN,
205
    CC_RING_OVERRUN,
206
    CC_VF_ER_FULL,
207
    CC_PARAMETER_ERROR,
208
    CC_BANDWIDTH_OVERRUN,
209
    CC_CONTEXT_STATE_ERROR,
210
    CC_NO_PING_RESPONSE_ERROR,
211
    CC_EVENT_RING_FULL_ERROR,
212
    CC_INCOMPATIBLE_DEVICE_ERROR,
213
    CC_MISSED_SERVICE_ERROR,
214
    CC_COMMAND_RING_STOPPED,
215
    CC_COMMAND_ABORTED,
216
    CC_STOPPED,
217
    CC_STOPPED_LENGTH_INVALID,
218
    CC_MAX_EXIT_LATENCY_TOO_LARGE_ERROR = 29,
219
    CC_ISOCH_BUFFER_OVERRUN = 31,
220
    CC_EVENT_LOST_ERROR,
221
    CC_UNDEFINED_ERROR,
222
    CC_INVALID_STREAM_ID_ERROR,
223
    CC_SECONDARY_BANDWIDTH_ERROR,
224
    CC_SPLIT_TRANSACTION_ERROR
225
} TRBCCode;
226

    
227
#define TRB_C               (1<<0)
228
#define TRB_TYPE_SHIFT          10
229
#define TRB_TYPE_MASK       0x3f
230
#define TRB_TYPE(t)         (((t).control >> TRB_TYPE_SHIFT) & TRB_TYPE_MASK)
231

    
232
#define TRB_EV_ED           (1<<2)
233

    
234
#define TRB_TR_ENT          (1<<1)
235
#define TRB_TR_ISP          (1<<2)
236
#define TRB_TR_NS           (1<<3)
237
#define TRB_TR_CH           (1<<4)
238
#define TRB_TR_IOC          (1<<5)
239
#define TRB_TR_IDT          (1<<6)
240
#define TRB_TR_TBC_SHIFT        7
241
#define TRB_TR_TBC_MASK     0x3
242
#define TRB_TR_BEI          (1<<9)
243
#define TRB_TR_TLBPC_SHIFT      16
244
#define TRB_TR_TLBPC_MASK   0xf
245
#define TRB_TR_FRAMEID_SHIFT    20
246
#define TRB_TR_FRAMEID_MASK 0x7ff
247
#define TRB_TR_SIA          (1<<31)
248

    
249
#define TRB_TR_DIR          (1<<16)
250

    
251
#define TRB_CR_SLOTID_SHIFT     24
252
#define TRB_CR_SLOTID_MASK  0xff
253
#define TRB_CR_EPID_SHIFT       16
254
#define TRB_CR_EPID_MASK    0x1f
255

    
256
#define TRB_CR_BSR          (1<<9)
257
#define TRB_CR_DC           (1<<9)
258

    
259
#define TRB_LK_TC           (1<<1)
260

    
261
#define EP_TYPE_MASK        0x7
262
#define EP_TYPE_SHIFT           3
263

    
264
#define EP_STATE_MASK       0x7
265
#define EP_DISABLED         (0<<0)
266
#define EP_RUNNING          (1<<0)
267
#define EP_HALTED           (2<<0)
268
#define EP_STOPPED          (3<<0)
269
#define EP_ERROR            (4<<0)
270

    
271
#define SLOT_STATE_MASK     0x1f
272
#define SLOT_STATE_SHIFT        27
273
#define SLOT_STATE(s)       (((s)>>SLOT_STATE_SHIFT)&SLOT_STATE_MASK)
274
#define SLOT_ENABLED        0
275
#define SLOT_DEFAULT        1
276
#define SLOT_ADDRESSED      2
277
#define SLOT_CONFIGURED     3
278

    
279
#define SLOT_CONTEXT_ENTRIES_MASK 0x1f
280
#define SLOT_CONTEXT_ENTRIES_SHIFT 27
281

    
282
typedef enum EPType {
283
    ET_INVALID = 0,
284
    ET_ISO_OUT,
285
    ET_BULK_OUT,
286
    ET_INTR_OUT,
287
    ET_CONTROL,
288
    ET_ISO_IN,
289
    ET_BULK_IN,
290
    ET_INTR_IN,
291
} EPType;
292

    
293
typedef struct XHCIRing {
294
    target_phys_addr_t base;
295
    target_phys_addr_t dequeue;
296
    bool ccs;
297
} XHCIRing;
298

    
299
typedef struct XHCIPort {
300
    USBPort port;
301
    uint32_t portsc;
302
} XHCIPort;
303

    
304
struct XHCIState;
305
typedef struct XHCIState XHCIState;
306

    
307
typedef struct XHCITransfer {
308
    XHCIState *xhci;
309
    USBPacket packet;
310
    bool running_async;
311
    bool running_retry;
312
    bool cancelled;
313
    bool complete;
314
    bool backgrounded;
315
    unsigned int iso_pkts;
316
    unsigned int slotid;
317
    unsigned int epid;
318
    bool in_xfer;
319
    bool iso_xfer;
320
    bool bg_xfer;
321

    
322
    unsigned int trb_count;
323
    unsigned int trb_alloced;
324
    XHCITRB *trbs;
325

    
326
    unsigned int data_length;
327
    unsigned int data_alloced;
328
    uint8_t *data;
329

    
330
    TRBCCode status;
331

    
332
    unsigned int pkts;
333
    unsigned int pktsize;
334
    unsigned int cur_pkt;
335
} XHCITransfer;
336

    
337
typedef struct XHCIEPContext {
338
    XHCIRing ring;
339
    unsigned int next_xfer;
340
    unsigned int comp_xfer;
341
    XHCITransfer transfers[TD_QUEUE];
342
    XHCITransfer *retry;
343
    bool bg_running;
344
    bool bg_updating;
345
    unsigned int next_bg;
346
    XHCITransfer bg_transfers[BG_XFERS];
347
    EPType type;
348
    target_phys_addr_t pctx;
349
    unsigned int max_psize;
350
    bool has_bg;
351
    uint32_t state;
352
} XHCIEPContext;
353

    
354
typedef struct XHCISlot {
355
    bool enabled;
356
    target_phys_addr_t ctx;
357
    unsigned int port;
358
    unsigned int devaddr;
359
    XHCIEPContext * eps[31];
360
} XHCISlot;
361

    
362
typedef struct XHCIEvent {
363
    TRBType type;
364
    TRBCCode ccode;
365
    uint64_t ptr;
366
    uint32_t length;
367
    uint32_t flags;
368
    uint8_t slotid;
369
    uint8_t epid;
370
} XHCIEvent;
371

    
372
struct XHCIState {
373
    PCIDevice pci_dev;
374
    USBBus bus;
375
    qemu_irq irq;
376
    MemoryRegion mem;
377
    const char *name;
378
    uint32_t msi;
379
    unsigned int devaddr;
380

    
381
    /* Operational Registers */
382
    uint32_t usbcmd;
383
    uint32_t usbsts;
384
    uint32_t dnctrl;
385
    uint32_t crcr_low;
386
    uint32_t crcr_high;
387
    uint32_t dcbaap_low;
388
    uint32_t dcbaap_high;
389
    uint32_t config;
390

    
391
    XHCIPort ports[MAXPORTS];
392
    XHCISlot slots[MAXSLOTS];
393

    
394
    /* Runtime Registers */
395
    uint32_t mfindex;
396
    /* note: we only support one interrupter */
397
    uint32_t iman;
398
    uint32_t imod;
399
    uint32_t erstsz;
400
    uint32_t erstba_low;
401
    uint32_t erstba_high;
402
    uint32_t erdp_low;
403
    uint32_t erdp_high;
404

    
405
    target_phys_addr_t er_start;
406
    uint32_t er_size;
407
    bool er_pcs;
408
    unsigned int er_ep_idx;
409
    bool er_full;
410

    
411
    XHCIEvent ev_buffer[EV_QUEUE];
412
    unsigned int ev_buffer_put;
413
    unsigned int ev_buffer_get;
414

    
415
    XHCIRing cmd_ring;
416
};
417

    
418
typedef struct XHCIEvRingSeg {
419
    uint32_t addr_low;
420
    uint32_t addr_high;
421
    uint32_t size;
422
    uint32_t rsvd;
423
} XHCIEvRingSeg;
424

    
425
#ifdef DEBUG_XHCI
426
static const char *TRBType_names[] = {
427
    [TRB_RESERVED]                     = "TRB_RESERVED",
428
    [TR_NORMAL]                        = "TR_NORMAL",
429
    [TR_SETUP]                         = "TR_SETUP",
430
    [TR_DATA]                          = "TR_DATA",
431
    [TR_STATUS]                        = "TR_STATUS",
432
    [TR_ISOCH]                         = "TR_ISOCH",
433
    [TR_LINK]                          = "TR_LINK",
434
    [TR_EVDATA]                        = "TR_EVDATA",
435
    [TR_NOOP]                          = "TR_NOOP",
436
    [CR_ENABLE_SLOT]                   = "CR_ENABLE_SLOT",
437
    [CR_DISABLE_SLOT]                  = "CR_DISABLE_SLOT",
438
    [CR_ADDRESS_DEVICE]                = "CR_ADDRESS_DEVICE",
439
    [CR_CONFIGURE_ENDPOINT]            = "CR_CONFIGURE_ENDPOINT",
440
    [CR_EVALUATE_CONTEXT]              = "CR_EVALUATE_CONTEXT",
441
    [CR_RESET_ENDPOINT]                = "CR_RESET_ENDPOINT",
442
    [CR_STOP_ENDPOINT]                 = "CR_STOP_ENDPOINT",
443
    [CR_SET_TR_DEQUEUE]                = "CR_SET_TR_DEQUEUE",
444
    [CR_RESET_DEVICE]                  = "CR_RESET_DEVICE",
445
    [CR_FORCE_EVENT]                   = "CR_FORCE_EVENT",
446
    [CR_NEGOTIATE_BW]                  = "CR_NEGOTIATE_BW",
447
    [CR_SET_LATENCY_TOLERANCE]         = "CR_SET_LATENCY_TOLERANCE",
448
    [CR_GET_PORT_BANDWIDTH]            = "CR_GET_PORT_BANDWIDTH",
449
    [CR_FORCE_HEADER]                  = "CR_FORCE_HEADER",
450
    [CR_NOOP]                          = "CR_NOOP",
451
    [ER_TRANSFER]                      = "ER_TRANSFER",
452
    [ER_COMMAND_COMPLETE]              = "ER_COMMAND_COMPLETE",
453
    [ER_PORT_STATUS_CHANGE]            = "ER_PORT_STATUS_CHANGE",
454
    [ER_BANDWIDTH_REQUEST]             = "ER_BANDWIDTH_REQUEST",
455
    [ER_DOORBELL]                      = "ER_DOORBELL",
456
    [ER_HOST_CONTROLLER]               = "ER_HOST_CONTROLLER",
457
    [ER_DEVICE_NOTIFICATION]           = "ER_DEVICE_NOTIFICATION",
458
    [ER_MFINDEX_WRAP]                  = "ER_MFINDEX_WRAP",
459
    [CR_VENDOR_VIA_CHALLENGE_RESPONSE] = "CR_VENDOR_VIA_CHALLENGE_RESPONSE",
460
    [CR_VENDOR_NEC_FIRMWARE_REVISION]  = "CR_VENDOR_NEC_FIRMWARE_REVISION",
461
    [CR_VENDOR_NEC_CHALLENGE_RESPONSE] = "CR_VENDOR_NEC_CHALLENGE_RESPONSE",
462
};
463

    
464
static const char *lookup_name(uint32_t index, const char **list, uint32_t llen)
465
{
466
    if (index >= llen || list[index] == NULL) {
467
        return "???";
468
    }
469
    return list[index];
470
}
471

    
472
static const char *trb_name(XHCITRB *trb)
473
{
474
    return lookup_name(TRB_TYPE(*trb), TRBType_names,
475
                       ARRAY_SIZE(TRBType_names));
476
}
477
#endif
478

    
479
static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
480
                         unsigned int epid);
481

    
482
static inline target_phys_addr_t xhci_addr64(uint32_t low, uint32_t high)
483
{
484
#if TARGET_PHYS_ADDR_BITS > 32
485
    return low | ((target_phys_addr_t)high << 32);
486
#else
487
    return low;
488
#endif
489
}
490

    
491
static inline target_phys_addr_t xhci_mask64(uint64_t addr)
492
{
493
#if TARGET_PHYS_ADDR_BITS > 32
494
    return addr;
495
#else
496
    return addr & 0xffffffff;
497
#endif
498
}
499

    
500
static void xhci_irq_update(XHCIState *xhci)
501
{
502
    int level = 0;
503

    
504
    if (xhci->iman & IMAN_IP && xhci->iman & IMAN_IE &&
505
        xhci->usbcmd && USBCMD_INTE) {
506
        level = 1;
507
    }
508

    
509
    DPRINTF("xhci_irq_update(): %d\n", level);
510

    
511
    if (xhci->msi && msi_enabled(&xhci->pci_dev)) {
512
        if (level) {
513
            DPRINTF("xhci_irq_update(): MSI signal\n");
514
            msi_notify(&xhci->pci_dev, 0);
515
        }
516
    } else {
517
        qemu_set_irq(xhci->irq, level);
518
    }
519
}
520

    
521
static inline int xhci_running(XHCIState *xhci)
522
{
523
    return !(xhci->usbsts & USBSTS_HCH) && !xhci->er_full;
524
}
525

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

    
532
static void xhci_write_event(XHCIState *xhci, XHCIEvent *event)
533
{
534
    XHCITRB ev_trb;
535
    target_phys_addr_t addr;
536

    
537
    ev_trb.parameter = cpu_to_le64(event->ptr);
538
    ev_trb.status = cpu_to_le32(event->length | (event->ccode << 24));
539
    ev_trb.control = (event->slotid << 24) | (event->epid << 16) |
540
                     event->flags | (event->type << TRB_TYPE_SHIFT);
541
    if (xhci->er_pcs) {
542
        ev_trb.control |= TRB_C;
543
    }
544
    ev_trb.control = cpu_to_le32(ev_trb.control);
545

    
546
    DPRINTF("xhci_write_event(): [%d] %016"PRIx64" %08x %08x %s\n",
547
            xhci->er_ep_idx, ev_trb.parameter, ev_trb.status, ev_trb.control,
548
            trb_name(&ev_trb));
549

    
550
    addr = xhci->er_start + TRB_SIZE*xhci->er_ep_idx;
551
    cpu_physical_memory_write(addr, (uint8_t *) &ev_trb, TRB_SIZE);
552

    
553
    xhci->er_ep_idx++;
554
    if (xhci->er_ep_idx >= xhci->er_size) {
555
        xhci->er_ep_idx = 0;
556
        xhci->er_pcs = !xhci->er_pcs;
557
    }
558
}
559

    
560
static void xhci_events_update(XHCIState *xhci)
561
{
562
    target_phys_addr_t erdp;
563
    unsigned int dp_idx;
564
    bool do_irq = 0;
565

    
566
    if (xhci->usbsts & USBSTS_HCH) {
567
        return;
568
    }
569

    
570
    erdp = xhci_addr64(xhci->erdp_low, xhci->erdp_high);
571
    if (erdp < xhci->er_start ||
572
        erdp >= (xhci->er_start + TRB_SIZE*xhci->er_size)) {
573
        fprintf(stderr, "xhci: ERDP out of bounds: "TARGET_FMT_plx"\n", erdp);
574
        fprintf(stderr, "xhci: ER at "TARGET_FMT_plx" len %d\n",
575
                xhci->er_start, xhci->er_size);
576
        xhci_die(xhci);
577
        return;
578
    }
579
    dp_idx = (erdp - xhci->er_start) / TRB_SIZE;
580
    assert(dp_idx < xhci->er_size);
581

    
582
    /* NEC didn't read section 4.9.4 of the spec (v1.0 p139 top Note) and thus
583
     * deadlocks when the ER is full. Hack it by holding off events until
584
     * the driver decides to free at least half of the ring */
585
    if (xhci->er_full) {
586
        int er_free = dp_idx - xhci->er_ep_idx;
587
        if (er_free <= 0) {
588
            er_free += xhci->er_size;
589
        }
590
        if (er_free < (xhci->er_size/2)) {
591
            DPRINTF("xhci_events_update(): event ring still "
592
                    "more than half full (hack)\n");
593
            return;
594
        }
595
    }
596

    
597
    while (xhci->ev_buffer_put != xhci->ev_buffer_get) {
598
        assert(xhci->er_full);
599
        if (((xhci->er_ep_idx+1) % xhci->er_size) == dp_idx) {
600
            DPRINTF("xhci_events_update(): event ring full again\n");
601
#ifndef ER_FULL_HACK
602
            XHCIEvent full = {ER_HOST_CONTROLLER, CC_EVENT_RING_FULL_ERROR};
603
            xhci_write_event(xhci, &full);
604
#endif
605
            do_irq = 1;
606
            break;
607
        }
608
        XHCIEvent *event = &xhci->ev_buffer[xhci->ev_buffer_get];
609
        xhci_write_event(xhci, event);
610
        xhci->ev_buffer_get++;
611
        do_irq = 1;
612
        if (xhci->ev_buffer_get == EV_QUEUE) {
613
            xhci->ev_buffer_get = 0;
614
        }
615
    }
616

    
617
    if (do_irq) {
618
        xhci->erdp_low |= ERDP_EHB;
619
        xhci->iman |= IMAN_IP;
620
        xhci->usbsts |= USBSTS_EINT;
621
        xhci_irq_update(xhci);
622
    }
623

    
624
    if (xhci->er_full && xhci->ev_buffer_put == xhci->ev_buffer_get) {
625
        DPRINTF("xhci_events_update(): event ring no longer full\n");
626
        xhci->er_full = 0;
627
    }
628
    return;
629
}
630

    
631
static void xhci_event(XHCIState *xhci, XHCIEvent *event)
632
{
633
    target_phys_addr_t erdp;
634
    unsigned int dp_idx;
635

    
636
    if (xhci->er_full) {
637
        DPRINTF("xhci_event(): ER full, queueing\n");
638
        if (((xhci->ev_buffer_put+1) % EV_QUEUE) == xhci->ev_buffer_get) {
639
            fprintf(stderr, "xhci: event queue full, dropping event!\n");
640
            return;
641
        }
642
        xhci->ev_buffer[xhci->ev_buffer_put++] = *event;
643
        if (xhci->ev_buffer_put == EV_QUEUE) {
644
            xhci->ev_buffer_put = 0;
645
        }
646
        return;
647
    }
648

    
649
    erdp = xhci_addr64(xhci->erdp_low, xhci->erdp_high);
650
    if (erdp < xhci->er_start ||
651
        erdp >= (xhci->er_start + TRB_SIZE*xhci->er_size)) {
652
        fprintf(stderr, "xhci: ERDP out of bounds: "TARGET_FMT_plx"\n", erdp);
653
        fprintf(stderr, "xhci: ER at "TARGET_FMT_plx" len %d\n",
654
                xhci->er_start, xhci->er_size);
655
        xhci_die(xhci);
656
        return;
657
    }
658

    
659
    dp_idx = (erdp - xhci->er_start) / TRB_SIZE;
660
    assert(dp_idx < xhci->er_size);
661

    
662
    if ((xhci->er_ep_idx+1) % xhci->er_size == dp_idx) {
663
        DPRINTF("xhci_event(): ER full, queueing\n");
664
#ifndef ER_FULL_HACK
665
        XHCIEvent full = {ER_HOST_CONTROLLER, CC_EVENT_RING_FULL_ERROR};
666
        xhci_write_event(xhci, &full);
667
#endif
668
        xhci->er_full = 1;
669
        if (((xhci->ev_buffer_put+1) % EV_QUEUE) == xhci->ev_buffer_get) {
670
            fprintf(stderr, "xhci: event queue full, dropping event!\n");
671
            return;
672
        }
673
        xhci->ev_buffer[xhci->ev_buffer_put++] = *event;
674
        if (xhci->ev_buffer_put == EV_QUEUE) {
675
            xhci->ev_buffer_put = 0;
676
        }
677
    } else {
678
        xhci_write_event(xhci, event);
679
    }
680

    
681
    xhci->erdp_low |= ERDP_EHB;
682
    xhci->iman |= IMAN_IP;
683
    xhci->usbsts |= USBSTS_EINT;
684

    
685
    xhci_irq_update(xhci);
686
}
687

    
688
static void xhci_ring_init(XHCIState *xhci, XHCIRing *ring,
689
                           target_phys_addr_t base)
690
{
691
    ring->base = base;
692
    ring->dequeue = base;
693
    ring->ccs = 1;
694
}
695

    
696
static TRBType xhci_ring_fetch(XHCIState *xhci, XHCIRing *ring, XHCITRB *trb,
697
                               target_phys_addr_t *addr)
698
{
699
    while (1) {
700
        TRBType type;
701
        cpu_physical_memory_read(ring->dequeue, (uint8_t *) trb, TRB_SIZE);
702
        trb->addr = ring->dequeue;
703
        trb->ccs = ring->ccs;
704
        le64_to_cpus(&trb->parameter);
705
        le32_to_cpus(&trb->status);
706
        le32_to_cpus(&trb->control);
707

    
708
        DPRINTF("xhci: TRB fetched [" TARGET_FMT_plx "]: "
709
                "%016" PRIx64 " %08x %08x %s\n",
710
                ring->dequeue, trb->parameter, trb->status, trb->control,
711
                trb_name(trb));
712

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

    
717
        type = TRB_TYPE(*trb);
718

    
719
        if (type != TR_LINK) {
720
            if (addr) {
721
                *addr = ring->dequeue;
722
            }
723
            ring->dequeue += TRB_SIZE;
724
            return type;
725
        } else {
726
            ring->dequeue = xhci_mask64(trb->parameter);
727
            if (trb->control & TRB_LK_TC) {
728
                ring->ccs = !ring->ccs;
729
            }
730
        }
731
    }
732
}
733

    
734
static int xhci_ring_chain_length(XHCIState *xhci, const XHCIRing *ring)
735
{
736
    XHCITRB trb;
737
    int length = 0;
738
    target_phys_addr_t dequeue = ring->dequeue;
739
    bool ccs = ring->ccs;
740
    /* hack to bundle together the two/three TDs that make a setup transfer */
741
    bool control_td_set = 0;
742

    
743
    while (1) {
744
        TRBType type;
745
        cpu_physical_memory_read(dequeue, (uint8_t *) &trb, TRB_SIZE);
746
        le64_to_cpus(&trb.parameter);
747
        le32_to_cpus(&trb.status);
748
        le32_to_cpus(&trb.control);
749

    
750
        DPRINTF("xhci: TRB peeked [" TARGET_FMT_plx "]: "
751
                "%016" PRIx64 " %08x %08x\n",
752
                dequeue, trb.parameter, trb.status, trb.control);
753

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

    
758
        type = TRB_TYPE(trb);
759

    
760
        if (type == TR_LINK) {
761
            dequeue = xhci_mask64(trb.parameter);
762
            if (trb.control & TRB_LK_TC) {
763
                ccs = !ccs;
764
            }
765
            continue;
766
        }
767

    
768
        length += 1;
769
        dequeue += TRB_SIZE;
770

    
771
        if (type == TR_SETUP) {
772
            control_td_set = 1;
773
        } else if (type == TR_STATUS) {
774
            control_td_set = 0;
775
        }
776

    
777
        if (!control_td_set && !(trb.control & TRB_TR_CH)) {
778
            return length;
779
        }
780
    }
781
}
782

    
783
static void xhci_er_reset(XHCIState *xhci)
784
{
785
    XHCIEvRingSeg seg;
786

    
787
    /* cache the (sole) event ring segment location */
788
    if (xhci->erstsz != 1) {
789
        fprintf(stderr, "xhci: invalid value for ERSTSZ: %d\n", xhci->erstsz);
790
        xhci_die(xhci);
791
        return;
792
    }
793
    target_phys_addr_t erstba = xhci_addr64(xhci->erstba_low, xhci->erstba_high);
794
    cpu_physical_memory_read(erstba, (uint8_t *) &seg, sizeof(seg));
795
    le32_to_cpus(&seg.addr_low);
796
    le32_to_cpus(&seg.addr_high);
797
    le32_to_cpus(&seg.size);
798
    if (seg.size < 16 || seg.size > 4096) {
799
        fprintf(stderr, "xhci: invalid value for segment size: %d\n", seg.size);
800
        xhci_die(xhci);
801
        return;
802
    }
803
    xhci->er_start = xhci_addr64(seg.addr_low, seg.addr_high);
804
    xhci->er_size = seg.size;
805

    
806
    xhci->er_ep_idx = 0;
807
    xhci->er_pcs = 1;
808
    xhci->er_full = 0;
809

    
810
    DPRINTF("xhci: event ring:" TARGET_FMT_plx " [%d]\n",
811
            xhci->er_start, xhci->er_size);
812
}
813

    
814
static void xhci_run(XHCIState *xhci)
815
{
816
    DPRINTF("xhci_run()\n");
817

    
818
    xhci->usbsts &= ~USBSTS_HCH;
819
}
820

    
821
static void xhci_stop(XHCIState *xhci)
822
{
823
    DPRINTF("xhci_stop()\n");
824
    xhci->usbsts |= USBSTS_HCH;
825
    xhci->crcr_low &= ~CRCR_CRR;
826
}
827

    
828
static void xhci_set_ep_state(XHCIState *xhci, XHCIEPContext *epctx,
829
                              uint32_t state)
830
{
831
    uint32_t ctx[5];
832
    if (epctx->state == state) {
833
        return;
834
    }
835

    
836
    cpu_physical_memory_read(epctx->pctx, (uint8_t *) ctx, sizeof(ctx));
837
    ctx[0] &= ~EP_STATE_MASK;
838
    ctx[0] |= state;
839
    ctx[2] = epctx->ring.dequeue | epctx->ring.ccs;
840
    ctx[3] = (epctx->ring.dequeue >> 16) >> 16;
841
    DPRINTF("xhci: set epctx: " TARGET_FMT_plx " state=%d dequeue=%08x%08x\n",
842
            epctx->pctx, state, ctx[3], ctx[2]);
843
    cpu_physical_memory_write(epctx->pctx, (uint8_t *) ctx, sizeof(ctx));
844
    epctx->state = state;
845
}
846

    
847
static TRBCCode xhci_enable_ep(XHCIState *xhci, unsigned int slotid,
848
                               unsigned int epid, target_phys_addr_t pctx,
849
                               uint32_t *ctx)
850
{
851
    XHCISlot *slot;
852
    XHCIEPContext *epctx;
853
    target_phys_addr_t dequeue;
854
    int i;
855

    
856
    assert(slotid >= 1 && slotid <= MAXSLOTS);
857
    assert(epid >= 1 && epid <= 31);
858

    
859
    DPRINTF("xhci_enable_ep(%d, %d)\n", slotid, epid);
860

    
861
    slot = &xhci->slots[slotid-1];
862
    if (slot->eps[epid-1]) {
863
        fprintf(stderr, "xhci: slot %d ep %d already enabled!\n", slotid, epid);
864
        return CC_TRB_ERROR;
865
    }
866

    
867
    epctx = g_malloc(sizeof(XHCIEPContext));
868
    memset(epctx, 0, sizeof(XHCIEPContext));
869

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

    
872
    dequeue = xhci_addr64(ctx[2] & ~0xf, ctx[3]);
873
    xhci_ring_init(xhci, &epctx->ring, dequeue);
874
    epctx->ring.ccs = ctx[2] & 1;
875

    
876
    epctx->type = (ctx[1] >> EP_TYPE_SHIFT) & EP_TYPE_MASK;
877
    DPRINTF("xhci: endpoint %d.%d type is %d\n", epid/2, epid%2, epctx->type);
878
    epctx->pctx = pctx;
879
    epctx->max_psize = ctx[1]>>16;
880
    epctx->max_psize *= 1+((ctx[1]>>8)&0xff);
881
    epctx->has_bg = false;
882
    if (epctx->type == ET_ISO_IN) {
883
        epctx->has_bg = true;
884
    }
885
    DPRINTF("xhci: endpoint %d.%d max transaction (burst) size is %d\n",
886
            epid/2, epid%2, epctx->max_psize);
887
    for (i = 0; i < ARRAY_SIZE(epctx->transfers); i++) {
888
        usb_packet_init(&epctx->transfers[i].packet);
889
    }
890

    
891
    epctx->state = EP_RUNNING;
892
    ctx[0] &= ~EP_STATE_MASK;
893
    ctx[0] |= EP_RUNNING;
894

    
895
    return CC_SUCCESS;
896
}
897

    
898
static int xhci_ep_nuke_xfers(XHCIState *xhci, unsigned int slotid,
899
                               unsigned int epid)
900
{
901
    XHCISlot *slot;
902
    XHCIEPContext *epctx;
903
    int i, xferi, killed = 0;
904
    assert(slotid >= 1 && slotid <= MAXSLOTS);
905
    assert(epid >= 1 && epid <= 31);
906

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

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

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

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

    
917
    xferi = epctx->next_xfer;
918
    for (i = 0; i < TD_QUEUE; i++) {
919
        XHCITransfer *t = &epctx->transfers[xferi];
920
        if (t->running_async) {
921
            usb_cancel_packet(&t->packet);
922
            t->running_async = 0;
923
            t->cancelled = 1;
924
            DPRINTF("xhci: cancelling transfer %d, waiting for it to complete...\n", i);
925
            killed++;
926
        }
927
        if (t->running_retry) {
928
            t->running_retry = 0;
929
            epctx->retry = NULL;
930
        }
931
        if (t->backgrounded) {
932
            t->backgrounded = 0;
933
        }
934
        if (t->trbs) {
935
            g_free(t->trbs);
936
        }
937
        if (t->data) {
938
            g_free(t->data);
939
        }
940

    
941
        t->trbs = NULL;
942
        t->data = NULL;
943
        t->trb_count = t->trb_alloced = 0;
944
        t->data_length = t->data_alloced = 0;
945
        xferi = (xferi + 1) % TD_QUEUE;
946
    }
947
    if (epctx->has_bg) {
948
        xferi = epctx->next_bg;
949
        for (i = 0; i < BG_XFERS; i++) {
950
            XHCITransfer *t = &epctx->bg_transfers[xferi];
951
            if (t->running_async) {
952
                usb_cancel_packet(&t->packet);
953
                t->running_async = 0;
954
                t->cancelled = 1;
955
                DPRINTF("xhci: cancelling bg transfer %d, waiting for it to complete...\n", i);
956
                killed++;
957
            }
958
            if (t->data) {
959
                g_free(t->data);
960
            }
961

    
962
            t->data = NULL;
963
            xferi = (xferi + 1) % BG_XFERS;
964
        }
965
    }
966
    return killed;
967
}
968

    
969
static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,
970
                               unsigned int epid)
971
{
972
    XHCISlot *slot;
973
    XHCIEPContext *epctx;
974

    
975
    assert(slotid >= 1 && slotid <= MAXSLOTS);
976
    assert(epid >= 1 && epid <= 31);
977

    
978
    DPRINTF("xhci_disable_ep(%d, %d)\n", slotid, epid);
979

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

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

    
987
    xhci_ep_nuke_xfers(xhci, slotid, epid);
988

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

    
991
    xhci_set_ep_state(xhci, epctx, EP_DISABLED);
992

    
993
    g_free(epctx);
994
    slot->eps[epid-1] = NULL;
995

    
996
    return CC_SUCCESS;
997
}
998

    
999
static TRBCCode xhci_stop_ep(XHCIState *xhci, unsigned int slotid,
1000
                             unsigned int epid)
1001
{
1002
    XHCISlot *slot;
1003
    XHCIEPContext *epctx;
1004

    
1005
    DPRINTF("xhci_stop_ep(%d, %d)\n", slotid, epid);
1006

    
1007
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1008

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

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

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

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

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

    
1028
    xhci_set_ep_state(xhci, epctx, EP_STOPPED);
1029

    
1030
    return CC_SUCCESS;
1031
}
1032

    
1033
static TRBCCode xhci_reset_ep(XHCIState *xhci, unsigned int slotid,
1034
                              unsigned int epid)
1035
{
1036
    XHCISlot *slot;
1037
    XHCIEPContext *epctx;
1038
    USBDevice *dev;
1039

    
1040
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1041

    
1042
    DPRINTF("xhci_reset_ep(%d, %d)\n", slotid, epid);
1043

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

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

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

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

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

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

    
1069
    uint8_t ep = epid>>1;
1070

    
1071
    if (epid & 1) {
1072
        ep |= 0x80;
1073
    }
1074

    
1075
    dev = xhci->ports[xhci->slots[slotid-1].port-1].port.dev;
1076
    if (!dev) {
1077
        return CC_USB_TRANSACTION_ERROR;
1078
    }
1079

    
1080
    xhci_set_ep_state(xhci, epctx, EP_STOPPED);
1081

    
1082
    return CC_SUCCESS;
1083
}
1084

    
1085
static TRBCCode xhci_set_ep_dequeue(XHCIState *xhci, unsigned int slotid,
1086
                                    unsigned int epid, uint64_t pdequeue)
1087
{
1088
    XHCISlot *slot;
1089
    XHCIEPContext *epctx;
1090
    target_phys_addr_t dequeue;
1091

    
1092
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1093

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

    
1099
    DPRINTF("xhci_set_ep_dequeue(%d, %d, %016"PRIx64")\n", slotid, epid, pdequeue);
1100
    dequeue = xhci_mask64(pdequeue);
1101

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

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

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

    
1111

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

    
1117
    xhci_ring_init(xhci, &epctx->ring, dequeue & ~0xF);
1118
    epctx->ring.ccs = dequeue & 1;
1119

    
1120
    xhci_set_ep_state(xhci, epctx, EP_STOPPED);
1121

    
1122
    return CC_SUCCESS;
1123
}
1124

    
1125
static int xhci_xfer_data(XHCITransfer *xfer, uint8_t *data,
1126
                          unsigned int length, bool in_xfer, bool out_xfer,
1127
                          bool report)
1128
{
1129
    int i;
1130
    uint32_t edtla = 0;
1131
    unsigned int transferred = 0;
1132
    unsigned int left = length;
1133
    bool reported = 0;
1134
    bool shortpkt = 0;
1135
    XHCIEvent event = {ER_TRANSFER, CC_SUCCESS};
1136
    XHCIState *xhci = xfer->xhci;
1137

    
1138
    DPRINTF("xhci_xfer_data(len=%d, in_xfer=%d, out_xfer=%d, report=%d)\n",
1139
            length, in_xfer, out_xfer, report);
1140

    
1141
    assert(!(in_xfer && out_xfer));
1142

    
1143
    for (i = 0; i < xfer->trb_count; i++) {
1144
        XHCITRB *trb = &xfer->trbs[i];
1145
        target_phys_addr_t addr;
1146
        unsigned int chunk = 0;
1147

    
1148
        switch (TRB_TYPE(*trb)) {
1149
        case TR_DATA:
1150
            if ((!(trb->control & TRB_TR_DIR)) != (!in_xfer)) {
1151
                fprintf(stderr, "xhci: data direction mismatch for TR_DATA\n");
1152
                xhci_die(xhci);
1153
                return transferred;
1154
            }
1155
            /* fallthrough */
1156
        case TR_NORMAL:
1157
        case TR_ISOCH:
1158
            addr = xhci_mask64(trb->parameter);
1159
            chunk = trb->status & 0x1ffff;
1160
            if (chunk > left) {
1161
                chunk = left;
1162
                shortpkt = 1;
1163
            }
1164
            if (in_xfer || out_xfer) {
1165
                if (trb->control & TRB_TR_IDT) {
1166
                    uint64_t idata;
1167
                    if (chunk > 8 || in_xfer) {
1168
                        fprintf(stderr, "xhci: invalid immediate data TRB\n");
1169
                        xhci_die(xhci);
1170
                        return transferred;
1171
                    }
1172
                    idata = le64_to_cpu(trb->parameter);
1173
                    memcpy(data, &idata, chunk);
1174
                } else {
1175
                    DPRINTF("xhci_xfer_data: r/w(%d) %d bytes at "
1176
                            TARGET_FMT_plx "\n", in_xfer, chunk, addr);
1177
                    if (in_xfer) {
1178
                        cpu_physical_memory_write(addr, data, chunk);
1179
                    } else {
1180
                        cpu_physical_memory_read(addr, data, chunk);
1181
                    }
1182
#ifdef DEBUG_DATA
1183
                    unsigned int count = chunk;
1184
                    int i;
1185
                    if (count > 16) {
1186
                        count = 16;
1187
                    }
1188
                    DPRINTF(" ::");
1189
                    for (i = 0; i < count; i++) {
1190
                        DPRINTF(" %02x", data[i]);
1191
                    }
1192
                    DPRINTF("\n");
1193
#endif
1194
                }
1195
            }
1196
            left -= chunk;
1197
            data += chunk;
1198
            edtla += chunk;
1199
            transferred += chunk;
1200
            break;
1201
        case TR_STATUS:
1202
            reported = 0;
1203
            shortpkt = 0;
1204
            break;
1205
        }
1206

    
1207
        if (report && !reported && (trb->control & TRB_TR_IOC ||
1208
            (shortpkt && (trb->control & TRB_TR_ISP)))) {
1209
            event.slotid = xfer->slotid;
1210
            event.epid = xfer->epid;
1211
            event.length = (trb->status & 0x1ffff) - chunk;
1212
            event.flags = 0;
1213
            event.ptr = trb->addr;
1214
            if (xfer->status == CC_SUCCESS) {
1215
                event.ccode = shortpkt ? CC_SHORT_PACKET : CC_SUCCESS;
1216
            } else {
1217
                event.ccode = xfer->status;
1218
            }
1219
            if (TRB_TYPE(*trb) == TR_EVDATA) {
1220
                event.ptr = trb->parameter;
1221
                event.flags |= TRB_EV_ED;
1222
                event.length = edtla & 0xffffff;
1223
                DPRINTF("xhci_xfer_data: EDTLA=%d\n", event.length);
1224
                edtla = 0;
1225
            }
1226
            xhci_event(xhci, &event);
1227
            reported = 1;
1228
        }
1229
    }
1230
    return transferred;
1231
}
1232

    
1233
static void xhci_stall_ep(XHCITransfer *xfer)
1234
{
1235
    XHCIState *xhci = xfer->xhci;
1236
    XHCISlot *slot = &xhci->slots[xfer->slotid-1];
1237
    XHCIEPContext *epctx = slot->eps[xfer->epid-1];
1238

    
1239
    epctx->ring.dequeue = xfer->trbs[0].addr;
1240
    epctx->ring.ccs = xfer->trbs[0].ccs;
1241
    xhci_set_ep_state(xhci, epctx, EP_HALTED);
1242
    DPRINTF("xhci: stalled slot %d ep %d\n", xfer->slotid, xfer->epid);
1243
    DPRINTF("xhci: will continue at "TARGET_FMT_plx"\n", epctx->ring.dequeue);
1244
}
1245

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

    
1249
static void xhci_bg_update(XHCIState *xhci, XHCIEPContext *epctx)
1250
{
1251
    if (epctx->bg_updating) {
1252
        return;
1253
    }
1254
    DPRINTF("xhci_bg_update(%p, %p)\n", xhci, epctx);
1255
    assert(epctx->has_bg);
1256
    DPRINTF("xhci: fg=%d bg=%d\n", epctx->comp_xfer, epctx->next_bg);
1257
    epctx->bg_updating = 1;
1258
    while (epctx->transfers[epctx->comp_xfer].backgrounded &&
1259
           epctx->bg_transfers[epctx->next_bg].complete) {
1260
        XHCITransfer *fg = &epctx->transfers[epctx->comp_xfer];
1261
        XHCITransfer *bg = &epctx->bg_transfers[epctx->next_bg];
1262
#if 0
1263
        DPRINTF("xhci: completing fg %d from bg %d.%d (stat: %d)\n",
1264
                epctx->comp_xfer, epctx->next_bg, bg->cur_pkt,
1265
                bg->usbxfer->iso_packet_desc[bg->cur_pkt].status
1266
               );
1267
#endif
1268
        assert(epctx->type == ET_ISO_IN);
1269
        assert(bg->iso_xfer);
1270
        assert(bg->in_xfer);
1271
        uint8_t *p = bg->data + bg->cur_pkt * bg->pktsize;
1272
#if 0
1273
        int len = bg->usbxfer->iso_packet_desc[bg->cur_pkt].actual_length;
1274
        fg->status = libusb_to_ccode(bg->usbxfer->iso_packet_desc[bg->cur_pkt].status);
1275
#else
1276
        int len = 0;
1277
        FIXME();
1278
#endif
1279
        fg->complete = 1;
1280
        fg->backgrounded = 0;
1281

    
1282
        if (fg->status == CC_STALL_ERROR) {
1283
            xhci_stall_ep(fg);
1284
        }
1285

    
1286
        xhci_xfer_data(fg, p, len, 1, 0, 1);
1287

    
1288
        epctx->comp_xfer++;
1289
        if (epctx->comp_xfer == TD_QUEUE) {
1290
            epctx->comp_xfer = 0;
1291
        }
1292
        DPRINTF("next fg xfer: %d\n", epctx->comp_xfer);
1293
        bg->cur_pkt++;
1294
        if (bg->cur_pkt == bg->pkts) {
1295
            bg->complete = 0;
1296
            if (xhci_submit(xhci, bg, epctx) < 0) {
1297
                fprintf(stderr, "xhci: bg resubmit failed\n");
1298
            }
1299
            epctx->next_bg++;
1300
            if (epctx->next_bg == BG_XFERS) {
1301
                epctx->next_bg = 0;
1302
            }
1303
            DPRINTF("next bg xfer: %d\n", epctx->next_bg);
1304

    
1305
        xhci_kick_ep(xhci, fg->slotid, fg->epid);
1306
        }
1307
    }
1308
    epctx->bg_updating = 0;
1309
}
1310

    
1311
#if 0
1312
static void xhci_xfer_cb(struct libusb_transfer *transfer)
1313
{
1314
    XHCIState *xhci;
1315
    XHCITransfer *xfer;
1316

1317
    xfer = (XHCITransfer *)transfer->user_data;
1318
    xhci = xfer->xhci;
1319

1320
    DPRINTF("xhci_xfer_cb(slot=%d, ep=%d, status=%d)\n", xfer->slotid,
1321
            xfer->epid, transfer->status);
1322

1323
    assert(xfer->slotid >= 1 && xfer->slotid <= MAXSLOTS);
1324
    assert(xfer->epid >= 1 && xfer->epid <= 31);
1325

1326
    if (xfer->cancelled) {
1327
        DPRINTF("xhci: transfer cancelled, not reporting anything\n");
1328
        xfer->running = 0;
1329
        return;
1330
    }
1331

1332
    XHCIEPContext *epctx;
1333
    XHCISlot *slot;
1334
    slot = &xhci->slots[xfer->slotid-1];
1335
    assert(slot->eps[xfer->epid-1]);
1336
    epctx = slot->eps[xfer->epid-1];
1337

1338
    if (xfer->bg_xfer) {
1339
        DPRINTF("xhci: background transfer, updating\n");
1340
        xfer->complete = 1;
1341
        xfer->running = 0;
1342
        xhci_bg_update(xhci, epctx);
1343
        return;
1344
    }
1345

1346
    if (xfer->iso_xfer) {
1347
        transfer->status = transfer->iso_packet_desc[0].status;
1348
        transfer->actual_length = transfer->iso_packet_desc[0].actual_length;
1349
    }
1350

1351
    xfer->status = libusb_to_ccode(transfer->status);
1352

1353
    xfer->complete = 1;
1354
    xfer->running = 0;
1355

1356
    if (transfer->status == LIBUSB_TRANSFER_STALL)
1357
        xhci_stall_ep(xhci, epctx, xfer);
1358

1359
    DPRINTF("xhci: transfer actual length = %d\n", transfer->actual_length);
1360

1361
    if (xfer->in_xfer) {
1362
        if (xfer->epid == 1) {
1363
            xhci_xfer_data(xhci, xfer, xfer->data + 8,
1364
                           transfer->actual_length, 1, 0, 1);
1365
        } else {
1366
            xhci_xfer_data(xhci, xfer, xfer->data,
1367
                           transfer->actual_length, 1, 0, 1);
1368
        }
1369
    } else {
1370
        xhci_xfer_data(xhci, xfer, NULL, transfer->actual_length, 0, 0, 1);
1371
    }
1372

1373
    xhci_kick_ep(xhci, xfer->slotid, xfer->epid);
1374
}
1375

1376
static int xhci_hle_control(XHCIState *xhci, XHCITransfer *xfer,
1377
                            uint8_t bmRequestType, uint8_t bRequest,
1378
                            uint16_t wValue, uint16_t wIndex, uint16_t wLength)
1379
{
1380
    uint16_t type_req = (bmRequestType << 8) | bRequest;
1381

1382
    switch (type_req) {
1383
        case 0x0000 | USB_REQ_SET_CONFIGURATION:
1384
            DPRINTF("xhci: HLE switch configuration\n");
1385
            return xhci_switch_config(xhci, xfer->slotid, wValue) == 0;
1386
        case 0x0100 | USB_REQ_SET_INTERFACE:
1387
            DPRINTF("xhci: HLE set interface altsetting\n");
1388
            return xhci_set_iface_alt(xhci, xfer->slotid, wIndex, wValue) == 0;
1389
        case 0x0200 | USB_REQ_CLEAR_FEATURE:
1390
            if (wValue == 0) { // endpoint halt
1391
                DPRINTF("xhci: HLE clear halt\n");
1392
                return xhci_clear_halt(xhci, xfer->slotid, wIndex);
1393
            }
1394
        case 0x0000 | USB_REQ_SET_ADDRESS:
1395
            fprintf(stderr, "xhci: warn: illegal SET_ADDRESS request\n");
1396
            return 0;
1397
        default:
1398
            return 0;
1399
    }
1400
}
1401
#endif
1402

    
1403
static int xhci_setup_packet(XHCITransfer *xfer, USBDevice *dev)
1404
{
1405
    USBEndpoint *ep;
1406
    int dir;
1407

    
1408
    dir = xfer->in_xfer ? USB_TOKEN_IN : USB_TOKEN_OUT;
1409
    ep = usb_ep_get(dev, dir, xfer->epid >> 1);
1410
    usb_packet_setup(&xfer->packet, dir, ep);
1411
    usb_packet_addbuf(&xfer->packet, xfer->data, xfer->data_length);
1412
    DPRINTF("xhci: setup packet pid 0x%x addr %d ep %d\n",
1413
            xfer->packet.pid, dev->addr, ep->nr);
1414
    return 0;
1415
}
1416

    
1417
static int xhci_complete_packet(XHCITransfer *xfer, int ret)
1418
{
1419
    if (ret == USB_RET_ASYNC) {
1420
        xfer->running_async = 1;
1421
        xfer->running_retry = 0;
1422
        xfer->complete = 0;
1423
        xfer->cancelled = 0;
1424
        return 0;
1425
    } else if (ret == USB_RET_NAK) {
1426
        xfer->running_async = 0;
1427
        xfer->running_retry = 1;
1428
        xfer->complete = 0;
1429
        xfer->cancelled = 0;
1430
        return 0;
1431
    } else {
1432
        xfer->running_async = 0;
1433
        xfer->running_retry = 0;
1434
        xfer->complete = 1;
1435
    }
1436

    
1437
    if (ret >= 0) {
1438
        xfer->status = CC_SUCCESS;
1439
        xhci_xfer_data(xfer, xfer->data, ret, xfer->in_xfer, 0, 1);
1440
        return 0;
1441
    }
1442

    
1443
    /* error */
1444
    switch (ret) {
1445
    case USB_RET_NODEV:
1446
        xfer->status = CC_USB_TRANSACTION_ERROR;
1447
        xhci_xfer_data(xfer, xfer->data, 0, xfer->in_xfer, 0, 1);
1448
        xhci_stall_ep(xfer);
1449
        break;
1450
    case USB_RET_STALL:
1451
        xfer->status = CC_STALL_ERROR;
1452
        xhci_xfer_data(xfer, xfer->data, 0, xfer->in_xfer, 0, 1);
1453
        xhci_stall_ep(xfer);
1454
        break;
1455
    default:
1456
        fprintf(stderr, "%s: FIXME: ret = %d\n", __FUNCTION__, ret);
1457
        FIXME();
1458
    }
1459
    return 0;
1460
}
1461

    
1462
static USBDevice *xhci_find_device(XHCIPort *port, uint8_t addr)
1463
{
1464
    if (!(port->portsc & PORTSC_PED)) {
1465
        return NULL;
1466
    }
1467
    return usb_find_device(&port->port, addr);
1468
}
1469

    
1470
static int xhci_fire_ctl_transfer(XHCIState *xhci, XHCITransfer *xfer)
1471
{
1472
    XHCITRB *trb_setup, *trb_status;
1473
    uint8_t bmRequestType, bRequest;
1474
    uint16_t wValue, wLength, wIndex;
1475
    XHCIPort *port;
1476
    USBDevice *dev;
1477
    int ret;
1478

    
1479
    DPRINTF("xhci_fire_ctl_transfer(slot=%d)\n", xfer->slotid);
1480

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

    
1484
    /* at most one Event Data TRB allowed after STATUS */
1485
    if (TRB_TYPE(*trb_status) == TR_EVDATA && xfer->trb_count > 2) {
1486
        trb_status--;
1487
    }
1488

    
1489
    /* do some sanity checks */
1490
    if (TRB_TYPE(*trb_setup) != TR_SETUP) {
1491
        fprintf(stderr, "xhci: ep0 first TD not SETUP: %d\n",
1492
                TRB_TYPE(*trb_setup));
1493
        return -1;
1494
    }
1495
    if (TRB_TYPE(*trb_status) != TR_STATUS) {
1496
        fprintf(stderr, "xhci: ep0 last TD not STATUS: %d\n",
1497
                TRB_TYPE(*trb_status));
1498
        return -1;
1499
    }
1500
    if (!(trb_setup->control & TRB_TR_IDT)) {
1501
        fprintf(stderr, "xhci: Setup TRB doesn't have IDT set\n");
1502
        return -1;
1503
    }
1504
    if ((trb_setup->status & 0x1ffff) != 8) {
1505
        fprintf(stderr, "xhci: Setup TRB has bad length (%d)\n",
1506
                (trb_setup->status & 0x1ffff));
1507
        return -1;
1508
    }
1509

    
1510
    bmRequestType = trb_setup->parameter;
1511
    bRequest = trb_setup->parameter >> 8;
1512
    wValue = trb_setup->parameter >> 16;
1513
    wIndex = trb_setup->parameter >> 32;
1514
    wLength = trb_setup->parameter >> 48;
1515

    
1516
    if (xfer->data && xfer->data_alloced < wLength) {
1517
        xfer->data_alloced = 0;
1518
        g_free(xfer->data);
1519
        xfer->data = NULL;
1520
    }
1521
    if (!xfer->data) {
1522
        DPRINTF("xhci: alloc %d bytes data\n", wLength);
1523
        xfer->data = g_malloc(wLength+1);
1524
        xfer->data_alloced = wLength;
1525
    }
1526
    xfer->data_length = wLength;
1527

    
1528
    port = &xhci->ports[xhci->slots[xfer->slotid-1].port-1];
1529
    dev = xhci_find_device(port, xhci->slots[xfer->slotid-1].devaddr);
1530
    if (!dev) {
1531
        fprintf(stderr, "xhci: slot %d port %d has no device\n", xfer->slotid,
1532
                xhci->slots[xfer->slotid-1].port);
1533
        return -1;
1534
    }
1535

    
1536
    xfer->in_xfer = bmRequestType & USB_DIR_IN;
1537
    xfer->iso_xfer = false;
1538

    
1539
    xhci_setup_packet(xfer, dev);
1540
    if (!xfer->in_xfer) {
1541
        xhci_xfer_data(xfer, xfer->data, wLength, 0, 1, 0);
1542
    }
1543
    ret = usb_device_handle_control(dev, &xfer->packet,
1544
                                    (bmRequestType << 8) | bRequest,
1545
                                    wValue, wIndex, wLength, xfer->data);
1546

    
1547
    xhci_complete_packet(xfer, ret);
1548
    if (!xfer->running_async && !xfer->running_retry) {
1549
        xhci_kick_ep(xhci, xfer->slotid, xfer->epid);
1550
    }
1551
    return 0;
1552
}
1553

    
1554
static int xhci_submit(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)
1555
{
1556
    XHCIPort *port;
1557
    USBDevice *dev;
1558
    int ret;
1559

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

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

    
1564
    if (xfer->data && xfer->data_alloced < xfer->data_length) {
1565
        xfer->data_alloced = 0;
1566
        g_free(xfer->data);
1567
        xfer->data = NULL;
1568
    }
1569
    if (!xfer->data && xfer->data_length) {
1570
        DPRINTF("xhci: alloc %d bytes data\n", xfer->data_length);
1571
        xfer->data = g_malloc(xfer->data_length);
1572
        xfer->data_alloced = xfer->data_length;
1573
    }
1574
    if (epctx->type == ET_ISO_IN || epctx->type == ET_ISO_OUT) {
1575
        if (!xfer->bg_xfer) {
1576
            xfer->pkts = 1;
1577
        }
1578
    } else {
1579
        xfer->pkts = 0;
1580
    }
1581

    
1582
    port = &xhci->ports[xhci->slots[xfer->slotid-1].port-1];
1583
    dev = xhci_find_device(port, xhci->slots[xfer->slotid-1].devaddr);
1584
    if (!dev) {
1585
        fprintf(stderr, "xhci: slot %d port %d has no device\n", xfer->slotid,
1586
                xhci->slots[xfer->slotid-1].port);
1587
        return -1;
1588
    }
1589

    
1590
    xhci_setup_packet(xfer, dev);
1591

    
1592
    switch(epctx->type) {
1593
    case ET_INTR_OUT:
1594
    case ET_INTR_IN:
1595
    case ET_BULK_OUT:
1596
    case ET_BULK_IN:
1597
        break;
1598
    case ET_ISO_OUT:
1599
    case ET_ISO_IN:
1600
        FIXME();
1601
        break;
1602
    default:
1603
        fprintf(stderr, "xhci: unknown or unhandled EP "
1604
                "(type %d, in %d, ep %02x)\n",
1605
                epctx->type, xfer->in_xfer, xfer->epid);
1606
        return -1;
1607
    }
1608

    
1609
    if (!xfer->in_xfer) {
1610
        xhci_xfer_data(xfer, xfer->data, xfer->data_length, 0, 1, 0);
1611
    }
1612
    ret = usb_handle_packet(dev, &xfer->packet);
1613

    
1614
    xhci_complete_packet(xfer, ret);
1615
    if (!xfer->running_async && !xfer->running_retry) {
1616
        xhci_kick_ep(xhci, xfer->slotid, xfer->epid);
1617
    }
1618
    return 0;
1619
}
1620

    
1621
static int xhci_fire_transfer(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)
1622
{
1623
    int i;
1624
    unsigned int length = 0;
1625
    XHCITRB *trb;
1626

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

    
1629
    for (i = 0; i < xfer->trb_count; i++) {
1630
        trb = &xfer->trbs[i];
1631
        if (TRB_TYPE(*trb) == TR_NORMAL || TRB_TYPE(*trb) == TR_ISOCH) {
1632
            length += trb->status & 0x1ffff;
1633
        }
1634
    }
1635
    DPRINTF("xhci: total TD length=%d\n", length);
1636

    
1637
    if (!epctx->has_bg) {
1638
        xfer->data_length = length;
1639
        xfer->backgrounded = 0;
1640
        return xhci_submit(xhci, xfer, epctx);
1641
    } else {
1642
        if (!epctx->bg_running) {
1643
            for (i = 0; i < BG_XFERS; i++) {
1644
                XHCITransfer *t = &epctx->bg_transfers[i];
1645
                t->xhci = xhci;
1646
                t->epid = xfer->epid;
1647
                t->slotid = xfer->slotid;
1648
                t->pkts = BG_PKTS;
1649
                t->pktsize = epctx->max_psize;
1650
                t->data_length = t->pkts * t->pktsize;
1651
                t->bg_xfer = 1;
1652
                if (xhci_submit(xhci, t, epctx) < 0) {
1653
                    fprintf(stderr, "xhci: bg submit failed\n");
1654
                    return -1;
1655
                }
1656
            }
1657
            epctx->bg_running = 1;
1658
        }
1659
        xfer->backgrounded = 1;
1660
        xhci_bg_update(xhci, epctx);
1661
        return 0;
1662
    }
1663
}
1664

    
1665
static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid, unsigned int epid)
1666
{
1667
    XHCIEPContext *epctx;
1668
    int length;
1669
    int i;
1670

    
1671
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1672
    assert(epid >= 1 && epid <= 31);
1673
    DPRINTF("xhci_kick_ep(%d, %d)\n", slotid, epid);
1674

    
1675
    if (!xhci->slots[slotid-1].enabled) {
1676
        fprintf(stderr, "xhci: xhci_kick_ep for disabled slot %d\n", slotid);
1677
        return;
1678
    }
1679
    epctx = xhci->slots[slotid-1].eps[epid-1];
1680
    if (!epctx) {
1681
        fprintf(stderr, "xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
1682
                epid, slotid);
1683
        return;
1684
    }
1685

    
1686
    if (epctx->retry) {
1687
        /* retry nak'ed transfer */
1688
        XHCITransfer *xfer = epctx->retry;
1689
        int result;
1690

    
1691
        DPRINTF("xhci: retry nack'ed transfer ...\n");
1692
        assert(xfer->running_retry);
1693
        xhci_setup_packet(xfer, xfer->packet.ep->dev);
1694
        result = usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);
1695
        if (result == USB_RET_NAK) {
1696
            DPRINTF("xhci: ... xfer still nacked\n");
1697
            return;
1698
        }
1699
        DPRINTF("xhci: ... result %d\n", result);
1700
        xhci_complete_packet(xfer, result);
1701
        assert(!xfer->running_retry);
1702
        epctx->retry = NULL;
1703
    }
1704

    
1705
    if (epctx->state == EP_HALTED) {
1706
        DPRINTF("xhci: ep halted, not running schedule\n");
1707
        return;
1708
    }
1709

    
1710
    xhci_set_ep_state(xhci, epctx, EP_RUNNING);
1711

    
1712
    while (1) {
1713
        XHCITransfer *xfer = &epctx->transfers[epctx->next_xfer];
1714
        if (xfer->running_async || xfer->running_retry || xfer->backgrounded) {
1715
            DPRINTF("xhci: ep is busy (#%d,%d,%d,%d)\n",
1716
                    epctx->next_xfer, xfer->running_async,
1717
                    xfer->running_retry, xfer->backgrounded);
1718
            break;
1719
        } else {
1720
            DPRINTF("xhci: ep: using #%d\n", epctx->next_xfer);
1721
        }
1722
        length = xhci_ring_chain_length(xhci, &epctx->ring);
1723
        if (length < 0) {
1724
            DPRINTF("xhci: incomplete TD (%d TRBs)\n", -length);
1725
            break;
1726
        } else if (length == 0) {
1727
            break;
1728
        }
1729
        DPRINTF("xhci: fetching %d-TRB TD\n", length);
1730
        if (xfer->trbs && xfer->trb_alloced < length) {
1731
            xfer->trb_count = 0;
1732
            xfer->trb_alloced = 0;
1733
            g_free(xfer->trbs);
1734
            xfer->trbs = NULL;
1735
        }
1736
        if (!xfer->trbs) {
1737
            xfer->trbs = g_malloc(sizeof(XHCITRB) * length);
1738
            xfer->trb_alloced = length;
1739
        }
1740
        xfer->trb_count = length;
1741

    
1742
        for (i = 0; i < length; i++) {
1743
            assert(xhci_ring_fetch(xhci, &epctx->ring, &xfer->trbs[i], NULL));
1744
        }
1745
        xfer->xhci = xhci;
1746
        xfer->epid = epid;
1747
        xfer->slotid = slotid;
1748

    
1749
        if (epid == 1) {
1750
            if (xhci_fire_ctl_transfer(xhci, xfer) >= 0) {
1751
                epctx->next_xfer = (epctx->next_xfer + 1) % TD_QUEUE;
1752
            } else {
1753
                fprintf(stderr, "xhci: error firing CTL transfer\n");
1754
            }
1755
        } else {
1756
            if (xhci_fire_transfer(xhci, xfer, epctx) >= 0) {
1757
                epctx->next_xfer = (epctx->next_xfer + 1) % TD_QUEUE;
1758
            } else {
1759
                fprintf(stderr, "xhci: error firing data transfer\n");
1760
            }
1761
        }
1762

    
1763
        if (epctx->state == EP_HALTED) {
1764
            DPRINTF("xhci: ep halted, stopping schedule\n");
1765
            break;
1766
        }
1767
        if (xfer->running_retry) {
1768
            DPRINTF("xhci: xfer nacked, stopping schedule\n");
1769
            epctx->retry = xfer;
1770
            break;
1771
        }
1772

    
1773
        /*
1774
         * Qemu usb can't handle multiple in-flight xfers.
1775
         * Stop here for now.
1776
         */
1777
        break;
1778
    }
1779
}
1780

    
1781
static TRBCCode xhci_enable_slot(XHCIState *xhci, unsigned int slotid)
1782
{
1783
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1784
    DPRINTF("xhci_enable_slot(%d)\n", slotid);
1785
    xhci->slots[slotid-1].enabled = 1;
1786
    xhci->slots[slotid-1].port = 0;
1787
    memset(xhci->slots[slotid-1].eps, 0, sizeof(XHCIEPContext*)*31);
1788

    
1789
    return CC_SUCCESS;
1790
}
1791

    
1792
static TRBCCode xhci_disable_slot(XHCIState *xhci, unsigned int slotid)
1793
{
1794
    int i;
1795

    
1796
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1797
    DPRINTF("xhci_disable_slot(%d)\n", slotid);
1798

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

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

    
1809
static TRBCCode xhci_address_slot(XHCIState *xhci, unsigned int slotid,
1810
                                  uint64_t pictx, bool bsr)
1811
{
1812
    XHCISlot *slot;
1813
    USBDevice *dev;
1814
    target_phys_addr_t ictx, octx, dcbaap;
1815
    uint64_t poctx;
1816
    uint32_t ictl_ctx[2];
1817
    uint32_t slot_ctx[4];
1818
    uint32_t ep0_ctx[5];
1819
    unsigned int port;
1820
    int i;
1821
    TRBCCode res;
1822

    
1823
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1824
    DPRINTF("xhci_address_slot(%d)\n", slotid);
1825

    
1826
    dcbaap = xhci_addr64(xhci->dcbaap_low, xhci->dcbaap_high);
1827
    cpu_physical_memory_read(dcbaap + 8*slotid,
1828
                             (uint8_t *) &poctx, sizeof(poctx));
1829
    ictx = xhci_mask64(pictx);
1830
    octx = xhci_mask64(le64_to_cpu(poctx));
1831

    
1832
    DPRINTF("xhci: input context at "TARGET_FMT_plx"\n", ictx);
1833
    DPRINTF("xhci: output context at "TARGET_FMT_plx"\n", octx);
1834

    
1835
    cpu_physical_memory_read(ictx, (uint8_t *) ictl_ctx, sizeof(ictl_ctx));
1836

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

    
1843
    cpu_physical_memory_read(ictx+32, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1844
    cpu_physical_memory_read(ictx+64, (uint8_t *) ep0_ctx, sizeof(ep0_ctx));
1845

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

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

    
1852
    port = (slot_ctx[1]>>16) & 0xFF;
1853
    dev = xhci->ports[port-1].port.dev;
1854

    
1855
    if (port < 1 || port > MAXPORTS) {
1856
        fprintf(stderr, "xhci: bad port %d\n", port);
1857
        return CC_TRB_ERROR;
1858
    } else if (!dev) {
1859
        fprintf(stderr, "xhci: port %d not connected\n", port);
1860
        return CC_USB_TRANSACTION_ERROR;
1861
    }
1862

    
1863
    for (i = 0; i < MAXSLOTS; i++) {
1864
        if (xhci->slots[i].port == port) {
1865
            fprintf(stderr, "xhci: port %d already assigned to slot %d\n",
1866
                    port, i+1);
1867
            return CC_TRB_ERROR;
1868
        }
1869
    }
1870

    
1871
    slot = &xhci->slots[slotid-1];
1872
    slot->port = port;
1873
    slot->ctx = octx;
1874

    
1875
    if (bsr) {
1876
        slot_ctx[3] = SLOT_DEFAULT << SLOT_STATE_SHIFT;
1877
    } else {
1878
        slot->devaddr = xhci->devaddr++;
1879
        slot_ctx[3] = (SLOT_ADDRESSED << SLOT_STATE_SHIFT) | slot->devaddr;
1880
        DPRINTF("xhci: device address is %d\n", slot->devaddr);
1881
        usb_device_handle_control(dev, NULL,
1882
                                  DeviceOutRequest | USB_REQ_SET_ADDRESS,
1883
                                  slot->devaddr, 0, 0, NULL);
1884
    }
1885

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

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

    
1893
    cpu_physical_memory_write(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1894
    cpu_physical_memory_write(octx+32, (uint8_t *) ep0_ctx, sizeof(ep0_ctx));
1895

    
1896
    return res;
1897
}
1898

    
1899

    
1900
static TRBCCode xhci_configure_slot(XHCIState *xhci, unsigned int slotid,
1901
                                  uint64_t pictx, bool dc)
1902
{
1903
    target_phys_addr_t ictx, octx;
1904
    uint32_t ictl_ctx[2];
1905
    uint32_t slot_ctx[4];
1906
    uint32_t islot_ctx[4];
1907
    uint32_t ep_ctx[5];
1908
    int i;
1909
    TRBCCode res;
1910

    
1911
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1912
    DPRINTF("xhci_configure_slot(%d)\n", slotid);
1913

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

    
1917
    DPRINTF("xhci: input context at "TARGET_FMT_plx"\n", ictx);
1918
    DPRINTF("xhci: output context at "TARGET_FMT_plx"\n", octx);
1919

    
1920
    if (dc) {
1921
        for (i = 2; i <= 31; i++) {
1922
            if (xhci->slots[slotid-1].eps[i-1]) {
1923
                xhci_disable_ep(xhci, slotid, i);
1924
            }
1925
        }
1926

    
1927
        cpu_physical_memory_read(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1928
        slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
1929
        slot_ctx[3] |= SLOT_ADDRESSED << SLOT_STATE_SHIFT;
1930
        DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
1931
                slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
1932
        cpu_physical_memory_write(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1933

    
1934
        return CC_SUCCESS;
1935
    }
1936

    
1937
    cpu_physical_memory_read(ictx, (uint8_t *) ictl_ctx, sizeof(ictl_ctx));
1938

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

    
1945
    cpu_physical_memory_read(ictx+32, (uint8_t *) islot_ctx, sizeof(islot_ctx));
1946
    cpu_physical_memory_read(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1947

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

    
1953
    for (i = 2; i <= 31; i++) {
1954
        if (ictl_ctx[0] & (1<<i)) {
1955
            xhci_disable_ep(xhci, slotid, i);
1956
        }
1957
        if (ictl_ctx[1] & (1<<i)) {
1958
            cpu_physical_memory_read(ictx+32+(32*i),
1959
                                     (uint8_t *) ep_ctx, sizeof(ep_ctx));
1960
            DPRINTF("xhci: input ep%d.%d context: %08x %08x %08x %08x %08x\n",
1961
                    i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2],
1962
                    ep_ctx[3], ep_ctx[4]);
1963
            xhci_disable_ep(xhci, slotid, i);
1964
            res = xhci_enable_ep(xhci, slotid, i, octx+(32*i), ep_ctx);
1965
            if (res != CC_SUCCESS) {
1966
                return res;
1967
            }
1968
            DPRINTF("xhci: output ep%d.%d context: %08x %08x %08x %08x %08x\n",
1969
                    i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2],
1970
                    ep_ctx[3], ep_ctx[4]);
1971
            cpu_physical_memory_write(octx+(32*i),
1972
                                      (uint8_t *) ep_ctx, sizeof(ep_ctx));
1973
        }
1974
    }
1975

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

    
1984
    cpu_physical_memory_write(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1985

    
1986
    return CC_SUCCESS;
1987
}
1988

    
1989

    
1990
static TRBCCode xhci_evaluate_slot(XHCIState *xhci, unsigned int slotid,
1991
                                   uint64_t pictx)
1992
{
1993
    target_phys_addr_t ictx, octx;
1994
    uint32_t ictl_ctx[2];
1995
    uint32_t iep0_ctx[5];
1996
    uint32_t ep0_ctx[5];
1997
    uint32_t islot_ctx[4];
1998
    uint32_t slot_ctx[4];
1999

    
2000
    assert(slotid >= 1 && slotid <= MAXSLOTS);
2001
    DPRINTF("xhci_evaluate_slot(%d)\n", slotid);
2002

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

    
2006
    DPRINTF("xhci: input context at "TARGET_FMT_plx"\n", ictx);
2007
    DPRINTF("xhci: output context at "TARGET_FMT_plx"\n", octx);
2008

    
2009
    cpu_physical_memory_read(ictx, (uint8_t *) ictl_ctx, sizeof(ictl_ctx));
2010

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

    
2017
    if (ictl_ctx[1] & 0x1) {
2018
        cpu_physical_memory_read(ictx+32,
2019
                                 (uint8_t *) islot_ctx, sizeof(islot_ctx));
2020

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

    
2024
        cpu_physical_memory_read(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
2025

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

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

    
2034
        cpu_physical_memory_write(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
2035
    }
2036

    
2037
    if (ictl_ctx[1] & 0x2) {
2038
        cpu_physical_memory_read(ictx+64,
2039
                                 (uint8_t *) iep0_ctx, sizeof(iep0_ctx));
2040

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

    
2045
        cpu_physical_memory_read(octx+32, (uint8_t *) ep0_ctx, sizeof(ep0_ctx));
2046

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

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

    
2053
        cpu_physical_memory_write(octx+32,
2054
                                  (uint8_t *) ep0_ctx, sizeof(ep0_ctx));
2055
    }
2056

    
2057
    return CC_SUCCESS;
2058
}
2059

    
2060
static TRBCCode xhci_reset_slot(XHCIState *xhci, unsigned int slotid)
2061
{
2062
    uint32_t slot_ctx[4];
2063
    target_phys_addr_t octx;
2064
    int i;
2065

    
2066
    assert(slotid >= 1 && slotid <= MAXSLOTS);
2067
    DPRINTF("xhci_reset_slot(%d)\n", slotid);
2068

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

    
2071
    DPRINTF("xhci: output context at "TARGET_FMT_plx"\n", octx);
2072

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

    
2079
    cpu_physical_memory_read(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
2080
    slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
2081
    slot_ctx[3] |= SLOT_DEFAULT << SLOT_STATE_SHIFT;
2082
    DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
2083
            slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
2084
    cpu_physical_memory_write(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
2085

    
2086
    return CC_SUCCESS;
2087
}
2088

    
2089
static unsigned int xhci_get_slot(XHCIState *xhci, XHCIEvent *event, XHCITRB *trb)
2090
{
2091
    unsigned int slotid;
2092
    slotid = (trb->control >> TRB_CR_SLOTID_SHIFT) & TRB_CR_SLOTID_MASK;
2093
    if (slotid < 1 || slotid > MAXSLOTS) {
2094
        fprintf(stderr, "xhci: bad slot id %d\n", slotid);
2095
        event->ccode = CC_TRB_ERROR;
2096
        return 0;
2097
    } else if (!xhci->slots[slotid-1].enabled) {
2098
        fprintf(stderr, "xhci: slot id %d not enabled\n", slotid);
2099
        event->ccode = CC_SLOT_NOT_ENABLED_ERROR;
2100
        return 0;
2101
    }
2102
    return slotid;
2103
}
2104

    
2105
static TRBCCode xhci_get_port_bandwidth(XHCIState *xhci, uint64_t pctx)
2106
{
2107
    target_phys_addr_t ctx;
2108
    uint8_t bw_ctx[MAXPORTS+1];
2109

    
2110
    DPRINTF("xhci_get_port_bandwidth()\n");
2111

    
2112
    ctx = xhci_mask64(pctx);
2113

    
2114
    DPRINTF("xhci: bandwidth context at "TARGET_FMT_plx"\n", ctx);
2115

    
2116
    /* TODO: actually implement real values here */
2117
    bw_ctx[0] = 0;
2118
    memset(&bw_ctx[1], 80, MAXPORTS); /* 80% */
2119
    cpu_physical_memory_write(ctx, bw_ctx, sizeof(bw_ctx));
2120

    
2121
    return CC_SUCCESS;
2122
}
2123

    
2124
static uint32_t rotl(uint32_t v, unsigned count)
2125
{
2126
    count &= 31;
2127
    return (v << count) | (v >> (32 - count));
2128
}
2129

    
2130

    
2131
static uint32_t xhci_nec_challenge(uint32_t hi, uint32_t lo)
2132
{
2133
    uint32_t val;
2134
    val = rotl(lo - 0x49434878, 32 - ((hi>>8) & 0x1F));
2135
    val += rotl(lo + 0x49434878, hi & 0x1F);
2136
    val -= rotl(hi ^ 0x49434878, (lo >> 16) & 0x1F);
2137
    return ~val;
2138
}
2139

    
2140
static void xhci_via_challenge(uint64_t addr)
2141
{
2142
    uint32_t buf[8];
2143
    uint32_t obuf[8];
2144
    target_phys_addr_t paddr = xhci_mask64(addr);
2145

    
2146
    cpu_physical_memory_read(paddr, (uint8_t *) &buf, 32);
2147

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

    
2150
    if ((buf[0] & 0xff) == 2) {
2151
        obuf[0] = 0x49932000 + 0x54dc200 * buf[2] + 0x7429b578 * buf[3];
2152
        obuf[0] |=  (buf[2] * buf[3]) & 0xff;
2153
        obuf[1] = 0x0132bb37 + 0xe89 * buf[2] + 0xf09 * buf[3];
2154
        obuf[2] = 0x0066c2e9 + 0x2091 * buf[2] + 0x19bd * buf[3];
2155
        obuf[3] = 0xd5281342 + 0x2cc9691 * buf[2] + 0x2367662 * buf[3];
2156
        obuf[4] = 0x0123c75c + 0x1595 * buf[2] + 0x19ec * buf[3];
2157
        obuf[5] = 0x00f695de + 0x26fd * buf[2] + 0x3e9 * buf[3];
2158
        obuf[6] = obuf[2] ^ obuf[3] ^ 0x29472956;
2159
        obuf[7] = obuf[2] ^ obuf[3] ^ 0x65866593;
2160
    }
2161

    
2162
    cpu_physical_memory_write(paddr, (uint8_t *) &obuf, 32);
2163
}
2164

    
2165
static void xhci_process_commands(XHCIState *xhci)
2166
{
2167
    XHCITRB trb;
2168
    TRBType type;
2169
    XHCIEvent event = {ER_COMMAND_COMPLETE, CC_SUCCESS};
2170
    target_phys_addr_t addr;
2171
    unsigned int i, slotid = 0;
2172

    
2173
    DPRINTF("xhci_process_commands()\n");
2174
    if (!xhci_running(xhci)) {
2175
        DPRINTF("xhci_process_commands() called while xHC stopped or paused\n");
2176
        return;
2177
    }
2178

    
2179
    xhci->crcr_low |= CRCR_CRR;
2180

    
2181
    while ((type = xhci_ring_fetch(xhci, &xhci->cmd_ring, &trb, &addr))) {
2182
        event.ptr = addr;
2183
        switch (type) {
2184
        case CR_ENABLE_SLOT:
2185
            for (i = 0; i < MAXSLOTS; i++) {
2186
                if (!xhci->slots[i].enabled) {
2187
                    break;
2188
                }
2189
            }
2190
            if (i >= MAXSLOTS) {
2191
                fprintf(stderr, "xhci: no device slots available\n");
2192
                event.ccode = CC_NO_SLOTS_ERROR;
2193
            } else {
2194
                slotid = i+1;
2195
                event.ccode = xhci_enable_slot(xhci, slotid);
2196
            }
2197
            break;
2198
        case CR_DISABLE_SLOT:
2199
            slotid = xhci_get_slot(xhci, &event, &trb);
2200
            if (slotid) {
2201
                event.ccode = xhci_disable_slot(xhci, slotid);
2202
            }
2203
            break;
2204
        case CR_ADDRESS_DEVICE:
2205
            slotid = xhci_get_slot(xhci, &event, &trb);
2206
            if (slotid) {
2207
                event.ccode = xhci_address_slot(xhci, slotid, trb.parameter,
2208
                                                trb.control & TRB_CR_BSR);
2209
            }
2210
            break;
2211
        case CR_CONFIGURE_ENDPOINT:
2212
            slotid = xhci_get_slot(xhci, &event, &trb);
2213
            if (slotid) {
2214
                event.ccode = xhci_configure_slot(xhci, slotid, trb.parameter,
2215
                                                  trb.control & TRB_CR_DC);
2216
            }
2217
            break;
2218
        case CR_EVALUATE_CONTEXT:
2219
            slotid = xhci_get_slot(xhci, &event, &trb);
2220
            if (slotid) {
2221
                event.ccode = xhci_evaluate_slot(xhci, slotid, trb.parameter);
2222
            }
2223
            break;
2224
        case CR_STOP_ENDPOINT:
2225
            slotid = xhci_get_slot(xhci, &event, &trb);
2226
            if (slotid) {
2227
                unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2228
                    & TRB_CR_EPID_MASK;
2229
                event.ccode = xhci_stop_ep(xhci, slotid, epid);
2230
            }
2231
            break;
2232
        case CR_RESET_ENDPOINT:
2233
            slotid = xhci_get_slot(xhci, &event, &trb);
2234
            if (slotid) {
2235
                unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2236
                    & TRB_CR_EPID_MASK;
2237
                event.ccode = xhci_reset_ep(xhci, slotid, epid);
2238
            }
2239
            break;
2240
        case CR_SET_TR_DEQUEUE:
2241
            slotid = xhci_get_slot(xhci, &event, &trb);
2242
            if (slotid) {
2243
                unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2244
                    & TRB_CR_EPID_MASK;
2245
                event.ccode = xhci_set_ep_dequeue(xhci, slotid, epid,
2246
                                                  trb.parameter);
2247
            }
2248
            break;
2249
        case CR_RESET_DEVICE:
2250
            slotid = xhci_get_slot(xhci, &event, &trb);
2251
            if (slotid) {
2252
                event.ccode = xhci_reset_slot(xhci, slotid);
2253
            }
2254
            break;
2255
        case CR_GET_PORT_BANDWIDTH:
2256
            event.ccode = xhci_get_port_bandwidth(xhci, trb.parameter);
2257
            break;
2258
        case CR_VENDOR_VIA_CHALLENGE_RESPONSE:
2259
            xhci_via_challenge(trb.parameter);
2260
            break;
2261
        case CR_VENDOR_NEC_FIRMWARE_REVISION:
2262
            event.type = 48; /* NEC reply */
2263
            event.length = 0x3025;
2264
            break;
2265
        case CR_VENDOR_NEC_CHALLENGE_RESPONSE:
2266
        {
2267
            uint32_t chi = trb.parameter >> 32;
2268
            uint32_t clo = trb.parameter;
2269
            uint32_t val = xhci_nec_challenge(chi, clo);
2270
            event.length = val & 0xFFFF;
2271
            event.epid = val >> 16;
2272
            slotid = val >> 24;
2273
            event.type = 48; /* NEC reply */
2274
        }
2275
        break;
2276
        default:
2277
            fprintf(stderr, "xhci: unimplemented command %d\n", type);
2278
            event.ccode = CC_TRB_ERROR;
2279
            break;
2280
        }
2281
        event.slotid = slotid;
2282
        xhci_event(xhci, &event);
2283
    }
2284
}
2285

    
2286
static void xhci_update_port(XHCIState *xhci, XHCIPort *port, int is_detach)
2287
{
2288
    int nr = port->port.index + 1;
2289

    
2290
    port->portsc = PORTSC_PP;
2291
    if (port->port.dev && !is_detach) {
2292
        port->portsc |= PORTSC_CCS;
2293
        switch (port->port.dev->speed) {
2294
        case USB_SPEED_LOW:
2295
            port->portsc |= PORTSC_SPEED_LOW;
2296
            break;
2297
        case USB_SPEED_FULL:
2298
            port->portsc |= PORTSC_SPEED_FULL;
2299
            break;
2300
        case USB_SPEED_HIGH:
2301
            port->portsc |= PORTSC_SPEED_HIGH;
2302
            break;
2303
        }
2304
    }
2305

    
2306
    if (xhci_running(xhci)) {
2307
        port->portsc |= PORTSC_CSC;
2308
        XHCIEvent ev = { ER_PORT_STATUS_CHANGE, CC_SUCCESS, nr << 24};
2309
        xhci_event(xhci, &ev);
2310
        DPRINTF("xhci: port change event for port %d\n", nr);
2311
    }
2312
}
2313

    
2314
static void xhci_reset(void *opaque)
2315
{
2316
    XHCIState *xhci = opaque;
2317
    int i;
2318

    
2319
    DPRINTF("xhci: full reset\n");
2320
    if (!(xhci->usbsts & USBSTS_HCH)) {
2321
        fprintf(stderr, "xhci: reset while running!\n");
2322
    }
2323

    
2324
    xhci->usbcmd = 0;
2325
    xhci->usbsts = USBSTS_HCH;
2326
    xhci->dnctrl = 0;
2327
    xhci->crcr_low = 0;
2328
    xhci->crcr_high = 0;
2329
    xhci->dcbaap_low = 0;
2330
    xhci->dcbaap_high = 0;
2331
    xhci->config = 0;
2332
    xhci->devaddr = 2;
2333

    
2334
    for (i = 0; i < MAXSLOTS; i++) {
2335
        xhci_disable_slot(xhci, i+1);
2336
    }
2337

    
2338
    for (i = 0; i < MAXPORTS; i++) {
2339
        xhci_update_port(xhci, xhci->ports + i, 0);
2340
    }
2341

    
2342
    xhci->mfindex = 0;
2343
    xhci->iman = 0;
2344
    xhci->imod = 0;
2345
    xhci->erstsz = 0;
2346
    xhci->erstba_low = 0;
2347
    xhci->erstba_high = 0;
2348
    xhci->erdp_low = 0;
2349
    xhci->erdp_high = 0;
2350

    
2351
    xhci->er_ep_idx = 0;
2352
    xhci->er_pcs = 1;
2353
    xhci->er_full = 0;
2354
    xhci->ev_buffer_put = 0;
2355
    xhci->ev_buffer_get = 0;
2356
}
2357

    
2358
static uint32_t xhci_cap_read(XHCIState *xhci, uint32_t reg)
2359
{
2360
    DPRINTF("xhci_cap_read(0x%x)\n", reg);
2361

    
2362
    switch (reg) {
2363
    case 0x00: /* HCIVERSION, CAPLENGTH */
2364
        return 0x01000000 | LEN_CAP;
2365
    case 0x04: /* HCSPARAMS 1 */
2366
        return (MAXPORTS<<24) | (MAXINTRS<<8) | MAXSLOTS;
2367
    case 0x08: /* HCSPARAMS 2 */
2368
        return 0x0000000f;
2369
    case 0x0c: /* HCSPARAMS 3 */
2370
        return 0x00000000;
2371
    case 0x10: /* HCCPARAMS */
2372
#if TARGET_PHYS_ADDR_BITS > 32
2373
        return 0x00081001;
2374
#else
2375
        return 0x00081000;
2376
#endif
2377
    case 0x14: /* DBOFF */
2378
        return OFF_DOORBELL;
2379
    case 0x18: /* RTSOFF */
2380
        return OFF_RUNTIME;
2381

    
2382
    /* extended capabilities */
2383
    case 0x20: /* Supported Protocol:00 */
2384
#if USB3_PORTS > 0
2385
        return 0x02000402; /* USB 2.0 */
2386
#else
2387
        return 0x02000002; /* USB 2.0 */
2388
#endif
2389
    case 0x24: /* Supported Protocol:04 */
2390
        return 0x20425455; /* "USB " */
2391
    case 0x28: /* Supported Protocol:08 */
2392
        return 0x00000001 | (USB2_PORTS<<8);
2393
    case 0x2c: /* Supported Protocol:0c */
2394
        return 0x00000000; /* reserved */
2395
#if USB3_PORTS > 0
2396
    case 0x30: /* Supported Protocol:00 */
2397
        return 0x03000002; /* USB 3.0 */
2398
    case 0x34: /* Supported Protocol:04 */
2399
        return 0x20425455; /* "USB " */
2400
    case 0x38: /* Supported Protocol:08 */
2401
        return 0x00000000 | (USB2_PORTS+1) | (USB3_PORTS<<8);
2402
    case 0x3c: /* Supported Protocol:0c */
2403
        return 0x00000000; /* reserved */
2404
#endif
2405
    default:
2406
        fprintf(stderr, "xhci_cap_read: reg %d unimplemented\n", reg);
2407
    }
2408
    return 0;
2409
}
2410

    
2411
static uint32_t xhci_port_read(XHCIState *xhci, uint32_t reg)
2412
{
2413
    uint32_t port = reg >> 4;
2414
    if (port >= MAXPORTS) {
2415
        fprintf(stderr, "xhci_port_read: port %d out of bounds\n", port);
2416
        return 0;
2417
    }
2418

    
2419
    switch (reg & 0xf) {
2420
    case 0x00: /* PORTSC */
2421
        return xhci->ports[port].portsc;
2422
    case 0x04: /* PORTPMSC */
2423
    case 0x08: /* PORTLI */
2424
        return 0;
2425
    case 0x0c: /* reserved */
2426
    default:
2427
        fprintf(stderr, "xhci_port_read (port %d): reg 0x%x unimplemented\n",
2428
                port, reg);
2429
        return 0;
2430
    }
2431
}
2432

    
2433
static void xhci_port_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2434
{
2435
    uint32_t port = reg >> 4;
2436
    uint32_t portsc;
2437

    
2438
    if (port >= MAXPORTS) {
2439
        fprintf(stderr, "xhci_port_read: port %d out of bounds\n", port);
2440
        return;
2441
    }
2442

    
2443
    switch (reg & 0xf) {
2444
    case 0x00: /* PORTSC */
2445
        portsc = xhci->ports[port].portsc;
2446
        /* write-1-to-clear bits*/
2447
        portsc &= ~(val & (PORTSC_CSC|PORTSC_PEC|PORTSC_WRC|PORTSC_OCC|
2448
                           PORTSC_PRC|PORTSC_PLC|PORTSC_CEC));
2449
        if (val & PORTSC_LWS) {
2450
            /* overwrite PLS only when LWS=1 */
2451
            portsc &= ~(PORTSC_PLS_MASK << PORTSC_PLS_SHIFT);
2452
            portsc |= val & (PORTSC_PLS_MASK << PORTSC_PLS_SHIFT);
2453
        }
2454
        /* read/write bits */
2455
        portsc &= ~(PORTSC_PP|PORTSC_WCE|PORTSC_WDE|PORTSC_WOE);
2456
        portsc |= (val & (PORTSC_PP|PORTSC_WCE|PORTSC_WDE|PORTSC_WOE));
2457
        /* write-1-to-start bits */
2458
        if (val & PORTSC_PR) {
2459
            DPRINTF("xhci: port %d reset\n", port);
2460
            usb_device_reset(xhci->ports[port].port.dev);
2461
            portsc |= PORTSC_PRC | PORTSC_PED;
2462
        }
2463
        xhci->ports[port].portsc = portsc;
2464
        break;
2465
    case 0x04: /* PORTPMSC */
2466
    case 0x08: /* PORTLI */
2467
    default:
2468
        fprintf(stderr, "xhci_port_write (port %d): reg 0x%x unimplemented\n",
2469
                port, reg);
2470
    }
2471
}
2472

    
2473
static uint32_t xhci_oper_read(XHCIState *xhci, uint32_t reg)
2474
{
2475
    DPRINTF("xhci_oper_read(0x%x)\n", reg);
2476

    
2477
    if (reg >= 0x400) {
2478
        return xhci_port_read(xhci, reg - 0x400);
2479
    }
2480

    
2481
    switch (reg) {
2482
    case 0x00: /* USBCMD */
2483
        return xhci->usbcmd;
2484
    case 0x04: /* USBSTS */
2485
        return xhci->usbsts;
2486
    case 0x08: /* PAGESIZE */
2487
        return 1; /* 4KiB */
2488
    case 0x14: /* DNCTRL */
2489
        return xhci->dnctrl;
2490
    case 0x18: /* CRCR low */
2491
        return xhci->crcr_low & ~0xe;
2492
    case 0x1c: /* CRCR high */
2493
        return xhci->crcr_high;
2494
    case 0x30: /* DCBAAP low */
2495
        return xhci->dcbaap_low;
2496
    case 0x34: /* DCBAAP high */
2497
        return xhci->dcbaap_high;
2498
    case 0x38: /* CONFIG */
2499
        return xhci->config;
2500
    default:
2501
        fprintf(stderr, "xhci_oper_read: reg 0x%x unimplemented\n", reg);
2502
    }
2503
    return 0;
2504
}
2505

    
2506
static void xhci_oper_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2507
{
2508
    DPRINTF("xhci_oper_write(0x%x, 0x%08x)\n", reg, val);
2509

    
2510
    if (reg >= 0x400) {
2511
        xhci_port_write(xhci, reg - 0x400, val);
2512
        return;
2513
    }
2514

    
2515
    switch (reg) {
2516
    case 0x00: /* USBCMD */
2517
        if ((val & USBCMD_RS) && !(xhci->usbcmd & USBCMD_RS)) {
2518
            xhci_run(xhci);
2519
        } else if (!(val & USBCMD_RS) && (xhci->usbcmd & USBCMD_RS)) {
2520
            xhci_stop(xhci);
2521
        }
2522
        xhci->usbcmd = val & 0xc0f;
2523
        if (val & USBCMD_HCRST) {
2524
            xhci_reset(xhci);
2525
        }
2526
        xhci_irq_update(xhci);
2527
        break;
2528

    
2529
    case 0x04: /* USBSTS */
2530
        /* these bits are write-1-to-clear */
2531
        xhci->usbsts &= ~(val & (USBSTS_HSE|USBSTS_EINT|USBSTS_PCD|USBSTS_SRE));
2532
        xhci_irq_update(xhci);
2533
        break;
2534

    
2535
    case 0x14: /* DNCTRL */
2536
        xhci->dnctrl = val & 0xffff;
2537
        break;
2538
    case 0x18: /* CRCR low */
2539
        xhci->crcr_low = (val & 0xffffffcf) | (xhci->crcr_low & CRCR_CRR);
2540
        break;
2541
    case 0x1c: /* CRCR high */
2542
        xhci->crcr_high = val;
2543
        if (xhci->crcr_low & (CRCR_CA|CRCR_CS) && (xhci->crcr_low & CRCR_CRR)) {
2544
            XHCIEvent event = {ER_COMMAND_COMPLETE, CC_COMMAND_RING_STOPPED};
2545
            xhci->crcr_low &= ~CRCR_CRR;
2546
            xhci_event(xhci, &event);
2547
            DPRINTF("xhci: command ring stopped (CRCR=%08x)\n", xhci->crcr_low);
2548
        } else {
2549
            target_phys_addr_t base = xhci_addr64(xhci->crcr_low & ~0x3f, val);
2550
            xhci_ring_init(xhci, &xhci->cmd_ring, base);
2551
        }
2552
        xhci->crcr_low &= ~(CRCR_CA | CRCR_CS);
2553
        break;
2554
    case 0x30: /* DCBAAP low */
2555
        xhci->dcbaap_low = val & 0xffffffc0;
2556
        break;
2557
    case 0x34: /* DCBAAP high */
2558
        xhci->dcbaap_high = val;
2559
        break;
2560
    case 0x38: /* CONFIG */
2561
        xhci->config = val & 0xff;
2562
        break;
2563
    default:
2564
        fprintf(stderr, "xhci_oper_write: reg 0x%x unimplemented\n", reg);
2565
    }
2566
}
2567

    
2568
static uint32_t xhci_runtime_read(XHCIState *xhci, uint32_t reg)
2569
{
2570
    DPRINTF("xhci_runtime_read(0x%x)\n", reg);
2571

    
2572
    switch (reg) {
2573
    case 0x00: /* MFINDEX */
2574
        fprintf(stderr, "xhci_runtime_read: MFINDEX not yet implemented\n");
2575
        return xhci->mfindex;
2576
    case 0x20: /* IMAN */
2577
        return xhci->iman;
2578
    case 0x24: /* IMOD */
2579
        return xhci->imod;
2580
    case 0x28: /* ERSTSZ */
2581
        return xhci->erstsz;
2582
    case 0x30: /* ERSTBA low */
2583
        return xhci->erstba_low;
2584
    case 0x34: /* ERSTBA high */
2585
        return xhci->erstba_high;
2586
    case 0x38: /* ERDP low */
2587
        return xhci->erdp_low;
2588
    case 0x3c: /* ERDP high */
2589
        return xhci->erdp_high;
2590
    default:
2591
        fprintf(stderr, "xhci_runtime_read: reg 0x%x unimplemented\n", reg);
2592
    }
2593
    return 0;
2594
}
2595

    
2596
static void xhci_runtime_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2597
{
2598
    DPRINTF("xhci_runtime_write(0x%x, 0x%08x)\n", reg, val);
2599

    
2600
    switch (reg) {
2601
    case 0x20: /* IMAN */
2602
        if (val & IMAN_IP) {
2603
            xhci->iman &= ~IMAN_IP;
2604
        }
2605
        xhci->iman &= ~IMAN_IE;
2606
        xhci->iman |= val & IMAN_IE;
2607
        xhci_irq_update(xhci);
2608
        break;
2609
    case 0x24: /* IMOD */
2610
        xhci->imod = val;
2611
        break;
2612
    case 0x28: /* ERSTSZ */
2613
        xhci->erstsz = val & 0xffff;
2614
        break;
2615
    case 0x30: /* ERSTBA low */
2616
        /* XXX NEC driver bug: it doesn't align this to 64 bytes
2617
        xhci->erstba_low = val & 0xffffffc0; */
2618
        xhci->erstba_low = val & 0xfffffff0;
2619
        break;
2620
    case 0x34: /* ERSTBA high */
2621
        xhci->erstba_high = val;
2622
        xhci_er_reset(xhci);
2623
        break;
2624
    case 0x38: /* ERDP low */
2625
        if (val & ERDP_EHB) {
2626
            xhci->erdp_low &= ~ERDP_EHB;
2627
        }
2628
        xhci->erdp_low = (val & ~ERDP_EHB) | (xhci->erdp_low & ERDP_EHB);
2629
        break;
2630
    case 0x3c: /* ERDP high */
2631
        xhci->erdp_high = val;
2632
        xhci_events_update(xhci);
2633
        break;
2634
    default:
2635
        fprintf(stderr, "xhci_oper_write: reg 0x%x unimplemented\n", reg);
2636
    }
2637
}
2638

    
2639
static uint32_t xhci_doorbell_read(XHCIState *xhci, uint32_t reg)
2640
{
2641
    DPRINTF("xhci_doorbell_read(0x%x)\n", reg);
2642
    /* doorbells always read as 0 */
2643
    return 0;
2644
}
2645

    
2646
static void xhci_doorbell_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2647
{
2648
    DPRINTF("xhci_doorbell_write(0x%x, 0x%08x)\n", reg, val);
2649

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

    
2655
    reg >>= 2;
2656

    
2657
    if (reg == 0) {
2658
        if (val == 0) {
2659
            xhci_process_commands(xhci);
2660
        } else {
2661
            fprintf(stderr, "xhci: bad doorbell 0 write: 0x%x\n", val);
2662
        }
2663
    } else {
2664
        if (reg > MAXSLOTS) {
2665
            fprintf(stderr, "xhci: bad doorbell %d\n", reg);
2666
        } else if (val > 31) {
2667
            fprintf(stderr, "xhci: bad doorbell %d write: 0x%x\n", reg, val);
2668
        } else {
2669
            xhci_kick_ep(xhci, reg, val);
2670
        }
2671
    }
2672
}
2673

    
2674
static uint64_t xhci_mem_read(void *ptr, target_phys_addr_t addr,
2675
                              unsigned size)
2676
{
2677
    XHCIState *xhci = ptr;
2678

    
2679
    /* Only aligned reads are allowed on xHCI */
2680
    if (addr & 3) {
2681
        fprintf(stderr, "xhci_mem_read: Mis-aligned read\n");
2682
        return 0;
2683
    }
2684

    
2685
    if (addr < LEN_CAP) {
2686
        return xhci_cap_read(xhci, addr);
2687
    } else if (addr >= OFF_OPER && addr < (OFF_OPER + LEN_OPER)) {
2688
        return xhci_oper_read(xhci, addr - OFF_OPER);
2689
    } else if (addr >= OFF_RUNTIME && addr < (OFF_RUNTIME + LEN_RUNTIME)) {
2690
        return xhci_runtime_read(xhci, addr - OFF_RUNTIME);
2691
    } else if (addr >= OFF_DOORBELL && addr < (OFF_DOORBELL + LEN_DOORBELL)) {
2692
        return xhci_doorbell_read(xhci, addr - OFF_DOORBELL);
2693
    } else {
2694
        fprintf(stderr, "xhci_mem_read: Bad offset %x\n", (int)addr);
2695
        return 0;
2696
    }
2697
}
2698

    
2699
static void xhci_mem_write(void *ptr, target_phys_addr_t addr,
2700
                           uint64_t val, unsigned size)
2701
{
2702
    XHCIState *xhci = ptr;
2703

    
2704
    /* Only aligned writes are allowed on xHCI */
2705
    if (addr & 3) {
2706
        fprintf(stderr, "xhci_mem_write: Mis-aligned write\n");
2707
        return;
2708
    }
2709

    
2710
    if (addr >= OFF_OPER && addr < (OFF_OPER + LEN_OPER)) {
2711
        xhci_oper_write(xhci, addr - OFF_OPER, val);
2712
    } else if (addr >= OFF_RUNTIME && addr < (OFF_RUNTIME + LEN_RUNTIME)) {
2713
        xhci_runtime_write(xhci, addr - OFF_RUNTIME, val);
2714
    } else if (addr >= OFF_DOORBELL && addr < (OFF_DOORBELL + LEN_DOORBELL)) {
2715
        xhci_doorbell_write(xhci, addr - OFF_DOORBELL, val);
2716
    } else {
2717
        fprintf(stderr, "xhci_mem_write: Bad offset %x\n", (int)addr);
2718
    }
2719
}
2720

    
2721
static const MemoryRegionOps xhci_mem_ops = {
2722
    .read = xhci_mem_read,
2723
    .write = xhci_mem_write,
2724
    .valid.min_access_size = 4,
2725
    .valid.max_access_size = 4,
2726
    .endianness = DEVICE_LITTLE_ENDIAN,
2727
};
2728

    
2729
static void xhci_attach(USBPort *usbport)
2730
{
2731
    XHCIState *xhci = usbport->opaque;
2732
    XHCIPort *port = &xhci->ports[usbport->index];
2733

    
2734
    xhci_update_port(xhci, port, 0);
2735
}
2736

    
2737
static void xhci_detach(USBPort *usbport)
2738
{
2739
    XHCIState *xhci = usbport->opaque;
2740
    XHCIPort *port = &xhci->ports[usbport->index];
2741

    
2742
    xhci_update_port(xhci, port, 1);
2743
}
2744

    
2745
static void xhci_wakeup(USBPort *usbport)
2746
{
2747
    XHCIState *xhci = usbport->opaque;
2748
    XHCIPort *port = &xhci->ports[usbport->index];
2749
    int nr = port->port.index + 1;
2750
    XHCIEvent ev = { ER_PORT_STATUS_CHANGE, CC_SUCCESS, nr << 24};
2751
    uint32_t pls;
2752

    
2753
    pls = (port->portsc >> PORTSC_PLS_SHIFT) & PORTSC_PLS_MASK;
2754
    if (pls != 3) {
2755
        return;
2756
    }
2757
    port->portsc |= 0xf << PORTSC_PLS_SHIFT;
2758
    if (port->portsc & PORTSC_PLC) {
2759
        return;
2760
    }
2761
    port->portsc |= PORTSC_PLC;
2762
    xhci_event(xhci, &ev);
2763
}
2764

    
2765
static void xhci_complete(USBPort *port, USBPacket *packet)
2766
{
2767
    XHCITransfer *xfer = container_of(packet, XHCITransfer, packet);
2768

    
2769
    xhci_complete_packet(xfer, packet->result);
2770
    xhci_kick_ep(xfer->xhci, xfer->slotid, xfer->epid);
2771
}
2772

    
2773
static void xhci_child_detach(USBPort *port, USBDevice *child)
2774
{
2775
    FIXME();
2776
}
2777

    
2778
static USBPortOps xhci_port_ops = {
2779
    .attach   = xhci_attach,
2780
    .detach   = xhci_detach,
2781
    .wakeup   = xhci_wakeup,
2782
    .complete = xhci_complete,
2783
    .child_detach = xhci_child_detach,
2784
};
2785

    
2786
static int xhci_find_slotid(XHCIState *xhci, USBDevice *dev)
2787
{
2788
    XHCISlot *slot;
2789
    int slotid;
2790

    
2791
    for (slotid = 1; slotid <= MAXSLOTS; slotid++) {
2792
        slot = &xhci->slots[slotid-1];
2793
        if (slot->devaddr == dev->addr) {
2794
            return slotid;
2795
        }
2796
    }
2797
    return 0;
2798
}
2799

    
2800
static int xhci_find_epid(USBEndpoint *ep)
2801
{
2802
    if (ep->nr == 0) {
2803
        return 1;
2804
    }
2805
    if (ep->pid == USB_TOKEN_IN) {
2806
        return ep->nr * 2 + 1;
2807
    } else {
2808
        return ep->nr * 2;
2809
    }
2810
}
2811

    
2812
static void xhci_wakeup_endpoint(USBBus *bus, USBEndpoint *ep)
2813
{
2814
    XHCIState *xhci = container_of(bus, XHCIState, bus);
2815
    int slotid;
2816

    
2817
    DPRINTF("%s\n", __func__);
2818
    slotid = xhci_find_slotid(xhci, ep->dev);
2819
    if (slotid == 0 || !xhci->slots[slotid-1].enabled) {
2820
        DPRINTF("%s: oops, no slot for dev %d\n", __func__, ep->dev->addr);
2821
        return;
2822
    }
2823
    xhci_kick_ep(xhci, slotid, xhci_find_epid(ep));
2824
}
2825

    
2826
static USBBusOps xhci_bus_ops = {
2827
    .wakeup_endpoint = xhci_wakeup_endpoint,
2828
};
2829

    
2830
static void usb_xhci_init(XHCIState *xhci, DeviceState *dev)
2831
{
2832
    int i;
2833

    
2834
    xhci->usbsts = USBSTS_HCH;
2835

    
2836
    usb_bus_new(&xhci->bus, &xhci_bus_ops, &xhci->pci_dev.qdev);
2837

    
2838
    for (i = 0; i < MAXPORTS; i++) {
2839
        memset(&xhci->ports[i], 0, sizeof(xhci->ports[i]));
2840
        usb_register_port(&xhci->bus, &xhci->ports[i].port, xhci, i,
2841
                          &xhci_port_ops,
2842
                          USB_SPEED_MASK_LOW  |
2843
                          USB_SPEED_MASK_FULL |
2844
                          USB_SPEED_MASK_HIGH);
2845
    }
2846
    for (i = 0; i < MAXSLOTS; i++) {
2847
        xhci->slots[i].enabled = 0;
2848
    }
2849

    
2850
    qemu_register_reset(xhci_reset, xhci);
2851
}
2852

    
2853
static int usb_xhci_initfn(struct PCIDevice *dev)
2854
{
2855
    int ret;
2856

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

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

    
2864
    usb_xhci_init(xhci, &dev->qdev);
2865

    
2866
    xhci->irq = xhci->pci_dev.irq[0];
2867

    
2868
    memory_region_init_io(&xhci->mem, &xhci_mem_ops, xhci,
2869
                          "xhci", LEN_REGS);
2870
    pci_register_bar(&xhci->pci_dev, 0,
2871
                     PCI_BASE_ADDRESS_SPACE_MEMORY|PCI_BASE_ADDRESS_MEM_TYPE_64,
2872
                     &xhci->mem);
2873

    
2874
    ret = pcie_cap_init(&xhci->pci_dev, 0xa0, PCI_EXP_TYPE_ENDPOINT, 0);
2875
    assert(ret >= 0);
2876

    
2877
    if (xhci->msi) {
2878
        ret = msi_init(&xhci->pci_dev, 0x70, 1, true, false);
2879
        assert(ret >= 0);
2880
    }
2881

    
2882
    return 0;
2883
}
2884

    
2885
static void xhci_write_config(PCIDevice *dev, uint32_t addr, uint32_t val,
2886
                              int len)
2887
{
2888
    XHCIState *xhci = DO_UPCAST(XHCIState, pci_dev, dev);
2889

    
2890
    pci_default_write_config(dev, addr, val, len);
2891
    if (xhci->msi) {
2892
        msi_write_config(dev, addr, val, len);
2893
    }
2894
}
2895

    
2896
static const VMStateDescription vmstate_xhci = {
2897
    .name = "xhci",
2898
    .unmigratable = 1,
2899
};
2900

    
2901
static Property xhci_properties[] = {
2902
    DEFINE_PROP_UINT32("msi", XHCIState, msi, 0),
2903
    DEFINE_PROP_END_OF_LIST(),
2904
};
2905

    
2906
static void xhci_class_init(ObjectClass *klass, void *data)
2907
{
2908
    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
2909
    DeviceClass *dc = DEVICE_CLASS(klass);
2910

    
2911
    dc->vmsd    = &vmstate_xhci;
2912
    dc->props   = xhci_properties;
2913
    k->init         = usb_xhci_initfn;
2914
    k->vendor_id    = PCI_VENDOR_ID_NEC;
2915
    k->device_id    = PCI_DEVICE_ID_NEC_UPD720200;
2916
    k->class_id     = PCI_CLASS_SERIAL_USB;
2917
    k->revision     = 0x03;
2918
    k->is_express   = 1;
2919
    k->config_write = xhci_write_config;
2920
}
2921

    
2922
static TypeInfo xhci_info = {
2923
    .name          = "nec-usb-xhci",
2924
    .parent        = TYPE_PCI_DEVICE,
2925
    .instance_size = sizeof(XHCIState),
2926
    .class_init    = xhci_class_init,
2927
};
2928

    
2929
static void xhci_register_types(void)
2930
{
2931
    type_register_static(&xhci_info);
2932
}
2933

    
2934
type_init(xhci_register_types)