Statistics
| Branch: | Revision:

root / hw / usb-uhci.c @ a0a3167a

History | View | Annotate | Download (30.9 kB)

1
/*
2
 * USB UHCI controller emulation
3
 *
4
 * Copyright (c) 2005 Fabrice Bellard
5
 *
6
 * Copyright (c) 2008 Max Krasnyansky
7
 *     Magor rewrite of the UHCI data structures parser and frame processor
8
 *     Support for fully async operation and multiple outstanding transactions
9
 *
10
 * Permission is hereby granted, free of charge, to any person obtaining a copy
11
 * of this software and associated documentation files (the "Software"), to deal
12
 * in the Software without restriction, including without limitation the rights
13
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
 * copies of the Software, and to permit persons to whom the Software is
15
 * furnished to do so, subject to the following conditions:
16
 *
17
 * The above copyright notice and this permission notice shall be included in
18
 * all copies or substantial portions of the Software.
19
 *
20
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
 * THE SOFTWARE.
27
 */
28
#include "hw.h"
29
#include "usb.h"
30
#include "pci.h"
31
#include "qemu-timer.h"
32
#include "usb-uhci.h"
33

    
34
//#define DEBUG
35
//#define DEBUG_DUMP_DATA
36

    
37
#define UHCI_CMD_FGR      (1 << 4)
38
#define UHCI_CMD_EGSM     (1 << 3)
39
#define UHCI_CMD_GRESET   (1 << 2)
40
#define UHCI_CMD_HCRESET  (1 << 1)
41
#define UHCI_CMD_RS       (1 << 0)
42

    
43
#define UHCI_STS_HCHALTED (1 << 5)
44
#define UHCI_STS_HCPERR   (1 << 4)
45
#define UHCI_STS_HSERR    (1 << 3)
46
#define UHCI_STS_RD       (1 << 2)
47
#define UHCI_STS_USBERR   (1 << 1)
48
#define UHCI_STS_USBINT   (1 << 0)
49

    
50
#define TD_CTRL_SPD     (1 << 29)
51
#define TD_CTRL_ERROR_SHIFT  27
52
#define TD_CTRL_IOS     (1 << 25)
53
#define TD_CTRL_IOC     (1 << 24)
54
#define TD_CTRL_ACTIVE  (1 << 23)
55
#define TD_CTRL_STALL   (1 << 22)
56
#define TD_CTRL_BABBLE  (1 << 20)
57
#define TD_CTRL_NAK     (1 << 19)
58
#define TD_CTRL_TIMEOUT (1 << 18)
59

    
60
#define UHCI_PORT_SUSPEND (1 << 12)
61
#define UHCI_PORT_RESET (1 << 9)
62
#define UHCI_PORT_LSDA  (1 << 8)
63
#define UHCI_PORT_RD    (1 << 6)
64
#define UHCI_PORT_ENC   (1 << 3)
65
#define UHCI_PORT_EN    (1 << 2)
66
#define UHCI_PORT_CSC   (1 << 1)
67
#define UHCI_PORT_CCS   (1 << 0)
68

    
69
#define UHCI_PORT_READ_ONLY    (0x1bb)
70
#define UHCI_PORT_WRITE_CLEAR  (UHCI_PORT_CSC | UHCI_PORT_ENC)
71

    
72
#define FRAME_TIMER_FREQ 1000
73

    
74
#define FRAME_MAX_LOOPS  100
75

    
76
#define NB_PORTS 2
77

    
78
#ifdef DEBUG
79
#define DPRINTF printf
80

    
81
static const char *pid2str(int pid)
82
{
83
    switch (pid) {
84
    case USB_TOKEN_SETUP: return "SETUP";
85
    case USB_TOKEN_IN:    return "IN";
86
    case USB_TOKEN_OUT:   return "OUT";
87
    }
88
    return "?";
89
}
90

    
91
#else
92
#define DPRINTF(...)
93
#endif
94

    
95
#ifdef DEBUG_DUMP_DATA
96
static void dump_data(const uint8_t *data, int len)
97
{
98
    int i;
99

    
100
    printf("uhci: data: ");
101
    for(i = 0; i < len; i++)
102
        printf(" %02x", data[i]);
103
    printf("\n");
104
}
105
#else
106
static void dump_data(const uint8_t *data, int len) {}
107
#endif
108

    
109
typedef struct UHCIState UHCIState;
110

    
111
/* 
112
 * Pending async transaction.
113
 * 'packet' must be the first field because completion
114
 * handler does "(UHCIAsync *) pkt" cast.
115
 */
116
typedef struct UHCIAsync {
117
    USBPacket packet;
118
    UHCIState *uhci;
119
    QTAILQ_ENTRY(UHCIAsync) next;
120
    uint32_t  td;
121
    uint32_t  token;
122
    int8_t    valid;
123
    uint8_t   isoc;
124
    uint8_t   done;
125
    uint8_t   buffer[2048];
126
} UHCIAsync;
127

    
128
typedef struct UHCIPort {
129
    USBPort port;
130
    uint16_t ctrl;
131
} UHCIPort;
132

    
133
struct UHCIState {
134
    PCIDevice dev;
135
    USBBus bus;
136
    uint16_t cmd; /* cmd register */
137
    uint16_t status;
138
    uint16_t intr; /* interrupt enable register */
139
    uint16_t frnum; /* frame number */
140
    uint32_t fl_base_addr; /* frame list base address */
141
    uint8_t sof_timing;
142
    uint8_t status2; /* bit 0 and 1 are used to generate UHCI_STS_USBINT */
143
    int64_t expire_time;
144
    QEMUTimer *frame_timer;
145
    UHCIPort ports[NB_PORTS];
146

    
147
    /* Interrupts that should be raised at the end of the current frame.  */
148
    uint32_t pending_int_mask;
149

    
150
    /* Active packets */
151
    QTAILQ_HEAD(,UHCIAsync) async_pending;
152
    uint8_t num_ports_vmstate;
153
};
154

    
155
typedef struct UHCI_TD {
156
    uint32_t link;
157
    uint32_t ctrl; /* see TD_CTRL_xxx */
158
    uint32_t token;
159
    uint32_t buffer;
160
} UHCI_TD;
161

    
162
typedef struct UHCI_QH {
163
    uint32_t link;
164
    uint32_t el_link;
165
} UHCI_QH;
166

    
167
static UHCIAsync *uhci_async_alloc(UHCIState *s)
168
{
169
    UHCIAsync *async = qemu_malloc(sizeof(UHCIAsync));
170

    
171
    memset(&async->packet, 0, sizeof(async->packet));
172
    async->uhci  = s;
173
    async->valid = 0;
174
    async->td    = 0;
175
    async->token = 0;
176
    async->done  = 0;
177
    async->isoc  = 0;
178

    
179
    return async;
180
}
181

    
182
static void uhci_async_free(UHCIState *s, UHCIAsync *async)
183
{
184
    qemu_free(async);
185
}
186

    
187
static void uhci_async_link(UHCIState *s, UHCIAsync *async)
188
{
189
    QTAILQ_INSERT_HEAD(&s->async_pending, async, next);
190
}
191

    
192
static void uhci_async_unlink(UHCIState *s, UHCIAsync *async)
193
{
194
    QTAILQ_REMOVE(&s->async_pending, async, next);
195
}
196

    
197
static void uhci_async_cancel(UHCIState *s, UHCIAsync *async)
198
{
199
    DPRINTF("uhci: cancel td 0x%x token 0x%x done %u\n",
200
           async->td, async->token, async->done);
201

    
202
    if (!async->done)
203
        usb_cancel_packet(&async->packet);
204
    uhci_async_free(s, async);
205
}
206

    
207
/*
208
 * Mark all outstanding async packets as invalid.
209
 * This is used for canceling them when TDs are removed by the HCD.
210
 */
211
static UHCIAsync *uhci_async_validate_begin(UHCIState *s)
212
{
213
    UHCIAsync *async;
214

    
215
    QTAILQ_FOREACH(async, &s->async_pending, next) {
216
        async->valid--;
217
    }
218
    return NULL;
219
}
220

    
221
/*
222
 * Cancel async packets that are no longer valid
223
 */
224
static void uhci_async_validate_end(UHCIState *s)
225
{
226
    UHCIAsync *curr, *n;
227

    
228
    QTAILQ_FOREACH_SAFE(curr, &s->async_pending, next, n) {
229
        if (curr->valid > 0) {
230
            continue;
231
        }
232
        uhci_async_unlink(s, curr);
233
        uhci_async_cancel(s, curr);
234
    }
235
}
236

    
237
static void uhci_async_cancel_device(UHCIState *s, USBDevice *dev)
238
{
239
    UHCIAsync *curr, *n;
240

    
241
    QTAILQ_FOREACH_SAFE(curr, &s->async_pending, next, n) {
242
        if (curr->packet.owner != dev) {
243
            continue;
244
        }
245
        uhci_async_unlink(s, curr);
246
        uhci_async_cancel(s, curr);
247
    }
248
}
249

    
250
static void uhci_async_cancel_all(UHCIState *s)
251
{
252
    UHCIAsync *curr, *n;
253

    
254
    QTAILQ_FOREACH_SAFE(curr, &s->async_pending, next, n) {
255
        uhci_async_unlink(s, curr);
256
        uhci_async_cancel(s, curr);
257
    }
258
}
259

    
260
static UHCIAsync *uhci_async_find_td(UHCIState *s, uint32_t addr, uint32_t token)
261
{
262
    UHCIAsync *async;
263
    UHCIAsync *match = NULL;
264
    int count = 0;
265

    
266
    /*
267
     * We're looking for the best match here. ie both td addr and token.
268
     * Otherwise we return last good match. ie just token.
269
     * It's ok to match just token because it identifies the transaction
270
     * rather well, token includes: device addr, endpoint, size, etc.
271
     *
272
     * Also since we queue async transactions in reverse order by returning
273
     * last good match we restores the order.
274
     *
275
     * It's expected that we wont have a ton of outstanding transactions.
276
     * If we ever do we'd want to optimize this algorithm.
277
     */
278

    
279
    QTAILQ_FOREACH(async, &s->async_pending, next) {
280
        if (async->token == token) {
281
            /* Good match */
282
            match = async;
283

    
284
            if (async->td == addr) {
285
                /* Best match */
286
                break;
287
            }
288
        }
289
        count++;
290
    }
291

    
292
    if (count > 64)
293
        fprintf(stderr, "uhci: warning lots of async transactions\n");
294

    
295
    return match;
296
}
297

    
298
static void uhci_update_irq(UHCIState *s)
299
{
300
    int level;
301
    if (((s->status2 & 1) && (s->intr & (1 << 2))) ||
302
        ((s->status2 & 2) && (s->intr & (1 << 3))) ||
303
        ((s->status & UHCI_STS_USBERR) && (s->intr & (1 << 0))) ||
304
        ((s->status & UHCI_STS_RD) && (s->intr & (1 << 1))) ||
305
        (s->status & UHCI_STS_HSERR) ||
306
        (s->status & UHCI_STS_HCPERR)) {
307
        level = 1;
308
    } else {
309
        level = 0;
310
    }
311
    qemu_set_irq(s->dev.irq[3], level);
312
}
313

    
314
static void uhci_reset(void *opaque)
315
{
316
    UHCIState *s = opaque;
317
    uint8_t *pci_conf;
318
    int i;
319
    UHCIPort *port;
320

    
321
    DPRINTF("uhci: full reset\n");
322

    
323
    pci_conf = s->dev.config;
324

    
325
    pci_conf[0x6a] = 0x01; /* usb clock */
326
    pci_conf[0x6b] = 0x00;
327
    s->cmd = 0;
328
    s->status = 0;
329
    s->status2 = 0;
330
    s->intr = 0;
331
    s->fl_base_addr = 0;
332
    s->sof_timing = 64;
333

    
334
    for(i = 0; i < NB_PORTS; i++) {
335
        port = &s->ports[i];
336
        port->ctrl = 0x0080;
337
        if (port->port.dev) {
338
            usb_attach(&port->port, port->port.dev);
339
        }
340
    }
341

    
342
    uhci_async_cancel_all(s);
343
}
344

    
345
static void uhci_pre_save(void *opaque)
346
{
347
    UHCIState *s = opaque;
348

    
349
    uhci_async_cancel_all(s);
350
}
351

    
352
static const VMStateDescription vmstate_uhci_port = {
353
    .name = "uhci port",
354
    .version_id = 1,
355
    .minimum_version_id = 1,
356
    .minimum_version_id_old = 1,
357
    .fields      = (VMStateField []) {
358
        VMSTATE_UINT16(ctrl, UHCIPort),
359
        VMSTATE_END_OF_LIST()
360
    }
361
};
362

    
363
static const VMStateDescription vmstate_uhci = {
364
    .name = "uhci",
365
    .version_id = 2,
366
    .minimum_version_id = 1,
367
    .minimum_version_id_old = 1,
368
    .pre_save = uhci_pre_save,
369
    .fields      = (VMStateField []) {
370
        VMSTATE_PCI_DEVICE(dev, UHCIState),
371
        VMSTATE_UINT8_EQUAL(num_ports_vmstate, UHCIState),
372
        VMSTATE_STRUCT_ARRAY(ports, UHCIState, NB_PORTS, 1,
373
                             vmstate_uhci_port, UHCIPort),
374
        VMSTATE_UINT16(cmd, UHCIState),
375
        VMSTATE_UINT16(status, UHCIState),
376
        VMSTATE_UINT16(intr, UHCIState),
377
        VMSTATE_UINT16(frnum, UHCIState),
378
        VMSTATE_UINT32(fl_base_addr, UHCIState),
379
        VMSTATE_UINT8(sof_timing, UHCIState),
380
        VMSTATE_UINT8(status2, UHCIState),
381
        VMSTATE_TIMER(frame_timer, UHCIState),
382
        VMSTATE_INT64_V(expire_time, UHCIState, 2),
383
        VMSTATE_END_OF_LIST()
384
    }
385
};
386

    
387
static void uhci_ioport_writeb(void *opaque, uint32_t addr, uint32_t val)
388
{
389
    UHCIState *s = opaque;
390

    
391
    addr &= 0x1f;
392
    switch(addr) {
393
    case 0x0c:
394
        s->sof_timing = val;
395
        break;
396
    }
397
}
398

    
399
static uint32_t uhci_ioport_readb(void *opaque, uint32_t addr)
400
{
401
    UHCIState *s = opaque;
402
    uint32_t val;
403

    
404
    addr &= 0x1f;
405
    switch(addr) {
406
    case 0x0c:
407
        val = s->sof_timing;
408
        break;
409
    default:
410
        val = 0xff;
411
        break;
412
    }
413
    return val;
414
}
415

    
416
static void uhci_ioport_writew(void *opaque, uint32_t addr, uint32_t val)
417
{
418
    UHCIState *s = opaque;
419

    
420
    addr &= 0x1f;
421
    DPRINTF("uhci: writew port=0x%04x val=0x%04x\n", addr, val);
422

    
423
    switch(addr) {
424
    case 0x00:
425
        if ((val & UHCI_CMD_RS) && !(s->cmd & UHCI_CMD_RS)) {
426
            /* start frame processing */
427
            s->expire_time = qemu_get_clock_ns(vm_clock) +
428
                (get_ticks_per_sec() / FRAME_TIMER_FREQ);
429
            qemu_mod_timer(s->frame_timer, qemu_get_clock_ns(vm_clock));
430
            s->status &= ~UHCI_STS_HCHALTED;
431
        } else if (!(val & UHCI_CMD_RS)) {
432
            s->status |= UHCI_STS_HCHALTED;
433
        }
434
        if (val & UHCI_CMD_GRESET) {
435
            UHCIPort *port;
436
            USBDevice *dev;
437
            int i;
438

    
439
            /* send reset on the USB bus */
440
            for(i = 0; i < NB_PORTS; i++) {
441
                port = &s->ports[i];
442
                dev = port->port.dev;
443
                if (dev) {
444
                    usb_send_msg(dev, USB_MSG_RESET);
445
                }
446
            }
447
            uhci_reset(s);
448
            return;
449
        }
450
        if (val & UHCI_CMD_HCRESET) {
451
            uhci_reset(s);
452
            return;
453
        }
454
        s->cmd = val;
455
        break;
456
    case 0x02:
457
        s->status &= ~val;
458
        /* XXX: the chip spec is not coherent, so we add a hidden
459
           register to distinguish between IOC and SPD */
460
        if (val & UHCI_STS_USBINT)
461
            s->status2 = 0;
462
        uhci_update_irq(s);
463
        break;
464
    case 0x04:
465
        s->intr = val;
466
        uhci_update_irq(s);
467
        break;
468
    case 0x06:
469
        if (s->status & UHCI_STS_HCHALTED)
470
            s->frnum = val & 0x7ff;
471
        break;
472
    case 0x10 ... 0x1f:
473
        {
474
            UHCIPort *port;
475
            USBDevice *dev;
476
            int n;
477

    
478
            n = (addr >> 1) & 7;
479
            if (n >= NB_PORTS)
480
                return;
481
            port = &s->ports[n];
482
            dev = port->port.dev;
483
            if (dev) {
484
                /* port reset */
485
                if ( (val & UHCI_PORT_RESET) &&
486
                     !(port->ctrl & UHCI_PORT_RESET) ) {
487
                    usb_send_msg(dev, USB_MSG_RESET);
488
                }
489
            }
490
            port->ctrl &= UHCI_PORT_READ_ONLY;
491
            port->ctrl |= (val & ~UHCI_PORT_READ_ONLY);
492
            /* some bits are reset when a '1' is written to them */
493
            port->ctrl &= ~(val & UHCI_PORT_WRITE_CLEAR);
494
        }
495
        break;
496
    }
497
}
498

    
499
static uint32_t uhci_ioport_readw(void *opaque, uint32_t addr)
500
{
501
    UHCIState *s = opaque;
502
    uint32_t val;
503

    
504
    addr &= 0x1f;
505
    switch(addr) {
506
    case 0x00:
507
        val = s->cmd;
508
        break;
509
    case 0x02:
510
        val = s->status;
511
        break;
512
    case 0x04:
513
        val = s->intr;
514
        break;
515
    case 0x06:
516
        val = s->frnum;
517
        break;
518
    case 0x10 ... 0x1f:
519
        {
520
            UHCIPort *port;
521
            int n;
522
            n = (addr >> 1) & 7;
523
            if (n >= NB_PORTS)
524
                goto read_default;
525
            port = &s->ports[n];
526
            val = port->ctrl;
527
        }
528
        break;
529
    default:
530
    read_default:
531
        val = 0xff7f; /* disabled port */
532
        break;
533
    }
534

    
535
    DPRINTF("uhci: readw port=0x%04x val=0x%04x\n", addr, val);
536

    
537
    return val;
538
}
539

    
540
static void uhci_ioport_writel(void *opaque, uint32_t addr, uint32_t val)
541
{
542
    UHCIState *s = opaque;
543

    
544
    addr &= 0x1f;
545
    DPRINTF("uhci: writel port=0x%04x val=0x%08x\n", addr, val);
546

    
547
    switch(addr) {
548
    case 0x08:
549
        s->fl_base_addr = val & ~0xfff;
550
        break;
551
    }
552
}
553

    
554
static uint32_t uhci_ioport_readl(void *opaque, uint32_t addr)
555
{
556
    UHCIState *s = opaque;
557
    uint32_t val;
558

    
559
    addr &= 0x1f;
560
    switch(addr) {
561
    case 0x08:
562
        val = s->fl_base_addr;
563
        break;
564
    default:
565
        val = 0xffffffff;
566
        break;
567
    }
568
    return val;
569
}
570

    
571
/* signal resume if controller suspended */
572
static void uhci_resume (void *opaque)
573
{
574
    UHCIState *s = (UHCIState *)opaque;
575

    
576
    if (!s)
577
        return;
578

    
579
    if (s->cmd & UHCI_CMD_EGSM) {
580
        s->cmd |= UHCI_CMD_FGR;
581
        s->status |= UHCI_STS_RD;
582
        uhci_update_irq(s);
583
    }
584
}
585

    
586
static void uhci_attach(USBPort *port1)
587
{
588
    UHCIState *s = port1->opaque;
589
    UHCIPort *port = &s->ports[port1->index];
590

    
591
    /* set connect status */
592
    port->ctrl |= UHCI_PORT_CCS | UHCI_PORT_CSC;
593

    
594
    /* update speed */
595
    if (port->port.dev->speed == USB_SPEED_LOW) {
596
        port->ctrl |= UHCI_PORT_LSDA;
597
    } else {
598
        port->ctrl &= ~UHCI_PORT_LSDA;
599
    }
600

    
601
    uhci_resume(s);
602
}
603

    
604
static void uhci_detach(USBPort *port1)
605
{
606
    UHCIState *s = port1->opaque;
607
    UHCIPort *port = &s->ports[port1->index];
608

    
609
    uhci_async_cancel_device(s, port1->dev);
610

    
611
    /* set connect status */
612
    if (port->ctrl & UHCI_PORT_CCS) {
613
        port->ctrl &= ~UHCI_PORT_CCS;
614
        port->ctrl |= UHCI_PORT_CSC;
615
    }
616
    /* disable port */
617
    if (port->ctrl & UHCI_PORT_EN) {
618
        port->ctrl &= ~UHCI_PORT_EN;
619
        port->ctrl |= UHCI_PORT_ENC;
620
    }
621

    
622
    uhci_resume(s);
623
}
624

    
625
static void uhci_child_detach(USBPort *port1, USBDevice *child)
626
{
627
    UHCIState *s = port1->opaque;
628

    
629
    uhci_async_cancel_device(s, child);
630
}
631

    
632
static void uhci_wakeup(USBPort *port1)
633
{
634
    UHCIState *s = port1->opaque;
635
    UHCIPort *port = &s->ports[port1->index];
636

    
637
    if (port->ctrl & UHCI_PORT_SUSPEND && !(port->ctrl & UHCI_PORT_RD)) {
638
        port->ctrl |= UHCI_PORT_RD;
639
        uhci_resume(s);
640
    }
641
}
642

    
643
static int uhci_broadcast_packet(UHCIState *s, USBPacket *p)
644
{
645
    int i, ret;
646

    
647
    DPRINTF("uhci: packet enter. pid %s addr 0x%02x ep %d len %d\n",
648
           pid2str(p->pid), p->devaddr, p->devep, p->len);
649
    if (p->pid == USB_TOKEN_OUT || p->pid == USB_TOKEN_SETUP)
650
        dump_data(p->data, p->len);
651

    
652
    ret = USB_RET_NODEV;
653
    for (i = 0; i < NB_PORTS && ret == USB_RET_NODEV; i++) {
654
        UHCIPort *port = &s->ports[i];
655
        USBDevice *dev = port->port.dev;
656

    
657
        if (dev && (port->ctrl & UHCI_PORT_EN))
658
            ret = usb_handle_packet(dev, p);
659
    }
660

    
661
    DPRINTF("uhci: packet exit. ret %d len %d\n", ret, p->len);
662
    if (p->pid == USB_TOKEN_IN && ret > 0)
663
        dump_data(p->data, ret);
664

    
665
    return ret;
666
}
667

    
668
static void uhci_async_complete(USBPort *port, USBPacket *packet);
669
static void uhci_process_frame(UHCIState *s);
670

    
671
/* return -1 if fatal error (frame must be stopped)
672
          0 if TD successful
673
          1 if TD unsuccessful or inactive
674
*/
675
static int uhci_complete_td(UHCIState *s, UHCI_TD *td, UHCIAsync *async, uint32_t *int_mask)
676
{
677
    int len = 0, max_len, err, ret;
678
    uint8_t pid;
679

    
680
    max_len = ((td->token >> 21) + 1) & 0x7ff;
681
    pid = td->token & 0xff;
682

    
683
    ret = async->packet.len;
684

    
685
    if (td->ctrl & TD_CTRL_IOS)
686
        td->ctrl &= ~TD_CTRL_ACTIVE;
687

    
688
    if (ret < 0)
689
        goto out;
690

    
691
    len = async->packet.len;
692
    td->ctrl = (td->ctrl & ~0x7ff) | ((len - 1) & 0x7ff);
693

    
694
    /* The NAK bit may have been set by a previous frame, so clear it
695
       here.  The docs are somewhat unclear, but win2k relies on this
696
       behavior.  */
697
    td->ctrl &= ~(TD_CTRL_ACTIVE | TD_CTRL_NAK);
698
    if (td->ctrl & TD_CTRL_IOC)
699
        *int_mask |= 0x01;
700

    
701
    if (pid == USB_TOKEN_IN) {
702
        if (len > max_len) {
703
            ret = USB_RET_BABBLE;
704
            goto out;
705
        }
706

    
707
        if (len > 0) {
708
            /* write the data back */
709
            cpu_physical_memory_write(td->buffer, async->buffer, len);
710
        }
711

    
712
        if ((td->ctrl & TD_CTRL_SPD) && len < max_len) {
713
            *int_mask |= 0x02;
714
            /* short packet: do not update QH */
715
            DPRINTF("uhci: short packet. td 0x%x token 0x%x\n", async->td, async->token);
716
            return 1;
717
        }
718
    }
719

    
720
    /* success */
721
    return 0;
722

    
723
out:
724
    switch(ret) {
725
    case USB_RET_STALL:
726
        td->ctrl |= TD_CTRL_STALL;
727
        td->ctrl &= ~TD_CTRL_ACTIVE;
728
        s->status |= UHCI_STS_USBERR;
729
        uhci_update_irq(s);
730
        return 1;
731

    
732
    case USB_RET_BABBLE:
733
        td->ctrl |= TD_CTRL_BABBLE | TD_CTRL_STALL;
734
        td->ctrl &= ~TD_CTRL_ACTIVE;
735
        s->status |= UHCI_STS_USBERR;
736
        uhci_update_irq(s);
737
        /* frame interrupted */
738
        return -1;
739

    
740
    case USB_RET_NAK:
741
        td->ctrl |= TD_CTRL_NAK;
742
        if (pid == USB_TOKEN_SETUP)
743
            break;
744
        return 1;
745

    
746
    case USB_RET_NODEV:
747
    default:
748
        break;
749
    }
750

    
751
    /* Retry the TD if error count is not zero */
752

    
753
    td->ctrl |= TD_CTRL_TIMEOUT;
754
    err = (td->ctrl >> TD_CTRL_ERROR_SHIFT) & 3;
755
    if (err != 0) {
756
        err--;
757
        if (err == 0) {
758
            td->ctrl &= ~TD_CTRL_ACTIVE;
759
            s->status |= UHCI_STS_USBERR;
760
            if (td->ctrl & TD_CTRL_IOC)
761
                *int_mask |= 0x01;
762
            uhci_update_irq(s);
763
        }
764
    }
765
    td->ctrl = (td->ctrl & ~(3 << TD_CTRL_ERROR_SHIFT)) |
766
        (err << TD_CTRL_ERROR_SHIFT);
767
    return 1;
768
}
769

    
770
static int uhci_handle_td(UHCIState *s, uint32_t addr, UHCI_TD *td, uint32_t *int_mask)
771
{
772
    UHCIAsync *async;
773
    int len = 0, max_len;
774
    uint8_t pid, isoc;
775
    uint32_t token;
776

    
777
    /* Is active ? */
778
    if (!(td->ctrl & TD_CTRL_ACTIVE))
779
        return 1;
780

    
781
    /* token field is not unique for isochronous requests,
782
     * so use the destination buffer 
783
     */
784
    if (td->ctrl & TD_CTRL_IOS) {
785
        token = td->buffer;
786
        isoc = 1;
787
    } else {
788
        token = td->token;
789
        isoc = 0;
790
    }
791

    
792
    async = uhci_async_find_td(s, addr, token);
793
    if (async) {
794
        /* Already submitted */
795
        async->valid = 32;
796

    
797
        if (!async->done)
798
            return 1;
799

    
800
        uhci_async_unlink(s, async);
801
        goto done;
802
    }
803

    
804
    /* Allocate new packet */
805
    async = uhci_async_alloc(s);
806
    if (!async)
807
        return 1;
808

    
809
    /* valid needs to be large enough to handle 10 frame delay
810
     * for initial isochronous requests
811
     */
812
    async->valid = 32;
813
    async->td    = addr;
814
    async->token = token;
815
    async->isoc  = isoc;
816

    
817
    max_len = ((td->token >> 21) + 1) & 0x7ff;
818
    pid = td->token & 0xff;
819

    
820
    async->packet.pid     = pid;
821
    async->packet.devaddr = (td->token >> 8) & 0x7f;
822
    async->packet.devep   = (td->token >> 15) & 0xf;
823
    async->packet.data    = async->buffer;
824
    async->packet.len     = max_len;
825

    
826
    switch(pid) {
827
    case USB_TOKEN_OUT:
828
    case USB_TOKEN_SETUP:
829
        cpu_physical_memory_read(td->buffer, async->buffer, max_len);
830
        len = uhci_broadcast_packet(s, &async->packet);
831
        if (len >= 0)
832
            len = max_len;
833
        break;
834

    
835
    case USB_TOKEN_IN:
836
        len = uhci_broadcast_packet(s, &async->packet);
837
        break;
838

    
839
    default:
840
        /* invalid pid : frame interrupted */
841
        uhci_async_free(s, async);
842
        s->status |= UHCI_STS_HCPERR;
843
        uhci_update_irq(s);
844
        return -1;
845
    }
846
 
847
    if (len == USB_RET_ASYNC) {
848
        uhci_async_link(s, async);
849
        return 2;
850
    }
851

    
852
    async->packet.len = len;
853

    
854
done:
855
    len = uhci_complete_td(s, td, async, int_mask);
856
    uhci_async_free(s, async);
857
    return len;
858
}
859

    
860
static void uhci_async_complete(USBPort *port, USBPacket *packet)
861
{
862
    UHCIAsync *async = container_of(packet, UHCIAsync, packet);
863
    UHCIState *s = async->uhci;
864

    
865
    DPRINTF("uhci: async complete. td 0x%x token 0x%x\n", async->td, async->token);
866

    
867
    if (async->isoc) {
868
        UHCI_TD td;
869
        uint32_t link = async->td;
870
        uint32_t int_mask = 0, val;
871

    
872
        cpu_physical_memory_read(link & ~0xf, (uint8_t *) &td, sizeof(td));
873
        le32_to_cpus(&td.link);
874
        le32_to_cpus(&td.ctrl);
875
        le32_to_cpus(&td.token);
876
        le32_to_cpus(&td.buffer);
877

    
878
        uhci_async_unlink(s, async);
879
        uhci_complete_td(s, &td, async, &int_mask);
880
        s->pending_int_mask |= int_mask;
881

    
882
        /* update the status bits of the TD */
883
        val = cpu_to_le32(td.ctrl);
884
        cpu_physical_memory_write((link & ~0xf) + 4,
885
                                  (const uint8_t *)&val, sizeof(val));
886
        uhci_async_free(s, async);
887
    } else {
888
        async->done = 1;
889
        uhci_process_frame(s);
890
    }
891
}
892

    
893
static int is_valid(uint32_t link)
894
{
895
    return (link & 1) == 0;
896
}
897

    
898
static int is_qh(uint32_t link)
899
{
900
    return (link & 2) != 0;
901
}
902

    
903
static int depth_first(uint32_t link)
904
{
905
    return (link & 4) != 0;
906
}
907

    
908
/* QH DB used for detecting QH loops */
909
#define UHCI_MAX_QUEUES 128
910
typedef struct {
911
    uint32_t addr[UHCI_MAX_QUEUES];
912
    int      count;
913
} QhDb;
914

    
915
static void qhdb_reset(QhDb *db)
916
{
917
    db->count = 0;
918
}
919

    
920
/* Add QH to DB. Returns 1 if already present or DB is full. */
921
static int qhdb_insert(QhDb *db, uint32_t addr)
922
{
923
    int i;
924
    for (i = 0; i < db->count; i++)
925
        if (db->addr[i] == addr)
926
            return 1;
927

    
928
    if (db->count >= UHCI_MAX_QUEUES)
929
        return 1;
930

    
931
    db->addr[db->count++] = addr;
932
    return 0;
933
}
934

    
935
static void uhci_process_frame(UHCIState *s)
936
{
937
    uint32_t frame_addr, link, old_td_ctrl, val, int_mask;
938
    uint32_t curr_qh;
939
    int cnt, ret;
940
    UHCI_TD td;
941
    UHCI_QH qh;
942
    QhDb qhdb;
943

    
944
    frame_addr = s->fl_base_addr + ((s->frnum & 0x3ff) << 2);
945

    
946
    DPRINTF("uhci: processing frame %d addr 0x%x\n" , s->frnum, frame_addr);
947

    
948
    cpu_physical_memory_read(frame_addr, (uint8_t *)&link, 4);
949
    le32_to_cpus(&link);
950

    
951
    int_mask = 0;
952
    curr_qh  = 0;
953

    
954
    qhdb_reset(&qhdb);
955

    
956
    for (cnt = FRAME_MAX_LOOPS; is_valid(link) && cnt; cnt--) {
957
        if (is_qh(link)) {
958
            /* QH */
959

    
960
            if (qhdb_insert(&qhdb, link)) {
961
                /*
962
                 * We're going in circles. Which is not a bug because
963
                 * HCD is allowed to do that as part of the BW management. 
964
                 * In our case though it makes no sense to spin here. Sync transations 
965
                 * are already done, and async completion handler will re-process 
966
                 * the frame when something is ready.
967
                 */
968
                DPRINTF("uhci: detected loop. qh 0x%x\n", link);
969
                break;
970
            }
971

    
972
            cpu_physical_memory_read(link & ~0xf, (uint8_t *) &qh, sizeof(qh));
973
            le32_to_cpus(&qh.link);
974
            le32_to_cpus(&qh.el_link);
975

    
976
            DPRINTF("uhci: QH 0x%x load. link 0x%x elink 0x%x\n",
977
                    link, qh.link, qh.el_link);
978

    
979
            if (!is_valid(qh.el_link)) {
980
                /* QH w/o elements */
981
                curr_qh = 0;
982
                link = qh.link;
983
            } else {
984
                /* QH with elements */
985
                    curr_qh = link;
986
                    link = qh.el_link;
987
            }
988
            continue;
989
        }
990

    
991
        /* TD */
992
        cpu_physical_memory_read(link & ~0xf, (uint8_t *) &td, sizeof(td));
993
        le32_to_cpus(&td.link);
994
        le32_to_cpus(&td.ctrl);
995
        le32_to_cpus(&td.token);
996
        le32_to_cpus(&td.buffer);
997

    
998
        DPRINTF("uhci: TD 0x%x load. link 0x%x ctrl 0x%x token 0x%x qh 0x%x\n", 
999
                link, td.link, td.ctrl, td.token, curr_qh);
1000

    
1001
        old_td_ctrl = td.ctrl;
1002
        ret = uhci_handle_td(s, link, &td, &int_mask);
1003
        if (old_td_ctrl != td.ctrl) {
1004
            /* update the status bits of the TD */
1005
            val = cpu_to_le32(td.ctrl);
1006
            cpu_physical_memory_write((link & ~0xf) + 4,
1007
                                      (const uint8_t *)&val, sizeof(val));
1008
        }
1009

    
1010
        if (ret < 0) {
1011
            /* interrupted frame */
1012
            break;
1013
        }
1014

    
1015
        if (ret == 2 || ret == 1) {
1016
            DPRINTF("uhci: TD 0x%x %s. link 0x%x ctrl 0x%x token 0x%x qh 0x%x\n",
1017
                    link, ret == 2 ? "pend" : "skip",
1018
                    td.link, td.ctrl, td.token, curr_qh);
1019

    
1020
            link = curr_qh ? qh.link : td.link;
1021
            continue;
1022
        }
1023

    
1024
        /* completed TD */
1025

    
1026
        DPRINTF("uhci: TD 0x%x done. link 0x%x ctrl 0x%x token 0x%x qh 0x%x\n", 
1027
                link, td.link, td.ctrl, td.token, curr_qh);
1028

    
1029
        link = td.link;
1030

    
1031
        if (curr_qh) {
1032
            /* update QH element link */
1033
            qh.el_link = link;
1034
            val = cpu_to_le32(qh.el_link);
1035
            cpu_physical_memory_write((curr_qh & ~0xf) + 4,
1036
                                          (const uint8_t *)&val, sizeof(val));
1037

    
1038
            if (!depth_first(link)) {
1039
               /* done with this QH */
1040

    
1041
               DPRINTF("uhci: QH 0x%x done. link 0x%x elink 0x%x\n",
1042
                       curr_qh, qh.link, qh.el_link);
1043

    
1044
               curr_qh = 0;
1045
               link    = qh.link;
1046
            }
1047
        }
1048

    
1049
        /* go to the next entry */
1050
    }
1051

    
1052
    s->pending_int_mask |= int_mask;
1053
}
1054

    
1055
static void uhci_frame_timer(void *opaque)
1056
{
1057
    UHCIState *s = opaque;
1058

    
1059
    /* prepare the timer for the next frame */
1060
    s->expire_time += (get_ticks_per_sec() / FRAME_TIMER_FREQ);
1061

    
1062
    if (!(s->cmd & UHCI_CMD_RS)) {
1063
        /* Full stop */
1064
        qemu_del_timer(s->frame_timer);
1065
        /* set hchalted bit in status - UHCI11D 2.1.2 */
1066
        s->status |= UHCI_STS_HCHALTED;
1067

    
1068
        DPRINTF("uhci: halted\n");
1069
        return;
1070
    }
1071

    
1072
    /* Complete the previous frame */
1073
    if (s->pending_int_mask) {
1074
        s->status2 |= s->pending_int_mask;
1075
        s->status  |= UHCI_STS_USBINT;
1076
        uhci_update_irq(s);
1077
    }
1078
    s->pending_int_mask = 0;
1079

    
1080
    /* Start new frame */
1081
    s->frnum = (s->frnum + 1) & 0x7ff;
1082

    
1083
    DPRINTF("uhci: new frame #%u\n" , s->frnum);
1084

    
1085
    uhci_async_validate_begin(s);
1086

    
1087
    uhci_process_frame(s);
1088

    
1089
    uhci_async_validate_end(s);
1090

    
1091
    qemu_mod_timer(s->frame_timer, s->expire_time);
1092
}
1093

    
1094
static void uhci_map(PCIDevice *pci_dev, int region_num,
1095
                    pcibus_t addr, pcibus_t size, int type)
1096
{
1097
    UHCIState *s = (UHCIState *)pci_dev;
1098

    
1099
    register_ioport_write(addr, 32, 2, uhci_ioport_writew, s);
1100
    register_ioport_read(addr, 32, 2, uhci_ioport_readw, s);
1101
    register_ioport_write(addr, 32, 4, uhci_ioport_writel, s);
1102
    register_ioport_read(addr, 32, 4, uhci_ioport_readl, s);
1103
    register_ioport_write(addr, 32, 1, uhci_ioport_writeb, s);
1104
    register_ioport_read(addr, 32, 1, uhci_ioport_readb, s);
1105
}
1106

    
1107
static USBPortOps uhci_port_ops = {
1108
    .attach = uhci_attach,
1109
    .detach = uhci_detach,
1110
    .child_detach = uhci_child_detach,
1111
    .wakeup = uhci_wakeup,
1112
    .complete = uhci_async_complete,
1113
};
1114

    
1115
static USBBusOps uhci_bus_ops = {
1116
};
1117

    
1118
static int usb_uhci_common_initfn(PCIDevice *dev)
1119
{
1120
    UHCIState *s = DO_UPCAST(UHCIState, dev, dev);
1121
    uint8_t *pci_conf = s->dev.config;
1122
    int i;
1123

    
1124
    pci_conf[PCI_CLASS_PROG] = 0x00;
1125
    /* TODO: reset value should be 0. */
1126
    pci_conf[PCI_INTERRUPT_PIN] = 4; // interrupt pin 3
1127
    pci_conf[USB_SBRN] = USB_RELEASE_1; // release number
1128

    
1129
    usb_bus_new(&s->bus, &uhci_bus_ops, &s->dev.qdev);
1130
    for(i = 0; i < NB_PORTS; i++) {
1131
        usb_register_port(&s->bus, &s->ports[i].port, s, i, &uhci_port_ops,
1132
                          USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL);
1133
    }
1134
    s->frame_timer = qemu_new_timer_ns(vm_clock, uhci_frame_timer, s);
1135
    s->num_ports_vmstate = NB_PORTS;
1136
    QTAILQ_INIT(&s->async_pending);
1137

    
1138
    qemu_register_reset(uhci_reset, s);
1139

    
1140
    /* Use region 4 for consistency with real hardware.  BSD guests seem
1141
       to rely on this.  */
1142
    pci_register_bar(&s->dev, 4, 0x20,
1143
                           PCI_BASE_ADDRESS_SPACE_IO, uhci_map);
1144

    
1145
    return 0;
1146
}
1147

    
1148
static int usb_uhci_vt82c686b_initfn(PCIDevice *dev)
1149
{
1150
    UHCIState *s = DO_UPCAST(UHCIState, dev, dev);
1151
    uint8_t *pci_conf = s->dev.config;
1152

    
1153
    /* USB misc control 1/2 */
1154
    pci_set_long(pci_conf + 0x40,0x00001000);
1155
    /* PM capability */
1156
    pci_set_long(pci_conf + 0x80,0x00020001);
1157
    /* USB legacy support  */
1158
    pci_set_long(pci_conf + 0xc0,0x00002000);
1159

    
1160
    return usb_uhci_common_initfn(dev);
1161
}
1162

    
1163
static PCIDeviceInfo uhci_info[] = {
1164
    {
1165
        .qdev.name    = "piix3-usb-uhci",
1166
        .qdev.size    = sizeof(UHCIState),
1167
        .qdev.vmsd    = &vmstate_uhci,
1168
        .init         = usb_uhci_common_initfn,
1169
        .vendor_id    = PCI_VENDOR_ID_INTEL,
1170
        .device_id    = PCI_DEVICE_ID_INTEL_82371SB_2,
1171
        .revision     = 0x01,
1172
        .class_id     = PCI_CLASS_SERIAL_USB,
1173
    },{
1174
        .qdev.name    = "piix4-usb-uhci",
1175
        .qdev.size    = sizeof(UHCIState),
1176
        .qdev.vmsd    = &vmstate_uhci,
1177
        .init         = usb_uhci_common_initfn,
1178
        .vendor_id    = PCI_VENDOR_ID_INTEL,
1179
        .device_id    = PCI_DEVICE_ID_INTEL_82371AB_2,
1180
        .revision     = 0x01,
1181
        .class_id     = PCI_CLASS_SERIAL_USB,
1182
    },{
1183
        .qdev.name    = "vt82c686b-usb-uhci",
1184
        .qdev.size    = sizeof(UHCIState),
1185
        .qdev.vmsd    = &vmstate_uhci,
1186
        .init         = usb_uhci_vt82c686b_initfn,
1187
        .vendor_id    = PCI_VENDOR_ID_VIA,
1188
        .device_id    = PCI_DEVICE_ID_VIA_UHCI,
1189
        .revision     = 0x01,
1190
        .class_id     = PCI_CLASS_SERIAL_USB,
1191
    },{
1192
        /* end of list */
1193
    }
1194
};
1195

    
1196
static void uhci_register(void)
1197
{
1198
    pci_qdev_register_many(uhci_info);
1199
}
1200
device_init(uhci_register);
1201

    
1202
void usb_uhci_piix3_init(PCIBus *bus, int devfn)
1203
{
1204
    pci_create_simple(bus, devfn, "piix3-usb-uhci");
1205
}
1206

    
1207
void usb_uhci_piix4_init(PCIBus *bus, int devfn)
1208
{
1209
    pci_create_simple(bus, devfn, "piix4-usb-uhci");
1210
}
1211

    
1212
void usb_uhci_vt82c686b_init(PCIBus *bus, int devfn)
1213
{
1214
    pci_create_simple(bus, devfn, "vt82c686b-usb-uhci");
1215
}