Statistics
| Branch: | Revision:

root / hw / usb-ehci.c @ 439a97cc

History | View | Annotate | Download (59.2 kB)

1
/*
2
 * QEMU USB EHCI Emulation
3
 *
4
 * Copyright(c) 2008  Emutex Ltd. (address@hidden)
5
 *
6
 * EHCI project was started by Mark Burkley, with contributions by
7
 * Niels de Vos.  David S. Ahern continued working on it.  Kevin Wolf,
8
 * Jan Kiszka and Vincent Palatin contributed bugfixes.
9
 *
10
 *
11
 * This library is free software; you can redistribute it and/or
12
 * modify it under the terms of the GNU Lesser General Public
13
 * License as published by the Free Software Foundation; either
14
 * version 2 of the License, or(at your option) any later version.
15
 *
16
 * This library is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19
 * Lesser General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
23
 *
24
 * TODO:
25
 *  o Downstream port handoff
26
 */
27

    
28
#include "hw.h"
29
#include "qemu-timer.h"
30
#include "usb.h"
31
#include "pci.h"
32
#include "monitor.h"
33
#include "trace.h"
34

    
35
#define EHCI_DEBUG   0
36
#define STATE_DEBUG  0       /* state transitions  */
37

    
38
#if EHCI_DEBUG || STATE_DEBUG
39
#define DPRINTF printf
40
#else
41
#define DPRINTF(...)
42
#endif
43

    
44
#if STATE_DEBUG
45
#define DPRINTF_ST DPRINTF
46
#else
47
#define DPRINTF_ST(...)
48
#endif
49

    
50
/* internal processing - reset HC to try and recover */
51
#define USB_RET_PROCERR   (-99)
52

    
53
#define MMIO_SIZE        0x1000
54

    
55
/* Capability Registers Base Address - section 2.2 */
56
#define CAPREGBASE       0x0000
57
#define CAPLENGTH        CAPREGBASE + 0x0000  // 1-byte, 0x0001 reserved
58
#define HCIVERSION       CAPREGBASE + 0x0002  // 2-bytes, i/f version #
59
#define HCSPARAMS        CAPREGBASE + 0x0004  // 4-bytes, structural params
60
#define HCCPARAMS        CAPREGBASE + 0x0008  // 4-bytes, capability params
61
#define EECP             HCCPARAMS + 1
62
#define HCSPPORTROUTE1   CAPREGBASE + 0x000c
63
#define HCSPPORTROUTE2   CAPREGBASE + 0x0010
64

    
65
#define OPREGBASE        0x0020        // Operational Registers Base Address
66

    
67
#define USBCMD           OPREGBASE + 0x0000
68
#define USBCMD_RUNSTOP   (1 << 0)      // run / Stop
69
#define USBCMD_HCRESET   (1 << 1)      // HC Reset
70
#define USBCMD_FLS       (3 << 2)      // Frame List Size
71
#define USBCMD_FLS_SH    2             // Frame List Size Shift
72
#define USBCMD_PSE       (1 << 4)      // Periodic Schedule Enable
73
#define USBCMD_ASE       (1 << 5)      // Asynch Schedule Enable
74
#define USBCMD_IAAD      (1 << 6)      // Int Asynch Advance Doorbell
75
#define USBCMD_LHCR      (1 << 7)      // Light Host Controller Reset
76
#define USBCMD_ASPMC     (3 << 8)      // Async Sched Park Mode Count
77
#define USBCMD_ASPME     (1 << 11)     // Async Sched Park Mode Enable
78
#define USBCMD_ITC       (0x7f << 16)  // Int Threshold Control
79
#define USBCMD_ITC_SH    16            // Int Threshold Control Shift
80

    
81
#define USBSTS           OPREGBASE + 0x0004
82
#define USBSTS_RO_MASK   0x0000003f
83
#define USBSTS_INT       (1 << 0)      // USB Interrupt
84
#define USBSTS_ERRINT    (1 << 1)      // Error Interrupt
85
#define USBSTS_PCD       (1 << 2)      // Port Change Detect
86
#define USBSTS_FLR       (1 << 3)      // Frame List Rollover
87
#define USBSTS_HSE       (1 << 4)      // Host System Error
88
#define USBSTS_IAA       (1 << 5)      // Interrupt on Async Advance
89
#define USBSTS_HALT      (1 << 12)     // HC Halted
90
#define USBSTS_REC       (1 << 13)     // Reclamation
91
#define USBSTS_PSS       (1 << 14)     // Periodic Schedule Status
92
#define USBSTS_ASS       (1 << 15)     // Asynchronous Schedule Status
93

    
94
/*
95
 *  Interrupt enable bits correspond to the interrupt active bits in USBSTS
96
 *  so no need to redefine here.
97
 */
98
#define USBINTR              OPREGBASE + 0x0008
99
#define USBINTR_MASK         0x0000003f
100

    
101
#define FRINDEX              OPREGBASE + 0x000c
102
#define CTRLDSSEGMENT        OPREGBASE + 0x0010
103
#define PERIODICLISTBASE     OPREGBASE + 0x0014
104
#define ASYNCLISTADDR        OPREGBASE + 0x0018
105
#define ASYNCLISTADDR_MASK   0xffffffe0
106

    
107
#define CONFIGFLAG           OPREGBASE + 0x0040
108

    
109
#define PORTSC               (OPREGBASE + 0x0044)
110
#define PORTSC_BEGIN         PORTSC
111
#define PORTSC_END           (PORTSC + 4 * NB_PORTS)
112
/*
113
 * Bits that are reserverd or are read-only are masked out of values
114
 * written to us by software
115
 */
116
#define PORTSC_RO_MASK       0x007021c5
117
#define PORTSC_RWC_MASK      0x0000002a
118
#define PORTSC_WKOC_E        (1 << 22)    // Wake on Over Current Enable
119
#define PORTSC_WKDS_E        (1 << 21)    // Wake on Disconnect Enable
120
#define PORTSC_WKCN_E        (1 << 20)    // Wake on Connect Enable
121
#define PORTSC_PTC           (15 << 16)   // Port Test Control
122
#define PORTSC_PTC_SH        16           // Port Test Control shift
123
#define PORTSC_PIC           (3 << 14)    // Port Indicator Control
124
#define PORTSC_PIC_SH        14           // Port Indicator Control Shift
125
#define PORTSC_POWNER        (1 << 13)    // Port Owner
126
#define PORTSC_PPOWER        (1 << 12)    // Port Power
127
#define PORTSC_LINESTAT      (3 << 10)    // Port Line Status
128
#define PORTSC_LINESTAT_SH   10           // Port Line Status Shift
129
#define PORTSC_PRESET        (1 << 8)     // Port Reset
130
#define PORTSC_SUSPEND       (1 << 7)     // Port Suspend
131
#define PORTSC_FPRES         (1 << 6)     // Force Port Resume
132
#define PORTSC_OCC           (1 << 5)     // Over Current Change
133
#define PORTSC_OCA           (1 << 4)     // Over Current Active
134
#define PORTSC_PEDC          (1 << 3)     // Port Enable/Disable Change
135
#define PORTSC_PED           (1 << 2)     // Port Enable/Disable
136
#define PORTSC_CSC           (1 << 1)     // Connect Status Change
137
#define PORTSC_CONNECT       (1 << 0)     // Current Connect Status
138

    
139
#define FRAME_TIMER_FREQ 1000
140
#define FRAME_TIMER_USEC (1000000 / FRAME_TIMER_FREQ)
141

    
142
#define NB_MAXINTRATE    8        // Max rate at which controller issues ints
143
#define NB_PORTS         4        // Number of downstream ports
144
#define BUFF_SIZE        5*4096   // Max bytes to transfer per transaction
145
#define MAX_ITERATIONS   20       // Max number of QH before we break the loop
146
#define MAX_QH           100      // Max allowable queue heads in a chain
147

    
148
/*  Internal periodic / asynchronous schedule state machine states
149
 */
150
typedef enum {
151
    EST_INACTIVE = 1000,
152
    EST_ACTIVE,
153
    EST_EXECUTING,
154
    EST_SLEEPING,
155
    /*  The following states are internal to the state machine function
156
    */
157
    EST_WAITLISTHEAD,
158
    EST_FETCHENTRY,
159
    EST_FETCHQH,
160
    EST_FETCHITD,
161
    EST_ADVANCEQUEUE,
162
    EST_FETCHQTD,
163
    EST_EXECUTE,
164
    EST_WRITEBACK,
165
    EST_HORIZONTALQH
166
} EHCI_STATES;
167

    
168
/* macros for accessing fields within next link pointer entry */
169
#define NLPTR_GET(x)             ((x) & 0xffffffe0)
170
#define NLPTR_TYPE_GET(x)        (((x) >> 1) & 3)
171
#define NLPTR_TBIT(x)            ((x) & 1)  // 1=invalid, 0=valid
172

    
173
/* link pointer types */
174
#define NLPTR_TYPE_ITD           0     // isoc xfer descriptor
175
#define NLPTR_TYPE_QH            1     // queue head
176
#define NLPTR_TYPE_STITD         2     // split xaction, isoc xfer descriptor
177
#define NLPTR_TYPE_FSTN          3     // frame span traversal node
178

    
179

    
180
/*  EHCI spec version 1.0 Section 3.3
181
 */
182
typedef struct EHCIitd {
183
    uint32_t next;
184

    
185
    uint32_t transact[8];
186
#define ITD_XACT_ACTIVE          (1 << 31)
187
#define ITD_XACT_DBERROR         (1 << 30)
188
#define ITD_XACT_BABBLE          (1 << 29)
189
#define ITD_XACT_XACTERR         (1 << 28)
190
#define ITD_XACT_LENGTH_MASK     0x0fff0000
191
#define ITD_XACT_LENGTH_SH       16
192
#define ITD_XACT_IOC             (1 << 15)
193
#define ITD_XACT_PGSEL_MASK      0x00007000
194
#define ITD_XACT_PGSEL_SH        12
195
#define ITD_XACT_OFFSET_MASK     0x00000fff
196

    
197
    uint32_t bufptr[7];
198
#define ITD_BUFPTR_MASK          0xfffff000
199
#define ITD_BUFPTR_SH            12
200
#define ITD_BUFPTR_EP_MASK       0x00000f00
201
#define ITD_BUFPTR_EP_SH         8
202
#define ITD_BUFPTR_DEVADDR_MASK  0x0000007f
203
#define ITD_BUFPTR_DEVADDR_SH    0
204
#define ITD_BUFPTR_DIRECTION     (1 << 11)
205
#define ITD_BUFPTR_MAXPKT_MASK   0x000007ff
206
#define ITD_BUFPTR_MAXPKT_SH     0
207
#define ITD_BUFPTR_MULT_MASK     0x00000003
208
} EHCIitd;
209

    
210
/*  EHCI spec version 1.0 Section 3.4
211
 */
212
typedef struct EHCIsitd {
213
    uint32_t next;                  // Standard next link pointer
214
    uint32_t epchar;
215
#define SITD_EPCHAR_IO              (1 << 31)
216
#define SITD_EPCHAR_PORTNUM_MASK    0x7f000000
217
#define SITD_EPCHAR_PORTNUM_SH      24
218
#define SITD_EPCHAR_HUBADD_MASK     0x007f0000
219
#define SITD_EPCHAR_HUBADDR_SH      16
220
#define SITD_EPCHAR_EPNUM_MASK      0x00000f00
221
#define SITD_EPCHAR_EPNUM_SH        8
222
#define SITD_EPCHAR_DEVADDR_MASK    0x0000007f
223

    
224
    uint32_t uframe;
225
#define SITD_UFRAME_CMASK_MASK      0x0000ff00
226
#define SITD_UFRAME_CMASK_SH        8
227
#define SITD_UFRAME_SMASK_MASK      0x000000ff
228

    
229
    uint32_t results;
230
#define SITD_RESULTS_IOC              (1 << 31)
231
#define SITD_RESULTS_PGSEL            (1 << 30)
232
#define SITD_RESULTS_TBYTES_MASK      0x03ff0000
233
#define SITD_RESULTS_TYBYTES_SH       16
234
#define SITD_RESULTS_CPROGMASK_MASK   0x0000ff00
235
#define SITD_RESULTS_CPROGMASK_SH     8
236
#define SITD_RESULTS_ACTIVE           (1 << 7)
237
#define SITD_RESULTS_ERR              (1 << 6)
238
#define SITD_RESULTS_DBERR            (1 << 5)
239
#define SITD_RESULTS_BABBLE           (1 << 4)
240
#define SITD_RESULTS_XACTERR          (1 << 3)
241
#define SITD_RESULTS_MISSEDUF         (1 << 2)
242
#define SITD_RESULTS_SPLITXSTATE      (1 << 1)
243

    
244
    uint32_t bufptr[2];
245
#define SITD_BUFPTR_MASK              0xfffff000
246
#define SITD_BUFPTR_CURROFF_MASK      0x00000fff
247
#define SITD_BUFPTR_TPOS_MASK         0x00000018
248
#define SITD_BUFPTR_TPOS_SH           3
249
#define SITD_BUFPTR_TCNT_MASK         0x00000007
250

    
251
    uint32_t backptr;                 // Standard next link pointer
252
} EHCIsitd;
253

    
254
/*  EHCI spec version 1.0 Section 3.5
255
 */
256
typedef struct EHCIqtd {
257
    uint32_t next;                    // Standard next link pointer
258
    uint32_t altnext;                 // Standard next link pointer
259
    uint32_t token;
260
#define QTD_TOKEN_DTOGGLE             (1 << 31)
261
#define QTD_TOKEN_TBYTES_MASK         0x7fff0000
262
#define QTD_TOKEN_TBYTES_SH           16
263
#define QTD_TOKEN_IOC                 (1 << 15)
264
#define QTD_TOKEN_CPAGE_MASK          0x00007000
265
#define QTD_TOKEN_CPAGE_SH            12
266
#define QTD_TOKEN_CERR_MASK           0x00000c00
267
#define QTD_TOKEN_CERR_SH             10
268
#define QTD_TOKEN_PID_MASK            0x00000300
269
#define QTD_TOKEN_PID_SH              8
270
#define QTD_TOKEN_ACTIVE              (1 << 7)
271
#define QTD_TOKEN_HALT                (1 << 6)
272
#define QTD_TOKEN_DBERR               (1 << 5)
273
#define QTD_TOKEN_BABBLE              (1 << 4)
274
#define QTD_TOKEN_XACTERR             (1 << 3)
275
#define QTD_TOKEN_MISSEDUF            (1 << 2)
276
#define QTD_TOKEN_SPLITXSTATE         (1 << 1)
277
#define QTD_TOKEN_PING                (1 << 0)
278

    
279
    uint32_t bufptr[5];               // Standard buffer pointer
280
#define QTD_BUFPTR_MASK               0xfffff000
281
} EHCIqtd;
282

    
283
/*  EHCI spec version 1.0 Section 3.6
284
 */
285
typedef struct EHCIqh {
286
    uint32_t next;                    // Standard next link pointer
287

    
288
    /* endpoint characteristics */
289
    uint32_t epchar;
290
#define QH_EPCHAR_RL_MASK             0xf0000000
291
#define QH_EPCHAR_RL_SH               28
292
#define QH_EPCHAR_C                   (1 << 27)
293
#define QH_EPCHAR_MPLEN_MASK          0x07FF0000
294
#define QH_EPCHAR_MPLEN_SH            16
295
#define QH_EPCHAR_H                   (1 << 15)
296
#define QH_EPCHAR_DTC                 (1 << 14)
297
#define QH_EPCHAR_EPS_MASK            0x00003000
298
#define QH_EPCHAR_EPS_SH              12
299
#define EHCI_QH_EPS_FULL              0
300
#define EHCI_QH_EPS_LOW               1
301
#define EHCI_QH_EPS_HIGH              2
302
#define EHCI_QH_EPS_RESERVED          3
303

    
304
#define QH_EPCHAR_EP_MASK             0x00000f00
305
#define QH_EPCHAR_EP_SH               8
306
#define QH_EPCHAR_I                   (1 << 7)
307
#define QH_EPCHAR_DEVADDR_MASK        0x0000007f
308
#define QH_EPCHAR_DEVADDR_SH          0
309

    
310
    /* endpoint capabilities */
311
    uint32_t epcap;
312
#define QH_EPCAP_MULT_MASK            0xc0000000
313
#define QH_EPCAP_MULT_SH              30
314
#define QH_EPCAP_PORTNUM_MASK         0x3f800000
315
#define QH_EPCAP_PORTNUM_SH           23
316
#define QH_EPCAP_HUBADDR_MASK         0x007f0000
317
#define QH_EPCAP_HUBADDR_SH           16
318
#define QH_EPCAP_CMASK_MASK           0x0000ff00
319
#define QH_EPCAP_CMASK_SH             8
320
#define QH_EPCAP_SMASK_MASK           0x000000ff
321
#define QH_EPCAP_SMASK_SH             0
322

    
323
    uint32_t current_qtd;             // Standard next link pointer
324
    uint32_t next_qtd;                // Standard next link pointer
325
    uint32_t altnext_qtd;
326
#define QH_ALTNEXT_NAKCNT_MASK        0x0000001e
327
#define QH_ALTNEXT_NAKCNT_SH          1
328

    
329
    uint32_t token;                   // Same as QTD token
330
    uint32_t bufptr[5];               // Standard buffer pointer
331
#define BUFPTR_CPROGMASK_MASK         0x000000ff
332
#define BUFPTR_FRAMETAG_MASK          0x0000001f
333
#define BUFPTR_SBYTES_MASK            0x00000fe0
334
#define BUFPTR_SBYTES_SH              5
335
} EHCIqh;
336

    
337
/*  EHCI spec version 1.0 Section 3.7
338
 */
339
typedef struct EHCIfstn {
340
    uint32_t next;                    // Standard next link pointer
341
    uint32_t backptr;                 // Standard next link pointer
342
} EHCIfstn;
343

    
344
typedef struct {
345
    PCIDevice dev;
346
    qemu_irq irq;
347
    target_phys_addr_t mem_base;
348
    int mem;
349
    int num_ports;
350
    /*
351
     *  EHCI spec version 1.0 Section 2.3
352
     *  Host Controller Operational Registers
353
     */
354
    union {
355
        uint8_t mmio[MMIO_SIZE];
356
        struct {
357
            uint8_t cap[OPREGBASE];
358
            uint32_t usbcmd;
359
            uint32_t usbsts;
360
            uint32_t usbintr;
361
            uint32_t frindex;
362
            uint32_t ctrldssegment;
363
            uint32_t periodiclistbase;
364
            uint32_t asynclistaddr;
365
            uint32_t notused[9];
366
            uint32_t configflag;
367
            uint32_t portsc[NB_PORTS];
368
        };
369
    };
370
    /*
371
     *  Internal states, shadow registers, etc
372
     */
373
    uint32_t sofv;
374
    QEMUTimer *frame_timer;
375
    int attach_poll_counter;
376
    int astate;                        // Current state in asynchronous schedule
377
    int pstate;                        // Current state in periodic schedule
378
    USBPort ports[NB_PORTS];
379
    uint8_t buffer[BUFF_SIZE];
380
    uint32_t usbsts_pending;
381

    
382
    /* cached data from guest - needs to be flushed
383
     * when guest removes an entry (doorbell, handshake sequence)
384
     */
385
    EHCIqh qh;             // copy of current QH (being worked on)
386
    uint32_t qhaddr;       // address QH read from
387

    
388
    EHCIqtd qtd;           // copy of current QTD (being worked on)
389
    uint32_t qtdaddr;      // address QTD read from
390

    
391
    uint32_t itdaddr;      // current ITD
392

    
393
    uint32_t fetch_addr;   // which address to look at next
394

    
395
    USBBus bus;
396
    USBPacket usb_packet;
397
    int async_complete;
398
    uint32_t tbytes;
399
    int pid;
400
    int exec_status;
401
    int isoch_pause;
402
    uint32_t last_run_usec;
403
    uint32_t frame_end_usec;
404
} EHCIState;
405

    
406
#define SET_LAST_RUN_CLOCK(s) \
407
    (s)->last_run_usec = qemu_get_clock_ns(vm_clock) / 1000;
408

    
409
/* nifty macros from Arnon's EHCI version  */
410
#define get_field(data, field) \
411
    (((data) & field##_MASK) >> field##_SH)
412

    
413
#define set_field(data, newval, field) do { \
414
    uint32_t val = *data; \
415
    val &= ~ field##_MASK; \
416
    val |= ((newval) << field##_SH) & field##_MASK; \
417
    *data = val; \
418
    } while(0)
419

    
420

    
421
static const char *addr2str(target_phys_addr_t addr)
422
{
423
    const char *r            = "unknown";
424
    const char *n[] = {
425
        [ CAPLENGTH ]        = "CAPLENGTH",
426
        [ HCIVERSION ]       = "HCIVERSION",
427
        [ HCSPARAMS ]        = "HCSPARAMS",
428
        [ HCCPARAMS ]        = "HCCPARAMS",
429
        [ USBCMD ]           = "USBCMD",
430
        [ USBSTS ]           = "USBSTS",
431
        [ USBINTR ]          = "USBINTR",
432
        [ FRINDEX ]          = "FRINDEX",
433
        [ PERIODICLISTBASE ] = "P-LIST BASE",
434
        [ ASYNCLISTADDR ]    = "A-LIST ADDR",
435
        [ PORTSC_BEGIN ...
436
          PORTSC_END ]       = "PORTSC",
437
        [ CONFIGFLAG ]       = "CONFIGFLAG",
438
    };
439

    
440
    if (addr < ARRAY_SIZE(n) && n[addr] != NULL) {
441
        return n[addr];
442
    } else {
443
        return r;
444
    }
445
}
446

    
447
static void ehci_trace_usbsts(uint32_t mask, int state)
448
{
449
    /* interrupts */
450
    if (mask & USBSTS_INT) {
451
        trace_usb_ehci_usbsts("INT", state);
452
    }
453
    if (mask & USBSTS_ERRINT) {
454
        trace_usb_ehci_usbsts("ERRINT", state);
455
    }
456
    if (mask & USBSTS_PCD) {
457
        trace_usb_ehci_usbsts("PCD", state);
458
    }
459
    if (mask & USBSTS_FLR) {
460
        trace_usb_ehci_usbsts("FLR", state);
461
    }
462
    if (mask & USBSTS_HSE) {
463
        trace_usb_ehci_usbsts("HSE", state);
464
    }
465
    if (mask & USBSTS_IAA) {
466
        trace_usb_ehci_usbsts("IAA", state);
467
    }
468

    
469
    /* status */
470
    if (mask & USBSTS_HALT) {
471
        trace_usb_ehci_usbsts("HALT", state);
472
    }
473
    if (mask & USBSTS_REC) {
474
        trace_usb_ehci_usbsts("REC", state);
475
    }
476
    if (mask & USBSTS_PSS) {
477
        trace_usb_ehci_usbsts("PSS", state);
478
    }
479
    if (mask & USBSTS_ASS) {
480
        trace_usb_ehci_usbsts("ASS", state);
481
    }
482
}
483

    
484
static inline void ehci_set_usbsts(EHCIState *s, int mask)
485
{
486
    if ((s->usbsts & mask) == mask) {
487
        return;
488
    }
489
    ehci_trace_usbsts(mask, 1);
490
    s->usbsts |= mask;
491
}
492

    
493
static inline void ehci_clear_usbsts(EHCIState *s, int mask)
494
{
495
    if ((s->usbsts & mask) == 0) {
496
        return;
497
    }
498
    ehci_trace_usbsts(mask, 0);
499
    s->usbsts &= ~mask;
500
}
501

    
502
static inline void ehci_set_interrupt(EHCIState *s, int intr)
503
{
504
    int level = 0;
505

    
506
    // TODO honour interrupt threshold requests
507

    
508
    ehci_set_usbsts(s, intr);
509

    
510
    if ((s->usbsts & USBINTR_MASK) & s->usbintr) {
511
        level = 1;
512
    }
513

    
514
    qemu_set_irq(s->irq, level);
515
}
516

    
517
static inline void ehci_record_interrupt(EHCIState *s, int intr)
518
{
519
    s->usbsts_pending |= intr;
520
}
521

    
522
static inline void ehci_commit_interrupt(EHCIState *s)
523
{
524
    if (!s->usbsts_pending) {
525
        return;
526
    }
527
    ehci_set_interrupt(s, s->usbsts_pending);
528
    s->usbsts_pending = 0;
529
}
530

    
531
/* Attach or detach a device on root hub */
532

    
533
static void ehci_attach(USBPort *port)
534
{
535
    EHCIState *s = port->opaque;
536
    uint32_t *portsc = &s->portsc[port->index];
537

    
538
    DPRINTF("ehci_attach invoked for index %d, portsc 0x%x, desc %s\n",
539
           port->index, *portsc, port->dev->product_desc);
540

    
541
    *portsc |= PORTSC_CONNECT;
542
    *portsc |= PORTSC_CSC;
543

    
544
    /*
545
     *  If a high speed device is attached then we own this port(indicated
546
     *  by zero in the PORTSC_POWNER bit field) so set the status bit
547
     *  and set an interrupt if enabled.
548
     */
549
    if ( !(*portsc & PORTSC_POWNER)) {
550
        ehci_set_interrupt(s, USBSTS_PCD);
551
    }
552
}
553

    
554
static void ehci_detach(USBPort *port)
555
{
556
    EHCIState *s = port->opaque;
557
    uint32_t *portsc = &s->portsc[port->index];
558

    
559
    DPRINTF("ehci_attach invoked for index %d, portsc 0x%x\n",
560
           port->index, *portsc);
561

    
562
    *portsc &= ~PORTSC_CONNECT;
563
    *portsc |= PORTSC_CSC;
564

    
565
    /*
566
     *  If a high speed device is attached then we own this port(indicated
567
     *  by zero in the PORTSC_POWNER bit field) so set the status bit
568
     *  and set an interrupt if enabled.
569
     */
570
    if ( !(*portsc & PORTSC_POWNER)) {
571
        ehci_set_interrupt(s, USBSTS_PCD);
572
    }
573
}
574

    
575
/* 4.1 host controller initialization */
576
static void ehci_reset(void *opaque)
577
{
578
    EHCIState *s = opaque;
579
    uint8_t *pci_conf;
580
    int i;
581

    
582
    trace_usb_ehci_reset();
583
    pci_conf = s->dev.config;
584

    
585
    memset(&s->mmio[OPREGBASE], 0x00, MMIO_SIZE - OPREGBASE);
586

    
587
    s->usbcmd = NB_MAXINTRATE << USBCMD_ITC_SH;
588
    s->usbsts = USBSTS_HALT;
589

    
590
    s->astate = EST_INACTIVE;
591
    s->pstate = EST_INACTIVE;
592
    s->async_complete = 0;
593
    s->isoch_pause = -1;
594
    s->attach_poll_counter = 0;
595

    
596
    for(i = 0; i < NB_PORTS; i++) {
597
        s->portsc[i] = PORTSC_POWNER | PORTSC_PPOWER;
598

    
599
        if (s->ports[i].dev) {
600
            usb_attach(&s->ports[i], s->ports[i].dev);
601
        }
602
    }
603
}
604

    
605
static uint32_t ehci_mem_readb(void *ptr, target_phys_addr_t addr)
606
{
607
    EHCIState *s = ptr;
608
    uint32_t val;
609

    
610
    val = s->mmio[addr];
611

    
612
    return val;
613
}
614

    
615
static uint32_t ehci_mem_readw(void *ptr, target_phys_addr_t addr)
616
{
617
    EHCIState *s = ptr;
618
    uint32_t val;
619

    
620
    val = s->mmio[addr] | (s->mmio[addr+1] << 8);
621

    
622
    return val;
623
}
624

    
625
static uint32_t ehci_mem_readl(void *ptr, target_phys_addr_t addr)
626
{
627
    EHCIState *s = ptr;
628
    uint32_t val;
629

    
630
    val = s->mmio[addr] | (s->mmio[addr+1] << 8) |
631
          (s->mmio[addr+2] << 16) | (s->mmio[addr+3] << 24);
632

    
633
    trace_usb_ehci_mmio_readl(addr, addr2str(addr), val);
634
    return val;
635
}
636

    
637
static void ehci_mem_writeb(void *ptr, target_phys_addr_t addr, uint32_t val)
638
{
639
    fprintf(stderr, "EHCI doesn't handle byte writes to MMIO\n");
640
    exit(1);
641
}
642

    
643
static void ehci_mem_writew(void *ptr, target_phys_addr_t addr, uint32_t val)
644
{
645
    fprintf(stderr, "EHCI doesn't handle 16-bit writes to MMIO\n");
646
    exit(1);
647
}
648

    
649
static void handle_port_status_write(EHCIState *s, int port, uint32_t val)
650
{
651
    uint32_t *portsc = &s->portsc[port];
652
    int rwc;
653
    USBDevice *dev = s->ports[port].dev;
654

    
655
    DPRINTF("port_status_write: "
656
            "PORTSC (port %d) curr %08X new %08X rw-clear %08X rw %08X\n",
657
            port, *portsc, val, (val & PORTSC_RWC_MASK), val & PORTSC_RO_MASK);
658

    
659
    rwc = val & PORTSC_RWC_MASK;
660
    val &= PORTSC_RO_MASK;
661

    
662
    // handle_read_write_clear(&val, portsc, PORTSC_PEDC | PORTSC_CSC);
663

    
664
    *portsc &= ~rwc;
665

    
666
    if ((val & PORTSC_PRESET) && !(*portsc & PORTSC_PRESET)) {
667
        DPRINTF("port_status_write: USBTRAN Port %d reset begin\n", port);
668
    }
669

    
670
    if (!(val & PORTSC_PRESET) &&(*portsc & PORTSC_PRESET)) {
671
        DPRINTF("port_status_write: USBTRAN Port %d reset done\n", port);
672
        usb_attach(&s->ports[port], dev);
673

    
674
        // TODO how to handle reset of ports with no device
675
        if (dev) {
676
            usb_send_msg(dev, USB_MSG_RESET);
677
        }
678

    
679
        if (s->ports[port].dev) {
680
            DPRINTF("port_status_write: "
681
                    "Device was connected before reset, clearing CSC bit\n");
682
            *portsc &= ~PORTSC_CSC;
683
        }
684

    
685
        /*  Table 2.16 Set the enable bit(and enable bit change) to indicate
686
         *  to SW that this port has a high speed device attached
687
         *
688
         *  TODO - when to disable?
689
         */
690
        val |= PORTSC_PED;
691
        val |= PORTSC_PEDC;
692
    }
693

    
694
    *portsc &= ~PORTSC_RO_MASK;
695
    *portsc |= val;
696
    DPRINTF("port_status_write: Port %d status set to 0x%08x\n", port, *portsc);
697
}
698

    
699
static void ehci_mem_writel(void *ptr, target_phys_addr_t addr, uint32_t val)
700
{
701
    EHCIState *s = ptr;
702
    int i;
703

    
704
    trace_usb_ehci_mmio_writel(addr, addr2str(addr), val,
705
                               *(uint32_t *)(&s->mmio[addr]));
706

    
707
    /* Only aligned reads are allowed on OHCI */
708
    if (addr & 3) {
709
        fprintf(stderr, "usb-ehci: Mis-aligned write to addr 0x"
710
                TARGET_FMT_plx "\n", addr);
711
        return;
712
    }
713

    
714
    if (addr >= PORTSC && addr < PORTSC + 4 * NB_PORTS) {
715
        handle_port_status_write(s, (addr-PORTSC)/4, val);
716
        return;
717
    }
718

    
719
    if (addr < OPREGBASE) {
720
        fprintf(stderr, "usb-ehci: write attempt to read-only register"
721
                TARGET_FMT_plx "\n", addr);
722
        return;
723
    }
724

    
725

    
726
    /* Do any register specific pre-write processing here.  */
727
    switch(addr) {
728
    case USBCMD:
729
        if ((val & USBCMD_RUNSTOP) && !(s->usbcmd & USBCMD_RUNSTOP)) {
730
            qemu_mod_timer(s->frame_timer, qemu_get_clock_ns(vm_clock));
731
            SET_LAST_RUN_CLOCK(s);
732
            ehci_clear_usbsts(s, USBSTS_HALT);
733
        }
734

    
735
        if (!(val & USBCMD_RUNSTOP) && (s->usbcmd & USBCMD_RUNSTOP)) {
736
            qemu_del_timer(s->frame_timer);
737
            // TODO - should finish out some stuff before setting halt
738
            ehci_set_usbsts(s, USBSTS_HALT);
739
        }
740

    
741
        if (val & USBCMD_HCRESET) {
742
            ehci_reset(s);
743
            val &= ~USBCMD_HCRESET;
744
        }
745

    
746
        /* not supporting dynamic frame list size at the moment */
747
        if ((val & USBCMD_FLS) && !(s->usbcmd & USBCMD_FLS)) {
748
            fprintf(stderr, "attempt to set frame list size -- value %d\n",
749
                    val & USBCMD_FLS);
750
            val &= ~USBCMD_FLS;
751
        }
752
        break;
753

    
754
    case USBSTS:
755
        val &= USBSTS_RO_MASK;              // bits 6 thru 31 are RO
756
        ehci_clear_usbsts(s, val);          // bits 0 thru 5 are R/WC
757
        val = s->usbsts;
758
        ehci_set_interrupt(s, 0);
759
        break;
760

    
761
    case USBINTR:
762
        val &= USBINTR_MASK;
763
        break;
764

    
765
    case FRINDEX:
766
        s->sofv = val >> 3;
767
        break;
768

    
769
    case CONFIGFLAG:
770
        val &= 0x1;
771
        if (val) {
772
            for(i = 0; i < NB_PORTS; i++)
773
                s->portsc[i] &= ~PORTSC_POWNER;
774
        }
775
        break;
776

    
777
    case PERIODICLISTBASE:
778
        if ((s->usbcmd & USBCMD_PSE) && (s->usbcmd & USBCMD_RUNSTOP)) {
779
            fprintf(stderr,
780
              "ehci: PERIODIC list base register set while periodic schedule\n"
781
              "      is enabled and HC is enabled\n");
782
        }
783
        break;
784

    
785
    case ASYNCLISTADDR:
786
        if ((s->usbcmd & USBCMD_ASE) && (s->usbcmd & USBCMD_RUNSTOP)) {
787
            fprintf(stderr,
788
              "ehci: ASYNC list address register set while async schedule\n"
789
              "      is enabled and HC is enabled\n");
790
        }
791
        break;
792
    }
793

    
794
    *(uint32_t *)(&s->mmio[addr]) = val;
795
}
796

    
797

    
798
// TODO : Put in common header file, duplication from usb-ohci.c
799

    
800
/* Get an array of dwords from main memory */
801
static inline int get_dwords(uint32_t addr, uint32_t *buf, int num)
802
{
803
    int i;
804

    
805
    for(i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
806
        cpu_physical_memory_rw(addr,(uint8_t *)buf, sizeof(*buf), 0);
807
        *buf = le32_to_cpu(*buf);
808
    }
809

    
810
    return 1;
811
}
812

    
813
/* Put an array of dwords in to main memory */
814
static inline int put_dwords(uint32_t addr, uint32_t *buf, int num)
815
{
816
    int i;
817

    
818
    for(i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
819
        uint32_t tmp = cpu_to_le32(*buf);
820
        cpu_physical_memory_rw(addr,(uint8_t *)&tmp, sizeof(tmp), 1);
821
    }
822

    
823
    return 1;
824
}
825

    
826
// 4.10.2
827

    
828
static int ehci_qh_do_overlay(EHCIState *ehci, EHCIqh *qh, EHCIqtd *qtd)
829
{
830
    int i;
831
    int dtoggle;
832
    int ping;
833
    int eps;
834
    int reload;
835

    
836
    // remember values in fields to preserve in qh after overlay
837

    
838
    dtoggle = qh->token & QTD_TOKEN_DTOGGLE;
839
    ping    = qh->token & QTD_TOKEN_PING;
840

    
841
    DPRINTF("setting qh.current from %08X to 0x%08X\n", qh->current_qtd,
842
            ehci->qtdaddr);
843
    qh->current_qtd = ehci->qtdaddr;
844
    qh->next_qtd    = qtd->next;
845
    qh->altnext_qtd = qtd->altnext;
846
    qh->token       = qtd->token;
847

    
848

    
849
    eps = get_field(qh->epchar, QH_EPCHAR_EPS);
850
    if (eps == EHCI_QH_EPS_HIGH) {
851
        qh->token &= ~QTD_TOKEN_PING;
852
        qh->token |= ping;
853
    }
854

    
855
    reload = get_field(qh->epchar, QH_EPCHAR_RL);
856
    set_field(&qh->altnext_qtd, reload, QH_ALTNEXT_NAKCNT);
857

    
858
    for (i = 0; i < 5; i++) {
859
        qh->bufptr[i] = qtd->bufptr[i];
860
    }
861

    
862
    if (!(qh->epchar & QH_EPCHAR_DTC)) {
863
        // preserve QH DT bit
864
        qh->token &= ~QTD_TOKEN_DTOGGLE;
865
        qh->token |= dtoggle;
866
    }
867

    
868
    qh->bufptr[1] &= ~BUFPTR_CPROGMASK_MASK;
869
    qh->bufptr[2] &= ~BUFPTR_FRAMETAG_MASK;
870

    
871
    put_dwords(NLPTR_GET(ehci->qhaddr), (uint32_t *) qh, sizeof(EHCIqh) >> 2);
872

    
873
    return 0;
874
}
875

    
876
static int ehci_buffer_rw(uint8_t *buffer, EHCIqh *qh, int bytes, int rw)
877
{
878
    int bufpos = 0;
879
    int cpage, offset;
880
    uint32_t head;
881
    uint32_t tail;
882

    
883

    
884
    if (!bytes) {
885
        return 0;
886
    }
887

    
888
    cpage = get_field(qh->token, QTD_TOKEN_CPAGE);
889
    if (cpage > 4) {
890
        fprintf(stderr, "cpage out of range (%d)\n", cpage);
891
        return USB_RET_PROCERR;
892
    }
893

    
894
    offset = qh->bufptr[0] & ~QTD_BUFPTR_MASK;
895
    DPRINTF("ehci_buffer_rw: %sing %d bytes %08x cpage %d offset %d\n",
896
           rw ? "writ" : "read", bytes, qh->bufptr[0], cpage, offset);
897

    
898
    do {
899
        /* start and end of this page */
900
        head = qh->bufptr[cpage] & QTD_BUFPTR_MASK;
901
        tail = head + ~QTD_BUFPTR_MASK + 1;
902
        /* add offset into page */
903
        head |= offset;
904

    
905
        if (bytes <= (tail - head)) {
906
            tail = head + bytes;
907
        }
908

    
909
        DPRINTF("DATA %s cpage:%d head:%08X tail:%08X target:%08X\n",
910
                rw ? "WRITE" : "READ ", cpage, head, tail, bufpos);
911

    
912
        cpu_physical_memory_rw(head, &buffer[bufpos], tail - head, rw);
913

    
914
        bufpos += (tail - head);
915
        bytes -= (tail - head);
916

    
917
        if (bytes > 0) {
918
            cpage++;
919
            offset = 0;
920
        }
921
    } while (bytes > 0);
922

    
923
    /* save cpage */
924
    set_field(&qh->token, cpage, QTD_TOKEN_CPAGE);
925

    
926
    /* save offset into cpage */
927
    offset = tail - head;
928
    qh->bufptr[0] &= ~QTD_BUFPTR_MASK;
929
    qh->bufptr[0] |= offset;
930

    
931
    return 0;
932
}
933

    
934
static void ehci_async_complete_packet(USBDevice *dev, USBPacket *packet)
935
{
936
    EHCIState *ehci = container_of(packet, EHCIState, usb_packet);
937

    
938
    DPRINTF("Async packet complete\n");
939
    ehci->async_complete = 1;
940
    ehci->exec_status = packet->len;
941
}
942

    
943
static int ehci_execute_complete(EHCIState *ehci, EHCIqh *qh, int ret)
944
{
945
    int c_err, reload;
946

    
947
    if (ret == USB_RET_ASYNC && !ehci->async_complete) {
948
        DPRINTF("not done yet\n");
949
        return ret;
950
    }
951

    
952
    ehci->async_complete = 0;
953

    
954
    DPRINTF("execute_complete: qhaddr 0x%x, next %x, qtdaddr 0x%x, status %d\n",
955
            ehci->qhaddr, qh->next, ehci->qtdaddr, ret);
956

    
957
    if (ret < 0) {
958
err:
959
        /* TO-DO: put this is in a function that can be invoked below as well */
960
        c_err = get_field(qh->token, QTD_TOKEN_CERR);
961
        c_err--;
962
        set_field(&qh->token, c_err, QTD_TOKEN_CERR);
963

    
964
        switch(ret) {
965
        case USB_RET_NODEV:
966
            fprintf(stderr, "USB no device\n");
967
            break;
968
        case USB_RET_STALL:
969
            fprintf(stderr, "USB stall\n");
970
            qh->token |= QTD_TOKEN_HALT;
971
            ehci_record_interrupt(ehci, USBSTS_ERRINT);
972
            break;
973
        case USB_RET_NAK:
974
            /* 4.10.3 */
975
            reload = get_field(qh->epchar, QH_EPCHAR_RL);
976
            if ((ehci->pid == USB_TOKEN_IN) && reload) {
977
                int nakcnt = get_field(qh->altnext_qtd, QH_ALTNEXT_NAKCNT);
978
                nakcnt--;
979
                set_field(&qh->altnext_qtd, nakcnt, QH_ALTNEXT_NAKCNT);
980
            } else if (!reload) {
981
                return USB_RET_NAK;
982
            }
983
            break;
984
        case USB_RET_BABBLE:
985
            fprintf(stderr, "USB babble TODO\n");
986
            qh->token |= QTD_TOKEN_BABBLE;
987
            ehci_record_interrupt(ehci, USBSTS_ERRINT);
988
            break;
989
        default:
990
            fprintf(stderr, "USB invalid response %d to handle\n", ret);
991
            /* TO-DO: transaction error */
992
            ret = USB_RET_PROCERR;
993
            break;
994
        }
995
    } else {
996
        // DPRINTF("Short packet condition\n");
997
        // TODO check 4.12 for splits
998

    
999
        if ((ret > ehci->tbytes) && (ehci->pid == USB_TOKEN_IN)) {
1000
            ret = USB_RET_BABBLE;
1001
            goto err;
1002
        }
1003

    
1004
        if (ehci->tbytes && ehci->pid == USB_TOKEN_IN) {
1005
            if (ehci_buffer_rw(ehci->buffer, qh, ret, 1) != 0) {
1006
                return USB_RET_PROCERR;
1007
            }
1008
            ehci->tbytes -= ret;
1009
        } else {
1010
            ehci->tbytes = 0;
1011
        }
1012

    
1013
        DPRINTF("updating tbytes to %d\n", ehci->tbytes);
1014
        set_field(&qh->token, ehci->tbytes, QTD_TOKEN_TBYTES);
1015
    }
1016

    
1017
    qh->token ^= QTD_TOKEN_DTOGGLE;
1018
    qh->token &= ~QTD_TOKEN_ACTIVE;
1019

    
1020
    if ((ret >= 0) && (qh->token & QTD_TOKEN_IOC)) {
1021
        ehci_record_interrupt(ehci, USBSTS_INT);
1022
    }
1023

    
1024
    return ret;
1025
}
1026

    
1027
// 4.10.3
1028

    
1029
static int ehci_execute(EHCIState *ehci, EHCIqh *qh)
1030
{
1031
    USBPort *port;
1032
    USBDevice *dev;
1033
    int ret;
1034
    int i;
1035
    int endp;
1036
    int devadr;
1037

    
1038
    if ( !(qh->token & QTD_TOKEN_ACTIVE)) {
1039
        fprintf(stderr, "Attempting to execute inactive QH\n");
1040
        return USB_RET_PROCERR;
1041
    }
1042

    
1043
    ehci->tbytes = (qh->token & QTD_TOKEN_TBYTES_MASK) >> QTD_TOKEN_TBYTES_SH;
1044
    if (ehci->tbytes > BUFF_SIZE) {
1045
        fprintf(stderr, "Request for more bytes than allowed\n");
1046
        return USB_RET_PROCERR;
1047
    }
1048

    
1049
    ehci->pid = (qh->token & QTD_TOKEN_PID_MASK) >> QTD_TOKEN_PID_SH;
1050
    switch(ehci->pid) {
1051
        case 0: ehci->pid = USB_TOKEN_OUT; break;
1052
        case 1: ehci->pid = USB_TOKEN_IN; break;
1053
        case 2: ehci->pid = USB_TOKEN_SETUP; break;
1054
        default: fprintf(stderr, "bad token\n"); break;
1055
    }
1056

    
1057
    if ((ehci->tbytes && ehci->pid != USB_TOKEN_IN) &&
1058
        (ehci_buffer_rw(ehci->buffer, qh, ehci->tbytes, 0) != 0)) {
1059
        return USB_RET_PROCERR;
1060
    }
1061

    
1062
    endp = get_field(qh->epchar, QH_EPCHAR_EP);
1063
    devadr = get_field(qh->epchar, QH_EPCHAR_DEVADDR);
1064

    
1065
    ret = USB_RET_NODEV;
1066

    
1067
    // TO-DO: associating device with ehci port
1068
    for(i = 0; i < NB_PORTS; i++) {
1069
        port = &ehci->ports[i];
1070
        dev = port->dev;
1071

    
1072
        // TODO sometime we will also need to check if we are the port owner
1073

    
1074
        if (!(ehci->portsc[i] &(PORTSC_CONNECT))) {
1075
            DPRINTF("Port %d, no exec, not connected(%08X)\n",
1076
                    i, ehci->portsc[i]);
1077
            continue;
1078
        }
1079

    
1080
        ehci->usb_packet.pid = ehci->pid;
1081
        ehci->usb_packet.devaddr = devadr;
1082
        ehci->usb_packet.devep = endp;
1083
        ehci->usb_packet.data = ehci->buffer;
1084
        ehci->usb_packet.len = ehci->tbytes;
1085

    
1086
        ret = usb_handle_packet(dev, &ehci->usb_packet);
1087

    
1088
        DPRINTF("submit: qh %x next %x qtd %x pid %x len %d (total %d) endp %x ret %d\n",
1089
                ehci->qhaddr, qh->next, ehci->qtdaddr, ehci->pid,
1090
                ehci->usb_packet.len, ehci->tbytes, endp, ret);
1091

    
1092
        if (ret != USB_RET_NODEV) {
1093
            break;
1094
        }
1095
    }
1096

    
1097
    if (ret > BUFF_SIZE) {
1098
        fprintf(stderr, "ret from usb_handle_packet > BUFF_SIZE\n");
1099
        return USB_RET_PROCERR;
1100
    }
1101

    
1102
    if (ret == USB_RET_ASYNC) {
1103
        ehci->async_complete = 0;
1104
    }
1105

    
1106
    return ret;
1107
}
1108

    
1109
/*  4.7.2
1110
 */
1111

    
1112
static int ehci_process_itd(EHCIState *ehci,
1113
                            EHCIitd *itd)
1114
{
1115
    USBPort *port;
1116
    USBDevice *dev;
1117
    int ret;
1118
    int i, j;
1119
    int ptr;
1120
    int pid;
1121
    int pg;
1122
    int len;
1123
    int dir;
1124
    int devadr;
1125
    int endp;
1126
    int maxpkt;
1127

    
1128
    dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
1129
    devadr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
1130
    endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
1131
    maxpkt = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
1132

    
1133
    for(i = 0; i < 8; i++) {
1134
        if (itd->transact[i] & ITD_XACT_ACTIVE) {
1135
            DPRINTF("ISOCHRONOUS active for frame %d, interval %d\n",
1136
                    ehci->frindex >> 3, i);
1137

    
1138
            pg = get_field(itd->transact[i], ITD_XACT_PGSEL);
1139
            ptr = (itd->bufptr[pg] & ITD_BUFPTR_MASK) |
1140
                (itd->transact[i] & ITD_XACT_OFFSET_MASK);
1141
            len = get_field(itd->transact[i], ITD_XACT_LENGTH);
1142

    
1143
            if (len > BUFF_SIZE) {
1144
                return USB_RET_PROCERR;
1145
            }
1146

    
1147
            DPRINTF("ISOCH: buffer %08X len %d\n", ptr, len);
1148

    
1149
            if (!dir) {
1150
                cpu_physical_memory_rw(ptr, &ehci->buffer[0], len, 0);
1151
                pid = USB_TOKEN_OUT;
1152
            } else
1153
                pid = USB_TOKEN_IN;
1154

    
1155
            ret = USB_RET_NODEV;
1156

    
1157
            for (j = 0; j < NB_PORTS; j++) {
1158
                port = &ehci->ports[j];
1159
                dev = port->dev;
1160

    
1161
                // TODO sometime we will also need to check if we are the port owner
1162

    
1163
                if (!(ehci->portsc[j] &(PORTSC_CONNECT))) {
1164
                    DPRINTF("Port %d, no exec, not connected(%08X)\n",
1165
                            j, ehci->portsc[j]);
1166
                    continue;
1167
                }
1168

    
1169
                ehci->usb_packet.pid = ehci->pid;
1170
                ehci->usb_packet.devaddr = devadr;
1171
                ehci->usb_packet.devep = endp;
1172
                ehci->usb_packet.data = ehci->buffer;
1173
                ehci->usb_packet.len = len;
1174

    
1175
                DPRINTF("calling usb_handle_packet\n");
1176
                ret = usb_handle_packet(dev, &ehci->usb_packet);
1177

    
1178
                if (ret != USB_RET_NODEV) {
1179
                    break;
1180
                }
1181
            }
1182

    
1183
            /*  In isoch, there is no facility to indicate a NAK so let's
1184
             *  instead just complete a zero-byte transaction.  Setting
1185
             *  DBERR seems too draconian.
1186
             */
1187

    
1188
            if (ret == USB_RET_NAK) {
1189
                if (ehci->isoch_pause > 0) {
1190
                    DPRINTF("ISOCH: received a NAK but paused so returning\n");
1191
                    ehci->isoch_pause--;
1192
                    return 0;
1193
                } else if (ehci->isoch_pause == -1) {
1194
                    DPRINTF("ISOCH: recv NAK & isoch pause inactive, setting\n");
1195
                    // Pause frindex for up to 50 msec waiting for data from
1196
                    // remote
1197
                    ehci->isoch_pause = 50;
1198
                    return 0;
1199
                } else {
1200
                    DPRINTF("ISOCH: isoch pause timeout! return 0\n");
1201
                    ret = 0;
1202
                }
1203
            } else {
1204
                DPRINTF("ISOCH: received ACK, clearing pause\n");
1205
                ehci->isoch_pause = -1;
1206
            }
1207

    
1208
            if (ret >= 0) {
1209
                itd->transact[i] &= ~ITD_XACT_ACTIVE;
1210

    
1211
                if (itd->transact[i] & ITD_XACT_IOC) {
1212
                    ehci_record_interrupt(ehci, USBSTS_INT);
1213
                }
1214
            }
1215

    
1216
            if (ret >= 0 && dir) {
1217
                cpu_physical_memory_rw(ptr, &ehci->buffer[0], len, 1);
1218

    
1219
                if (ret != len) {
1220
                    DPRINTF("ISOCH IN expected %d, got %d\n",
1221
                            len, ret);
1222
                    set_field(&itd->transact[i], ret, ITD_XACT_LENGTH);
1223
                }
1224
            }
1225
        }
1226
    }
1227
    return 0;
1228
}
1229

    
1230
/*  This state is the entry point for asynchronous schedule
1231
 *  processing.  Entry here consitutes a EHCI start event state (4.8.5)
1232
 */
1233
static int ehci_state_waitlisthead(EHCIState *ehci,  int async, int *state)
1234
{
1235
    EHCIqh *qh = &ehci->qh;
1236
    int i = 0;
1237
    int again = 0;
1238
    uint32_t entry = ehci->asynclistaddr;
1239

    
1240
    /* set reclamation flag at start event (4.8.6) */
1241
    if (async) {
1242
        ehci_set_usbsts(ehci, USBSTS_REC);
1243
    }
1244

    
1245
    /*  Find the head of the list (4.9.1.1) */
1246
    for(i = 0; i < MAX_QH; i++) {
1247
        get_dwords(NLPTR_GET(entry), (uint32_t *) qh, sizeof(EHCIqh) >> 2);
1248

    
1249
        if (qh->epchar & QH_EPCHAR_H) {
1250
            DPRINTF_ST("WAITLISTHEAD: QH %08X is the HEAD of the list\n",
1251
                       entry);
1252
            if (async) {
1253
                entry |= (NLPTR_TYPE_QH << 1);
1254
            }
1255

    
1256
            ehci->fetch_addr = entry;
1257
            *state = EST_FETCHENTRY;
1258
            again = 1;
1259
            goto out;
1260
        }
1261

    
1262
        DPRINTF_ST("WAITLISTHEAD: QH %08X is NOT the HEAD of the list\n",
1263
                   entry);
1264
        entry = qh->next;
1265
        if (entry == ehci->asynclistaddr) {
1266
            DPRINTF("WAITLISTHEAD: reached beginning of QH list\n");
1267
            break;
1268
        }
1269
    }
1270

    
1271
    /* no head found for list. */
1272

    
1273
    *state = EST_ACTIVE;
1274

    
1275
out:
1276
    return again;
1277
}
1278

    
1279

    
1280
/*  This state is the entry point for periodic schedule processing as
1281
 *  well as being a continuation state for async processing.
1282
 */
1283
static int ehci_state_fetchentry(EHCIState *ehci, int async, int *state)
1284
{
1285
    int again = 0;
1286
    uint32_t entry = ehci->fetch_addr;
1287

    
1288
#if EHCI_DEBUG == 0
1289
    if (qemu_get_clock_ns(vm_clock) / 1000 >= ehci->frame_end_usec) {
1290
        if (async) {
1291
            DPRINTF("FETCHENTRY: FRAME timer elapsed, exit state machine\n");
1292
            goto out;
1293
        } else {
1294
            DPRINTF("FETCHENTRY: WARNING "
1295
                    "- frame timer elapsed during periodic\n");
1296
        }
1297
    }
1298
#endif
1299
    if (entry < 0x1000) {
1300
        DPRINTF("fetchentry: entry invalid (0x%08x)\n", entry);
1301
        *state = EST_ACTIVE;
1302
        goto out;
1303
    }
1304

    
1305
    /* section 4.8, only QH in async schedule */
1306
    if (async && (NLPTR_TYPE_GET(entry) != NLPTR_TYPE_QH)) {
1307
        fprintf(stderr, "non queue head request in async schedule\n");
1308
        return -1;
1309
    }
1310

    
1311
    switch (NLPTR_TYPE_GET(entry)) {
1312
    case NLPTR_TYPE_QH:
1313
        DPRINTF_ST("FETCHENTRY: entry %X is a Queue Head\n", entry);
1314
        *state = EST_FETCHQH;
1315
        ehci->qhaddr = entry;
1316
        again = 1;
1317
        break;
1318

    
1319
    case NLPTR_TYPE_ITD:
1320
        DPRINTF_ST("FETCHENTRY: entry %X is an ITD\n", entry);
1321
        *state = EST_FETCHITD;
1322
        ehci->itdaddr = entry;
1323
        again = 1;
1324
        break;
1325

    
1326
    default:
1327
        // TODO: handle siTD and FSTN types
1328
        fprintf(stderr, "FETCHENTRY: entry at %X is of type %d "
1329
                "which is not supported yet\n", entry, NLPTR_TYPE_GET(entry));
1330
        return -1;
1331
    }
1332

    
1333
out:
1334
    return again;
1335
}
1336

    
1337
static int ehci_state_fetchqh(EHCIState *ehci, int async, int *state)
1338
{
1339
    EHCIqh *qh = &ehci->qh;
1340
    int reload;
1341
    int again = 0;
1342

    
1343
    get_dwords(NLPTR_GET(ehci->qhaddr), (uint32_t *) qh, sizeof(EHCIqh) >> 2);
1344

    
1345
    if (async && (qh->epchar & QH_EPCHAR_H)) {
1346

    
1347
        /*  EHCI spec version 1.0 Section 4.8.3 & 4.10.1 */
1348
        if (ehci->usbsts & USBSTS_REC) {
1349
            ehci_clear_usbsts(ehci, USBSTS_REC);
1350
        } else {
1351
            DPRINTF("FETCHQH:  QH 0x%08x. H-bit set, reclamation status reset"
1352
                       " - done processing\n", ehci->qhaddr);
1353
            *state = EST_ACTIVE;
1354
            goto out;
1355
        }
1356
    }
1357

    
1358
#if EHCI_DEBUG
1359
    if (ehci->qhaddr != qh->next) {
1360
    DPRINTF("FETCHQH:  QH 0x%08x (h %x halt %x active %x) next 0x%08x\n",
1361
               ehci->qhaddr,
1362
               qh->epchar & QH_EPCHAR_H,
1363
               qh->token & QTD_TOKEN_HALT,
1364
               qh->token & QTD_TOKEN_ACTIVE,
1365
               qh->next);
1366
    }
1367
#endif
1368

    
1369
    reload = get_field(qh->epchar, QH_EPCHAR_RL);
1370
    if (reload) {
1371
        DPRINTF_ST("FETCHQH: reloading nakcnt to %d\n", reload);
1372
        set_field(&qh->altnext_qtd, reload, QH_ALTNEXT_NAKCNT);
1373
    }
1374

    
1375
    if (qh->token & QTD_TOKEN_HALT) {
1376
        DPRINTF_ST("FETCHQH: QH Halted, go horizontal\n");
1377
        *state = EST_HORIZONTALQH;
1378
        again = 1;
1379

    
1380
    } else if ((qh->token & QTD_TOKEN_ACTIVE) && (qh->current_qtd > 0x1000)) {
1381
        DPRINTF_ST("FETCHQH: Active, !Halt, execute - fetch qTD\n");
1382
        ehci->qtdaddr = qh->current_qtd;
1383
        *state = EST_FETCHQTD;
1384
        again = 1;
1385

    
1386
    } else {
1387
        /*  EHCI spec version 1.0 Section 4.10.2 */
1388
        DPRINTF_ST("FETCHQH: !Active, !Halt, advance queue\n");
1389
        *state = EST_ADVANCEQUEUE;
1390
        again = 1;
1391
    }
1392

    
1393
out:
1394
    return again;
1395
}
1396

    
1397
static int ehci_state_fetchitd(EHCIState *ehci, int async, int *state)
1398
{
1399
    EHCIitd itd;
1400

    
1401
    get_dwords(NLPTR_GET(ehci->itdaddr),(uint32_t *) &itd,
1402
               sizeof(EHCIitd) >> 2);
1403
    DPRINTF_ST("FETCHITD: Fetched ITD at address %08X " "(next is %08X)\n",
1404
               ehci->itdaddr, itd.next);
1405

    
1406
    if (ehci_process_itd(ehci, &itd) != 0) {
1407
        return -1;
1408
    }
1409

    
1410
    put_dwords(NLPTR_GET(ehci->itdaddr), (uint32_t *) &itd,
1411
                sizeof(EHCIitd) >> 2);
1412
    ehci->fetch_addr = itd.next;
1413
    *state = EST_FETCHENTRY;
1414

    
1415
    return 1;
1416
}
1417

    
1418
/* Section 4.10.2 - paragraph 3 */
1419
static int ehci_state_advqueue(EHCIState *ehci, int async, int *state)
1420
{
1421
#if 0
1422
    /* TO-DO: 4.10.2 - paragraph 2
1423
     * if I-bit is set to 1 and QH is not active
1424
     * go to horizontal QH
1425
     */
1426
    if (I-bit set) {
1427
        *state = EST_HORIZONTALQH;
1428
        goto out;
1429
    }
1430
#endif
1431

    
1432
    /*
1433
     * want data and alt-next qTD is valid
1434
     */
1435
    if (((ehci->qh.token & QTD_TOKEN_TBYTES_MASK) != 0) &&
1436
        (ehci->qh.altnext_qtd > 0x1000) &&
1437
        (NLPTR_TBIT(ehci->qh.altnext_qtd) == 0)) {
1438
        DPRINTF_ST("ADVQUEUE: goto alt next qTD. "
1439
                   "curr 0x%08x next 0x%08x alt 0x%08x (next qh %x)\n",
1440
                   ehci->qh.current_qtd, ehci->qh.altnext_qtd,
1441
                   ehci->qh.next_qtd, ehci->qh.next);
1442
        ehci->qtdaddr = ehci->qh.altnext_qtd;
1443
        *state = EST_FETCHQTD;
1444

    
1445
    /*
1446
     *  next qTD is valid
1447
     */
1448
    } else if ((ehci->qh.next_qtd > 0x1000) &&
1449
               (NLPTR_TBIT(ehci->qh.next_qtd) == 0)) {
1450
        DPRINTF_ST("ADVQUEUE: next qTD. "
1451
                   "curr 0x%08x next 0x%08x alt 0x%08x (next qh %x)\n",
1452
                   ehci->qh.current_qtd, ehci->qh.altnext_qtd,
1453
                   ehci->qh.next_qtd, ehci->qh.next);
1454
        ehci->qtdaddr = ehci->qh.next_qtd;
1455
        *state = EST_FETCHQTD;
1456

    
1457
    /*
1458
     *  no valid qTD, try next QH
1459
     */
1460
    } else {
1461
        DPRINTF_ST("ADVQUEUE: go to horizontal QH\n");
1462
        *state = EST_HORIZONTALQH;
1463
    }
1464

    
1465
    return 1;
1466
}
1467

    
1468
/* Section 4.10.2 - paragraph 4 */
1469
static int ehci_state_fetchqtd(EHCIState *ehci, int async, int *state)
1470
{
1471
    EHCIqtd *qtd = &ehci->qtd;
1472
    int again = 0;
1473

    
1474
    get_dwords(NLPTR_GET(ehci->qtdaddr),(uint32_t *) qtd, sizeof(EHCIqtd) >> 2);
1475

    
1476
    if (qtd->token & QTD_TOKEN_ACTIVE) {
1477
        *state = EST_EXECUTE;
1478
        again = 1;
1479
    } else {
1480
        *state = EST_HORIZONTALQH;
1481
        again = 1;
1482
    }
1483

    
1484
    return again;
1485
}
1486

    
1487
static int ehci_state_horizqh(EHCIState *ehci, int async, int *state)
1488
{
1489
    int again = 0;
1490

    
1491
    if (ehci->fetch_addr != ehci->qh.next) {
1492
        ehci->fetch_addr = ehci->qh.next;
1493
        *state = EST_FETCHENTRY;
1494
        again = 1;
1495
    } else {
1496
        *state = EST_ACTIVE;
1497
    }
1498

    
1499
    return again;
1500
}
1501

    
1502
static int ehci_state_execute(EHCIState *ehci, int async, int *state)
1503
{
1504
    EHCIqh *qh = &ehci->qh;
1505
    EHCIqtd *qtd = &ehci->qtd;
1506
    int again = 0;
1507
    int reload, nakcnt;
1508
    int smask;
1509

    
1510
    if (async) {
1511
        DPRINTF_ST(">>>>> ASYNC STATE MACHINE execute QH 0x%08x, QTD 0x%08x\n",
1512
                  ehci->qhaddr, ehci->qtdaddr);
1513
    } else {
1514
        DPRINTF_ST(">>>>> PERIODIC STATE MACHINE execute\n");
1515
    }
1516

    
1517
    if (ehci_qh_do_overlay(ehci, qh, qtd) != 0) {
1518
        return -1;
1519
    }
1520

    
1521
    smask = get_field(qh->epcap, QH_EPCAP_SMASK);
1522

    
1523
    if (!smask) {
1524
        reload = get_field(qh->epchar, QH_EPCHAR_RL);
1525
        nakcnt = get_field(qh->altnext_qtd, QH_ALTNEXT_NAKCNT);
1526
        if (reload && !nakcnt) {
1527
            DPRINTF_ST("EXECUTE: RL != 0 but NakCnt == 0 -- no execute\n");
1528
            *state = EST_HORIZONTALQH;
1529
            again = 1;
1530
            goto out;
1531
        }
1532
    }
1533

    
1534
    // TODO verify enough time remains in the uframe as in 4.4.1.1
1535
    // TODO write back ptr to async list when done or out of time
1536
    // TODO Windows does not seem to ever set the MULT field
1537

    
1538
    if (!async) {
1539
        int transactCtr = get_field(qh->epcap, QH_EPCAP_MULT);
1540
        if (!transactCtr) {
1541
            DPRINTF("ZERO transactctr for int qh, go HORIZ\n");
1542
            *state = EST_HORIZONTALQH;
1543
            again = 1;
1544
            goto out;
1545
        }
1546
    }
1547

    
1548
    if (async) {
1549
        ehci_set_usbsts(ehci, USBSTS_REC);
1550
    }
1551

    
1552
    ehci->exec_status = ehci_execute(ehci, qh);
1553
    if (ehci->exec_status == USB_RET_PROCERR) {
1554
        again = -1;
1555
        goto out;
1556
    }
1557
    *state = EST_EXECUTING;
1558

    
1559
    if (ehci->exec_status != USB_RET_ASYNC) {
1560
        again = 1;
1561
    }
1562

    
1563
out:
1564
    return again;
1565
}
1566

    
1567
static int ehci_state_executing(EHCIState *ehci, int async, int *state)
1568
{
1569
    EHCIqh *qh = &ehci->qh;
1570
    int again = 0;
1571
    int reload, nakcnt;
1572

    
1573
    ehci->exec_status = ehci_execute_complete(ehci, qh, ehci->exec_status);
1574
    if (ehci->exec_status == USB_RET_ASYNC) {
1575
        goto out;
1576
    }
1577
    if (ehci->exec_status == USB_RET_PROCERR) {
1578
        again = -1;
1579
        goto out;
1580
    }
1581

    
1582
    // 4.10.3
1583
    if (!async) {
1584
        int transactCtr = get_field(qh->epcap, QH_EPCAP_MULT);
1585
        transactCtr--;
1586
        set_field(&qh->epcap, transactCtr, QH_EPCAP_MULT);
1587
        // 4.10.3, bottom of page 82, should exit this state when transaction
1588
        // counter decrements to 0
1589
    }
1590

    
1591

    
1592
    reload = get_field(qh->epchar, QH_EPCHAR_RL);
1593
    if (reload) {
1594
        nakcnt = get_field(qh->altnext_qtd, QH_ALTNEXT_NAKCNT);
1595
        if (ehci->exec_status == USB_RET_NAK) {
1596
            if (nakcnt) {
1597
                nakcnt--;
1598
            }
1599
            DPRINTF_ST("EXECUTING: Nak occured and RL != 0, dec NakCnt to %d\n",
1600
                    nakcnt);
1601
        } else {
1602
            nakcnt = reload;
1603
            DPRINTF_ST("EXECUTING: Nak didn't occur, reloading to %d\n",
1604
                       nakcnt);
1605
        }
1606
        set_field(&qh->altnext_qtd, nakcnt, QH_ALTNEXT_NAKCNT);
1607
    }
1608

    
1609
    /*
1610
     *  Write the qh back to guest physical memory.  This step isn't
1611
     *  in the EHCI spec but we need to do it since we don't share
1612
     *  physical memory with our guest VM.
1613
     */
1614

    
1615
    DPRINTF("EXECUTING: write QH to VM memory: qhaddr 0x%x, next 0x%x\n",
1616
              ehci->qhaddr, qh->next);
1617
    put_dwords(NLPTR_GET(ehci->qhaddr), (uint32_t *) qh, sizeof(EHCIqh) >> 2);
1618

    
1619
    /* 4.10.5 */
1620
    if ((ehci->exec_status == USB_RET_NAK) || (qh->token & QTD_TOKEN_ACTIVE)) {
1621
        *state = EST_HORIZONTALQH;
1622
    } else {
1623
        *state = EST_WRITEBACK;
1624
    }
1625

    
1626
    again = 1;
1627

    
1628
out:
1629
    return again;
1630
}
1631

    
1632

    
1633
static int ehci_state_writeback(EHCIState *ehci, int async, int *state)
1634
{
1635
    EHCIqh *qh = &ehci->qh;
1636
    int again = 0;
1637

    
1638
    /*  Write back the QTD from the QH area */
1639
    DPRINTF_ST("WRITEBACK: write QTD to VM memory\n");
1640
    put_dwords(NLPTR_GET(ehci->qtdaddr),(uint32_t *) &qh->next_qtd,
1641
                sizeof(EHCIqtd) >> 2);
1642

    
1643
    /* TODO confirm next state.  For now, keep going if async
1644
     * but stop after one qtd if periodic
1645
     */
1646
    //if (async) {
1647
        *state = EST_ADVANCEQUEUE;
1648
        again = 1;
1649
    //} else {
1650
    //    *state = EST_ACTIVE;
1651
    //}
1652
    return again;
1653
}
1654

    
1655
/*
1656
 * This is the state machine that is common to both async and periodic
1657
 */
1658

    
1659
static int ehci_advance_state(EHCIState *ehci,
1660
                              int async,
1661
                              int state)
1662
{
1663
    int again;
1664
    int iter = 0;
1665

    
1666
    do {
1667
        if (state == EST_FETCHQH) {
1668
            iter++;
1669
            /* if we are roaming a lot of QH without executing a qTD
1670
             * something is wrong with the linked list. TO-DO: why is
1671
             * this hack needed?
1672
             */
1673
            if (iter > MAX_ITERATIONS) {
1674
                DPRINTF("\n*** advance_state: bailing on MAX ITERATIONS***\n");
1675
                state = EST_ACTIVE;
1676
                break;
1677
            }
1678
        }
1679
        switch(state) {
1680
        case EST_WAITLISTHEAD:
1681
            again = ehci_state_waitlisthead(ehci, async, &state);
1682
            break;
1683

    
1684
        case EST_FETCHENTRY:
1685
            again = ehci_state_fetchentry(ehci, async, &state);
1686
            break;
1687

    
1688
        case EST_FETCHQH:
1689
            again = ehci_state_fetchqh(ehci, async, &state);
1690
            break;
1691

    
1692
        case EST_FETCHITD:
1693
            again = ehci_state_fetchitd(ehci, async, &state);
1694
            break;
1695

    
1696
        case EST_ADVANCEQUEUE:
1697
            again = ehci_state_advqueue(ehci, async, &state);
1698
            break;
1699

    
1700
        case EST_FETCHQTD:
1701
            again = ehci_state_fetchqtd(ehci, async, &state);
1702
            break;
1703

    
1704
        case EST_HORIZONTALQH:
1705
            again = ehci_state_horizqh(ehci, async, &state);
1706
            break;
1707

    
1708
        case EST_EXECUTE:
1709
            iter = 0;
1710
            again = ehci_state_execute(ehci, async, &state);
1711
            break;
1712

    
1713
        case EST_EXECUTING:
1714
            again = ehci_state_executing(ehci, async, &state);
1715
            break;
1716

    
1717
        case EST_WRITEBACK:
1718
            again = ehci_state_writeback(ehci, async, &state);
1719
            break;
1720

    
1721
        default:
1722
            fprintf(stderr, "Bad state!\n");
1723
            again = -1;
1724
            break;
1725
        }
1726

    
1727
        if (again < 0) {
1728
            fprintf(stderr, "processing error - resetting ehci HC\n");
1729
            ehci_reset(ehci);
1730
            again = 0;
1731
        }
1732
    }
1733
    while (again);
1734

    
1735
    ehci_commit_interrupt(ehci);
1736
    return state;
1737
}
1738

    
1739
static void ehci_advance_async_state(EHCIState *ehci)
1740
{
1741
    EHCIqh qh;
1742
    int state = ehci->astate;
1743

    
1744
    switch(state) {
1745
    case EST_INACTIVE:
1746
        if (!(ehci->usbcmd & USBCMD_ASE)) {
1747
            break;
1748
        }
1749
        ehci_set_usbsts(ehci, USBSTS_ASS);
1750
        ehci->astate = EST_ACTIVE;
1751
        // No break, fall through to ACTIVE
1752

    
1753
    case EST_ACTIVE:
1754
        if ( !(ehci->usbcmd & USBCMD_ASE)) {
1755
            ehci_clear_usbsts(ehci, USBSTS_ASS);
1756
            ehci->astate = EST_INACTIVE;
1757
            break;
1758
        }
1759

    
1760
        /* If the doorbell is set, the guest wants to make a change to the
1761
         * schedule. The host controller needs to release cached data.
1762
         * (section 4.8.2)
1763
         */
1764
        if (ehci->usbcmd & USBCMD_IAAD) {
1765
            DPRINTF("ASYNC: doorbell request acknowledged\n");
1766
            ehci->usbcmd &= ~USBCMD_IAAD;
1767
            ehci_set_interrupt(ehci, USBSTS_IAA);
1768
            break;
1769
        }
1770

    
1771
        /* make sure guest has acknowledged */
1772
        /* TO-DO: is this really needed? */
1773
        if (ehci->usbsts & USBSTS_IAA) {
1774
            DPRINTF("IAA status bit still set.\n");
1775
            break;
1776
        }
1777

    
1778
        DPRINTF_ST("ASYNC: waiting for listhead, starting at %08x\n",
1779
                ehci->asynclistaddr);
1780
        /* check that address register has been set */
1781
        if (ehci->asynclistaddr == 0) {
1782
            break;
1783
        }
1784

    
1785
        state = EST_WAITLISTHEAD;
1786
        /* fall through */
1787

    
1788
    case EST_FETCHENTRY:
1789
        /* fall through */
1790

    
1791
    case EST_EXECUTING:
1792
        get_dwords(NLPTR_GET(ehci->qhaddr), (uint32_t *) &qh,
1793
                   sizeof(EHCIqh) >> 2);
1794
        ehci->astate = ehci_advance_state(ehci, 1, state);
1795
        break;
1796

    
1797
    default:
1798
        /* this should only be due to a developer mistake */
1799
        fprintf(stderr, "ehci: Bad asynchronous state %d. "
1800
                "Resetting to active\n", ehci->astate);
1801
        ehci->astate = EST_ACTIVE;
1802
    }
1803
}
1804

    
1805
static void ehci_advance_periodic_state(EHCIState *ehci)
1806
{
1807
    uint32_t entry;
1808
    uint32_t list;
1809

    
1810
    // 4.6
1811

    
1812
    switch(ehci->pstate) {
1813
    case EST_INACTIVE:
1814
        if ( !(ehci->frindex & 7) && (ehci->usbcmd & USBCMD_PSE)) {
1815
            ehci_set_usbsts(ehci, USBSTS_PSS);
1816
            ehci->pstate = EST_ACTIVE;
1817
            // No break, fall through to ACTIVE
1818
        } else
1819
            break;
1820

    
1821
    case EST_ACTIVE:
1822
        if ( !(ehci->frindex & 7) && !(ehci->usbcmd & USBCMD_PSE)) {
1823
            ehci_clear_usbsts(ehci, USBSTS_PSS);
1824
            ehci->pstate = EST_INACTIVE;
1825
            break;
1826
        }
1827

    
1828
        list = ehci->periodiclistbase & 0xfffff000;
1829
        /* check that register has been set */
1830
        if (list == 0) {
1831
            break;
1832
        }
1833
        list |= ((ehci->frindex & 0x1ff8) >> 1);
1834

    
1835
        cpu_physical_memory_rw(list, (uint8_t *) &entry, sizeof entry, 0);
1836
        entry = le32_to_cpu(entry);
1837

    
1838
        DPRINTF("PERIODIC state adv fr=%d.  [%08X] -> %08X\n",
1839
                ehci->frindex / 8, list, entry);
1840
        ehci->fetch_addr = entry;
1841
        ehci->pstate = ehci_advance_state(ehci, 0, EST_FETCHENTRY);
1842
        break;
1843

    
1844
    case EST_EXECUTING:
1845
        DPRINTF("PERIODIC state adv for executing\n");
1846
        ehci->pstate = ehci_advance_state(ehci, 0, EST_EXECUTING);
1847
        break;
1848

    
1849
    default:
1850
        /* this should only be due to a developer mistake */
1851
        fprintf(stderr, "ehci: Bad periodic state %d. "
1852
                "Resetting to active\n", ehci->pstate);
1853
        ehci->pstate = EST_ACTIVE;
1854
    }
1855
}
1856

    
1857
static void ehci_frame_timer(void *opaque)
1858
{
1859
    EHCIState *ehci = opaque;
1860
    int64_t expire_time, t_now;
1861
    int usec_elapsed;
1862
    int frames;
1863
    int usec_now;
1864
    int i;
1865
    int skipped_frames = 0;
1866

    
1867

    
1868
    t_now = qemu_get_clock_ns(vm_clock);
1869
    expire_time = t_now + (get_ticks_per_sec() / FRAME_TIMER_FREQ);
1870
    if (expire_time == t_now) {
1871
        expire_time++;
1872
    }
1873

    
1874
    usec_now = t_now / 1000;
1875
    usec_elapsed = usec_now - ehci->last_run_usec;
1876
    frames = usec_elapsed / FRAME_TIMER_USEC;
1877
    ehci->frame_end_usec = usec_now + FRAME_TIMER_USEC - 10;
1878

    
1879
    for (i = 0; i < frames; i++) {
1880
        if ( !(ehci->usbsts & USBSTS_HALT)) {
1881
            if (ehci->isoch_pause <= 0) {
1882
                ehci->frindex += 8;
1883
            }
1884

    
1885
            if (ehci->frindex > 0x00001fff) {
1886
                ehci->frindex = 0;
1887
                ehci_set_interrupt(ehci, USBSTS_FLR);
1888
            }
1889

    
1890
            ehci->sofv = (ehci->frindex - 1) >> 3;
1891
            ehci->sofv &= 0x000003ff;
1892
        }
1893

    
1894
        if (frames - i > 10) {
1895
            skipped_frames++;
1896
        } else {
1897
            // TODO could this cause periodic frames to get skipped if async
1898
            // active?
1899
            if (ehci->astate != EST_EXECUTING) {
1900
                ehci_advance_periodic_state(ehci);
1901
            }
1902
        }
1903

    
1904
        ehci->last_run_usec += FRAME_TIMER_USEC;
1905
    }
1906

    
1907
#if 0
1908
    if (skipped_frames) {
1909
        DPRINTF("WARNING - EHCI skipped %d frames\n", skipped_frames);
1910
    }
1911
#endif
1912

    
1913
    /*  Async is not inside loop since it executes everything it can once
1914
     *  called
1915
     */
1916
    if (ehci->pstate != EST_EXECUTING) {
1917
        ehci_advance_async_state(ehci);
1918
    }
1919

    
1920
    qemu_mod_timer(ehci->frame_timer, expire_time);
1921
}
1922

    
1923
static CPUReadMemoryFunc *ehci_readfn[3]={
1924
    ehci_mem_readb,
1925
    ehci_mem_readw,
1926
    ehci_mem_readl
1927
};
1928

    
1929
static CPUWriteMemoryFunc *ehci_writefn[3]={
1930
    ehci_mem_writeb,
1931
    ehci_mem_writew,
1932
    ehci_mem_writel
1933
};
1934

    
1935
static void ehci_map(PCIDevice *pci_dev, int region_num,
1936
                     pcibus_t addr, pcibus_t size, int type)
1937
{
1938
    EHCIState *s =(EHCIState *)pci_dev;
1939

    
1940
    DPRINTF("ehci_map: region %d, addr %08" PRIx64 ", size %" PRId64 ", s->mem %08X\n",
1941
            region_num, addr, size, s->mem);
1942
    s->mem_base = addr;
1943
    cpu_register_physical_memory(addr, size, s->mem);
1944
}
1945

    
1946
static int usb_ehci_initfn(PCIDevice *dev);
1947

    
1948
static USBPortOps ehci_port_ops = {
1949
    .attach = ehci_attach,
1950
    .detach = ehci_detach,
1951
    .complete = ehci_async_complete_packet,
1952
};
1953

    
1954
static PCIDeviceInfo ehci_info = {
1955
    .qdev.name    = "usb-ehci",
1956
    .qdev.size    = sizeof(EHCIState),
1957
    .init         = usb_ehci_initfn,
1958
};
1959

    
1960
static int usb_ehci_initfn(PCIDevice *dev)
1961
{
1962
    EHCIState *s = DO_UPCAST(EHCIState, dev, dev);
1963
    uint8_t *pci_conf = s->dev.config;
1964
    int i;
1965

    
1966
    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);
1967
    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_82801D);
1968
    pci_set_byte(&pci_conf[PCI_REVISION_ID], 0x10);
1969
    pci_set_byte(&pci_conf[PCI_CLASS_PROG], 0x20);
1970
    pci_config_set_class(pci_conf, PCI_CLASS_SERIAL_USB);
1971
    pci_set_byte(&pci_conf[PCI_HEADER_TYPE], PCI_HEADER_TYPE_NORMAL);
1972

    
1973
    /* capabilities pointer */
1974
    pci_set_byte(&pci_conf[PCI_CAPABILITY_LIST], 0x00);
1975
    //pci_set_byte(&pci_conf[PCI_CAPABILITY_LIST], 0x50);
1976

    
1977
    pci_set_byte(&pci_conf[PCI_INTERRUPT_PIN], 4); // interrupt pin 3
1978
    pci_set_byte(&pci_conf[PCI_MIN_GNT], 0);
1979
    pci_set_byte(&pci_conf[PCI_MAX_LAT], 0);
1980

    
1981
    // pci_conf[0x50] = 0x01; // power management caps
1982

    
1983
    pci_set_byte(&pci_conf[0x60], 0x20);  // spec release number (2.1.4)
1984
    pci_set_byte(&pci_conf[0x61], 0x20);  // frame length adjustment (2.1.5)
1985
    pci_set_word(&pci_conf[0x62], 0x00);  // port wake up capability (2.1.6)
1986

    
1987
    pci_conf[0x64] = 0x00;
1988
    pci_conf[0x65] = 0x00;
1989
    pci_conf[0x66] = 0x00;
1990
    pci_conf[0x67] = 0x00;
1991
    pci_conf[0x68] = 0x01;
1992
    pci_conf[0x69] = 0x00;
1993
    pci_conf[0x6a] = 0x00;
1994
    pci_conf[0x6b] = 0x00;  // USBLEGSUP
1995
    pci_conf[0x6c] = 0x00;
1996
    pci_conf[0x6d] = 0x00;
1997
    pci_conf[0x6e] = 0x00;
1998
    pci_conf[0x6f] = 0xc0;  // USBLEFCTLSTS
1999

    
2000
    // 2.2 host controller interface version
2001
    s->mmio[0x00] = (uint8_t) OPREGBASE;
2002
    s->mmio[0x01] = 0x00;
2003
    s->mmio[0x02] = 0x00;
2004
    s->mmio[0x03] = 0x01;        // HC version
2005
    s->mmio[0x04] = NB_PORTS;    // Number of downstream ports
2006
    s->mmio[0x05] = 0x00;        // No companion ports at present
2007
    s->mmio[0x06] = 0x00;
2008
    s->mmio[0x07] = 0x00;
2009
    s->mmio[0x08] = 0x80;        // We can cache whole frame, not 64-bit capable
2010
    s->mmio[0x09] = 0x68;        // EECP
2011
    s->mmio[0x0a] = 0x00;
2012
    s->mmio[0x0b] = 0x00;
2013

    
2014
    s->irq = s->dev.irq[3];
2015

    
2016
    usb_bus_new(&s->bus, &s->dev.qdev);
2017
    for(i = 0; i < NB_PORTS; i++) {
2018
        usb_register_port(&s->bus, &s->ports[i], s, i, &ehci_port_ops,
2019
                          USB_SPEED_MASK_HIGH);
2020
        usb_port_location(&s->ports[i], NULL, i+1);
2021
        s->ports[i].dev = 0;
2022
    }
2023

    
2024
    s->frame_timer = qemu_new_timer_ns(vm_clock, ehci_frame_timer, s);
2025

    
2026
    qemu_register_reset(ehci_reset, s);
2027

    
2028
    s->mem = cpu_register_io_memory(ehci_readfn, ehci_writefn, s,
2029
                                    DEVICE_LITTLE_ENDIAN);
2030

    
2031
    pci_register_bar(&s->dev, 0, MMIO_SIZE, PCI_BASE_ADDRESS_SPACE_MEMORY,
2032
                                                            ehci_map);
2033

    
2034
    fprintf(stderr, "*** EHCI support is under development ***\n");
2035

    
2036
    return 0;
2037
}
2038

    
2039
static void ehci_register(void)
2040
{
2041
    pci_qdev_register(&ehci_info);
2042
}
2043
device_init(ehci_register);
2044

    
2045
/*
2046
 * vim: expandtab ts=4
2047
 */