Statistics
| Branch: | Revision:

root / hw / usb-xhci.c @ 079d0b7f

History | View | Annotate | Download (79.6 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;
311
    bool cancelled;
312
    bool complete;
313
    bool backgrounded;
314
    unsigned int iso_pkts;
315
    unsigned int slotid;
316
    unsigned int epid;
317
    bool in_xfer;
318
    bool iso_xfer;
319
    bool bg_xfer;
320

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

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

    
329
    TRBCCode status;
330

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

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

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

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

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

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

    
389
    XHCIPort ports[MAXPORTS];
390
    XHCISlot slots[MAXSLOTS];
391

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

    
403
    target_phys_addr_t er_start;
404
    uint32_t er_size;
405
    bool er_pcs;
406
    unsigned int er_ep_idx;
407
    bool er_full;
408

    
409
    XHCIEvent ev_buffer[EV_QUEUE];
410
    unsigned int ev_buffer_put;
411
    unsigned int ev_buffer_get;
412

    
413
    XHCIRing cmd_ring;
414
};
415

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

    
423
static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
424
                         unsigned int epid);
425

    
426
static inline target_phys_addr_t xhci_addr64(uint32_t low, uint32_t high)
427
{
428
#if TARGET_PHYS_ADDR_BITS > 32
429
    return low | ((target_phys_addr_t)high << 32);
430
#else
431
    return low;
432
#endif
433
}
434

    
435
static inline target_phys_addr_t xhci_mask64(uint64_t addr)
436
{
437
#if TARGET_PHYS_ADDR_BITS > 32
438
    return addr;
439
#else
440
    return addr & 0xffffffff;
441
#endif
442
}
443

    
444
static void xhci_irq_update(XHCIState *xhci)
445
{
446
    int level = 0;
447

    
448
    if (xhci->iman & IMAN_IP && xhci->iman & IMAN_IE &&
449
        xhci->usbcmd && USBCMD_INTE) {
450
        level = 1;
451
    }
452

    
453
    DPRINTF("xhci_irq_update(): %d\n", level);
454

    
455
    if (xhci->msi && msi_enabled(&xhci->pci_dev)) {
456
        if (level) {
457
            DPRINTF("xhci_irq_update(): MSI signal\n");
458
            msi_notify(&xhci->pci_dev, 0);
459
        }
460
    } else {
461
        qemu_set_irq(xhci->irq, level);
462
    }
463
}
464

    
465
static inline int xhci_running(XHCIState *xhci)
466
{
467
    return !(xhci->usbsts & USBSTS_HCH) && !xhci->er_full;
468
}
469

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

    
476
static void xhci_write_event(XHCIState *xhci, XHCIEvent *event)
477
{
478
    XHCITRB ev_trb;
479
    target_phys_addr_t addr;
480

    
481
    ev_trb.parameter = cpu_to_le64(event->ptr);
482
    ev_trb.status = cpu_to_le32(event->length | (event->ccode << 24));
483
    ev_trb.control = (event->slotid << 24) | (event->epid << 16) |
484
                     event->flags | (event->type << TRB_TYPE_SHIFT);
485
    if (xhci->er_pcs) {
486
        ev_trb.control |= TRB_C;
487
    }
488
    ev_trb.control = cpu_to_le32(ev_trb.control);
489

    
490
    DPRINTF("xhci_write_event(): [%d] %016"PRIx64" %08x %08x\n",
491
            xhci->er_ep_idx, ev_trb.parameter, ev_trb.status, ev_trb.control);
492

    
493
    addr = xhci->er_start + TRB_SIZE*xhci->er_ep_idx;
494
    cpu_physical_memory_write(addr, (uint8_t *) &ev_trb, TRB_SIZE);
495

    
496
    xhci->er_ep_idx++;
497
    if (xhci->er_ep_idx >= xhci->er_size) {
498
        xhci->er_ep_idx = 0;
499
        xhci->er_pcs = !xhci->er_pcs;
500
    }
501
}
502

    
503
static void xhci_events_update(XHCIState *xhci)
504
{
505
    target_phys_addr_t erdp;
506
    unsigned int dp_idx;
507
    bool do_irq = 0;
508

    
509
    if (xhci->usbsts & USBSTS_HCH) {
510
        return;
511
    }
512

    
513
    erdp = xhci_addr64(xhci->erdp_low, xhci->erdp_high);
514
    if (erdp < xhci->er_start ||
515
        erdp >= (xhci->er_start + TRB_SIZE*xhci->er_size)) {
516
        fprintf(stderr, "xhci: ERDP out of bounds: "TARGET_FMT_plx"\n", erdp);
517
        fprintf(stderr, "xhci: ER at "TARGET_FMT_plx" len %d\n",
518
                xhci->er_start, xhci->er_size);
519
        xhci_die(xhci);
520
        return;
521
    }
522
    dp_idx = (erdp - xhci->er_start) / TRB_SIZE;
523
    assert(dp_idx < xhci->er_size);
524

    
525
    /* NEC didn't read section 4.9.4 of the spec (v1.0 p139 top Note) and thus
526
     * deadlocks when the ER is full. Hack it by holding off events until
527
     * the driver decides to free at least half of the ring */
528
    if (xhci->er_full) {
529
        int er_free = dp_idx - xhci->er_ep_idx;
530
        if (er_free <= 0) {
531
            er_free += xhci->er_size;
532
        }
533
        if (er_free < (xhci->er_size/2)) {
534
            DPRINTF("xhci_events_update(): event ring still "
535
                    "more than half full (hack)\n");
536
            return;
537
        }
538
    }
539

    
540
    while (xhci->ev_buffer_put != xhci->ev_buffer_get) {
541
        assert(xhci->er_full);
542
        if (((xhci->er_ep_idx+1) % xhci->er_size) == dp_idx) {
543
            DPRINTF("xhci_events_update(): event ring full again\n");
544
#ifndef ER_FULL_HACK
545
            XHCIEvent full = {ER_HOST_CONTROLLER, CC_EVENT_RING_FULL_ERROR};
546
            xhci_write_event(xhci, &full);
547
#endif
548
            do_irq = 1;
549
            break;
550
        }
551
        XHCIEvent *event = &xhci->ev_buffer[xhci->ev_buffer_get];
552
        xhci_write_event(xhci, event);
553
        xhci->ev_buffer_get++;
554
        do_irq = 1;
555
        if (xhci->ev_buffer_get == EV_QUEUE) {
556
            xhci->ev_buffer_get = 0;
557
        }
558
    }
559

    
560
    if (do_irq) {
561
        xhci->erdp_low |= ERDP_EHB;
562
        xhci->iman |= IMAN_IP;
563
        xhci->usbsts |= USBSTS_EINT;
564
        xhci_irq_update(xhci);
565
    }
566

    
567
    if (xhci->er_full && xhci->ev_buffer_put == xhci->ev_buffer_get) {
568
        DPRINTF("xhci_events_update(): event ring no longer full\n");
569
        xhci->er_full = 0;
570
    }
571
    return;
572
}
573

    
574
static void xhci_event(XHCIState *xhci, XHCIEvent *event)
575
{
576
    target_phys_addr_t erdp;
577
    unsigned int dp_idx;
578

    
579
    if (xhci->er_full) {
580
        DPRINTF("xhci_event(): ER full, queueing\n");
581
        if (((xhci->ev_buffer_put+1) % EV_QUEUE) == xhci->ev_buffer_get) {
582
            fprintf(stderr, "xhci: event queue full, dropping event!\n");
583
            return;
584
        }
585
        xhci->ev_buffer[xhci->ev_buffer_put++] = *event;
586
        if (xhci->ev_buffer_put == EV_QUEUE) {
587
            xhci->ev_buffer_put = 0;
588
        }
589
        return;
590
    }
591

    
592
    erdp = xhci_addr64(xhci->erdp_low, xhci->erdp_high);
593
    if (erdp < xhci->er_start ||
594
        erdp >= (xhci->er_start + TRB_SIZE*xhci->er_size)) {
595
        fprintf(stderr, "xhci: ERDP out of bounds: "TARGET_FMT_plx"\n", erdp);
596
        fprintf(stderr, "xhci: ER at "TARGET_FMT_plx" len %d\n",
597
                xhci->er_start, xhci->er_size);
598
        xhci_die(xhci);
599
        return;
600
    }
601

    
602
    dp_idx = (erdp - xhci->er_start) / TRB_SIZE;
603
    assert(dp_idx < xhci->er_size);
604

    
605
    if ((xhci->er_ep_idx+1) % xhci->er_size == dp_idx) {
606
        DPRINTF("xhci_event(): ER full, queueing\n");
607
#ifndef ER_FULL_HACK
608
        XHCIEvent full = {ER_HOST_CONTROLLER, CC_EVENT_RING_FULL_ERROR};
609
        xhci_write_event(xhci, &full);
610
#endif
611
        xhci->er_full = 1;
612
        if (((xhci->ev_buffer_put+1) % EV_QUEUE) == xhci->ev_buffer_get) {
613
            fprintf(stderr, "xhci: event queue full, dropping event!\n");
614
            return;
615
        }
616
        xhci->ev_buffer[xhci->ev_buffer_put++] = *event;
617
        if (xhci->ev_buffer_put == EV_QUEUE) {
618
            xhci->ev_buffer_put = 0;
619
        }
620
    } else {
621
        xhci_write_event(xhci, event);
622
    }
623

    
624
    xhci->erdp_low |= ERDP_EHB;
625
    xhci->iman |= IMAN_IP;
626
    xhci->usbsts |= USBSTS_EINT;
627

    
628
    xhci_irq_update(xhci);
629
}
630

    
631
static void xhci_ring_init(XHCIState *xhci, XHCIRing *ring,
632
                           target_phys_addr_t base)
633
{
634
    ring->base = base;
635
    ring->dequeue = base;
636
    ring->ccs = 1;
637
}
638

    
639
static TRBType xhci_ring_fetch(XHCIState *xhci, XHCIRing *ring, XHCITRB *trb,
640
                               target_phys_addr_t *addr)
641
{
642
    while (1) {
643
        TRBType type;
644
        cpu_physical_memory_read(ring->dequeue, (uint8_t *) trb, TRB_SIZE);
645
        trb->addr = ring->dequeue;
646
        trb->ccs = ring->ccs;
647
        le64_to_cpus(&trb->parameter);
648
        le32_to_cpus(&trb->status);
649
        le32_to_cpus(&trb->control);
650

    
651
        DPRINTF("xhci: TRB fetched [" TARGET_FMT_plx "]: "
652
                "%016" PRIx64 " %08x %08x\n",
653
                ring->dequeue, trb->parameter, trb->status, trb->control);
654

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

    
659
        type = TRB_TYPE(*trb);
660

    
661
        if (type != TR_LINK) {
662
            if (addr) {
663
                *addr = ring->dequeue;
664
            }
665
            ring->dequeue += TRB_SIZE;
666
            return type;
667
        } else {
668
            ring->dequeue = xhci_mask64(trb->parameter);
669
            if (trb->control & TRB_LK_TC) {
670
                ring->ccs = !ring->ccs;
671
            }
672
        }
673
    }
674
}
675

    
676
static int xhci_ring_chain_length(XHCIState *xhci, const XHCIRing *ring)
677
{
678
    XHCITRB trb;
679
    int length = 0;
680
    target_phys_addr_t dequeue = ring->dequeue;
681
    bool ccs = ring->ccs;
682
    /* hack to bundle together the two/three TDs that make a setup transfer */
683
    bool control_td_set = 0;
684

    
685
    while (1) {
686
        TRBType type;
687
        cpu_physical_memory_read(dequeue, (uint8_t *) &trb, TRB_SIZE);
688
        le64_to_cpus(&trb.parameter);
689
        le32_to_cpus(&trb.status);
690
        le32_to_cpus(&trb.control);
691

    
692
        DPRINTF("xhci: TRB peeked [" TARGET_FMT_plx "]: "
693
                "%016" PRIx64 " %08x %08x\n",
694
                dequeue, trb.parameter, trb.status, trb.control);
695

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

    
700
        type = TRB_TYPE(trb);
701

    
702
        if (type == TR_LINK) {
703
            dequeue = xhci_mask64(trb.parameter);
704
            if (trb.control & TRB_LK_TC) {
705
                ccs = !ccs;
706
            }
707
            continue;
708
        }
709

    
710
        length += 1;
711
        dequeue += TRB_SIZE;
712

    
713
        if (type == TR_SETUP) {
714
            control_td_set = 1;
715
        } else if (type == TR_STATUS) {
716
            control_td_set = 0;
717
        }
718

    
719
        if (!control_td_set && !(trb.control & TRB_TR_CH)) {
720
            return length;
721
        }
722
    }
723
}
724

    
725
static void xhci_er_reset(XHCIState *xhci)
726
{
727
    XHCIEvRingSeg seg;
728

    
729
    /* cache the (sole) event ring segment location */
730
    if (xhci->erstsz != 1) {
731
        fprintf(stderr, "xhci: invalid value for ERSTSZ: %d\n", xhci->erstsz);
732
        xhci_die(xhci);
733
        return;
734
    }
735
    target_phys_addr_t erstba = xhci_addr64(xhci->erstba_low, xhci->erstba_high);
736
    cpu_physical_memory_read(erstba, (uint8_t *) &seg, sizeof(seg));
737
    le32_to_cpus(&seg.addr_low);
738
    le32_to_cpus(&seg.addr_high);
739
    le32_to_cpus(&seg.size);
740
    if (seg.size < 16 || seg.size > 4096) {
741
        fprintf(stderr, "xhci: invalid value for segment size: %d\n", seg.size);
742
        xhci_die(xhci);
743
        return;
744
    }
745
    xhci->er_start = xhci_addr64(seg.addr_low, seg.addr_high);
746
    xhci->er_size = seg.size;
747

    
748
    xhci->er_ep_idx = 0;
749
    xhci->er_pcs = 1;
750
    xhci->er_full = 0;
751

    
752
    DPRINTF("xhci: event ring:" TARGET_FMT_plx " [%d]\n",
753
            xhci->er_start, xhci->er_size);
754
}
755

    
756
static void xhci_run(XHCIState *xhci)
757
{
758
    DPRINTF("xhci_run()\n");
759

    
760
    xhci->usbsts &= ~USBSTS_HCH;
761
}
762

    
763
static void xhci_stop(XHCIState *xhci)
764
{
765
    DPRINTF("xhci_stop()\n");
766
    xhci->usbsts |= USBSTS_HCH;
767
    xhci->crcr_low &= ~CRCR_CRR;
768
}
769

    
770
static void xhci_set_ep_state(XHCIState *xhci, XHCIEPContext *epctx,
771
                              uint32_t state)
772
{
773
    uint32_t ctx[5];
774
    if (epctx->state == state) {
775
        return;
776
    }
777

    
778
    cpu_physical_memory_read(epctx->pctx, (uint8_t *) ctx, sizeof(ctx));
779
    ctx[0] &= ~EP_STATE_MASK;
780
    ctx[0] |= state;
781
    ctx[2] = epctx->ring.dequeue | epctx->ring.ccs;
782
    ctx[3] = (epctx->ring.dequeue >> 16) >> 16;
783
    DPRINTF("xhci: set epctx: " TARGET_FMT_plx " state=%d dequeue=%08x%08x\n",
784
            epctx->pctx, state, ctx[3], ctx[2]);
785
    cpu_physical_memory_write(epctx->pctx, (uint8_t *) ctx, sizeof(ctx));
786
    epctx->state = state;
787
}
788

    
789
static TRBCCode xhci_enable_ep(XHCIState *xhci, unsigned int slotid,
790
                               unsigned int epid, target_phys_addr_t pctx,
791
                               uint32_t *ctx)
792
{
793
    XHCISlot *slot;
794
    XHCIEPContext *epctx;
795
    target_phys_addr_t dequeue;
796
    int i;
797

    
798
    assert(slotid >= 1 && slotid <= MAXSLOTS);
799
    assert(epid >= 1 && epid <= 31);
800

    
801
    DPRINTF("xhci_enable_ep(%d, %d)\n", slotid, epid);
802

    
803
    slot = &xhci->slots[slotid-1];
804
    if (slot->eps[epid-1]) {
805
        fprintf(stderr, "xhci: slot %d ep %d already enabled!\n", slotid, epid);
806
        return CC_TRB_ERROR;
807
    }
808

    
809
    epctx = g_malloc(sizeof(XHCIEPContext));
810
    memset(epctx, 0, sizeof(XHCIEPContext));
811

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

    
814
    dequeue = xhci_addr64(ctx[2] & ~0xf, ctx[3]);
815
    xhci_ring_init(xhci, &epctx->ring, dequeue);
816
    epctx->ring.ccs = ctx[2] & 1;
817

    
818
    epctx->type = (ctx[1] >> EP_TYPE_SHIFT) & EP_TYPE_MASK;
819
    DPRINTF("xhci: endpoint %d.%d type is %d\n", epid/2, epid%2, epctx->type);
820
    epctx->pctx = pctx;
821
    epctx->max_psize = ctx[1]>>16;
822
    epctx->max_psize *= 1+((ctx[1]>>8)&0xff);
823
    epctx->has_bg = false;
824
    if (epctx->type == ET_ISO_IN) {
825
        epctx->has_bg = true;
826
    }
827
    DPRINTF("xhci: endpoint %d.%d max transaction (burst) size is %d\n",
828
            epid/2, epid%2, epctx->max_psize);
829
    for (i = 0; i < ARRAY_SIZE(epctx->transfers); i++) {
830
        usb_packet_init(&epctx->transfers[i].packet);
831
    }
832

    
833
    epctx->state = EP_RUNNING;
834
    ctx[0] &= ~EP_STATE_MASK;
835
    ctx[0] |= EP_RUNNING;
836

    
837
    return CC_SUCCESS;
838
}
839

    
840
static int xhci_ep_nuke_xfers(XHCIState *xhci, unsigned int slotid,
841
                               unsigned int epid)
842
{
843
    XHCISlot *slot;
844
    XHCIEPContext *epctx;
845
    int i, xferi, killed = 0;
846
    assert(slotid >= 1 && slotid <= MAXSLOTS);
847
    assert(epid >= 1 && epid <= 31);
848

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

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

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

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

    
859
    xferi = epctx->next_xfer;
860
    for (i = 0; i < TD_QUEUE; i++) {
861
        XHCITransfer *t = &epctx->transfers[xferi];
862
        if (t->running) {
863
            t->cancelled = 1;
864
            /* libusb_cancel_transfer(t->usbxfer) */
865
            DPRINTF("xhci: cancelling transfer %d, waiting for it to complete...\n", i);
866
            killed++;
867
        }
868
        if (t->backgrounded) {
869
            t->backgrounded = 0;
870
        }
871
        if (t->trbs) {
872
            g_free(t->trbs);
873
        }
874
        if (t->data) {
875
            g_free(t->data);
876
        }
877

    
878
        t->trbs = NULL;
879
        t->data = NULL;
880
        t->trb_count = t->trb_alloced = 0;
881
        t->data_length = t->data_alloced = 0;
882
        xferi = (xferi + 1) % TD_QUEUE;
883
    }
884
    if (epctx->has_bg) {
885
        xferi = epctx->next_bg;
886
        for (i = 0; i < BG_XFERS; i++) {
887
            XHCITransfer *t = &epctx->bg_transfers[xferi];
888
            if (t->running) {
889
                t->cancelled = 1;
890
                /* libusb_cancel_transfer(t->usbxfer); */
891
                DPRINTF("xhci: cancelling bg transfer %d, waiting for it to complete...\n", i);
892
                killed++;
893
            }
894
            if (t->data) {
895
                g_free(t->data);
896
            }
897

    
898
            t->data = NULL;
899
            xferi = (xferi + 1) % BG_XFERS;
900
        }
901
    }
902
    return killed;
903
}
904

    
905
static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,
906
                               unsigned int epid)
907
{
908
    XHCISlot *slot;
909
    XHCIEPContext *epctx;
910

    
911
    assert(slotid >= 1 && slotid <= MAXSLOTS);
912
    assert(epid >= 1 && epid <= 31);
913

    
914
    DPRINTF("xhci_disable_ep(%d, %d)\n", slotid, epid);
915

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

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

    
923
    xhci_ep_nuke_xfers(xhci, slotid, epid);
924

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

    
927
    xhci_set_ep_state(xhci, epctx, EP_DISABLED);
928

    
929
    g_free(epctx);
930
    slot->eps[epid-1] = NULL;
931

    
932
    return CC_SUCCESS;
933
}
934

    
935
static TRBCCode xhci_stop_ep(XHCIState *xhci, unsigned int slotid,
936
                             unsigned int epid)
937
{
938
    XHCISlot *slot;
939
    XHCIEPContext *epctx;
940

    
941
    DPRINTF("xhci_stop_ep(%d, %d)\n", slotid, epid);
942

    
943
    assert(slotid >= 1 && slotid <= MAXSLOTS);
944

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

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

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

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

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

    
964
    xhci_set_ep_state(xhci, epctx, EP_STOPPED);
965

    
966
    return CC_SUCCESS;
967
}
968

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

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

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

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

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

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

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

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

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

    
1005
    uint8_t ep = epid>>1;
1006

    
1007
    if (epid & 1) {
1008
        ep |= 0x80;
1009
    }
1010

    
1011
    dev = xhci->ports[xhci->slots[slotid-1].port-1].port.dev;
1012
    if (!dev) {
1013
        return CC_USB_TRANSACTION_ERROR;
1014
    }
1015

    
1016
    xhci_set_ep_state(xhci, epctx, EP_STOPPED);
1017

    
1018
    return CC_SUCCESS;
1019
}
1020

    
1021
static TRBCCode xhci_set_ep_dequeue(XHCIState *xhci, unsigned int slotid,
1022
                                    unsigned int epid, uint64_t pdequeue)
1023
{
1024
    XHCISlot *slot;
1025
    XHCIEPContext *epctx;
1026
    target_phys_addr_t dequeue;
1027

    
1028
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1029

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

    
1035
    DPRINTF("xhci_set_ep_dequeue(%d, %d, %016"PRIx64")\n", slotid, epid, pdequeue);
1036
    dequeue = xhci_mask64(pdequeue);
1037

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

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

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

    
1047

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

    
1053
    xhci_ring_init(xhci, &epctx->ring, dequeue & ~0xF);
1054
    epctx->ring.ccs = dequeue & 1;
1055

    
1056
    xhci_set_ep_state(xhci, epctx, EP_STOPPED);
1057

    
1058
    return CC_SUCCESS;
1059
}
1060

    
1061
static int xhci_xfer_data(XHCITransfer *xfer, uint8_t *data,
1062
                          unsigned int length, bool in_xfer, bool out_xfer,
1063
                          bool report)
1064
{
1065
    int i;
1066
    uint32_t edtla = 0;
1067
    unsigned int transferred = 0;
1068
    unsigned int left = length;
1069
    bool reported = 0;
1070
    bool shortpkt = 0;
1071
    XHCIEvent event = {ER_TRANSFER, CC_SUCCESS};
1072
    XHCIState *xhci = xfer->xhci;
1073

    
1074
    DPRINTF("xhci_xfer_data(len=%d, in_xfer=%d, out_xfer=%d, report=%d)\n",
1075
            length, in_xfer, out_xfer, report);
1076

    
1077
    assert(!(in_xfer && out_xfer));
1078

    
1079
    for (i = 0; i < xfer->trb_count; i++) {
1080
        XHCITRB *trb = &xfer->trbs[i];
1081
        target_phys_addr_t addr;
1082
        unsigned int chunk = 0;
1083

    
1084
        switch (TRB_TYPE(*trb)) {
1085
        case TR_DATA:
1086
            if ((!(trb->control & TRB_TR_DIR)) != (!in_xfer)) {
1087
                fprintf(stderr, "xhci: data direction mismatch for TR_DATA\n");
1088
                xhci_die(xhci);
1089
                return transferred;
1090
            }
1091
            /* fallthrough */
1092
        case TR_NORMAL:
1093
        case TR_ISOCH:
1094
            addr = xhci_mask64(trb->parameter);
1095
            chunk = trb->status & 0x1ffff;
1096
            if (chunk > left) {
1097
                chunk = left;
1098
                shortpkt = 1;
1099
            }
1100
            if (in_xfer || out_xfer) {
1101
                if (trb->control & TRB_TR_IDT) {
1102
                    uint64_t idata;
1103
                    if (chunk > 8 || in_xfer) {
1104
                        fprintf(stderr, "xhci: invalid immediate data TRB\n");
1105
                        xhci_die(xhci);
1106
                        return transferred;
1107
                    }
1108
                    idata = le64_to_cpu(trb->parameter);
1109
                    memcpy(data, &idata, chunk);
1110
                } else {
1111
                    DPRINTF("xhci_xfer_data: r/w(%d) %d bytes at "
1112
                            TARGET_FMT_plx "\n", in_xfer, chunk, addr);
1113
                    if (in_xfer) {
1114
                        cpu_physical_memory_write(addr, data, chunk);
1115
                    } else {
1116
                        cpu_physical_memory_read(addr, data, chunk);
1117
                    }
1118
#ifdef DEBUG_DATA
1119
                    unsigned int count = chunk;
1120
                    int i;
1121
                    if (count > 16) {
1122
                        count = 16;
1123
                    }
1124
                    DPRINTF(" ::");
1125
                    for (i = 0; i < count; i++) {
1126
                        DPRINTF(" %02x", data[i]);
1127
                    }
1128
                    DPRINTF("\n");
1129
#endif
1130
                }
1131
            }
1132
            left -= chunk;
1133
            data += chunk;
1134
            edtla += chunk;
1135
            transferred += chunk;
1136
            break;
1137
        case TR_STATUS:
1138
            reported = 0;
1139
            shortpkt = 0;
1140
            break;
1141
        }
1142

    
1143
        if (report && !reported && (trb->control & TRB_TR_IOC ||
1144
            (shortpkt && (trb->control & TRB_TR_ISP)))) {
1145
            event.slotid = xfer->slotid;
1146
            event.epid = xfer->epid;
1147
            event.length = (trb->status & 0x1ffff) - chunk;
1148
            event.flags = 0;
1149
            event.ptr = trb->addr;
1150
            if (xfer->status == CC_SUCCESS) {
1151
                event.ccode = shortpkt ? CC_SHORT_PACKET : CC_SUCCESS;
1152
            } else {
1153
                event.ccode = xfer->status;
1154
            }
1155
            if (TRB_TYPE(*trb) == TR_EVDATA) {
1156
                event.ptr = trb->parameter;
1157
                event.flags |= TRB_EV_ED;
1158
                event.length = edtla & 0xffffff;
1159
                DPRINTF("xhci_xfer_data: EDTLA=%d\n", event.length);
1160
                edtla = 0;
1161
            }
1162
            xhci_event(xhci, &event);
1163
            reported = 1;
1164
        }
1165
    }
1166
    return transferred;
1167
}
1168

    
1169
static void xhci_stall_ep(XHCITransfer *xfer)
1170
{
1171
    XHCIState *xhci = xfer->xhci;
1172
    XHCISlot *slot = &xhci->slots[xfer->slotid-1];
1173
    XHCIEPContext *epctx = slot->eps[xfer->epid-1];
1174

    
1175
    epctx->ring.dequeue = xfer->trbs[0].addr;
1176
    epctx->ring.ccs = xfer->trbs[0].ccs;
1177
    xhci_set_ep_state(xhci, epctx, EP_HALTED);
1178
    DPRINTF("xhci: stalled slot %d ep %d\n", xfer->slotid, xfer->epid);
1179
    DPRINTF("xhci: will continue at "TARGET_FMT_plx"\n", epctx->ring.dequeue);
1180
}
1181

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

    
1185
static void xhci_bg_update(XHCIState *xhci, XHCIEPContext *epctx)
1186
{
1187
    if (epctx->bg_updating) {
1188
        return;
1189
    }
1190
    DPRINTF("xhci_bg_update(%p, %p)\n", xhci, epctx);
1191
    assert(epctx->has_bg);
1192
    DPRINTF("xhci: fg=%d bg=%d\n", epctx->comp_xfer, epctx->next_bg);
1193
    epctx->bg_updating = 1;
1194
    while (epctx->transfers[epctx->comp_xfer].backgrounded &&
1195
           epctx->bg_transfers[epctx->next_bg].complete) {
1196
        XHCITransfer *fg = &epctx->transfers[epctx->comp_xfer];
1197
        XHCITransfer *bg = &epctx->bg_transfers[epctx->next_bg];
1198
#if 0
1199
        DPRINTF("xhci: completing fg %d from bg %d.%d (stat: %d)\n",
1200
                epctx->comp_xfer, epctx->next_bg, bg->cur_pkt,
1201
                bg->usbxfer->iso_packet_desc[bg->cur_pkt].status
1202
               );
1203
#endif
1204
        assert(epctx->type == ET_ISO_IN);
1205
        assert(bg->iso_xfer);
1206
        assert(bg->in_xfer);
1207
        uint8_t *p = bg->data + bg->cur_pkt * bg->pktsize;
1208
#if 0
1209
        int len = bg->usbxfer->iso_packet_desc[bg->cur_pkt].actual_length;
1210
        fg->status = libusb_to_ccode(bg->usbxfer->iso_packet_desc[bg->cur_pkt].status);
1211
#else
1212
        int len = 0;
1213
        FIXME();
1214
#endif
1215
        fg->complete = 1;
1216
        fg->backgrounded = 0;
1217

    
1218
        if (fg->status == CC_STALL_ERROR) {
1219
            xhci_stall_ep(fg);
1220
        }
1221

    
1222
        xhci_xfer_data(fg, p, len, 1, 0, 1);
1223

    
1224
        epctx->comp_xfer++;
1225
        if (epctx->comp_xfer == TD_QUEUE) {
1226
            epctx->comp_xfer = 0;
1227
        }
1228
        DPRINTF("next fg xfer: %d\n", epctx->comp_xfer);
1229
        bg->cur_pkt++;
1230
        if (bg->cur_pkt == bg->pkts) {
1231
            bg->complete = 0;
1232
            if (xhci_submit(xhci, bg, epctx) < 0) {
1233
                fprintf(stderr, "xhci: bg resubmit failed\n");
1234
            }
1235
            epctx->next_bg++;
1236
            if (epctx->next_bg == BG_XFERS) {
1237
                epctx->next_bg = 0;
1238
            }
1239
            DPRINTF("next bg xfer: %d\n", epctx->next_bg);
1240

    
1241
        xhci_kick_ep(xhci, fg->slotid, fg->epid);
1242
        }
1243
    }
1244
    epctx->bg_updating = 0;
1245
}
1246

    
1247
#if 0
1248
static void xhci_xfer_cb(struct libusb_transfer *transfer)
1249
{
1250
    XHCIState *xhci;
1251
    XHCITransfer *xfer;
1252

1253
    xfer = (XHCITransfer *)transfer->user_data;
1254
    xhci = xfer->xhci;
1255

1256
    DPRINTF("xhci_xfer_cb(slot=%d, ep=%d, status=%d)\n", xfer->slotid,
1257
            xfer->epid, transfer->status);
1258

1259
    assert(xfer->slotid >= 1 && xfer->slotid <= MAXSLOTS);
1260
    assert(xfer->epid >= 1 && xfer->epid <= 31);
1261

1262
    if (xfer->cancelled) {
1263
        DPRINTF("xhci: transfer cancelled, not reporting anything\n");
1264
        xfer->running = 0;
1265
        return;
1266
    }
1267

1268
    XHCIEPContext *epctx;
1269
    XHCISlot *slot;
1270
    slot = &xhci->slots[xfer->slotid-1];
1271
    assert(slot->eps[xfer->epid-1]);
1272
    epctx = slot->eps[xfer->epid-1];
1273

1274
    if (xfer->bg_xfer) {
1275
        DPRINTF("xhci: background transfer, updating\n");
1276
        xfer->complete = 1;
1277
        xfer->running = 0;
1278
        xhci_bg_update(xhci, epctx);
1279
        return;
1280
    }
1281

1282
    if (xfer->iso_xfer) {
1283
        transfer->status = transfer->iso_packet_desc[0].status;
1284
        transfer->actual_length = transfer->iso_packet_desc[0].actual_length;
1285
    }
1286

1287
    xfer->status = libusb_to_ccode(transfer->status);
1288

1289
    xfer->complete = 1;
1290
    xfer->running = 0;
1291

1292
    if (transfer->status == LIBUSB_TRANSFER_STALL)
1293
        xhci_stall_ep(xhci, epctx, xfer);
1294

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

1297
    if (xfer->in_xfer) {
1298
        if (xfer->epid == 1) {
1299
            xhci_xfer_data(xhci, xfer, xfer->data + 8,
1300
                           transfer->actual_length, 1, 0, 1);
1301
        } else {
1302
            xhci_xfer_data(xhci, xfer, xfer->data,
1303
                           transfer->actual_length, 1, 0, 1);
1304
        }
1305
    } else {
1306
        xhci_xfer_data(xhci, xfer, NULL, transfer->actual_length, 0, 0, 1);
1307
    }
1308

1309
    xhci_kick_ep(xhci, xfer->slotid, xfer->epid);
1310
}
1311

1312
static int xhci_hle_control(XHCIState *xhci, XHCITransfer *xfer,
1313
                            uint8_t bmRequestType, uint8_t bRequest,
1314
                            uint16_t wValue, uint16_t wIndex, uint16_t wLength)
1315
{
1316
    uint16_t type_req = (bmRequestType << 8) | bRequest;
1317

1318
    switch (type_req) {
1319
        case 0x0000 | USB_REQ_SET_CONFIGURATION:
1320
            DPRINTF("xhci: HLE switch configuration\n");
1321
            return xhci_switch_config(xhci, xfer->slotid, wValue) == 0;
1322
        case 0x0100 | USB_REQ_SET_INTERFACE:
1323
            DPRINTF("xhci: HLE set interface altsetting\n");
1324
            return xhci_set_iface_alt(xhci, xfer->slotid, wIndex, wValue) == 0;
1325
        case 0x0200 | USB_REQ_CLEAR_FEATURE:
1326
            if (wValue == 0) { // endpoint halt
1327
                DPRINTF("xhci: HLE clear halt\n");
1328
                return xhci_clear_halt(xhci, xfer->slotid, wIndex);
1329
            }
1330
        case 0x0000 | USB_REQ_SET_ADDRESS:
1331
            fprintf(stderr, "xhci: warn: illegal SET_ADDRESS request\n");
1332
            return 0;
1333
        default:
1334
            return 0;
1335
    }
1336
}
1337
#endif
1338

    
1339
static int xhci_setup_packet(XHCITransfer *xfer, XHCIPort *port, USBDevice *dev)
1340
{
1341
    USBEndpoint *ep;
1342
    int dir;
1343

    
1344
    dir = xfer->in_xfer ? USB_TOKEN_IN : USB_TOKEN_OUT;
1345
    ep = usb_ep_get(dev, dir, xfer->epid >> 1);
1346
    usb_packet_setup(&xfer->packet, dir, ep);
1347
    usb_packet_addbuf(&xfer->packet, xfer->data, xfer->data_length);
1348
    DPRINTF("xhci: setup packet pid 0x%x addr %d ep %d\n",
1349
            xfer->packet.pid, dev->addr, ep->nr);
1350
    return 0;
1351
}
1352

    
1353
static int xhci_complete_packet(XHCITransfer *xfer, int ret)
1354
{
1355
    if (ret == USB_RET_ASYNC) {
1356
        xfer->running = 1;
1357
        xfer->complete = 0;
1358
        xfer->cancelled = 0;
1359
        return 0;
1360
    } else {
1361
        xfer->running = 0;
1362
        xfer->complete = 1;
1363
    }
1364

    
1365
    if (ret >= 0) {
1366
        xfer->status = CC_SUCCESS;
1367
        xhci_xfer_data(xfer, xfer->data, ret, xfer->in_xfer, 0, 1);
1368
        return 0;
1369
    }
1370

    
1371
    /* error */
1372
    switch (ret) {
1373
    case USB_RET_NODEV:
1374
        xfer->status = CC_USB_TRANSACTION_ERROR;
1375
        xhci_xfer_data(xfer, xfer->data, 0, xfer->in_xfer, 0, 1);
1376
        xhci_stall_ep(xfer);
1377
        break;
1378
    case USB_RET_STALL:
1379
        xfer->status = CC_STALL_ERROR;
1380
        xhci_xfer_data(xfer, xfer->data, 0, xfer->in_xfer, 0, 1);
1381
        xhci_stall_ep(xfer);
1382
        break;
1383
    default:
1384
        fprintf(stderr, "%s: FIXME: ret = %d\n", __FUNCTION__, ret);
1385
        FIXME();
1386
    }
1387
    return 0;
1388
}
1389

    
1390
static USBDevice *xhci_find_device(XHCIPort *port, uint8_t addr)
1391
{
1392
    if (!(port->portsc & PORTSC_PED)) {
1393
        return NULL;
1394
    }
1395
    return usb_find_device(&port->port, addr);
1396
}
1397

    
1398
static int xhci_fire_ctl_transfer(XHCIState *xhci, XHCITransfer *xfer)
1399
{
1400
    XHCITRB *trb_setup, *trb_status;
1401
    uint8_t bmRequestType, bRequest;
1402
    uint16_t wValue, wLength, wIndex;
1403
    XHCIPort *port;
1404
    USBDevice *dev;
1405
    int ret;
1406

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

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

    
1412
    /* at most one Event Data TRB allowed after STATUS */
1413
    if (TRB_TYPE(*trb_status) == TR_EVDATA && xfer->trb_count > 2) {
1414
        trb_status--;
1415
    }
1416

    
1417
    /* do some sanity checks */
1418
    if (TRB_TYPE(*trb_setup) != TR_SETUP) {
1419
        fprintf(stderr, "xhci: ep0 first TD not SETUP: %d\n",
1420
                TRB_TYPE(*trb_setup));
1421
        return -1;
1422
    }
1423
    if (TRB_TYPE(*trb_status) != TR_STATUS) {
1424
        fprintf(stderr, "xhci: ep0 last TD not STATUS: %d\n",
1425
                TRB_TYPE(*trb_status));
1426
        return -1;
1427
    }
1428
    if (!(trb_setup->control & TRB_TR_IDT)) {
1429
        fprintf(stderr, "xhci: Setup TRB doesn't have IDT set\n");
1430
        return -1;
1431
    }
1432
    if ((trb_setup->status & 0x1ffff) != 8) {
1433
        fprintf(stderr, "xhci: Setup TRB has bad length (%d)\n",
1434
                (trb_setup->status & 0x1ffff));
1435
        return -1;
1436
    }
1437

    
1438
    bmRequestType = trb_setup->parameter;
1439
    bRequest = trb_setup->parameter >> 8;
1440
    wValue = trb_setup->parameter >> 16;
1441
    wIndex = trb_setup->parameter >> 32;
1442
    wLength = trb_setup->parameter >> 48;
1443

    
1444
    if (xfer->data && xfer->data_alloced < wLength) {
1445
        xfer->data_alloced = 0;
1446
        g_free(xfer->data);
1447
        xfer->data = NULL;
1448
    }
1449
    if (!xfer->data) {
1450
        DPRINTF("xhci: alloc %d bytes data\n", wLength);
1451
        xfer->data = g_malloc(wLength+1);
1452
        xfer->data_alloced = wLength;
1453
    }
1454
    xfer->data_length = wLength;
1455

    
1456
    port = &xhci->ports[xhci->slots[xfer->slotid-1].port-1];
1457
    dev = xhci_find_device(port, xhci->slots[xfer->slotid-1].devaddr);
1458
    if (!dev) {
1459
        fprintf(stderr, "xhci: slot %d port %d has no device\n", xfer->slotid,
1460
                xhci->slots[xfer->slotid-1].port);
1461
        return -1;
1462
    }
1463

    
1464
    xfer->in_xfer = bmRequestType & USB_DIR_IN;
1465
    xfer->iso_xfer = false;
1466

    
1467
    xhci_setup_packet(xfer, port, dev);
1468
    if (!xfer->in_xfer) {
1469
        xhci_xfer_data(xfer, xfer->data, wLength, 0, 1, 0);
1470
    }
1471
    ret = usb_device_handle_control(dev, &xfer->packet,
1472
                                    (bmRequestType << 8) | bRequest,
1473
                                    wValue, wIndex, wLength, xfer->data);
1474

    
1475
    xhci_complete_packet(xfer, ret);
1476
    if (!xfer->running) {
1477
        xhci_kick_ep(xhci, xfer->slotid, xfer->epid);
1478
    }
1479
    return 0;
1480
}
1481

    
1482
static int xhci_submit(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)
1483
{
1484
    XHCIPort *port;
1485
    USBDevice *dev;
1486
    int ret;
1487

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

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

    
1492
    if (xfer->data && xfer->data_alloced < xfer->data_length) {
1493
        xfer->data_alloced = 0;
1494
        g_free(xfer->data);
1495
        xfer->data = NULL;
1496
    }
1497
    if (!xfer->data && xfer->data_length) {
1498
        DPRINTF("xhci: alloc %d bytes data\n", xfer->data_length);
1499
        xfer->data = g_malloc(xfer->data_length);
1500
        xfer->data_alloced = xfer->data_length;
1501
    }
1502
    if (epctx->type == ET_ISO_IN || epctx->type == ET_ISO_OUT) {
1503
        if (!xfer->bg_xfer) {
1504
            xfer->pkts = 1;
1505
        }
1506
    } else {
1507
        xfer->pkts = 0;
1508
    }
1509

    
1510
    port = &xhci->ports[xhci->slots[xfer->slotid-1].port-1];
1511
    dev = xhci_find_device(port, xhci->slots[xfer->slotid-1].devaddr);
1512
    if (!dev) {
1513
        fprintf(stderr, "xhci: slot %d port %d has no device\n", xfer->slotid,
1514
                xhci->slots[xfer->slotid-1].port);
1515
        return -1;
1516
    }
1517

    
1518
    xhci_setup_packet(xfer, port, dev);
1519

    
1520
    switch(epctx->type) {
1521
    case ET_INTR_OUT:
1522
    case ET_INTR_IN:
1523
    case ET_BULK_OUT:
1524
    case ET_BULK_IN:
1525
        break;
1526
    case ET_ISO_OUT:
1527
    case ET_ISO_IN:
1528
        FIXME();
1529
        break;
1530
    default:
1531
        fprintf(stderr, "xhci: unknown or unhandled EP "
1532
                "(type %d, in %d, ep %02x)\n",
1533
                epctx->type, xfer->in_xfer, xfer->epid);
1534
        return -1;
1535
    }
1536

    
1537
    if (!xfer->in_xfer) {
1538
        xhci_xfer_data(xfer, xfer->data, xfer->data_length, 0, 1, 0);
1539
    }
1540
    ret = usb_handle_packet(dev, &xfer->packet);
1541

    
1542
    xhci_complete_packet(xfer, ret);
1543
    if (!xfer->running) {
1544
        xhci_kick_ep(xhci, xfer->slotid, xfer->epid);
1545
    }
1546
    return 0;
1547
}
1548

    
1549
static int xhci_fire_transfer(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)
1550
{
1551
    int i;
1552
    unsigned int length = 0;
1553
    XHCITRB *trb;
1554

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

    
1557
    for (i = 0; i < xfer->trb_count; i++) {
1558
        trb = &xfer->trbs[i];
1559
        if (TRB_TYPE(*trb) == TR_NORMAL || TRB_TYPE(*trb) == TR_ISOCH) {
1560
            length += trb->status & 0x1ffff;
1561
        }
1562
    }
1563
    DPRINTF("xhci: total TD length=%d\n", length);
1564

    
1565
    if (!epctx->has_bg) {
1566
        xfer->data_length = length;
1567
        xfer->backgrounded = 0;
1568
        return xhci_submit(xhci, xfer, epctx);
1569
    } else {
1570
        if (!epctx->bg_running) {
1571
            for (i = 0; i < BG_XFERS; i++) {
1572
                XHCITransfer *t = &epctx->bg_transfers[i];
1573
                t->xhci = xhci;
1574
                t->epid = xfer->epid;
1575
                t->slotid = xfer->slotid;
1576
                t->pkts = BG_PKTS;
1577
                t->pktsize = epctx->max_psize;
1578
                t->data_length = t->pkts * t->pktsize;
1579
                t->bg_xfer = 1;
1580
                if (xhci_submit(xhci, t, epctx) < 0) {
1581
                    fprintf(stderr, "xhci: bg submit failed\n");
1582
                    return -1;
1583
                }
1584
            }
1585
            epctx->bg_running = 1;
1586
        }
1587
        xfer->backgrounded = 1;
1588
        xhci_bg_update(xhci, epctx);
1589
        return 0;
1590
    }
1591
}
1592

    
1593
static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid, unsigned int epid)
1594
{
1595
    XHCIEPContext *epctx;
1596
    int length;
1597
    int i;
1598

    
1599
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1600
    assert(epid >= 1 && epid <= 31);
1601
    DPRINTF("xhci_kick_ep(%d, %d)\n", slotid, epid);
1602

    
1603
    if (!xhci->slots[slotid-1].enabled) {
1604
        fprintf(stderr, "xhci: xhci_kick_ep for disabled slot %d\n", slotid);
1605
        return;
1606
    }
1607
    epctx = xhci->slots[slotid-1].eps[epid-1];
1608
    if (!epctx) {
1609
        fprintf(stderr, "xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
1610
                epid, slotid);
1611
        return;
1612
    }
1613

    
1614
    if (epctx->state == EP_HALTED) {
1615
        DPRINTF("xhci: ep halted, not running schedule\n");
1616
        return;
1617
    }
1618

    
1619
    xhci_set_ep_state(xhci, epctx, EP_RUNNING);
1620

    
1621
    while (1) {
1622
        XHCITransfer *xfer = &epctx->transfers[epctx->next_xfer];
1623
        if (xfer->running || xfer->backgrounded) {
1624
            DPRINTF("xhci: ep is busy\n");
1625
            break;
1626
        }
1627
        length = xhci_ring_chain_length(xhci, &epctx->ring);
1628
        if (length < 0) {
1629
            DPRINTF("xhci: incomplete TD (%d TRBs)\n", -length);
1630
            break;
1631
        } else if (length == 0) {
1632
            break;
1633
        }
1634
        DPRINTF("xhci: fetching %d-TRB TD\n", length);
1635
        if (xfer->trbs && xfer->trb_alloced < length) {
1636
            xfer->trb_count = 0;
1637
            xfer->trb_alloced = 0;
1638
            g_free(xfer->trbs);
1639
            xfer->trbs = NULL;
1640
        }
1641
        if (!xfer->trbs) {
1642
            xfer->trbs = g_malloc(sizeof(XHCITRB) * length);
1643
            xfer->trb_alloced = length;
1644
        }
1645
        xfer->trb_count = length;
1646

    
1647
        for (i = 0; i < length; i++) {
1648
            assert(xhci_ring_fetch(xhci, &epctx->ring, &xfer->trbs[i], NULL));
1649
        }
1650
        xfer->xhci = xhci;
1651
        xfer->epid = epid;
1652
        xfer->slotid = slotid;
1653

    
1654
        if (epid == 1) {
1655
            if (xhci_fire_ctl_transfer(xhci, xfer) >= 0) {
1656
                epctx->next_xfer = (epctx->next_xfer + 1) % TD_QUEUE;
1657
            } else {
1658
                fprintf(stderr, "xhci: error firing CTL transfer\n");
1659
            }
1660
        } else {
1661
            if (xhci_fire_transfer(xhci, xfer, epctx) >= 0) {
1662
                epctx->next_xfer = (epctx->next_xfer + 1) % TD_QUEUE;
1663
            } else {
1664
                fprintf(stderr, "xhci: error firing data transfer\n");
1665
            }
1666
        }
1667

    
1668
        /*
1669
         * Qemu usb can't handle multiple in-flight xfers.
1670
         * Also xfers might be finished here already,
1671
         * possibly with an error.  Stop here for now.
1672
         */
1673
        break;
1674
    }
1675
}
1676

    
1677
static TRBCCode xhci_enable_slot(XHCIState *xhci, unsigned int slotid)
1678
{
1679
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1680
    DPRINTF("xhci_enable_slot(%d)\n", slotid);
1681
    xhci->slots[slotid-1].enabled = 1;
1682
    xhci->slots[slotid-1].port = 0;
1683
    memset(xhci->slots[slotid-1].eps, 0, sizeof(XHCIEPContext*)*31);
1684

    
1685
    return CC_SUCCESS;
1686
}
1687

    
1688
static TRBCCode xhci_disable_slot(XHCIState *xhci, unsigned int slotid)
1689
{
1690
    int i;
1691

    
1692
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1693
    DPRINTF("xhci_disable_slot(%d)\n", slotid);
1694

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

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

    
1705
static TRBCCode xhci_address_slot(XHCIState *xhci, unsigned int slotid,
1706
                                  uint64_t pictx, bool bsr)
1707
{
1708
    XHCISlot *slot;
1709
    USBDevice *dev;
1710
    target_phys_addr_t ictx, octx, dcbaap;
1711
    uint64_t poctx;
1712
    uint32_t ictl_ctx[2];
1713
    uint32_t slot_ctx[4];
1714
    uint32_t ep0_ctx[5];
1715
    unsigned int port;
1716
    int i;
1717
    TRBCCode res;
1718

    
1719
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1720
    DPRINTF("xhci_address_slot(%d)\n", slotid);
1721

    
1722
    dcbaap = xhci_addr64(xhci->dcbaap_low, xhci->dcbaap_high);
1723
    cpu_physical_memory_read(dcbaap + 8*slotid,
1724
                             (uint8_t *) &poctx, sizeof(poctx));
1725
    ictx = xhci_mask64(pictx);
1726
    octx = xhci_mask64(le64_to_cpu(poctx));
1727

    
1728
    DPRINTF("xhci: input context at "TARGET_FMT_plx"\n", ictx);
1729
    DPRINTF("xhci: output context at "TARGET_FMT_plx"\n", octx);
1730

    
1731
    cpu_physical_memory_read(ictx, (uint8_t *) ictl_ctx, sizeof(ictl_ctx));
1732

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

    
1739
    cpu_physical_memory_read(ictx+32, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1740
    cpu_physical_memory_read(ictx+64, (uint8_t *) ep0_ctx, sizeof(ep0_ctx));
1741

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

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

    
1748
    port = (slot_ctx[1]>>16) & 0xFF;
1749
    dev = xhci->ports[port-1].port.dev;
1750

    
1751
    if (port < 1 || port > MAXPORTS) {
1752
        fprintf(stderr, "xhci: bad port %d\n", port);
1753
        return CC_TRB_ERROR;
1754
    } else if (!dev) {
1755
        fprintf(stderr, "xhci: port %d not connected\n", port);
1756
        return CC_USB_TRANSACTION_ERROR;
1757
    }
1758

    
1759
    for (i = 0; i < MAXSLOTS; i++) {
1760
        if (xhci->slots[i].port == port) {
1761
            fprintf(stderr, "xhci: port %d already assigned to slot %d\n",
1762
                    port, i+1);
1763
            return CC_TRB_ERROR;
1764
        }
1765
    }
1766

    
1767
    slot = &xhci->slots[slotid-1];
1768
    slot->port = port;
1769
    slot->ctx = octx;
1770

    
1771
    if (bsr) {
1772
        slot_ctx[3] = SLOT_DEFAULT << SLOT_STATE_SHIFT;
1773
    } else {
1774
        slot->devaddr = xhci->devaddr++;
1775
        slot_ctx[3] = (SLOT_ADDRESSED << SLOT_STATE_SHIFT) | slot->devaddr;
1776
        DPRINTF("xhci: device address is %d\n", slot->devaddr);
1777
        usb_device_handle_control(dev, NULL,
1778
                                  DeviceOutRequest | USB_REQ_SET_ADDRESS,
1779
                                  slot->devaddr, 0, 0, NULL);
1780
    }
1781

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

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

    
1789
    cpu_physical_memory_write(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1790
    cpu_physical_memory_write(octx+32, (uint8_t *) ep0_ctx, sizeof(ep0_ctx));
1791

    
1792
    return res;
1793
}
1794

    
1795

    
1796
static TRBCCode xhci_configure_slot(XHCIState *xhci, unsigned int slotid,
1797
                                  uint64_t pictx, bool dc)
1798
{
1799
    target_phys_addr_t ictx, octx;
1800
    uint32_t ictl_ctx[2];
1801
    uint32_t slot_ctx[4];
1802
    uint32_t islot_ctx[4];
1803
    uint32_t ep_ctx[5];
1804
    int i;
1805
    TRBCCode res;
1806

    
1807
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1808
    DPRINTF("xhci_configure_slot(%d)\n", slotid);
1809

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

    
1813
    DPRINTF("xhci: input context at "TARGET_FMT_plx"\n", ictx);
1814
    DPRINTF("xhci: output context at "TARGET_FMT_plx"\n", octx);
1815

    
1816
    if (dc) {
1817
        for (i = 2; i <= 31; i++) {
1818
            if (xhci->slots[slotid-1].eps[i-1]) {
1819
                xhci_disable_ep(xhci, slotid, i);
1820
            }
1821
        }
1822

    
1823
        cpu_physical_memory_read(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1824
        slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
1825
        slot_ctx[3] |= SLOT_ADDRESSED << SLOT_STATE_SHIFT;
1826
        DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
1827
                slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
1828
        cpu_physical_memory_write(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1829

    
1830
        return CC_SUCCESS;
1831
    }
1832

    
1833
    cpu_physical_memory_read(ictx, (uint8_t *) ictl_ctx, sizeof(ictl_ctx));
1834

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

    
1841
    cpu_physical_memory_read(ictx+32, (uint8_t *) islot_ctx, sizeof(islot_ctx));
1842
    cpu_physical_memory_read(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1843

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

    
1849
    for (i = 2; i <= 31; i++) {
1850
        if (ictl_ctx[0] & (1<<i)) {
1851
            xhci_disable_ep(xhci, slotid, i);
1852
        }
1853
        if (ictl_ctx[1] & (1<<i)) {
1854
            cpu_physical_memory_read(ictx+32+(32*i),
1855
                                     (uint8_t *) ep_ctx, sizeof(ep_ctx));
1856
            DPRINTF("xhci: input ep%d.%d context: %08x %08x %08x %08x %08x\n",
1857
                    i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2],
1858
                    ep_ctx[3], ep_ctx[4]);
1859
            xhci_disable_ep(xhci, slotid, i);
1860
            res = xhci_enable_ep(xhci, slotid, i, octx+(32*i), ep_ctx);
1861
            if (res != CC_SUCCESS) {
1862
                return res;
1863
            }
1864
            DPRINTF("xhci: output ep%d.%d context: %08x %08x %08x %08x %08x\n",
1865
                    i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2],
1866
                    ep_ctx[3], ep_ctx[4]);
1867
            cpu_physical_memory_write(octx+(32*i),
1868
                                      (uint8_t *) ep_ctx, sizeof(ep_ctx));
1869
        }
1870
    }
1871

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

    
1880
    cpu_physical_memory_write(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1881

    
1882
    return CC_SUCCESS;
1883
}
1884

    
1885

    
1886
static TRBCCode xhci_evaluate_slot(XHCIState *xhci, unsigned int slotid,
1887
                                   uint64_t pictx)
1888
{
1889
    target_phys_addr_t ictx, octx;
1890
    uint32_t ictl_ctx[2];
1891
    uint32_t iep0_ctx[5];
1892
    uint32_t ep0_ctx[5];
1893
    uint32_t islot_ctx[4];
1894
    uint32_t slot_ctx[4];
1895

    
1896
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1897
    DPRINTF("xhci_evaluate_slot(%d)\n", slotid);
1898

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

    
1902
    DPRINTF("xhci: input context at "TARGET_FMT_plx"\n", ictx);
1903
    DPRINTF("xhci: output context at "TARGET_FMT_plx"\n", octx);
1904

    
1905
    cpu_physical_memory_read(ictx, (uint8_t *) ictl_ctx, sizeof(ictl_ctx));
1906

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

    
1913
    if (ictl_ctx[1] & 0x1) {
1914
        cpu_physical_memory_read(ictx+32,
1915
                                 (uint8_t *) islot_ctx, sizeof(islot_ctx));
1916

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

    
1920
        cpu_physical_memory_read(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1921

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

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

    
1930
        cpu_physical_memory_write(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1931
    }
1932

    
1933
    if (ictl_ctx[1] & 0x2) {
1934
        cpu_physical_memory_read(ictx+64,
1935
                                 (uint8_t *) iep0_ctx, sizeof(iep0_ctx));
1936

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

    
1941
        cpu_physical_memory_read(octx+32, (uint8_t *) ep0_ctx, sizeof(ep0_ctx));
1942

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

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

    
1949
        cpu_physical_memory_write(octx+32,
1950
                                  (uint8_t *) ep0_ctx, sizeof(ep0_ctx));
1951
    }
1952

    
1953
    return CC_SUCCESS;
1954
}
1955

    
1956
static TRBCCode xhci_reset_slot(XHCIState *xhci, unsigned int slotid)
1957
{
1958
    uint32_t slot_ctx[4];
1959
    target_phys_addr_t octx;
1960
    int i;
1961

    
1962
    assert(slotid >= 1 && slotid <= MAXSLOTS);
1963
    DPRINTF("xhci_reset_slot(%d)\n", slotid);
1964

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

    
1967
    DPRINTF("xhci: output context at "TARGET_FMT_plx"\n", octx);
1968

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

    
1975
    cpu_physical_memory_read(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1976
    slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT);
1977
    slot_ctx[3] |= SLOT_DEFAULT << SLOT_STATE_SHIFT;
1978
    DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n",
1979
            slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]);
1980
    cpu_physical_memory_write(octx, (uint8_t *) slot_ctx, sizeof(slot_ctx));
1981

    
1982
    return CC_SUCCESS;
1983
}
1984

    
1985
static unsigned int xhci_get_slot(XHCIState *xhci, XHCIEvent *event, XHCITRB *trb)
1986
{
1987
    unsigned int slotid;
1988
    slotid = (trb->control >> TRB_CR_SLOTID_SHIFT) & TRB_CR_SLOTID_MASK;
1989
    if (slotid < 1 || slotid > MAXSLOTS) {
1990
        fprintf(stderr, "xhci: bad slot id %d\n", slotid);
1991
        event->ccode = CC_TRB_ERROR;
1992
        return 0;
1993
    } else if (!xhci->slots[slotid-1].enabled) {
1994
        fprintf(stderr, "xhci: slot id %d not enabled\n", slotid);
1995
        event->ccode = CC_SLOT_NOT_ENABLED_ERROR;
1996
        return 0;
1997
    }
1998
    return slotid;
1999
}
2000

    
2001
static TRBCCode xhci_get_port_bandwidth(XHCIState *xhci, uint64_t pctx)
2002
{
2003
    target_phys_addr_t ctx;
2004
    uint8_t bw_ctx[MAXPORTS+1];
2005

    
2006
    DPRINTF("xhci_get_port_bandwidth()\n");
2007

    
2008
    ctx = xhci_mask64(pctx);
2009

    
2010
    DPRINTF("xhci: bandwidth context at "TARGET_FMT_plx"\n", ctx);
2011

    
2012
    /* TODO: actually implement real values here */
2013
    bw_ctx[0] = 0;
2014
    memset(&bw_ctx[1], 80, MAXPORTS); /* 80% */
2015
    cpu_physical_memory_write(ctx, bw_ctx, sizeof(bw_ctx));
2016

    
2017
    return CC_SUCCESS;
2018
}
2019

    
2020
static uint32_t rotl(uint32_t v, unsigned count)
2021
{
2022
    count &= 31;
2023
    return (v << count) | (v >> (32 - count));
2024
}
2025

    
2026

    
2027
static uint32_t xhci_nec_challenge(uint32_t hi, uint32_t lo)
2028
{
2029
    uint32_t val;
2030
    val = rotl(lo - 0x49434878, 32 - ((hi>>8) & 0x1F));
2031
    val += rotl(lo + 0x49434878, hi & 0x1F);
2032
    val -= rotl(hi ^ 0x49434878, (lo >> 16) & 0x1F);
2033
    return ~val;
2034
}
2035

    
2036
static void xhci_via_challenge(uint64_t addr)
2037
{
2038
    uint32_t buf[8];
2039
    uint32_t obuf[8];
2040
    target_phys_addr_t paddr = xhci_mask64(addr);
2041

    
2042
    cpu_physical_memory_read(paddr, (uint8_t *) &buf, 32);
2043

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

    
2046
    if ((buf[0] & 0xff) == 2) {
2047
        obuf[0] = 0x49932000 + 0x54dc200 * buf[2] + 0x7429b578 * buf[3];
2048
        obuf[0] |=  (buf[2] * buf[3]) & 0xff;
2049
        obuf[1] = 0x0132bb37 + 0xe89 * buf[2] + 0xf09 * buf[3];
2050
        obuf[2] = 0x0066c2e9 + 0x2091 * buf[2] + 0x19bd * buf[3];
2051
        obuf[3] = 0xd5281342 + 0x2cc9691 * buf[2] + 0x2367662 * buf[3];
2052
        obuf[4] = 0x0123c75c + 0x1595 * buf[2] + 0x19ec * buf[3];
2053
        obuf[5] = 0x00f695de + 0x26fd * buf[2] + 0x3e9 * buf[3];
2054
        obuf[6] = obuf[2] ^ obuf[3] ^ 0x29472956;
2055
        obuf[7] = obuf[2] ^ obuf[3] ^ 0x65866593;
2056
    }
2057

    
2058
    cpu_physical_memory_write(paddr, (uint8_t *) &obuf, 32);
2059
}
2060

    
2061
static void xhci_process_commands(XHCIState *xhci)
2062
{
2063
    XHCITRB trb;
2064
    TRBType type;
2065
    XHCIEvent event = {ER_COMMAND_COMPLETE, CC_SUCCESS};
2066
    target_phys_addr_t addr;
2067
    unsigned int i, slotid = 0;
2068

    
2069
    DPRINTF("xhci_process_commands()\n");
2070
    if (!xhci_running(xhci)) {
2071
        DPRINTF("xhci_process_commands() called while xHC stopped or paused\n");
2072
        return;
2073
    }
2074

    
2075
    xhci->crcr_low |= CRCR_CRR;
2076

    
2077
    while ((type = xhci_ring_fetch(xhci, &xhci->cmd_ring, &trb, &addr))) {
2078
        event.ptr = addr;
2079
        switch (type) {
2080
        case CR_ENABLE_SLOT:
2081
            for (i = 0; i < MAXSLOTS; i++) {
2082
                if (!xhci->slots[i].enabled) {
2083
                    break;
2084
                }
2085
            }
2086
            if (i >= MAXSLOTS) {
2087
                fprintf(stderr, "xhci: no device slots available\n");
2088
                event.ccode = CC_NO_SLOTS_ERROR;
2089
            } else {
2090
                slotid = i+1;
2091
                event.ccode = xhci_enable_slot(xhci, slotid);
2092
            }
2093
            break;
2094
        case CR_DISABLE_SLOT:
2095
            slotid = xhci_get_slot(xhci, &event, &trb);
2096
            if (slotid) {
2097
                event.ccode = xhci_disable_slot(xhci, slotid);
2098
            }
2099
            break;
2100
        case CR_ADDRESS_DEVICE:
2101
            slotid = xhci_get_slot(xhci, &event, &trb);
2102
            if (slotid) {
2103
                event.ccode = xhci_address_slot(xhci, slotid, trb.parameter,
2104
                                                trb.control & TRB_CR_BSR);
2105
            }
2106
            break;
2107
        case CR_CONFIGURE_ENDPOINT:
2108
            slotid = xhci_get_slot(xhci, &event, &trb);
2109
            if (slotid) {
2110
                event.ccode = xhci_configure_slot(xhci, slotid, trb.parameter,
2111
                                                  trb.control & TRB_CR_DC);
2112
            }
2113
            break;
2114
        case CR_EVALUATE_CONTEXT:
2115
            slotid = xhci_get_slot(xhci, &event, &trb);
2116
            if (slotid) {
2117
                event.ccode = xhci_evaluate_slot(xhci, slotid, trb.parameter);
2118
            }
2119
            break;
2120
        case CR_STOP_ENDPOINT:
2121
            slotid = xhci_get_slot(xhci, &event, &trb);
2122
            if (slotid) {
2123
                unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2124
                    & TRB_CR_EPID_MASK;
2125
                event.ccode = xhci_stop_ep(xhci, slotid, epid);
2126
            }
2127
            break;
2128
        case CR_RESET_ENDPOINT:
2129
            slotid = xhci_get_slot(xhci, &event, &trb);
2130
            if (slotid) {
2131
                unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2132
                    & TRB_CR_EPID_MASK;
2133
                event.ccode = xhci_reset_ep(xhci, slotid, epid);
2134
            }
2135
            break;
2136
        case CR_SET_TR_DEQUEUE:
2137
            slotid = xhci_get_slot(xhci, &event, &trb);
2138
            if (slotid) {
2139
                unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT)
2140
                    & TRB_CR_EPID_MASK;
2141
                event.ccode = xhci_set_ep_dequeue(xhci, slotid, epid,
2142
                                                  trb.parameter);
2143
            }
2144
            break;
2145
        case CR_RESET_DEVICE:
2146
            slotid = xhci_get_slot(xhci, &event, &trb);
2147
            if (slotid) {
2148
                event.ccode = xhci_reset_slot(xhci, slotid);
2149
            }
2150
            break;
2151
        case CR_GET_PORT_BANDWIDTH:
2152
            event.ccode = xhci_get_port_bandwidth(xhci, trb.parameter);
2153
            break;
2154
        case CR_VENDOR_VIA_CHALLENGE_RESPONSE:
2155
            xhci_via_challenge(trb.parameter);
2156
            break;
2157
        case CR_VENDOR_NEC_FIRMWARE_REVISION:
2158
            event.type = 48; /* NEC reply */
2159
            event.length = 0x3025;
2160
            break;
2161
        case CR_VENDOR_NEC_CHALLENGE_RESPONSE:
2162
        {
2163
            uint32_t chi = trb.parameter >> 32;
2164
            uint32_t clo = trb.parameter;
2165
            uint32_t val = xhci_nec_challenge(chi, clo);
2166
            event.length = val & 0xFFFF;
2167
            event.epid = val >> 16;
2168
            slotid = val >> 24;
2169
            event.type = 48; /* NEC reply */
2170
        }
2171
        break;
2172
        default:
2173
            fprintf(stderr, "xhci: unimplemented command %d\n", type);
2174
            event.ccode = CC_TRB_ERROR;
2175
            break;
2176
        }
2177
        event.slotid = slotid;
2178
        xhci_event(xhci, &event);
2179
    }
2180
}
2181

    
2182
static void xhci_update_port(XHCIState *xhci, XHCIPort *port, int is_detach)
2183
{
2184
    int nr = port->port.index + 1;
2185

    
2186
    port->portsc = PORTSC_PP;
2187
    if (port->port.dev && !is_detach) {
2188
        port->portsc |= PORTSC_CCS;
2189
        switch (port->port.dev->speed) {
2190
        case USB_SPEED_LOW:
2191
            port->portsc |= PORTSC_SPEED_LOW;
2192
            break;
2193
        case USB_SPEED_FULL:
2194
            port->portsc |= PORTSC_SPEED_FULL;
2195
            break;
2196
        case USB_SPEED_HIGH:
2197
            port->portsc |= PORTSC_SPEED_HIGH;
2198
            break;
2199
        }
2200
    }
2201

    
2202
    if (xhci_running(xhci)) {
2203
        port->portsc |= PORTSC_CSC;
2204
        XHCIEvent ev = { ER_PORT_STATUS_CHANGE, CC_SUCCESS, nr << 24};
2205
        xhci_event(xhci, &ev);
2206
        DPRINTF("xhci: port change event for port %d\n", nr);
2207
    }
2208
}
2209

    
2210
static void xhci_reset(void *opaque)
2211
{
2212
    XHCIState *xhci = opaque;
2213
    int i;
2214

    
2215
    DPRINTF("xhci: full reset\n");
2216
    if (!(xhci->usbsts & USBSTS_HCH)) {
2217
        fprintf(stderr, "xhci: reset while running!\n");
2218
    }
2219

    
2220
    xhci->usbcmd = 0;
2221
    xhci->usbsts = USBSTS_HCH;
2222
    xhci->dnctrl = 0;
2223
    xhci->crcr_low = 0;
2224
    xhci->crcr_high = 0;
2225
    xhci->dcbaap_low = 0;
2226
    xhci->dcbaap_high = 0;
2227
    xhci->config = 0;
2228
    xhci->devaddr = 2;
2229

    
2230
    for (i = 0; i < MAXSLOTS; i++) {
2231
        xhci_disable_slot(xhci, i+1);
2232
    }
2233

    
2234
    for (i = 0; i < MAXPORTS; i++) {
2235
        xhci_update_port(xhci, xhci->ports + i, 0);
2236
    }
2237

    
2238
    xhci->mfindex = 0;
2239
    xhci->iman = 0;
2240
    xhci->imod = 0;
2241
    xhci->erstsz = 0;
2242
    xhci->erstba_low = 0;
2243
    xhci->erstba_high = 0;
2244
    xhci->erdp_low = 0;
2245
    xhci->erdp_high = 0;
2246

    
2247
    xhci->er_ep_idx = 0;
2248
    xhci->er_pcs = 1;
2249
    xhci->er_full = 0;
2250
    xhci->ev_buffer_put = 0;
2251
    xhci->ev_buffer_get = 0;
2252
}
2253

    
2254
static uint32_t xhci_cap_read(XHCIState *xhci, uint32_t reg)
2255
{
2256
    DPRINTF("xhci_cap_read(0x%x)\n", reg);
2257

    
2258
    switch (reg) {
2259
    case 0x00: /* HCIVERSION, CAPLENGTH */
2260
        return 0x01000000 | LEN_CAP;
2261
    case 0x04: /* HCSPARAMS 1 */
2262
        return (MAXPORTS<<24) | (MAXINTRS<<8) | MAXSLOTS;
2263
    case 0x08: /* HCSPARAMS 2 */
2264
        return 0x0000000f;
2265
    case 0x0c: /* HCSPARAMS 3 */
2266
        return 0x00000000;
2267
    case 0x10: /* HCCPARAMS */
2268
#if TARGET_PHYS_ADDR_BITS > 32
2269
        return 0x00081001;
2270
#else
2271
        return 0x00081000;
2272
#endif
2273
    case 0x14: /* DBOFF */
2274
        return OFF_DOORBELL;
2275
    case 0x18: /* RTSOFF */
2276
        return OFF_RUNTIME;
2277

    
2278
    /* extended capabilities */
2279
    case 0x20: /* Supported Protocol:00 */
2280
#if USB3_PORTS > 0
2281
        return 0x02000402; /* USB 2.0 */
2282
#else
2283
        return 0x02000002; /* USB 2.0 */
2284
#endif
2285
    case 0x24: /* Supported Protocol:04 */
2286
        return 0x20425455; /* "USB " */
2287
    case 0x28: /* Supported Protocol:08 */
2288
        return 0x00000001 | (USB2_PORTS<<8);
2289
    case 0x2c: /* Supported Protocol:0c */
2290
        return 0x00000000; /* reserved */
2291
#if USB3_PORTS > 0
2292
    case 0x30: /* Supported Protocol:00 */
2293
        return 0x03000002; /* USB 3.0 */
2294
    case 0x34: /* Supported Protocol:04 */
2295
        return 0x20425455; /* "USB " */
2296
    case 0x38: /* Supported Protocol:08 */
2297
        return 0x00000000 | (USB2_PORTS+1) | (USB3_PORTS<<8);
2298
    case 0x3c: /* Supported Protocol:0c */
2299
        return 0x00000000; /* reserved */
2300
#endif
2301
    default:
2302
        fprintf(stderr, "xhci_cap_read: reg %d unimplemented\n", reg);
2303
    }
2304
    return 0;
2305
}
2306

    
2307
static uint32_t xhci_port_read(XHCIState *xhci, uint32_t reg)
2308
{
2309
    uint32_t port = reg >> 4;
2310
    if (port >= MAXPORTS) {
2311
        fprintf(stderr, "xhci_port_read: port %d out of bounds\n", port);
2312
        return 0;
2313
    }
2314

    
2315
    switch (reg & 0xf) {
2316
    case 0x00: /* PORTSC */
2317
        return xhci->ports[port].portsc;
2318
    case 0x04: /* PORTPMSC */
2319
    case 0x08: /* PORTLI */
2320
        return 0;
2321
    case 0x0c: /* reserved */
2322
    default:
2323
        fprintf(stderr, "xhci_port_read (port %d): reg 0x%x unimplemented\n",
2324
                port, reg);
2325
        return 0;
2326
    }
2327
}
2328

    
2329
static void xhci_port_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2330
{
2331
    uint32_t port = reg >> 4;
2332
    uint32_t portsc;
2333

    
2334
    if (port >= MAXPORTS) {
2335
        fprintf(stderr, "xhci_port_read: port %d out of bounds\n", port);
2336
        return;
2337
    }
2338

    
2339
    switch (reg & 0xf) {
2340
    case 0x00: /* PORTSC */
2341
        portsc = xhci->ports[port].portsc;
2342
        /* write-1-to-clear bits*/
2343
        portsc &= ~(val & (PORTSC_CSC|PORTSC_PEC|PORTSC_WRC|PORTSC_OCC|
2344
                           PORTSC_PRC|PORTSC_PLC|PORTSC_CEC));
2345
        if (val & PORTSC_LWS) {
2346
            /* overwrite PLS only when LWS=1 */
2347
            portsc &= ~(PORTSC_PLS_MASK << PORTSC_PLS_SHIFT);
2348
            portsc |= val & (PORTSC_PLS_MASK << PORTSC_PLS_SHIFT);
2349
        }
2350
        /* read/write bits */
2351
        portsc &= ~(PORTSC_PP|PORTSC_WCE|PORTSC_WDE|PORTSC_WOE);
2352
        portsc |= (val & (PORTSC_PP|PORTSC_WCE|PORTSC_WDE|PORTSC_WOE));
2353
        /* write-1-to-start bits */
2354
        if (val & PORTSC_PR) {
2355
            DPRINTF("xhci: port %d reset\n", port);
2356
            usb_device_reset(xhci->ports[port].port.dev);
2357
            portsc |= PORTSC_PRC | PORTSC_PED;
2358
        }
2359
        xhci->ports[port].portsc = portsc;
2360
        break;
2361
    case 0x04: /* PORTPMSC */
2362
    case 0x08: /* PORTLI */
2363
    default:
2364
        fprintf(stderr, "xhci_port_write (port %d): reg 0x%x unimplemented\n",
2365
                port, reg);
2366
    }
2367
}
2368

    
2369
static uint32_t xhci_oper_read(XHCIState *xhci, uint32_t reg)
2370
{
2371
    DPRINTF("xhci_oper_read(0x%x)\n", reg);
2372

    
2373
    if (reg >= 0x400) {
2374
        return xhci_port_read(xhci, reg - 0x400);
2375
    }
2376

    
2377
    switch (reg) {
2378
    case 0x00: /* USBCMD */
2379
        return xhci->usbcmd;
2380
    case 0x04: /* USBSTS */
2381
        return xhci->usbsts;
2382
    case 0x08: /* PAGESIZE */
2383
        return 1; /* 4KiB */
2384
    case 0x14: /* DNCTRL */
2385
        return xhci->dnctrl;
2386
    case 0x18: /* CRCR low */
2387
        return xhci->crcr_low & ~0xe;
2388
    case 0x1c: /* CRCR high */
2389
        return xhci->crcr_high;
2390
    case 0x30: /* DCBAAP low */
2391
        return xhci->dcbaap_low;
2392
    case 0x34: /* DCBAAP high */
2393
        return xhci->dcbaap_high;
2394
    case 0x38: /* CONFIG */
2395
        return xhci->config;
2396
    default:
2397
        fprintf(stderr, "xhci_oper_read: reg 0x%x unimplemented\n", reg);
2398
    }
2399
    return 0;
2400
}
2401

    
2402
static void xhci_oper_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2403
{
2404
    DPRINTF("xhci_oper_write(0x%x, 0x%08x)\n", reg, val);
2405

    
2406
    if (reg >= 0x400) {
2407
        xhci_port_write(xhci, reg - 0x400, val);
2408
        return;
2409
    }
2410

    
2411
    switch (reg) {
2412
    case 0x00: /* USBCMD */
2413
        if ((val & USBCMD_RS) && !(xhci->usbcmd & USBCMD_RS)) {
2414
            xhci_run(xhci);
2415
        } else if (!(val & USBCMD_RS) && (xhci->usbcmd & USBCMD_RS)) {
2416
            xhci_stop(xhci);
2417
        }
2418
        xhci->usbcmd = val & 0xc0f;
2419
        if (val & USBCMD_HCRST) {
2420
            xhci_reset(xhci);
2421
        }
2422
        xhci_irq_update(xhci);
2423
        break;
2424

    
2425
    case 0x04: /* USBSTS */
2426
        /* these bits are write-1-to-clear */
2427
        xhci->usbsts &= ~(val & (USBSTS_HSE|USBSTS_EINT|USBSTS_PCD|USBSTS_SRE));
2428
        xhci_irq_update(xhci);
2429
        break;
2430

    
2431
    case 0x14: /* DNCTRL */
2432
        xhci->dnctrl = val & 0xffff;
2433
        break;
2434
    case 0x18: /* CRCR low */
2435
        xhci->crcr_low = (val & 0xffffffcf) | (xhci->crcr_low & CRCR_CRR);
2436
        break;
2437
    case 0x1c: /* CRCR high */
2438
        xhci->crcr_high = val;
2439
        if (xhci->crcr_low & (CRCR_CA|CRCR_CS) && (xhci->crcr_low & CRCR_CRR)) {
2440
            XHCIEvent event = {ER_COMMAND_COMPLETE, CC_COMMAND_RING_STOPPED};
2441
            xhci->crcr_low &= ~CRCR_CRR;
2442
            xhci_event(xhci, &event);
2443
            DPRINTF("xhci: command ring stopped (CRCR=%08x)\n", xhci->crcr_low);
2444
        } else {
2445
            target_phys_addr_t base = xhci_addr64(xhci->crcr_low & ~0x3f, val);
2446
            xhci_ring_init(xhci, &xhci->cmd_ring, base);
2447
        }
2448
        xhci->crcr_low &= ~(CRCR_CA | CRCR_CS);
2449
        break;
2450
    case 0x30: /* DCBAAP low */
2451
        xhci->dcbaap_low = val & 0xffffffc0;
2452
        break;
2453
    case 0x34: /* DCBAAP high */
2454
        xhci->dcbaap_high = val;
2455
        break;
2456
    case 0x38: /* CONFIG */
2457
        xhci->config = val & 0xff;
2458
        break;
2459
    default:
2460
        fprintf(stderr, "xhci_oper_write: reg 0x%x unimplemented\n", reg);
2461
    }
2462
}
2463

    
2464
static uint32_t xhci_runtime_read(XHCIState *xhci, uint32_t reg)
2465
{
2466
    DPRINTF("xhci_runtime_read(0x%x)\n", reg);
2467

    
2468
    switch (reg) {
2469
    case 0x00: /* MFINDEX */
2470
        fprintf(stderr, "xhci_runtime_read: MFINDEX not yet implemented\n");
2471
        return xhci->mfindex;
2472
    case 0x20: /* IMAN */
2473
        return xhci->iman;
2474
    case 0x24: /* IMOD */
2475
        return xhci->imod;
2476
    case 0x28: /* ERSTSZ */
2477
        return xhci->erstsz;
2478
    case 0x30: /* ERSTBA low */
2479
        return xhci->erstba_low;
2480
    case 0x34: /* ERSTBA high */
2481
        return xhci->erstba_high;
2482
    case 0x38: /* ERDP low */
2483
        return xhci->erdp_low;
2484
    case 0x3c: /* ERDP high */
2485
        return xhci->erdp_high;
2486
    default:
2487
        fprintf(stderr, "xhci_runtime_read: reg 0x%x unimplemented\n", reg);
2488
    }
2489
    return 0;
2490
}
2491

    
2492
static void xhci_runtime_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2493
{
2494
    DPRINTF("xhci_runtime_write(0x%x, 0x%08x)\n", reg, val);
2495

    
2496
    switch (reg) {
2497
    case 0x20: /* IMAN */
2498
        if (val & IMAN_IP) {
2499
            xhci->iman &= ~IMAN_IP;
2500
        }
2501
        xhci->iman &= ~IMAN_IE;
2502
        xhci->iman |= val & IMAN_IE;
2503
        xhci_irq_update(xhci);
2504
        break;
2505
    case 0x24: /* IMOD */
2506
        xhci->imod = val;
2507
        break;
2508
    case 0x28: /* ERSTSZ */
2509
        xhci->erstsz = val & 0xffff;
2510
        break;
2511
    case 0x30: /* ERSTBA low */
2512
        /* XXX NEC driver bug: it doesn't align this to 64 bytes
2513
        xhci->erstba_low = val & 0xffffffc0; */
2514
        xhci->erstba_low = val & 0xfffffff0;
2515
        break;
2516
    case 0x34: /* ERSTBA high */
2517
        xhci->erstba_high = val;
2518
        xhci_er_reset(xhci);
2519
        break;
2520
    case 0x38: /* ERDP low */
2521
        if (val & ERDP_EHB) {
2522
            xhci->erdp_low &= ~ERDP_EHB;
2523
        }
2524
        xhci->erdp_low = (val & ~ERDP_EHB) | (xhci->erdp_low & ERDP_EHB);
2525
        break;
2526
    case 0x3c: /* ERDP high */
2527
        xhci->erdp_high = val;
2528
        xhci_events_update(xhci);
2529
        break;
2530
    default:
2531
        fprintf(stderr, "xhci_oper_write: reg 0x%x unimplemented\n", reg);
2532
    }
2533
}
2534

    
2535
static uint32_t xhci_doorbell_read(XHCIState *xhci, uint32_t reg)
2536
{
2537
    DPRINTF("xhci_doorbell_read(0x%x)\n", reg);
2538
    /* doorbells always read as 0 */
2539
    return 0;
2540
}
2541

    
2542
static void xhci_doorbell_write(XHCIState *xhci, uint32_t reg, uint32_t val)
2543
{
2544
    DPRINTF("xhci_doorbell_write(0x%x, 0x%08x)\n", reg, val);
2545

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

    
2551
    reg >>= 2;
2552

    
2553
    if (reg == 0) {
2554
        if (val == 0) {
2555
            xhci_process_commands(xhci);
2556
        } else {
2557
            fprintf(stderr, "xhci: bad doorbell 0 write: 0x%x\n", val);
2558
        }
2559
    } else {
2560
        if (reg > MAXSLOTS) {
2561
            fprintf(stderr, "xhci: bad doorbell %d\n", reg);
2562
        } else if (val > 31) {
2563
            fprintf(stderr, "xhci: bad doorbell %d write: 0x%x\n", reg, val);
2564
        } else {
2565
            xhci_kick_ep(xhci, reg, val);
2566
        }
2567
    }
2568
}
2569

    
2570
static uint64_t xhci_mem_read(void *ptr, target_phys_addr_t addr,
2571
                              unsigned size)
2572
{
2573
    XHCIState *xhci = ptr;
2574

    
2575
    /* Only aligned reads are allowed on xHCI */
2576
    if (addr & 3) {
2577
        fprintf(stderr, "xhci_mem_read: Mis-aligned read\n");
2578
        return 0;
2579
    }
2580

    
2581
    if (addr < LEN_CAP) {
2582
        return xhci_cap_read(xhci, addr);
2583
    } else if (addr >= OFF_OPER && addr < (OFF_OPER + LEN_OPER)) {
2584
        return xhci_oper_read(xhci, addr - OFF_OPER);
2585
    } else if (addr >= OFF_RUNTIME && addr < (OFF_RUNTIME + LEN_RUNTIME)) {
2586
        return xhci_runtime_read(xhci, addr - OFF_RUNTIME);
2587
    } else if (addr >= OFF_DOORBELL && addr < (OFF_DOORBELL + LEN_DOORBELL)) {
2588
        return xhci_doorbell_read(xhci, addr - OFF_DOORBELL);
2589
    } else {
2590
        fprintf(stderr, "xhci_mem_read: Bad offset %x\n", (int)addr);
2591
        return 0;
2592
    }
2593
}
2594

    
2595
static void xhci_mem_write(void *ptr, target_phys_addr_t addr,
2596
                           uint64_t val, unsigned size)
2597
{
2598
    XHCIState *xhci = ptr;
2599

    
2600
    /* Only aligned writes are allowed on xHCI */
2601
    if (addr & 3) {
2602
        fprintf(stderr, "xhci_mem_write: Mis-aligned write\n");
2603
        return;
2604
    }
2605

    
2606
    if (addr >= OFF_OPER && addr < (OFF_OPER + LEN_OPER)) {
2607
        xhci_oper_write(xhci, addr - OFF_OPER, val);
2608
    } else if (addr >= OFF_RUNTIME && addr < (OFF_RUNTIME + LEN_RUNTIME)) {
2609
        xhci_runtime_write(xhci, addr - OFF_RUNTIME, val);
2610
    } else if (addr >= OFF_DOORBELL && addr < (OFF_DOORBELL + LEN_DOORBELL)) {
2611
        xhci_doorbell_write(xhci, addr - OFF_DOORBELL, val);
2612
    } else {
2613
        fprintf(stderr, "xhci_mem_write: Bad offset %x\n", (int)addr);
2614
    }
2615
}
2616

    
2617
static const MemoryRegionOps xhci_mem_ops = {
2618
    .read = xhci_mem_read,
2619
    .write = xhci_mem_write,
2620
    .valid.min_access_size = 4,
2621
    .valid.max_access_size = 4,
2622
    .endianness = DEVICE_LITTLE_ENDIAN,
2623
};
2624

    
2625
static void xhci_attach(USBPort *usbport)
2626
{
2627
    XHCIState *xhci = usbport->opaque;
2628
    XHCIPort *port = &xhci->ports[usbport->index];
2629

    
2630
    xhci_update_port(xhci, port, 0);
2631
}
2632

    
2633
static void xhci_detach(USBPort *usbport)
2634
{
2635
    XHCIState *xhci = usbport->opaque;
2636
    XHCIPort *port = &xhci->ports[usbport->index];
2637

    
2638
    xhci_update_port(xhci, port, 1);
2639
}
2640

    
2641
static void xhci_complete(USBPort *port, USBPacket *packet)
2642
{
2643
    XHCITransfer *xfer = container_of(packet, XHCITransfer, packet);
2644

    
2645
    xhci_complete_packet(xfer, packet->result);
2646
    xhci_kick_ep(xfer->xhci, xfer->slotid, xfer->epid);
2647
}
2648

    
2649
static void xhci_child_detach(USBPort *port, USBDevice *child)
2650
{
2651
    FIXME();
2652
}
2653

    
2654
static USBPortOps xhci_port_ops = {
2655
    .attach   = xhci_attach,
2656
    .detach   = xhci_detach,
2657
    .complete = xhci_complete,
2658
    .child_detach = xhci_child_detach,
2659
};
2660

    
2661
static USBBusOps xhci_bus_ops = {
2662
};
2663

    
2664
static void usb_xhci_init(XHCIState *xhci, DeviceState *dev)
2665
{
2666
    int i;
2667

    
2668
    xhci->usbsts = USBSTS_HCH;
2669

    
2670
    usb_bus_new(&xhci->bus, &xhci_bus_ops, &xhci->pci_dev.qdev);
2671

    
2672
    for (i = 0; i < MAXPORTS; i++) {
2673
        memset(&xhci->ports[i], 0, sizeof(xhci->ports[i]));
2674
        usb_register_port(&xhci->bus, &xhci->ports[i].port, xhci, i,
2675
                          &xhci_port_ops, USB_SPEED_MASK_HIGH);
2676
    }
2677
    for (i = 0; i < MAXSLOTS; i++) {
2678
        xhci->slots[i].enabled = 0;
2679
    }
2680

    
2681
    qemu_register_reset(xhci_reset, xhci);
2682
}
2683

    
2684
static int usb_xhci_initfn(struct PCIDevice *dev)
2685
{
2686
    int ret;
2687

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

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

    
2695
    usb_xhci_init(xhci, &dev->qdev);
2696

    
2697
    xhci->irq = xhci->pci_dev.irq[0];
2698

    
2699
    memory_region_init_io(&xhci->mem, &xhci_mem_ops, xhci,
2700
                          "xhci", LEN_REGS);
2701
    pci_register_bar(&xhci->pci_dev, 0,
2702
                     PCI_BASE_ADDRESS_SPACE_MEMORY|PCI_BASE_ADDRESS_MEM_TYPE_64,
2703
                     &xhci->mem);
2704

    
2705
    ret = pcie_cap_init(&xhci->pci_dev, 0xa0, PCI_EXP_TYPE_ENDPOINT, 0);
2706
    assert(ret >= 0);
2707

    
2708
    if (xhci->msi) {
2709
        ret = msi_init(&xhci->pci_dev, 0x70, 1, true, false);
2710
        assert(ret >= 0);
2711
    }
2712

    
2713
    return 0;
2714
}
2715

    
2716
static void xhci_write_config(PCIDevice *dev, uint32_t addr, uint32_t val,
2717
                              int len)
2718
{
2719
    XHCIState *xhci = DO_UPCAST(XHCIState, pci_dev, dev);
2720

    
2721
    pci_default_write_config(dev, addr, val, len);
2722
    if (xhci->msi) {
2723
        msi_write_config(dev, addr, val, len);
2724
    }
2725
}
2726

    
2727
static const VMStateDescription vmstate_xhci = {
2728
    .name = "xhci",
2729
    .unmigratable = 1,
2730
};
2731

    
2732
static Property xhci_properties[] = {
2733
    DEFINE_PROP_UINT32("msi", XHCIState, msi, 0),
2734
    DEFINE_PROP_END_OF_LIST(),
2735
};
2736

    
2737
static void xhci_class_init(ObjectClass *klass, void *data)
2738
{
2739
    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
2740
    DeviceClass *dc = DEVICE_CLASS(klass);
2741

    
2742
    dc->vmsd    = &vmstate_xhci;
2743
    dc->props   = xhci_properties;
2744
    k->init         = usb_xhci_initfn;
2745
    k->vendor_id    = PCI_VENDOR_ID_NEC;
2746
    k->device_id    = PCI_DEVICE_ID_NEC_UPD720200;
2747
    k->class_id     = PCI_CLASS_SERIAL_USB;
2748
    k->revision     = 0x03;
2749
    k->is_express   = 1;
2750
    k->config_write = xhci_write_config;
2751
}
2752

    
2753
static TypeInfo xhci_info = {
2754
    .name          = "nec-usb-xhci",
2755
    .parent        = TYPE_PCI_DEVICE,
2756
    .instance_size = sizeof(XHCIState),
2757
    .class_init    = xhci_class_init,
2758
};
2759

    
2760
static void xhci_register(void)
2761
{
2762
    type_register_static(&xhci_info);
2763
}
2764
device_init(xhci_register);