]> rtime.felk.cvut.cz Git - lisovros/qemu_apohw.git/blob - hw/usb-uhci.c
pci: convert to QEMU Object Model
[lisovros/qemu_apohw.git] / hw / usb-uhci.c
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 #include "iov.h"
34 #include "dma.h"
35
36 //#define DEBUG
37 //#define DEBUG_DUMP_DATA
38
39 #define UHCI_CMD_FGR      (1 << 4)
40 #define UHCI_CMD_EGSM     (1 << 3)
41 #define UHCI_CMD_GRESET   (1 << 2)
42 #define UHCI_CMD_HCRESET  (1 << 1)
43 #define UHCI_CMD_RS       (1 << 0)
44
45 #define UHCI_STS_HCHALTED (1 << 5)
46 #define UHCI_STS_HCPERR   (1 << 4)
47 #define UHCI_STS_HSERR    (1 << 3)
48 #define UHCI_STS_RD       (1 << 2)
49 #define UHCI_STS_USBERR   (1 << 1)
50 #define UHCI_STS_USBINT   (1 << 0)
51
52 #define TD_CTRL_SPD     (1 << 29)
53 #define TD_CTRL_ERROR_SHIFT  27
54 #define TD_CTRL_IOS     (1 << 25)
55 #define TD_CTRL_IOC     (1 << 24)
56 #define TD_CTRL_ACTIVE  (1 << 23)
57 #define TD_CTRL_STALL   (1 << 22)
58 #define TD_CTRL_BABBLE  (1 << 20)
59 #define TD_CTRL_NAK     (1 << 19)
60 #define TD_CTRL_TIMEOUT (1 << 18)
61
62 #define UHCI_PORT_SUSPEND (1 << 12)
63 #define UHCI_PORT_RESET (1 << 9)
64 #define UHCI_PORT_LSDA  (1 << 8)
65 #define UHCI_PORT_RD    (1 << 6)
66 #define UHCI_PORT_ENC   (1 << 3)
67 #define UHCI_PORT_EN    (1 << 2)
68 #define UHCI_PORT_CSC   (1 << 1)
69 #define UHCI_PORT_CCS   (1 << 0)
70
71 #define UHCI_PORT_READ_ONLY    (0x1bb)
72 #define UHCI_PORT_WRITE_CLEAR  (UHCI_PORT_CSC | UHCI_PORT_ENC)
73
74 #define FRAME_TIMER_FREQ 1000
75
76 #define FRAME_MAX_LOOPS  100
77
78 #define NB_PORTS 2
79
80 #ifdef DEBUG
81 #define DPRINTF printf
82
83 static const char *pid2str(int pid)
84 {
85     switch (pid) {
86     case USB_TOKEN_SETUP: return "SETUP";
87     case USB_TOKEN_IN:    return "IN";
88     case USB_TOKEN_OUT:   return "OUT";
89     }
90     return "?";
91 }
92
93 #else
94 #define DPRINTF(...)
95 #endif
96
97 #ifdef DEBUG_DUMP_DATA
98 static void dump_data(USBPacket *p, int ret)
99 {
100     iov_hexdump(p->iov.iov, p->iov.niov, stderr, "uhci", ret);
101 }
102 #else
103 static void dump_data(USBPacket *p, int ret) {}
104 #endif
105
106 typedef struct UHCIState UHCIState;
107
108 /* 
109  * Pending async transaction.
110  * 'packet' must be the first field because completion
111  * handler does "(UHCIAsync *) pkt" cast.
112  */
113 typedef struct UHCIAsync {
114     USBPacket packet;
115     QEMUSGList sgl;
116     UHCIState *uhci;
117     QTAILQ_ENTRY(UHCIAsync) next;
118     uint32_t  td;
119     uint32_t  token;
120     int8_t    valid;
121     uint8_t   isoc;
122     uint8_t   done;
123 } UHCIAsync;
124
125 typedef struct UHCIPort {
126     USBPort port;
127     uint16_t ctrl;
128 } UHCIPort;
129
130 struct UHCIState {
131     PCIDevice dev;
132     MemoryRegion io_bar;
133     USBBus bus; /* Note unused when we're a companion controller */
134     uint16_t cmd; /* cmd register */
135     uint16_t status;
136     uint16_t intr; /* interrupt enable register */
137     uint16_t frnum; /* frame number */
138     uint32_t fl_base_addr; /* frame list base address */
139     uint8_t sof_timing;
140     uint8_t status2; /* bit 0 and 1 are used to generate UHCI_STS_USBINT */
141     int64_t expire_time;
142     QEMUTimer *frame_timer;
143     UHCIPort ports[NB_PORTS];
144
145     /* Interrupts that should be raised at the end of the current frame.  */
146     uint32_t pending_int_mask;
147
148     /* Active packets */
149     QTAILQ_HEAD(,UHCIAsync) async_pending;
150     uint8_t num_ports_vmstate;
151
152     /* Properties */
153     char *masterbus;
154     uint32_t firstport;
155 };
156
157 typedef struct UHCI_TD {
158     uint32_t link;
159     uint32_t ctrl; /* see TD_CTRL_xxx */
160     uint32_t token;
161     uint32_t buffer;
162 } UHCI_TD;
163
164 typedef struct UHCI_QH {
165     uint32_t link;
166     uint32_t el_link;
167 } UHCI_QH;
168
169 static UHCIAsync *uhci_async_alloc(UHCIState *s)
170 {
171     UHCIAsync *async = g_malloc(sizeof(UHCIAsync));
172
173     memset(&async->packet, 0, sizeof(async->packet));
174     async->uhci  = s;
175     async->valid = 0;
176     async->td    = 0;
177     async->token = 0;
178     async->done  = 0;
179     async->isoc  = 0;
180     usb_packet_init(&async->packet);
181     pci_dma_sglist_init(&async->sgl, &s->dev, 1);
182
183     return async;
184 }
185
186 static void uhci_async_free(UHCIState *s, UHCIAsync *async)
187 {
188     usb_packet_cleanup(&async->packet);
189     qemu_sglist_destroy(&async->sgl);
190     g_free(async);
191 }
192
193 static void uhci_async_link(UHCIState *s, UHCIAsync *async)
194 {
195     QTAILQ_INSERT_HEAD(&s->async_pending, async, next);
196 }
197
198 static void uhci_async_unlink(UHCIState *s, UHCIAsync *async)
199 {
200     QTAILQ_REMOVE(&s->async_pending, async, next);
201 }
202
203 static void uhci_async_cancel(UHCIState *s, UHCIAsync *async)
204 {
205     DPRINTF("uhci: cancel td 0x%x token 0x%x done %u\n",
206            async->td, async->token, async->done);
207
208     if (!async->done)
209         usb_cancel_packet(&async->packet);
210     uhci_async_free(s, async);
211 }
212
213 /*
214  * Mark all outstanding async packets as invalid.
215  * This is used for canceling them when TDs are removed by the HCD.
216  */
217 static UHCIAsync *uhci_async_validate_begin(UHCIState *s)
218 {
219     UHCIAsync *async;
220
221     QTAILQ_FOREACH(async, &s->async_pending, next) {
222         async->valid--;
223     }
224     return NULL;
225 }
226
227 /*
228  * Cancel async packets that are no longer valid
229  */
230 static void uhci_async_validate_end(UHCIState *s)
231 {
232     UHCIAsync *curr, *n;
233
234     QTAILQ_FOREACH_SAFE(curr, &s->async_pending, next, n) {
235         if (curr->valid > 0) {
236             continue;
237         }
238         uhci_async_unlink(s, curr);
239         uhci_async_cancel(s, curr);
240     }
241 }
242
243 static void uhci_async_cancel_device(UHCIState *s, USBDevice *dev)
244 {
245     UHCIAsync *curr, *n;
246
247     QTAILQ_FOREACH_SAFE(curr, &s->async_pending, next, n) {
248         if (curr->packet.owner == NULL ||
249             curr->packet.owner->dev != dev) {
250             continue;
251         }
252         uhci_async_unlink(s, curr);
253         uhci_async_cancel(s, curr);
254     }
255 }
256
257 static void uhci_async_cancel_all(UHCIState *s)
258 {
259     UHCIAsync *curr, *n;
260
261     QTAILQ_FOREACH_SAFE(curr, &s->async_pending, next, n) {
262         uhci_async_unlink(s, curr);
263         uhci_async_cancel(s, curr);
264     }
265 }
266
267 static UHCIAsync *uhci_async_find_td(UHCIState *s, uint32_t addr, uint32_t token)
268 {
269     UHCIAsync *async;
270     UHCIAsync *match = NULL;
271     int count = 0;
272
273     /*
274      * We're looking for the best match here. ie both td addr and token.
275      * Otherwise we return last good match. ie just token.
276      * It's ok to match just token because it identifies the transaction
277      * rather well, token includes: device addr, endpoint, size, etc.
278      *
279      * Also since we queue async transactions in reverse order by returning
280      * last good match we restores the order.
281      *
282      * It's expected that we wont have a ton of outstanding transactions.
283      * If we ever do we'd want to optimize this algorithm.
284      */
285
286     QTAILQ_FOREACH(async, &s->async_pending, next) {
287         if (async->token == token) {
288             /* Good match */
289             match = async;
290
291             if (async->td == addr) {
292                 /* Best match */
293                 break;
294             }
295         }
296         count++;
297     }
298
299     if (count > 64)
300         fprintf(stderr, "uhci: warning lots of async transactions\n");
301
302     return match;
303 }
304
305 static void uhci_update_irq(UHCIState *s)
306 {
307     int level;
308     if (((s->status2 & 1) && (s->intr & (1 << 2))) ||
309         ((s->status2 & 2) && (s->intr & (1 << 3))) ||
310         ((s->status & UHCI_STS_USBERR) && (s->intr & (1 << 0))) ||
311         ((s->status & UHCI_STS_RD) && (s->intr & (1 << 1))) ||
312         (s->status & UHCI_STS_HSERR) ||
313         (s->status & UHCI_STS_HCPERR)) {
314         level = 1;
315     } else {
316         level = 0;
317     }
318     qemu_set_irq(s->dev.irq[3], level);
319 }
320
321 static void uhci_reset(void *opaque)
322 {
323     UHCIState *s = opaque;
324     uint8_t *pci_conf;
325     int i;
326     UHCIPort *port;
327
328     DPRINTF("uhci: full reset\n");
329
330     pci_conf = s->dev.config;
331
332     pci_conf[0x6a] = 0x01; /* usb clock */
333     pci_conf[0x6b] = 0x00;
334     s->cmd = 0;
335     s->status = 0;
336     s->status2 = 0;
337     s->intr = 0;
338     s->fl_base_addr = 0;
339     s->sof_timing = 64;
340
341     for(i = 0; i < NB_PORTS; i++) {
342         port = &s->ports[i];
343         port->ctrl = 0x0080;
344         if (port->port.dev && port->port.dev->attached) {
345             usb_reset(&port->port);
346         }
347     }
348
349     uhci_async_cancel_all(s);
350 }
351
352 static void uhci_pre_save(void *opaque)
353 {
354     UHCIState *s = opaque;
355
356     uhci_async_cancel_all(s);
357 }
358
359 static const VMStateDescription vmstate_uhci_port = {
360     .name = "uhci port",
361     .version_id = 1,
362     .minimum_version_id = 1,
363     .minimum_version_id_old = 1,
364     .fields      = (VMStateField []) {
365         VMSTATE_UINT16(ctrl, UHCIPort),
366         VMSTATE_END_OF_LIST()
367     }
368 };
369
370 static const VMStateDescription vmstate_uhci = {
371     .name = "uhci",
372     .version_id = 2,
373     .minimum_version_id = 1,
374     .minimum_version_id_old = 1,
375     .pre_save = uhci_pre_save,
376     .fields      = (VMStateField []) {
377         VMSTATE_PCI_DEVICE(dev, UHCIState),
378         VMSTATE_UINT8_EQUAL(num_ports_vmstate, UHCIState),
379         VMSTATE_STRUCT_ARRAY(ports, UHCIState, NB_PORTS, 1,
380                              vmstate_uhci_port, UHCIPort),
381         VMSTATE_UINT16(cmd, UHCIState),
382         VMSTATE_UINT16(status, UHCIState),
383         VMSTATE_UINT16(intr, UHCIState),
384         VMSTATE_UINT16(frnum, UHCIState),
385         VMSTATE_UINT32(fl_base_addr, UHCIState),
386         VMSTATE_UINT8(sof_timing, UHCIState),
387         VMSTATE_UINT8(status2, UHCIState),
388         VMSTATE_TIMER(frame_timer, UHCIState),
389         VMSTATE_INT64_V(expire_time, UHCIState, 2),
390         VMSTATE_END_OF_LIST()
391     }
392 };
393
394 static void uhci_ioport_writeb(void *opaque, uint32_t addr, uint32_t val)
395 {
396     UHCIState *s = opaque;
397
398     addr &= 0x1f;
399     switch(addr) {
400     case 0x0c:
401         s->sof_timing = val;
402         break;
403     }
404 }
405
406 static uint32_t uhci_ioport_readb(void *opaque, uint32_t addr)
407 {
408     UHCIState *s = opaque;
409     uint32_t val;
410
411     addr &= 0x1f;
412     switch(addr) {
413     case 0x0c:
414         val = s->sof_timing;
415         break;
416     default:
417         val = 0xff;
418         break;
419     }
420     return val;
421 }
422
423 static void uhci_ioport_writew(void *opaque, uint32_t addr, uint32_t val)
424 {
425     UHCIState *s = opaque;
426
427     addr &= 0x1f;
428     DPRINTF("uhci: writew port=0x%04x val=0x%04x\n", addr, val);
429
430     switch(addr) {
431     case 0x00:
432         if ((val & UHCI_CMD_RS) && !(s->cmd & UHCI_CMD_RS)) {
433             /* start frame processing */
434             s->expire_time = qemu_get_clock_ns(vm_clock) +
435                 (get_ticks_per_sec() / FRAME_TIMER_FREQ);
436             qemu_mod_timer(s->frame_timer, qemu_get_clock_ns(vm_clock));
437             s->status &= ~UHCI_STS_HCHALTED;
438         } else if (!(val & UHCI_CMD_RS)) {
439             s->status |= UHCI_STS_HCHALTED;
440         }
441         if (val & UHCI_CMD_GRESET) {
442             UHCIPort *port;
443             USBDevice *dev;
444             int i;
445
446             /* send reset on the USB bus */
447             for(i = 0; i < NB_PORTS; i++) {
448                 port = &s->ports[i];
449                 dev = port->port.dev;
450                 if (dev && dev->attached) {
451                     usb_send_msg(dev, USB_MSG_RESET);
452                 }
453             }
454             uhci_reset(s);
455             return;
456         }
457         if (val & UHCI_CMD_HCRESET) {
458             uhci_reset(s);
459             return;
460         }
461         s->cmd = val;
462         break;
463     case 0x02:
464         s->status &= ~val;
465         /* XXX: the chip spec is not coherent, so we add a hidden
466            register to distinguish between IOC and SPD */
467         if (val & UHCI_STS_USBINT)
468             s->status2 = 0;
469         uhci_update_irq(s);
470         break;
471     case 0x04:
472         s->intr = val;
473         uhci_update_irq(s);
474         break;
475     case 0x06:
476         if (s->status & UHCI_STS_HCHALTED)
477             s->frnum = val & 0x7ff;
478         break;
479     case 0x10 ... 0x1f:
480         {
481             UHCIPort *port;
482             USBDevice *dev;
483             int n;
484
485             n = (addr >> 1) & 7;
486             if (n >= NB_PORTS)
487                 return;
488             port = &s->ports[n];
489             dev = port->port.dev;
490             if (dev && dev->attached) {
491                 /* port reset */
492                 if ( (val & UHCI_PORT_RESET) &&
493                      !(port->ctrl & UHCI_PORT_RESET) ) {
494                     usb_send_msg(dev, USB_MSG_RESET);
495                 }
496             }
497             port->ctrl &= UHCI_PORT_READ_ONLY;
498             port->ctrl |= (val & ~UHCI_PORT_READ_ONLY);
499             /* some bits are reset when a '1' is written to them */
500             port->ctrl &= ~(val & UHCI_PORT_WRITE_CLEAR);
501         }
502         break;
503     }
504 }
505
506 static uint32_t uhci_ioport_readw(void *opaque, uint32_t addr)
507 {
508     UHCIState *s = opaque;
509     uint32_t val;
510
511     addr &= 0x1f;
512     switch(addr) {
513     case 0x00:
514         val = s->cmd;
515         break;
516     case 0x02:
517         val = s->status;
518         break;
519     case 0x04:
520         val = s->intr;
521         break;
522     case 0x06:
523         val = s->frnum;
524         break;
525     case 0x10 ... 0x1f:
526         {
527             UHCIPort *port;
528             int n;
529             n = (addr >> 1) & 7;
530             if (n >= NB_PORTS)
531                 goto read_default;
532             port = &s->ports[n];
533             val = port->ctrl;
534         }
535         break;
536     default:
537     read_default:
538         val = 0xff7f; /* disabled port */
539         break;
540     }
541
542     DPRINTF("uhci: readw port=0x%04x val=0x%04x\n", addr, val);
543
544     return val;
545 }
546
547 static void uhci_ioport_writel(void *opaque, uint32_t addr, uint32_t val)
548 {
549     UHCIState *s = opaque;
550
551     addr &= 0x1f;
552     DPRINTF("uhci: writel port=0x%04x val=0x%08x\n", addr, val);
553
554     switch(addr) {
555     case 0x08:
556         s->fl_base_addr = val & ~0xfff;
557         break;
558     }
559 }
560
561 static uint32_t uhci_ioport_readl(void *opaque, uint32_t addr)
562 {
563     UHCIState *s = opaque;
564     uint32_t val;
565
566     addr &= 0x1f;
567     switch(addr) {
568     case 0x08:
569         val = s->fl_base_addr;
570         break;
571     default:
572         val = 0xffffffff;
573         break;
574     }
575     return val;
576 }
577
578 /* signal resume if controller suspended */
579 static void uhci_resume (void *opaque)
580 {
581     UHCIState *s = (UHCIState *)opaque;
582
583     if (!s)
584         return;
585
586     if (s->cmd & UHCI_CMD_EGSM) {
587         s->cmd |= UHCI_CMD_FGR;
588         s->status |= UHCI_STS_RD;
589         uhci_update_irq(s);
590     }
591 }
592
593 static void uhci_attach(USBPort *port1)
594 {
595     UHCIState *s = port1->opaque;
596     UHCIPort *port = &s->ports[port1->index];
597
598     /* set connect status */
599     port->ctrl |= UHCI_PORT_CCS | UHCI_PORT_CSC;
600
601     /* update speed */
602     if (port->port.dev->speed == USB_SPEED_LOW) {
603         port->ctrl |= UHCI_PORT_LSDA;
604     } else {
605         port->ctrl &= ~UHCI_PORT_LSDA;
606     }
607
608     uhci_resume(s);
609 }
610
611 static void uhci_detach(USBPort *port1)
612 {
613     UHCIState *s = port1->opaque;
614     UHCIPort *port = &s->ports[port1->index];
615
616     uhci_async_cancel_device(s, port1->dev);
617
618     /* set connect status */
619     if (port->ctrl & UHCI_PORT_CCS) {
620         port->ctrl &= ~UHCI_PORT_CCS;
621         port->ctrl |= UHCI_PORT_CSC;
622     }
623     /* disable port */
624     if (port->ctrl & UHCI_PORT_EN) {
625         port->ctrl &= ~UHCI_PORT_EN;
626         port->ctrl |= UHCI_PORT_ENC;
627     }
628
629     uhci_resume(s);
630 }
631
632 static void uhci_child_detach(USBPort *port1, USBDevice *child)
633 {
634     UHCIState *s = port1->opaque;
635
636     uhci_async_cancel_device(s, child);
637 }
638
639 static void uhci_wakeup(USBPort *port1)
640 {
641     UHCIState *s = port1->opaque;
642     UHCIPort *port = &s->ports[port1->index];
643
644     if (port->ctrl & UHCI_PORT_SUSPEND && !(port->ctrl & UHCI_PORT_RD)) {
645         port->ctrl |= UHCI_PORT_RD;
646         uhci_resume(s);
647     }
648 }
649
650 static int uhci_broadcast_packet(UHCIState *s, USBPacket *p)
651 {
652     int i, ret;
653
654     DPRINTF("uhci: packet enter. pid %s addr 0x%02x ep %d len %zd\n",
655            pid2str(p->pid), p->devaddr, p->devep, p->iov.size);
656     if (p->pid == USB_TOKEN_OUT || p->pid == USB_TOKEN_SETUP)
657         dump_data(p, 0);
658
659     ret = USB_RET_NODEV;
660     for (i = 0; i < NB_PORTS && ret == USB_RET_NODEV; i++) {
661         UHCIPort *port = &s->ports[i];
662         USBDevice *dev = port->port.dev;
663
664         if (dev && dev->attached && (port->ctrl & UHCI_PORT_EN)) {
665             ret = usb_handle_packet(dev, p);
666         }
667     }
668
669     DPRINTF("uhci: packet exit. ret %d len %zd\n", ret, p->iov.size);
670     if (p->pid == USB_TOKEN_IN && ret > 0)
671         dump_data(p, ret);
672
673     return ret;
674 }
675
676 static void uhci_async_complete(USBPort *port, USBPacket *packet);
677 static void uhci_process_frame(UHCIState *s);
678
679 /* return -1 if fatal error (frame must be stopped)
680           0 if TD successful
681           1 if TD unsuccessful or inactive
682 */
683 static int uhci_complete_td(UHCIState *s, UHCI_TD *td, UHCIAsync *async, uint32_t *int_mask)
684 {
685     int len = 0, max_len, err, ret;
686     uint8_t pid;
687
688     max_len = ((td->token >> 21) + 1) & 0x7ff;
689     pid = td->token & 0xff;
690
691     ret = async->packet.result;
692
693     if (td->ctrl & TD_CTRL_IOS)
694         td->ctrl &= ~TD_CTRL_ACTIVE;
695
696     if (ret < 0)
697         goto out;
698
699     len = async->packet.result;
700     td->ctrl = (td->ctrl & ~0x7ff) | ((len - 1) & 0x7ff);
701
702     /* The NAK bit may have been set by a previous frame, so clear it
703        here.  The docs are somewhat unclear, but win2k relies on this
704        behavior.  */
705     td->ctrl &= ~(TD_CTRL_ACTIVE | TD_CTRL_NAK);
706     if (td->ctrl & TD_CTRL_IOC)
707         *int_mask |= 0x01;
708
709     if (pid == USB_TOKEN_IN) {
710         if (len > max_len) {
711             ret = USB_RET_BABBLE;
712             goto out;
713         }
714
715         if ((td->ctrl & TD_CTRL_SPD) && len < max_len) {
716             *int_mask |= 0x02;
717             /* short packet: do not update QH */
718             DPRINTF("uhci: short packet. td 0x%x token 0x%x\n", async->td, async->token);
719             return 1;
720         }
721     }
722
723     /* success */
724     return 0;
725
726 out:
727     switch(ret) {
728     case USB_RET_STALL:
729         td->ctrl |= TD_CTRL_STALL;
730         td->ctrl &= ~TD_CTRL_ACTIVE;
731         s->status |= UHCI_STS_USBERR;
732         if (td->ctrl & TD_CTRL_IOC) {
733             *int_mask |= 0x01;
734         }
735         uhci_update_irq(s);
736         return 1;
737
738     case USB_RET_BABBLE:
739         td->ctrl |= TD_CTRL_BABBLE | TD_CTRL_STALL;
740         td->ctrl &= ~TD_CTRL_ACTIVE;
741         s->status |= UHCI_STS_USBERR;
742         if (td->ctrl & TD_CTRL_IOC) {
743             *int_mask |= 0x01;
744         }
745         uhci_update_irq(s);
746         /* frame interrupted */
747         return -1;
748
749     case USB_RET_NAK:
750         td->ctrl |= TD_CTRL_NAK;
751         if (pid == USB_TOKEN_SETUP)
752             break;
753         return 1;
754
755     case USB_RET_NODEV:
756     default:
757         break;
758     }
759
760     /* Retry the TD if error count is not zero */
761
762     td->ctrl |= TD_CTRL_TIMEOUT;
763     err = (td->ctrl >> TD_CTRL_ERROR_SHIFT) & 3;
764     if (err != 0) {
765         err--;
766         if (err == 0) {
767             td->ctrl &= ~TD_CTRL_ACTIVE;
768             s->status |= UHCI_STS_USBERR;
769             if (td->ctrl & TD_CTRL_IOC)
770                 *int_mask |= 0x01;
771             uhci_update_irq(s);
772         }
773     }
774     td->ctrl = (td->ctrl & ~(3 << TD_CTRL_ERROR_SHIFT)) |
775         (err << TD_CTRL_ERROR_SHIFT);
776     return 1;
777 }
778
779 static int uhci_handle_td(UHCIState *s, uint32_t addr, UHCI_TD *td, uint32_t *int_mask)
780 {
781     UHCIAsync *async;
782     int len = 0, max_len;
783     uint8_t pid, isoc;
784     uint32_t token;
785
786     /* Is active ? */
787     if (!(td->ctrl & TD_CTRL_ACTIVE))
788         return 1;
789
790     /* token field is not unique for isochronous requests,
791      * so use the destination buffer 
792      */
793     if (td->ctrl & TD_CTRL_IOS) {
794         token = td->buffer;
795         isoc = 1;
796     } else {
797         token = td->token;
798         isoc = 0;
799     }
800
801     async = uhci_async_find_td(s, addr, token);
802     if (async) {
803         /* Already submitted */
804         async->valid = 32;
805
806         if (!async->done)
807             return 1;
808
809         uhci_async_unlink(s, async);
810         goto done;
811     }
812
813     /* Allocate new packet */
814     async = uhci_async_alloc(s);
815     if (!async)
816         return 1;
817
818     /* valid needs to be large enough to handle 10 frame delay
819      * for initial isochronous requests
820      */
821     async->valid = 32;
822     async->td    = addr;
823     async->token = token;
824     async->isoc  = isoc;
825
826     max_len = ((td->token >> 21) + 1) & 0x7ff;
827     pid = td->token & 0xff;
828
829     usb_packet_setup(&async->packet, pid, (td->token >> 8) & 0x7f,
830                      (td->token >> 15) & 0xf);
831     qemu_sglist_add(&async->sgl, td->buffer, max_len);
832     usb_packet_map(&async->packet, &async->sgl);
833
834     switch(pid) {
835     case USB_TOKEN_OUT:
836     case USB_TOKEN_SETUP:
837         len = uhci_broadcast_packet(s, &async->packet);
838         if (len >= 0)
839             len = max_len;
840         break;
841
842     case USB_TOKEN_IN:
843         len = uhci_broadcast_packet(s, &async->packet);
844         break;
845
846     default:
847         /* invalid pid : frame interrupted */
848         uhci_async_free(s, async);
849         s->status |= UHCI_STS_HCPERR;
850         uhci_update_irq(s);
851         return -1;
852     }
853  
854     if (len == USB_RET_ASYNC) {
855         uhci_async_link(s, async);
856         return 2;
857     }
858
859     async->packet.result = len;
860
861 done:
862     len = uhci_complete_td(s, td, async, int_mask);
863     usb_packet_unmap(&async->packet);
864     uhci_async_free(s, async);
865     return len;
866 }
867
868 static void uhci_async_complete(USBPort *port, USBPacket *packet)
869 {
870     UHCIAsync *async = container_of(packet, UHCIAsync, packet);
871     UHCIState *s = async->uhci;
872
873     DPRINTF("uhci: async complete. td 0x%x token 0x%x\n", async->td, async->token);
874
875     if (async->isoc) {
876         UHCI_TD td;
877         uint32_t link = async->td;
878         uint32_t int_mask = 0, val;
879
880         pci_dma_read(&s->dev, link & ~0xf, &td, sizeof(td));
881         le32_to_cpus(&td.link);
882         le32_to_cpus(&td.ctrl);
883         le32_to_cpus(&td.token);
884         le32_to_cpus(&td.buffer);
885
886         uhci_async_unlink(s, async);
887         uhci_complete_td(s, &td, async, &int_mask);
888         s->pending_int_mask |= int_mask;
889
890         /* update the status bits of the TD */
891         val = cpu_to_le32(td.ctrl);
892         pci_dma_write(&s->dev, (link & ~0xf) + 4, &val, sizeof(val));
893         uhci_async_free(s, async);
894     } else {
895         async->done = 1;
896         uhci_process_frame(s);
897     }
898 }
899
900 static int is_valid(uint32_t link)
901 {
902     return (link & 1) == 0;
903 }
904
905 static int is_qh(uint32_t link)
906 {
907     return (link & 2) != 0;
908 }
909
910 static int depth_first(uint32_t link)
911 {
912     return (link & 4) != 0;
913 }
914
915 /* QH DB used for detecting QH loops */
916 #define UHCI_MAX_QUEUES 128
917 typedef struct {
918     uint32_t addr[UHCI_MAX_QUEUES];
919     int      count;
920 } QhDb;
921
922 static void qhdb_reset(QhDb *db)
923 {
924     db->count = 0;
925 }
926
927 /* Add QH to DB. Returns 1 if already present or DB is full. */
928 static int qhdb_insert(QhDb *db, uint32_t addr)
929 {
930     int i;
931     for (i = 0; i < db->count; i++)
932         if (db->addr[i] == addr)
933             return 1;
934
935     if (db->count >= UHCI_MAX_QUEUES)
936         return 1;
937
938     db->addr[db->count++] = addr;
939     return 0;
940 }
941
942 static void uhci_process_frame(UHCIState *s)
943 {
944     uint32_t frame_addr, link, old_td_ctrl, val, int_mask;
945     uint32_t curr_qh;
946     int cnt, ret;
947     UHCI_TD td;
948     UHCI_QH qh;
949     QhDb qhdb;
950
951     frame_addr = s->fl_base_addr + ((s->frnum & 0x3ff) << 2);
952
953     DPRINTF("uhci: processing frame %d addr 0x%x\n" , s->frnum, frame_addr);
954
955     pci_dma_read(&s->dev, frame_addr, &link, 4);
956     le32_to_cpus(&link);
957
958     int_mask = 0;
959     curr_qh  = 0;
960
961     qhdb_reset(&qhdb);
962
963     for (cnt = FRAME_MAX_LOOPS; is_valid(link) && cnt; cnt--) {
964         if (is_qh(link)) {
965             /* QH */
966
967             if (qhdb_insert(&qhdb, link)) {
968                 /*
969                  * We're going in circles. Which is not a bug because
970                  * HCD is allowed to do that as part of the BW management. 
971                  * In our case though it makes no sense to spin here. Sync transations 
972                  * are already done, and async completion handler will re-process 
973                  * the frame when something is ready.
974                  */
975                 DPRINTF("uhci: detected loop. qh 0x%x\n", link);
976                 break;
977             }
978
979             pci_dma_read(&s->dev, link & ~0xf, &qh, sizeof(qh));
980             le32_to_cpus(&qh.link);
981             le32_to_cpus(&qh.el_link);
982
983             DPRINTF("uhci: QH 0x%x load. link 0x%x elink 0x%x\n",
984                     link, qh.link, qh.el_link);
985
986             if (!is_valid(qh.el_link)) {
987                 /* QH w/o elements */
988                 curr_qh = 0;
989                 link = qh.link;
990             } else {
991                 /* QH with elements */
992                 curr_qh = link;
993                 link = qh.el_link;
994             }
995             continue;
996         }
997
998         /* TD */
999         pci_dma_read(&s->dev, link & ~0xf, &td, sizeof(td));
1000         le32_to_cpus(&td.link);
1001         le32_to_cpus(&td.ctrl);
1002         le32_to_cpus(&td.token);
1003         le32_to_cpus(&td.buffer);
1004
1005         DPRINTF("uhci: TD 0x%x load. link 0x%x ctrl 0x%x token 0x%x qh 0x%x\n", 
1006                 link, td.link, td.ctrl, td.token, curr_qh);
1007
1008         old_td_ctrl = td.ctrl;
1009         ret = uhci_handle_td(s, link, &td, &int_mask);
1010         if (old_td_ctrl != td.ctrl) {
1011             /* update the status bits of the TD */
1012             val = cpu_to_le32(td.ctrl);
1013             pci_dma_write(&s->dev, (link & ~0xf) + 4, &val, sizeof(val));
1014         }
1015
1016         if (ret < 0) {
1017             /* interrupted frame */
1018             break;
1019         }
1020
1021         if (ret == 2 || ret == 1) {
1022             DPRINTF("uhci: TD 0x%x %s. link 0x%x ctrl 0x%x token 0x%x qh 0x%x\n",
1023                     link, ret == 2 ? "pend" : "skip",
1024                     td.link, td.ctrl, td.token, curr_qh);
1025
1026             link = curr_qh ? qh.link : td.link;
1027             continue;
1028         }
1029
1030         /* completed TD */
1031
1032         DPRINTF("uhci: TD 0x%x done. link 0x%x ctrl 0x%x token 0x%x qh 0x%x\n", 
1033                 link, td.link, td.ctrl, td.token, curr_qh);
1034
1035         link = td.link;
1036
1037         if (curr_qh) {
1038             /* update QH element link */
1039             qh.el_link = link;
1040             val = cpu_to_le32(qh.el_link);
1041             pci_dma_write(&s->dev, (curr_qh & ~0xf) + 4, &val, sizeof(val));
1042
1043             if (!depth_first(link)) {
1044                /* done with this QH */
1045
1046                DPRINTF("uhci: QH 0x%x done. link 0x%x elink 0x%x\n",
1047                        curr_qh, qh.link, qh.el_link);
1048
1049                curr_qh = 0;
1050                link    = qh.link;
1051             }
1052         }
1053
1054         /* go to the next entry */
1055     }
1056
1057     s->pending_int_mask |= int_mask;
1058 }
1059
1060 static void uhci_frame_timer(void *opaque)
1061 {
1062     UHCIState *s = opaque;
1063
1064     /* prepare the timer for the next frame */
1065     s->expire_time += (get_ticks_per_sec() / FRAME_TIMER_FREQ);
1066
1067     if (!(s->cmd & UHCI_CMD_RS)) {
1068         /* Full stop */
1069         qemu_del_timer(s->frame_timer);
1070         /* set hchalted bit in status - UHCI11D 2.1.2 */
1071         s->status |= UHCI_STS_HCHALTED;
1072
1073         DPRINTF("uhci: halted\n");
1074         return;
1075     }
1076
1077     /* Complete the previous frame */
1078     if (s->pending_int_mask) {
1079         s->status2 |= s->pending_int_mask;
1080         s->status  |= UHCI_STS_USBINT;
1081         uhci_update_irq(s);
1082     }
1083     s->pending_int_mask = 0;
1084
1085     /* Start new frame */
1086     s->frnum = (s->frnum + 1) & 0x7ff;
1087
1088     DPRINTF("uhci: new frame #%u\n" , s->frnum);
1089
1090     uhci_async_validate_begin(s);
1091
1092     uhci_process_frame(s);
1093
1094     uhci_async_validate_end(s);
1095
1096     qemu_mod_timer(s->frame_timer, s->expire_time);
1097 }
1098
1099 static const MemoryRegionPortio uhci_portio[] = {
1100     { 0, 32, 2, .write = uhci_ioport_writew, },
1101     { 0, 32, 2, .read = uhci_ioport_readw, },
1102     { 0, 32, 4, .write = uhci_ioport_writel, },
1103     { 0, 32, 4, .read = uhci_ioport_readl, },
1104     { 0, 32, 1, .write = uhci_ioport_writeb, },
1105     { 0, 32, 1, .read = uhci_ioport_readb, },
1106     PORTIO_END_OF_LIST()
1107 };
1108
1109 static const MemoryRegionOps uhci_ioport_ops = {
1110     .old_portio = uhci_portio,
1111 };
1112
1113 static USBPortOps uhci_port_ops = {
1114     .attach = uhci_attach,
1115     .detach = uhci_detach,
1116     .child_detach = uhci_child_detach,
1117     .wakeup = uhci_wakeup,
1118     .complete = uhci_async_complete,
1119 };
1120
1121 static USBBusOps uhci_bus_ops = {
1122 };
1123
1124 static int usb_uhci_common_initfn(PCIDevice *dev)
1125 {
1126     UHCIState *s = DO_UPCAST(UHCIState, dev, dev);
1127     uint8_t *pci_conf = s->dev.config;
1128     int i;
1129
1130     pci_conf[PCI_CLASS_PROG] = 0x00;
1131     /* TODO: reset value should be 0. */
1132     pci_conf[PCI_INTERRUPT_PIN] = 4; /* interrupt pin D */
1133     pci_conf[USB_SBRN] = USB_RELEASE_1; // release number
1134
1135     if (s->masterbus) {
1136         USBPort *ports[NB_PORTS];
1137         for(i = 0; i < NB_PORTS; i++) {
1138             ports[i] = &s->ports[i].port;
1139         }
1140         if (usb_register_companion(s->masterbus, ports, NB_PORTS,
1141                 s->firstport, s, &uhci_port_ops,
1142                 USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL) != 0) {
1143             return -1;
1144         }
1145     } else {
1146         usb_bus_new(&s->bus, &uhci_bus_ops, &s->dev.qdev);
1147         for (i = 0; i < NB_PORTS; i++) {
1148             usb_register_port(&s->bus, &s->ports[i].port, s, i, &uhci_port_ops,
1149                               USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL);
1150         }
1151     }
1152     s->frame_timer = qemu_new_timer_ns(vm_clock, uhci_frame_timer, s);
1153     s->num_ports_vmstate = NB_PORTS;
1154     QTAILQ_INIT(&s->async_pending);
1155
1156     qemu_register_reset(uhci_reset, s);
1157
1158     memory_region_init_io(&s->io_bar, &uhci_ioport_ops, s, "uhci", 0x20);
1159     /* Use region 4 for consistency with real hardware.  BSD guests seem
1160        to rely on this.  */
1161     pci_register_bar(&s->dev, 4, PCI_BASE_ADDRESS_SPACE_IO, &s->io_bar);
1162
1163     return 0;
1164 }
1165
1166 static int usb_uhci_vt82c686b_initfn(PCIDevice *dev)
1167 {
1168     UHCIState *s = DO_UPCAST(UHCIState, dev, dev);
1169     uint8_t *pci_conf = s->dev.config;
1170
1171     /* USB misc control 1/2 */
1172     pci_set_long(pci_conf + 0x40,0x00001000);
1173     /* PM capability */
1174     pci_set_long(pci_conf + 0x80,0x00020001);
1175     /* USB legacy support  */
1176     pci_set_long(pci_conf + 0xc0,0x00002000);
1177
1178     return usb_uhci_common_initfn(dev);
1179 }
1180
1181 static int usb_uhci_exit(PCIDevice *dev)
1182 {
1183     UHCIState *s = DO_UPCAST(UHCIState, dev, dev);
1184
1185     memory_region_destroy(&s->io_bar);
1186     return 0;
1187 }
1188
1189 static Property uhci_properties[] = {
1190     DEFINE_PROP_STRING("masterbus", UHCIState, masterbus),
1191     DEFINE_PROP_UINT32("firstport", UHCIState, firstport, 0),
1192     DEFINE_PROP_END_OF_LIST(),
1193 };
1194
1195 static void piix3_uhci_class_init(ObjectClass *klass, void *data)
1196 {
1197     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1198
1199     k->init = usb_uhci_common_initfn;
1200     k->exit = usb_uhci_exit;
1201     k->vendor_id = PCI_VENDOR_ID_INTEL;
1202     k->device_id = PCI_DEVICE_ID_INTEL_82371SB_2;
1203     k->revision = 0x01;
1204     k->class_id = PCI_CLASS_SERIAL_USB;
1205 }
1206
1207 static DeviceInfo piix3_uhci_info = {
1208     .name = "piix3-usb-uhci",
1209     .size = sizeof(UHCIState),
1210     .vmsd = &vmstate_uhci,
1211     .props = uhci_properties,
1212     .class_init = piix3_uhci_class_init,
1213 };
1214
1215 static void piix4_uhci_class_init(ObjectClass *klass, void *data)
1216 {
1217     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1218
1219     k->init = usb_uhci_common_initfn;
1220     k->exit = usb_uhci_exit;
1221     k->vendor_id = PCI_VENDOR_ID_INTEL;
1222     k->device_id = PCI_DEVICE_ID_INTEL_82371AB_2;
1223     k->revision = 0x01;
1224     k->class_id = PCI_CLASS_SERIAL_USB;
1225 }
1226
1227 static DeviceInfo piix4_uhci_info = {
1228     .name = "piix4-usb-uhci",
1229     .size = sizeof(UHCIState),
1230     .vmsd = &vmstate_uhci,
1231     .props = uhci_properties,
1232     .class_init = piix4_uhci_class_init,
1233 };
1234
1235 static void vt82c686b_uhci_class_init(ObjectClass *klass, void *data)
1236 {
1237     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1238
1239     k->init = usb_uhci_vt82c686b_initfn;
1240     k->exit = usb_uhci_exit;
1241     k->vendor_id = PCI_VENDOR_ID_VIA;
1242     k->device_id = PCI_DEVICE_ID_VIA_UHCI;
1243     k->revision = 0x01;
1244     k->class_id = PCI_CLASS_SERIAL_USB;
1245 }
1246
1247 static DeviceInfo vt82c686b_uhci_info = {
1248     .name = "vt82c686b-usb-uhci",
1249     .size = sizeof(UHCIState),
1250     .vmsd = &vmstate_uhci,
1251     .props = uhci_properties,
1252     .class_init = vt82c686b_uhci_class_init,
1253 };
1254
1255 static void ich9_uhci1_class_init(ObjectClass *klass, void *data)
1256 {
1257     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1258
1259     k->init = usb_uhci_common_initfn;
1260     k->vendor_id = PCI_VENDOR_ID_INTEL;
1261     k->device_id = PCI_DEVICE_ID_INTEL_82801I_UHCI1;
1262     k->revision = 0x03;
1263     k->class_id = PCI_CLASS_SERIAL_USB;
1264 }
1265
1266 static DeviceInfo ich9_uhci1_info = {
1267     .name = "ich9-usb-uhci1",
1268     .size = sizeof(UHCIState),
1269     .vmsd = &vmstate_uhci,
1270     .props = uhci_properties,
1271     .class_init = ich9_uhci1_class_init,
1272 };
1273
1274 static void ich9_uhci2_class_init(ObjectClass *klass, void *data)
1275 {
1276     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1277
1278     k->init = usb_uhci_common_initfn;
1279     k->vendor_id = PCI_VENDOR_ID_INTEL;
1280     k->device_id = PCI_DEVICE_ID_INTEL_82801I_UHCI2;
1281     k->revision = 0x03;
1282     k->class_id = PCI_CLASS_SERIAL_USB;
1283 }
1284
1285 static DeviceInfo ich9_uhci2_info = {
1286     .name = "ich9-usb-uhci2",
1287     .size = sizeof(UHCIState),
1288     .vmsd = &vmstate_uhci,
1289     .props = uhci_properties,
1290     .class_init = ich9_uhci2_class_init,
1291 };
1292
1293 static void ich9_uhci3_class_init(ObjectClass *klass, void *data)
1294 {
1295     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1296
1297     k->init = usb_uhci_common_initfn;
1298     k->vendor_id = PCI_VENDOR_ID_INTEL;
1299     k->device_id = PCI_DEVICE_ID_INTEL_82801I_UHCI3;
1300     k->revision = 0x03;
1301     k->class_id = PCI_CLASS_SERIAL_USB;
1302 }
1303
1304 static DeviceInfo ich9_uhci3_info = {
1305     .name = "ich9-usb-uhci3",
1306     .size = sizeof(UHCIState),
1307     .vmsd = &vmstate_uhci,
1308     .props = uhci_properties,
1309     .class_init = ich9_uhci3_class_init,
1310 };
1311
1312 static void uhci_register(void)
1313 {
1314     pci_qdev_register(&piix3_uhci_info);
1315     pci_qdev_register(&piix4_uhci_info);
1316     pci_qdev_register(&vt82c686b_uhci_info);
1317     pci_qdev_register(&ich9_uhci1_info);
1318     pci_qdev_register(&ich9_uhci2_info);
1319     pci_qdev_register(&ich9_uhci3_info);
1320 }
1321 device_init(uhci_register);
1322
1323 void usb_uhci_piix3_init(PCIBus *bus, int devfn)
1324 {
1325     pci_create_simple(bus, devfn, "piix3-usb-uhci");
1326 }
1327
1328 void usb_uhci_piix4_init(PCIBus *bus, int devfn)
1329 {
1330     pci_create_simple(bus, devfn, "piix4-usb-uhci");
1331 }
1332
1333 void usb_uhci_vt82c686b_init(PCIBus *bus, int devfn)
1334 {
1335     pci_create_simple(bus, devfn, "vt82c686b-usb-uhci");
1336 }