Statistics
| Branch: | Revision:

root / hw / usb-uhci.c @ 6e355d90

History | View | Annotate | Download (28.4 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

    
33
//#define DEBUG
34
//#define DEBUG_DUMP_DATA
35

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

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

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

    
59
#define UHCI_PORT_RESET (1 << 9)
60
#define UHCI_PORT_LSDA  (1 << 8)
61
#define UHCI_PORT_ENC   (1 << 3)
62
#define UHCI_PORT_EN    (1 << 2)
63
#define UHCI_PORT_CSC   (1 << 1)
64
#define UHCI_PORT_CCS   (1 << 0)
65

    
66
#define FRAME_TIMER_FREQ 1000
67

    
68
#define FRAME_MAX_LOOPS  100
69

    
70
#define NB_PORTS 2
71

    
72
#ifdef DEBUG
73
#define dprintf printf
74

    
75
static const char *pid2str(int pid)
76
{
77
    switch (pid) {
78
    case USB_TOKEN_SETUP: return "SETUP";
79
    case USB_TOKEN_IN:    return "IN";
80
    case USB_TOKEN_OUT:   return "OUT";
81
    }
82
    return "?";
83
}
84

    
85
#else
86
#define dprintf(...)
87
#endif
88

    
89
#ifdef DEBUG_DUMP_DATA
90
static void dump_data(const uint8_t *data, int len)
91
{
92
    int i;
93

    
94
    printf("uhci: data: ");
95
    for(i = 0; i < len; i++)
96
        printf(" %02x", data[i]);
97
    printf("\n");
98
}
99
#else
100
static void dump_data(const uint8_t *data, int len) {}
101
#endif
102

    
103
/* 
104
 * Pending async transaction.
105
 * 'packet' must be the first field because completion
106
 * handler does "(UHCIAsync *) pkt" cast.
107
 */
108
typedef struct UHCIAsync {
109
    USBPacket packet;
110
    struct UHCIAsync *next;
111
    uint32_t  td;
112
    uint32_t  token;
113
    int8_t    valid;
114
    uint8_t   done;
115
    uint8_t   buffer[2048];
116
} UHCIAsync;
117

    
118
typedef struct UHCIPort {
119
    USBPort port;
120
    uint16_t ctrl;
121
} UHCIPort;
122

    
123
typedef struct UHCIState {
124
    PCIDevice dev;
125
    USBBus bus;
126
    uint16_t cmd; /* cmd register */
127
    uint16_t status;
128
    uint16_t intr; /* interrupt enable register */
129
    uint16_t frnum; /* frame number */
130
    uint32_t fl_base_addr; /* frame list base address */
131
    uint8_t sof_timing;
132
    uint8_t status2; /* bit 0 and 1 are used to generate UHCI_STS_USBINT */
133
    QEMUTimer *frame_timer;
134
    UHCIPort ports[NB_PORTS];
135

    
136
    /* Interrupts that should be raised at the end of the current frame.  */
137
    uint32_t pending_int_mask;
138

    
139
    /* Active packets */
140
    UHCIAsync *async_pending;
141
    UHCIAsync *async_pool;
142
    uint8_t num_ports_vmstate;
143
} UHCIState;
144

    
145
typedef struct UHCI_TD {
146
    uint32_t link;
147
    uint32_t ctrl; /* see TD_CTRL_xxx */
148
    uint32_t token;
149
    uint32_t buffer;
150
} UHCI_TD;
151

    
152
typedef struct UHCI_QH {
153
    uint32_t link;
154
    uint32_t el_link;
155
} UHCI_QH;
156

    
157
static UHCIAsync *uhci_async_alloc(UHCIState *s)
158
{
159
    UHCIAsync *async = qemu_malloc(sizeof(UHCIAsync));
160

    
161
    memset(&async->packet, 0, sizeof(async->packet));
162
    async->valid = 0;
163
    async->td    = 0;
164
    async->token = 0;
165
    async->done  = 0;
166
    async->next  = NULL;
167

    
168
    return async;
169
}
170

    
171
static void uhci_async_free(UHCIState *s, UHCIAsync *async)
172
{
173
    qemu_free(async);
174
}
175

    
176
static void uhci_async_link(UHCIState *s, UHCIAsync *async)
177
{
178
    async->next = s->async_pending;
179
    s->async_pending = async;
180
}
181

    
182
static void uhci_async_unlink(UHCIState *s, UHCIAsync *async)
183
{
184
    UHCIAsync *curr = s->async_pending;
185
    UHCIAsync **prev = &s->async_pending;
186

    
187
    while (curr) {
188
        if (curr == async) {
189
            *prev = curr->next;
190
            return;
191
        }
192

    
193
        prev = &curr->next;
194
        curr = curr->next;
195
    }
196
}
197

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

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

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

    
216
    while (async) {
217
        async->valid--;
218
        async = async->next;
219
    }
220
    return NULL;
221
}
222

    
223
/*
224
 * Cancel async packets that are no longer valid
225
 */
226
static void uhci_async_validate_end(UHCIState *s)
227
{
228
    UHCIAsync *curr = s->async_pending;
229
    UHCIAsync **prev = &s->async_pending;
230
    UHCIAsync *next;
231

    
232
    while (curr) {
233
        if (curr->valid > 0) {
234
            prev = &curr->next;
235
            curr = curr->next;
236
            continue;
237
        }
238

    
239
        next = curr->next;
240

    
241
        /* Unlink */
242
        *prev = next;
243

    
244
        uhci_async_cancel(s, curr);
245

    
246
        curr = next;
247
    }
248
}
249

    
250
static void uhci_async_cancel_all(UHCIState *s)
251
{
252
    UHCIAsync *curr = s->async_pending;
253
    UHCIAsync *next;
254

    
255
    while (curr) {
256
        next = curr->next;
257

    
258
        uhci_async_cancel(s, curr);
259

    
260
        curr = next;
261
    }
262

    
263
    s->async_pending = NULL;
264
}
265

    
266
static UHCIAsync *uhci_async_find_td(UHCIState *s, uint32_t addr, uint32_t token)
267
{
268
    UHCIAsync *async = s->async_pending;
269
    UHCIAsync *match = NULL;
270
    int count = 0;
271

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

    
285
    while (async) {
286
        if (async->token == token) {
287
            /* Good match */
288
            match = async;
289

    
290
            if (async->td == addr) {
291
                /* Best match */
292
                break;
293
            }
294
        }
295

    
296
        async = async->next;
297
        count++;
298
    }
299

    
300
    if (count > 64)
301
        fprintf(stderr, "uhci: warning lots of async transactions\n");
302

    
303
    return match;
304
}
305

    
306
static void uhci_attach(USBPort *port1, USBDevice *dev);
307

    
308
static void uhci_update_irq(UHCIState *s)
309
{
310
    int level;
311
    if (((s->status2 & 1) && (s->intr & (1 << 2))) ||
312
        ((s->status2 & 2) && (s->intr & (1 << 3))) ||
313
        ((s->status & UHCI_STS_USBERR) && (s->intr & (1 << 0))) ||
314
        ((s->status & UHCI_STS_RD) && (s->intr & (1 << 1))) ||
315
        (s->status & UHCI_STS_HSERR) ||
316
        (s->status & UHCI_STS_HCPERR)) {
317
        level = 1;
318
    } else {
319
        level = 0;
320
    }
321
    qemu_set_irq(s->dev.irq[3], level);
322
}
323

    
324
static void uhci_reset(void *opaque)
325
{
326
    UHCIState *s = opaque;
327
    uint8_t *pci_conf;
328
    int i;
329
    UHCIPort *port;
330

    
331
    dprintf("uhci: full reset\n");
332

    
333
    pci_conf = s->dev.config;
334

    
335
    pci_conf[0x6a] = 0x01; /* usb clock */
336
    pci_conf[0x6b] = 0x00;
337
    s->cmd = 0;
338
    s->status = 0;
339
    s->status2 = 0;
340
    s->intr = 0;
341
    s->fl_base_addr = 0;
342
    s->sof_timing = 64;
343

    
344
    for(i = 0; i < NB_PORTS; i++) {
345
        port = &s->ports[i];
346
        port->ctrl = 0x0080;
347
        if (port->port.dev)
348
            uhci_attach(&port->port, port->port.dev);
349
    }
350

    
351
    uhci_async_cancel_all(s);
352
}
353

    
354
static void uhci_pre_save(void *opaque)
355
{
356
    UHCIState *s = opaque;
357

    
358
    uhci_async_cancel_all(s);
359
}
360

    
361
static const VMStateDescription vmstate_uhci_port = {
362
    .name = "uhci port",
363
    .version_id = 1,
364
    .minimum_version_id = 1,
365
    .minimum_version_id_old = 1,
366
    .fields      = (VMStateField []) {
367
        VMSTATE_UINT16(ctrl, UHCIPort),
368
        VMSTATE_END_OF_LIST()
369
    }
370
};
371

    
372
static const VMStateDescription vmstate_uhci = {
373
    .name = "uhci",
374
    .version_id = 1,
375
    .minimum_version_id = 1,
376
    .minimum_version_id_old = 1,
377
    .pre_save = uhci_pre_save,
378
    .fields      = (VMStateField []) {
379
        VMSTATE_PCI_DEVICE(dev, UHCIState),
380
        VMSTATE_UINT8_EQUAL(num_ports_vmstate, UHCIState),
381
        VMSTATE_STRUCT_ARRAY(ports, UHCIState, NB_PORTS, 1,
382
                             vmstate_uhci_port, UHCIPort),
383
        VMSTATE_UINT16(cmd, UHCIState),
384
        VMSTATE_UINT16(status, UHCIState),
385
        VMSTATE_UINT16(intr, UHCIState),
386
        VMSTATE_UINT16(frnum, UHCIState),
387
        VMSTATE_UINT32(fl_base_addr, UHCIState),
388
        VMSTATE_UINT8(sof_timing, UHCIState),
389
        VMSTATE_UINT8(status2, UHCIState),
390
        VMSTATE_TIMER(frame_timer, UHCIState),
391
        VMSTATE_END_OF_LIST()
392
    }
393
};
394

    
395
static void uhci_ioport_writeb(void *opaque, uint32_t addr, uint32_t val)
396
{
397
    UHCIState *s = opaque;
398

    
399
    addr &= 0x1f;
400
    switch(addr) {
401
    case 0x0c:
402
        s->sof_timing = val;
403
        break;
404
    }
405
}
406

    
407
static uint32_t uhci_ioport_readb(void *opaque, uint32_t addr)
408
{
409
    UHCIState *s = opaque;
410
    uint32_t val;
411

    
412
    addr &= 0x1f;
413
    switch(addr) {
414
    case 0x0c:
415
        val = s->sof_timing;
416
        break;
417
    default:
418
        val = 0xff;
419
        break;
420
    }
421
    return val;
422
}
423

    
424
static void uhci_ioport_writew(void *opaque, uint32_t addr, uint32_t val)
425
{
426
    UHCIState *s = opaque;
427

    
428
    addr &= 0x1f;
429
    dprintf("uhci: writew port=0x%04x val=0x%04x\n", addr, val);
430

    
431
    switch(addr) {
432
    case 0x00:
433
        if ((val & UHCI_CMD_RS) && !(s->cmd & UHCI_CMD_RS)) {
434
            /* start frame processing */
435
            qemu_mod_timer(s->frame_timer, qemu_get_clock(vm_clock));
436
            s->status &= ~UHCI_STS_HCHALTED;
437
        } else if (!(val & UHCI_CMD_RS)) {
438
            s->status |= UHCI_STS_HCHALTED;
439
        }
440
        if (val & UHCI_CMD_GRESET) {
441
            UHCIPort *port;
442
            USBDevice *dev;
443
            int i;
444

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

    
484
            n = (addr >> 1) & 7;
485
            if (n >= NB_PORTS)
486
                return;
487
            port = &s->ports[n];
488
            dev = port->port.dev;
489
            if (dev) {
490
                /* port reset */
491
                if ( (val & UHCI_PORT_RESET) &&
492
                     !(port->ctrl & UHCI_PORT_RESET) ) {
493
                    usb_send_msg(dev, USB_MSG_RESET);
494
                }
495
            }
496
            port->ctrl = (port->ctrl & 0x01fb) | (val & ~0x01fb);
497
            /* some bits are reset when a '1' is written to them */
498
            port->ctrl &= ~(val & 0x000a);
499
        }
500
        break;
501
    }
502
}
503

    
504
static uint32_t uhci_ioport_readw(void *opaque, uint32_t addr)
505
{
506
    UHCIState *s = opaque;
507
    uint32_t val;
508

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

    
540
    dprintf("uhci: readw port=0x%04x val=0x%04x\n", addr, val);
541

    
542
    return val;
543
}
544

    
545
static void uhci_ioport_writel(void *opaque, uint32_t addr, uint32_t val)
546
{
547
    UHCIState *s = opaque;
548

    
549
    addr &= 0x1f;
550
    dprintf("uhci: writel port=0x%04x val=0x%08x\n", addr, val);
551

    
552
    switch(addr) {
553
    case 0x08:
554
        s->fl_base_addr = val & ~0xfff;
555
        break;
556
    }
557
}
558

    
559
static uint32_t uhci_ioport_readl(void *opaque, uint32_t addr)
560
{
561
    UHCIState *s = opaque;
562
    uint32_t val;
563

    
564
    addr &= 0x1f;
565
    switch(addr) {
566
    case 0x08:
567
        val = s->fl_base_addr;
568
        break;
569
    default:
570
        val = 0xffffffff;
571
        break;
572
    }
573
    return val;
574
}
575

    
576
/* signal resume if controller suspended */
577
static void uhci_resume (void *opaque)
578
{
579
    UHCIState *s = (UHCIState *)opaque;
580

    
581
    if (!s)
582
        return;
583

    
584
    if (s->cmd & UHCI_CMD_EGSM) {
585
        s->cmd |= UHCI_CMD_FGR;
586
        s->status |= UHCI_STS_RD;
587
        uhci_update_irq(s);
588
    }
589
}
590

    
591
static void uhci_attach(USBPort *port1, USBDevice *dev)
592
{
593
    UHCIState *s = port1->opaque;
594
    UHCIPort *port = &s->ports[port1->index];
595

    
596
    if (dev) {
597
        if (port->port.dev) {
598
            usb_attach(port1, NULL);
599
        }
600
        /* set connect status */
601
        port->ctrl |= UHCI_PORT_CCS | UHCI_PORT_CSC;
602

    
603
        /* update speed */
604
        if (dev->speed == USB_SPEED_LOW)
605
            port->ctrl |= UHCI_PORT_LSDA;
606
        else
607
            port->ctrl &= ~UHCI_PORT_LSDA;
608

    
609
        uhci_resume(s);
610

    
611
        port->port.dev = dev;
612
        /* send the attach message */
613
        usb_send_msg(dev, USB_MSG_ATTACH);
614
    } else {
615
        /* set connect status */
616
        if (port->ctrl & UHCI_PORT_CCS) {
617
            port->ctrl &= ~UHCI_PORT_CCS;
618
            port->ctrl |= UHCI_PORT_CSC;
619
        }
620
        /* disable port */
621
        if (port->ctrl & UHCI_PORT_EN) {
622
            port->ctrl &= ~UHCI_PORT_EN;
623
            port->ctrl |= UHCI_PORT_ENC;
624
        }
625

    
626
        uhci_resume(s);
627

    
628
        dev = port->port.dev;
629
        if (dev) {
630
            /* send the detach message */
631
            usb_send_msg(dev, USB_MSG_DETACH);
632
        }
633
        port->port.dev = NULL;
634
    }
635
}
636

    
637
static int uhci_broadcast_packet(UHCIState *s, USBPacket *p)
638
{
639
    int i, ret;
640

    
641
    dprintf("uhci: packet enter. pid %s addr 0x%02x ep %d len %d\n",
642
           pid2str(p->pid), p->devaddr, p->devep, p->len);
643
    if (p->pid == USB_TOKEN_OUT || p->pid == USB_TOKEN_SETUP)
644
        dump_data(p->data, p->len);
645

    
646
    ret = USB_RET_NODEV;
647
    for (i = 0; i < NB_PORTS && ret == USB_RET_NODEV; i++) {
648
        UHCIPort *port = &s->ports[i];
649
        USBDevice *dev = port->port.dev;
650

    
651
        if (dev && (port->ctrl & UHCI_PORT_EN))
652
            ret = dev->info->handle_packet(dev, p);
653
    }
654

    
655
    dprintf("uhci: packet exit. ret %d len %d\n", ret, p->len);
656
    if (p->pid == USB_TOKEN_IN && ret > 0)
657
        dump_data(p->data, ret);
658

    
659
    return ret;
660
}
661

    
662
static void uhci_async_complete(USBPacket * packet, void *opaque);
663
static void uhci_process_frame(UHCIState *s);
664

    
665
/* return -1 if fatal error (frame must be stopped)
666
          0 if TD successful
667
          1 if TD unsuccessful or inactive
668
*/
669
static int uhci_complete_td(UHCIState *s, UHCI_TD *td, UHCIAsync *async, uint32_t *int_mask)
670
{
671
    int len = 0, max_len, err, ret;
672
    uint8_t pid;
673

    
674
    max_len = ((td->token >> 21) + 1) & 0x7ff;
675
    pid = td->token & 0xff;
676

    
677
    ret = async->packet.len;
678

    
679
    if (td->ctrl & TD_CTRL_IOC)
680
        *int_mask |= 0x01;
681

    
682
    if (td->ctrl & TD_CTRL_IOS)
683
        td->ctrl &= ~TD_CTRL_ACTIVE;
684

    
685
    if (ret < 0)
686
        goto out;
687

    
688
    len = async->packet.len;
689
    td->ctrl = (td->ctrl & ~0x7ff) | ((len - 1) & 0x7ff);
690

    
691
    /* The NAK bit may have been set by a previous frame, so clear it
692
       here.  The docs are somewhat unclear, but win2k relies on this
693
       behavior.  */
694
    td->ctrl &= ~(TD_CTRL_ACTIVE | TD_CTRL_NAK);
695

    
696
    if (pid == USB_TOKEN_IN) {
697
        if (len > max_len) {
698
            len = max_len;
699
            ret = USB_RET_BABBLE;
700
            goto out;
701
        }
702

    
703
        if (len > 0) {
704
            /* write the data back */
705
            cpu_physical_memory_write(td->buffer, async->buffer, len);
706
        }
707

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

    
716
    /* success */
717
    return 0;
718

    
719
out:
720
    switch(ret) {
721
    case USB_RET_STALL:
722
        td->ctrl |= TD_CTRL_STALL;
723
        td->ctrl &= ~TD_CTRL_ACTIVE;
724
        return 1;
725

    
726
    case USB_RET_BABBLE:
727
        td->ctrl |= TD_CTRL_BABBLE | TD_CTRL_STALL;
728
        td->ctrl &= ~TD_CTRL_ACTIVE;
729
        /* frame interrupted */
730
        return -1;
731

    
732
    case USB_RET_NAK:
733
        td->ctrl |= TD_CTRL_NAK;
734
        if (pid == USB_TOKEN_SETUP)
735
            break;
736
        return 1;
737

    
738
    case USB_RET_NODEV:
739
    default:
740
        break;
741
    }
742

    
743
    /* Retry the TD if error count is not zero */
744

    
745
    td->ctrl |= TD_CTRL_TIMEOUT;
746
    err = (td->ctrl >> TD_CTRL_ERROR_SHIFT) & 3;
747
    if (err != 0) {
748
        err--;
749
        if (err == 0) {
750
            td->ctrl &= ~TD_CTRL_ACTIVE;
751
            s->status |= UHCI_STS_USBERR;
752
            uhci_update_irq(s);
753
        }
754
    }
755
    td->ctrl = (td->ctrl & ~(3 << TD_CTRL_ERROR_SHIFT)) |
756
        (err << TD_CTRL_ERROR_SHIFT);
757
    return 1;
758
}
759

    
760
static int uhci_handle_td(UHCIState *s, uint32_t addr, UHCI_TD *td, uint32_t *int_mask)
761
{
762
    UHCIAsync *async;
763
    int len = 0, max_len;
764
    uint8_t pid;
765

    
766
    /* Is active ? */
767
    if (!(td->ctrl & TD_CTRL_ACTIVE))
768
        return 1;
769

    
770
    async = uhci_async_find_td(s, addr, td->token);
771
    if (async) {
772
        /* Already submitted */
773
        async->valid = 32;
774

    
775
        if (!async->done)
776
            return 1;
777

    
778
        uhci_async_unlink(s, async);
779
        goto done;
780
    }
781

    
782
    /* Allocate new packet */
783
    async = uhci_async_alloc(s);
784
    if (!async)
785
        return 1;
786

    
787
    async->valid = 10;
788
    async->td    = addr;
789
    async->token = td->token;
790

    
791
    max_len = ((td->token >> 21) + 1) & 0x7ff;
792
    pid = td->token & 0xff;
793

    
794
    async->packet.pid     = pid;
795
    async->packet.devaddr = (td->token >> 8) & 0x7f;
796
    async->packet.devep   = (td->token >> 15) & 0xf;
797
    async->packet.data    = async->buffer;
798
    async->packet.len     = max_len;
799
    async->packet.complete_cb     = uhci_async_complete;
800
    async->packet.complete_opaque = s;
801

    
802
    switch(pid) {
803
    case USB_TOKEN_OUT:
804
    case USB_TOKEN_SETUP:
805
        cpu_physical_memory_read(td->buffer, async->buffer, max_len);
806
        len = uhci_broadcast_packet(s, &async->packet);
807
        if (len >= 0)
808
            len = max_len;
809
        break;
810

    
811
    case USB_TOKEN_IN:
812
        len = uhci_broadcast_packet(s, &async->packet);
813
        break;
814

    
815
    default:
816
        /* invalid pid : frame interrupted */
817
        uhci_async_free(s, async);
818
        s->status |= UHCI_STS_HCPERR;
819
        uhci_update_irq(s);
820
        return -1;
821
    }
822
 
823
    if (len == USB_RET_ASYNC) {
824
        uhci_async_link(s, async);
825
        return 2;
826
    }
827

    
828
    async->packet.len = len;
829

    
830
done:
831
    len = uhci_complete_td(s, td, async, int_mask);
832
    uhci_async_free(s, async);
833
    return len;
834
}
835

    
836
static void uhci_async_complete(USBPacket *packet, void *opaque)
837
{
838
    UHCIState *s = opaque;
839
    UHCIAsync *async = (UHCIAsync *) packet;
840

    
841
    dprintf("uhci: async complete. td 0x%x token 0x%x\n", async->td, async->token);
842

    
843
    async->done = 1;
844

    
845
    uhci_process_frame(s);
846
}
847

    
848
static int is_valid(uint32_t link)
849
{
850
    return (link & 1) == 0;
851
}
852

    
853
static int is_qh(uint32_t link)
854
{
855
    return (link & 2) != 0;
856
}
857

    
858
static int depth_first(uint32_t link)
859
{
860
    return (link & 4) != 0;
861
}
862

    
863
/* QH DB used for detecting QH loops */
864
#define UHCI_MAX_QUEUES 128
865
typedef struct {
866
    uint32_t addr[UHCI_MAX_QUEUES];
867
    int      count;
868
} QhDb;
869

    
870
static void qhdb_reset(QhDb *db)
871
{
872
    db->count = 0;
873
}
874

    
875
/* Add QH to DB. Returns 1 if already present or DB is full. */
876
static int qhdb_insert(QhDb *db, uint32_t addr)
877
{
878
    int i;
879
    for (i = 0; i < db->count; i++)
880
        if (db->addr[i] == addr)
881
            return 1;
882

    
883
    if (db->count >= UHCI_MAX_QUEUES)
884
        return 1;
885

    
886
    db->addr[db->count++] = addr;
887
    return 0;
888
}
889

    
890
static void uhci_process_frame(UHCIState *s)
891
{
892
    uint32_t frame_addr, link, old_td_ctrl, val, int_mask;
893
    uint32_t curr_qh;
894
    int cnt, ret;
895
    UHCI_TD td;
896
    UHCI_QH qh;
897
    QhDb qhdb;
898

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

    
901
    dprintf("uhci: processing frame %d addr 0x%x\n" , s->frnum, frame_addr);
902

    
903
    cpu_physical_memory_read(frame_addr, (uint8_t *)&link, 4);
904
    le32_to_cpus(&link);
905

    
906
    int_mask = 0;
907
    curr_qh  = 0;
908

    
909
    qhdb_reset(&qhdb);
910

    
911
    for (cnt = FRAME_MAX_LOOPS; is_valid(link) && cnt; cnt--) {
912
        if (is_qh(link)) {
913
            /* QH */
914

    
915
            if (qhdb_insert(&qhdb, link)) {
916
                /*
917
                 * We're going in circles. Which is not a bug because
918
                 * HCD is allowed to do that as part of the BW management. 
919
                 * In our case though it makes no sense to spin here. Sync transations 
920
                 * are already done, and async completion handler will re-process 
921
                 * the frame when something is ready.
922
                 */
923
                dprintf("uhci: detected loop. qh 0x%x\n", link);
924
                break;
925
            }
926

    
927
            cpu_physical_memory_read(link & ~0xf, (uint8_t *) &qh, sizeof(qh));
928
            le32_to_cpus(&qh.link);
929
            le32_to_cpus(&qh.el_link);
930

    
931
            dprintf("uhci: QH 0x%x load. link 0x%x elink 0x%x\n",
932
                    link, qh.link, qh.el_link);
933

    
934
            if (!is_valid(qh.el_link)) {
935
                /* QH w/o elements */
936
                curr_qh = 0;
937
                link = qh.link;
938
            } else {
939
                /* QH with elements */
940
                    curr_qh = link;
941
                    link = qh.el_link;
942
            }
943
            continue;
944
        }
945

    
946
        /* TD */
947
        cpu_physical_memory_read(link & ~0xf, (uint8_t *) &td, sizeof(td));
948
        le32_to_cpus(&td.link);
949
        le32_to_cpus(&td.ctrl);
950
        le32_to_cpus(&td.token);
951
        le32_to_cpus(&td.buffer);
952

    
953
        dprintf("uhci: TD 0x%x load. link 0x%x ctrl 0x%x token 0x%x qh 0x%x\n", 
954
                link, td.link, td.ctrl, td.token, curr_qh);
955

    
956
        old_td_ctrl = td.ctrl;
957
        ret = uhci_handle_td(s, link, &td, &int_mask);
958
        if (old_td_ctrl != td.ctrl) {
959
            /* update the status bits of the TD */
960
            val = cpu_to_le32(td.ctrl);
961
            cpu_physical_memory_write((link & ~0xf) + 4,
962
                                      (const uint8_t *)&val, sizeof(val));
963
        }
964

    
965
        if (ret < 0) {
966
            /* interrupted frame */
967
            break;
968
        }
969

    
970
        if (ret == 2 || ret == 1) {
971
            dprintf("uhci: TD 0x%x %s. link 0x%x ctrl 0x%x token 0x%x qh 0x%x\n",
972
                    link, ret == 2 ? "pend" : "skip",
973
                    td.link, td.ctrl, td.token, curr_qh);
974

    
975
            link = curr_qh ? qh.link : td.link;
976
            continue;
977
        }
978

    
979
        /* completed TD */
980

    
981
        dprintf("uhci: TD 0x%x done. link 0x%x ctrl 0x%x token 0x%x qh 0x%x\n", 
982
                link, td.link, td.ctrl, td.token, curr_qh);
983

    
984
        link = td.link;
985

    
986
        if (curr_qh) {
987
            /* update QH element link */
988
            qh.el_link = link;
989
            val = cpu_to_le32(qh.el_link);
990
            cpu_physical_memory_write((curr_qh & ~0xf) + 4,
991
                                          (const uint8_t *)&val, sizeof(val));
992

    
993
            if (!depth_first(link)) {
994
               /* done with this QH */
995

    
996
               dprintf("uhci: QH 0x%x done. link 0x%x elink 0x%x\n",
997
                       curr_qh, qh.link, qh.el_link);
998

    
999
               curr_qh = 0;
1000
               link    = qh.link;
1001
            }
1002
        }
1003

    
1004
        /* go to the next entry */
1005
    }
1006

    
1007
    s->pending_int_mask = int_mask;
1008
}
1009

    
1010
static void uhci_frame_timer(void *opaque)
1011
{
1012
    UHCIState *s = opaque;
1013
    int64_t expire_time;
1014

    
1015
    if (!(s->cmd & UHCI_CMD_RS)) {
1016
        /* Full stop */
1017
        qemu_del_timer(s->frame_timer);
1018
        /* set hchalted bit in status - UHCI11D 2.1.2 */
1019
        s->status |= UHCI_STS_HCHALTED;
1020

    
1021
        dprintf("uhci: halted\n");
1022
        return;
1023
    }
1024

    
1025
    /* Complete the previous frame */
1026
    if (s->pending_int_mask) {
1027
        s->status2 |= s->pending_int_mask;
1028
        s->status  |= UHCI_STS_USBINT;
1029
        uhci_update_irq(s);
1030
    }
1031

    
1032
    /* Start new frame */
1033
    s->frnum = (s->frnum + 1) & 0x7ff;
1034

    
1035
    dprintf("uhci: new frame #%u\n" , s->frnum);
1036

    
1037
    uhci_async_validate_begin(s);
1038

    
1039
    uhci_process_frame(s);
1040

    
1041
    uhci_async_validate_end(s);
1042

    
1043
    /* prepare the timer for the next frame */
1044
    expire_time = qemu_get_clock(vm_clock) +
1045
        (get_ticks_per_sec() / FRAME_TIMER_FREQ);
1046
    qemu_mod_timer(s->frame_timer, expire_time);
1047
}
1048

    
1049
static void uhci_map(PCIDevice *pci_dev, int region_num,
1050
                    pcibus_t addr, pcibus_t size, int type)
1051
{
1052
    UHCIState *s = (UHCIState *)pci_dev;
1053

    
1054
    register_ioport_write(addr, 32, 2, uhci_ioport_writew, s);
1055
    register_ioport_read(addr, 32, 2, uhci_ioport_readw, s);
1056
    register_ioport_write(addr, 32, 4, uhci_ioport_writel, s);
1057
    register_ioport_read(addr, 32, 4, uhci_ioport_readl, s);
1058
    register_ioport_write(addr, 32, 1, uhci_ioport_writeb, s);
1059
    register_ioport_read(addr, 32, 1, uhci_ioport_readb, s);
1060
}
1061

    
1062
static int usb_uhci_common_initfn(UHCIState *s)
1063
{
1064
    uint8_t *pci_conf = s->dev.config;
1065
    int i;
1066

    
1067
    pci_conf[0x08] = 0x01; // revision number
1068
    pci_conf[0x09] = 0x00;
1069
    pci_config_set_class(pci_conf, PCI_CLASS_SERIAL_USB);
1070
    pci_conf[PCI_HEADER_TYPE] = PCI_HEADER_TYPE_NORMAL; // header_type
1071
    pci_conf[0x3d] = 4; // interrupt pin 3
1072
    pci_conf[0x60] = 0x10; // release number
1073

    
1074
    usb_bus_new(&s->bus, &s->dev.qdev);
1075
    for(i = 0; i < NB_PORTS; i++) {
1076
        usb_register_port(&s->bus, &s->ports[i].port, s, i, uhci_attach);
1077
    }
1078
    s->frame_timer = qemu_new_timer(vm_clock, uhci_frame_timer, s);
1079
    s->num_ports_vmstate = NB_PORTS;
1080

    
1081
    qemu_register_reset(uhci_reset, s);
1082

    
1083
    /* Use region 4 for consistency with real hardware.  BSD guests seem
1084
       to rely on this.  */
1085
    pci_register_bar(&s->dev, 4, 0x20,
1086
                           PCI_BASE_ADDRESS_SPACE_IO, uhci_map);
1087

    
1088
    vmstate_register(0, &vmstate_uhci, s);
1089
    return 0;
1090
}
1091

    
1092
static int usb_uhci_piix3_initfn(PCIDevice *dev)
1093
{
1094
    UHCIState *s = DO_UPCAST(UHCIState, dev, dev);
1095
    uint8_t *pci_conf = s->dev.config;
1096

    
1097
    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);
1098
    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_82371SB_2);
1099
    return usb_uhci_common_initfn(s);
1100
}
1101

    
1102
static int usb_uhci_piix4_initfn(PCIDevice *dev)
1103
{
1104
    UHCIState *s = DO_UPCAST(UHCIState, dev, dev);
1105
    uint8_t *pci_conf = s->dev.config;
1106

    
1107
    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);
1108
    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_82371AB_2);
1109
    return usb_uhci_common_initfn(s);
1110
}
1111

    
1112
static PCIDeviceInfo uhci_info[] = {
1113
    {
1114
        .qdev.name    = "PIIX3 USB-UHCI",
1115
        .qdev.size    = sizeof(UHCIState),
1116
        .init         = usb_uhci_piix3_initfn,
1117
    },{
1118
        .qdev.name    = "PIIX4 USB-UHCI",
1119
        .qdev.size    = sizeof(UHCIState),
1120
        .init         = usb_uhci_piix4_initfn,
1121
    },{
1122
        /* end of list */
1123
    }
1124
};
1125

    
1126
static void uhci_register(void)
1127
{
1128
    pci_qdev_register_many(uhci_info);
1129
}
1130
device_init(uhci_register);
1131

    
1132
void usb_uhci_piix3_init(PCIBus *bus, int devfn)
1133
{
1134
    pci_create_simple(bus, devfn, "PIIX3 USB-UHCI");
1135
}
1136

    
1137
void usb_uhci_piix4_init(PCIBus *bus, int devfn)
1138
{
1139
    pci_create_simple(bus, devfn, "PIIX4 USB-UHCI");
1140
}