xref: /illumos-kvm-cmd/hw/usb-uhci.c (revision fe0e2a69)
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 
pid2str(int pid)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
dump_data(const uint8_t * data,int len)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
dump_data(const uint8_t * data,int len)106 static void dump_data(const uint8_t *data, int len) {}
107 #endif
108 
109 /*
110  * Pending async transaction.
111  * 'packet' must be the first field because completion
112  * handler does "(UHCIAsync *) pkt" cast.
113  */
114 typedef struct UHCIAsync {
115     USBPacket packet;
116     struct UHCIAsync *next;
117     uint32_t  td;
118     uint32_t  token;
119     int8_t    valid;
120     uint8_t   isoc;
121     uint8_t   done;
122     uint8_t   buffer[2048];
123 } UHCIAsync;
124 
125 typedef struct UHCIPort {
126     USBPort port;
127     uint16_t ctrl;
128 } UHCIPort;
129 
130 typedef struct UHCIState {
131     PCIDevice dev;
132     USBBus bus;
133     uint16_t cmd; /* cmd register */
134     uint16_t status;
135     uint16_t intr; /* interrupt enable register */
136     uint16_t frnum; /* frame number */
137     uint32_t fl_base_addr; /* frame list base address */
138     uint8_t sof_timing;
139     uint8_t status2; /* bit 0 and 1 are used to generate UHCI_STS_USBINT */
140     int64_t expire_time;
141     QEMUTimer *frame_timer;
142     UHCIPort ports[NB_PORTS];
143 
144     /* Interrupts that should be raised at the end of the current frame.  */
145     uint32_t pending_int_mask;
146 
147     /* Active packets */
148     UHCIAsync *async_pending;
149     UHCIAsync *async_pool;
150     uint8_t num_ports_vmstate;
151 } UHCIState;
152 
153 typedef struct UHCI_TD {
154     uint32_t link;
155     uint32_t ctrl; /* see TD_CTRL_xxx */
156     uint32_t token;
157     uint32_t buffer;
158 } UHCI_TD;
159 
160 typedef struct UHCI_QH {
161     uint32_t link;
162     uint32_t el_link;
163 } UHCI_QH;
164 
uhci_async_alloc(UHCIState * s)165 static UHCIAsync *uhci_async_alloc(UHCIState *s)
166 {
167     UHCIAsync *async = qemu_malloc(sizeof(UHCIAsync));
168 
169     memset(&async->packet, 0, sizeof(async->packet));
170     async->valid = 0;
171     async->td    = 0;
172     async->token = 0;
173     async->done  = 0;
174     async->isoc  = 0;
175     async->next  = NULL;
176 
177     return async;
178 }
179 
uhci_async_free(UHCIState * s,UHCIAsync * async)180 static void uhci_async_free(UHCIState *s, UHCIAsync *async)
181 {
182     qemu_free(async);
183 }
184 
uhci_async_link(UHCIState * s,UHCIAsync * async)185 static void uhci_async_link(UHCIState *s, UHCIAsync *async)
186 {
187     async->next = s->async_pending;
188     s->async_pending = async;
189 }
190 
uhci_async_unlink(UHCIState * s,UHCIAsync * async)191 static void uhci_async_unlink(UHCIState *s, UHCIAsync *async)
192 {
193     UHCIAsync *curr = s->async_pending;
194     UHCIAsync **prev = &s->async_pending;
195 
196     while (curr) {
197 	if (curr == async) {
198             *prev = curr->next;
199             return;
200         }
201 
202         prev = &curr->next;
203         curr = curr->next;
204     }
205 }
206 
uhci_async_cancel(UHCIState * s,UHCIAsync * async)207 static void uhci_async_cancel(UHCIState *s, UHCIAsync *async)
208 {
209     DPRINTF("uhci: cancel td 0x%x token 0x%x done %u\n",
210            async->td, async->token, async->done);
211 
212     if (!async->done)
213         usb_cancel_packet(&async->packet);
214     uhci_async_free(s, async);
215 }
216 
217 /*
218  * Mark all outstanding async packets as invalid.
219  * This is used for canceling them when TDs are removed by the HCD.
220  */
uhci_async_validate_begin(UHCIState * s)221 static UHCIAsync *uhci_async_validate_begin(UHCIState *s)
222 {
223     UHCIAsync *async = s->async_pending;
224 
225     while (async) {
226         async->valid--;
227         async = async->next;
228     }
229     return NULL;
230 }
231 
232 /*
233  * Cancel async packets that are no longer valid
234  */
uhci_async_validate_end(UHCIState * s)235 static void uhci_async_validate_end(UHCIState *s)
236 {
237     UHCIAsync *curr = s->async_pending;
238     UHCIAsync **prev = &s->async_pending;
239     UHCIAsync *next;
240 
241     while (curr) {
242         if (curr->valid > 0) {
243             prev = &curr->next;
244             curr = curr->next;
245             continue;
246         }
247 
248         next = curr->next;
249 
250         /* Unlink */
251         *prev = next;
252 
253         uhci_async_cancel(s, curr);
254 
255         curr = next;
256     }
257 }
258 
uhci_async_cancel_all(UHCIState * s)259 static void uhci_async_cancel_all(UHCIState *s)
260 {
261     UHCIAsync *curr = s->async_pending;
262     UHCIAsync *next;
263 
264     while (curr) {
265         next = curr->next;
266 
267         uhci_async_cancel(s, curr);
268 
269         curr = next;
270     }
271 
272     s->async_pending = NULL;
273 }
274 
uhci_async_find_td(UHCIState * s,uint32_t addr,uint32_t token)275 static UHCIAsync *uhci_async_find_td(UHCIState *s, uint32_t addr, uint32_t token)
276 {
277     UHCIAsync *async = s->async_pending;
278     UHCIAsync *match = NULL;
279     int count = 0;
280 
281     /*
282      * We're looking for the best match here. ie both td addr and token.
283      * Otherwise we return last good match. ie just token.
284      * It's ok to match just token because it identifies the transaction
285      * rather well, token includes: device addr, endpoint, size, etc.
286      *
287      * Also since we queue async transactions in reverse order by returning
288      * last good match we restores the order.
289      *
290      * It's expected that we wont have a ton of outstanding transactions.
291      * If we ever do we'd want to optimize this algorithm.
292      */
293 
294     while (async) {
295         if (async->token == token) {
296             /* Good match */
297             match = async;
298 
299             if (async->td == addr) {
300                 /* Best match */
301                 break;
302             }
303         }
304 
305         async = async->next;
306         count++;
307     }
308 
309     if (count > 64)
310 	fprintf(stderr, "uhci: warning lots of async transactions\n");
311 
312     return match;
313 }
314 
uhci_update_irq(UHCIState * s)315 static void uhci_update_irq(UHCIState *s)
316 {
317     int level;
318     if (((s->status2 & 1) && (s->intr & (1 << 2))) ||
319         ((s->status2 & 2) && (s->intr & (1 << 3))) ||
320         ((s->status & UHCI_STS_USBERR) && (s->intr & (1 << 0))) ||
321         ((s->status & UHCI_STS_RD) && (s->intr & (1 << 1))) ||
322         (s->status & UHCI_STS_HSERR) ||
323         (s->status & UHCI_STS_HCPERR)) {
324         level = 1;
325     } else {
326         level = 0;
327     }
328     qemu_set_irq(s->dev.irq[3], level);
329 }
330 
uhci_reset(void * opaque)331 static void uhci_reset(void *opaque)
332 {
333     UHCIState *s = opaque;
334     uint8_t *pci_conf;
335     int i;
336     UHCIPort *port;
337 
338     DPRINTF("uhci: full reset\n");
339 
340     pci_conf = s->dev.config;
341 
342     pci_conf[0x6a] = 0x01; /* usb clock */
343     pci_conf[0x6b] = 0x00;
344     s->cmd = 0;
345     s->status = 0;
346     s->status2 = 0;
347     s->intr = 0;
348     s->fl_base_addr = 0;
349     s->sof_timing = 64;
350 
351     for(i = 0; i < NB_PORTS; i++) {
352         port = &s->ports[i];
353         port->ctrl = 0x0080;
354         if (port->port.dev) {
355             usb_attach(&port->port, port->port.dev);
356         }
357     }
358 
359     uhci_async_cancel_all(s);
360 }
361 
uhci_pre_save(void * opaque)362 static void uhci_pre_save(void *opaque)
363 {
364     UHCIState *s = opaque;
365 
366     uhci_async_cancel_all(s);
367 }
368 
369 static const VMStateDescription vmstate_uhci_port = {
370     .name = "uhci port",
371     .version_id = 1,
372     .minimum_version_id = 1,
373     .minimum_version_id_old = 1,
374     .fields      = (VMStateField []) {
375         VMSTATE_UINT16(ctrl, UHCIPort),
376         VMSTATE_END_OF_LIST()
377     }
378 };
379 
380 static const VMStateDescription vmstate_uhci = {
381     .name = "uhci",
382     .version_id = 2,
383     .minimum_version_id = 1,
384     .minimum_version_id_old = 1,
385     .pre_save = uhci_pre_save,
386     .fields      = (VMStateField []) {
387         VMSTATE_PCI_DEVICE(dev, UHCIState),
388         VMSTATE_UINT8_EQUAL(num_ports_vmstate, UHCIState),
389         VMSTATE_STRUCT_ARRAY(ports, UHCIState, NB_PORTS, 1,
390                              vmstate_uhci_port, UHCIPort),
391         VMSTATE_UINT16(cmd, UHCIState),
392         VMSTATE_UINT16(status, UHCIState),
393         VMSTATE_UINT16(intr, UHCIState),
394         VMSTATE_UINT16(frnum, UHCIState),
395         VMSTATE_UINT32(fl_base_addr, UHCIState),
396         VMSTATE_UINT8(sof_timing, UHCIState),
397         VMSTATE_UINT8(status2, UHCIState),
398         VMSTATE_TIMER(frame_timer, UHCIState),
399         VMSTATE_INT64_V(expire_time, UHCIState, 2),
400         VMSTATE_END_OF_LIST()
401     }
402 };
403 
uhci_ioport_writeb(void * opaque,uint32_t addr,uint32_t val)404 static void uhci_ioport_writeb(void *opaque, uint32_t addr, uint32_t val)
405 {
406     UHCIState *s = opaque;
407 
408     addr &= 0x1f;
409     switch(addr) {
410     case 0x0c:
411         s->sof_timing = val;
412         break;
413     }
414 }
415 
uhci_ioport_readb(void * opaque,uint32_t addr)416 static uint32_t uhci_ioport_readb(void *opaque, uint32_t addr)
417 {
418     UHCIState *s = opaque;
419     uint32_t val;
420 
421     addr &= 0x1f;
422     switch(addr) {
423     case 0x0c:
424         val = s->sof_timing;
425         break;
426     default:
427         val = 0xff;
428         break;
429     }
430     return val;
431 }
432 
uhci_ioport_writew(void * opaque,uint32_t addr,uint32_t val)433 static void uhci_ioport_writew(void *opaque, uint32_t addr, uint32_t val)
434 {
435     UHCIState *s = opaque;
436 
437     addr &= 0x1f;
438     DPRINTF("uhci: writew port=0x%04x val=0x%04x\n", addr, val);
439 
440     switch(addr) {
441     case 0x00:
442         if ((val & UHCI_CMD_RS) && !(s->cmd & UHCI_CMD_RS)) {
443             /* start frame processing */
444             s->expire_time = qemu_get_clock_ns(vm_clock) +
445                 (get_ticks_per_sec() / FRAME_TIMER_FREQ);
446             qemu_mod_timer(s->frame_timer, qemu_get_clock(vm_clock));
447             s->status &= ~UHCI_STS_HCHALTED;
448         } else if (!(val & UHCI_CMD_RS)) {
449             s->status |= UHCI_STS_HCHALTED;
450         }
451         if (val & UHCI_CMD_GRESET) {
452             UHCIPort *port;
453             USBDevice *dev;
454             int i;
455 
456             /* send reset on the USB bus */
457             for(i = 0; i < NB_PORTS; i++) {
458                 port = &s->ports[i];
459                 dev = port->port.dev;
460                 if (dev) {
461                     usb_send_msg(dev, USB_MSG_RESET);
462                 }
463             }
464             uhci_reset(s);
465             return;
466         }
467         if (val & UHCI_CMD_HCRESET) {
468             uhci_reset(s);
469             return;
470         }
471         s->cmd = val;
472         break;
473     case 0x02:
474         s->status &= ~val;
475         /* XXX: the chip spec is not coherent, so we add a hidden
476            register to distinguish between IOC and SPD */
477         if (val & UHCI_STS_USBINT)
478             s->status2 = 0;
479         uhci_update_irq(s);
480         break;
481     case 0x04:
482         s->intr = val;
483         uhci_update_irq(s);
484         break;
485     case 0x06:
486         if (s->status & UHCI_STS_HCHALTED)
487             s->frnum = val & 0x7ff;
488         break;
489     case 0x10 ... 0x1f:
490         {
491             UHCIPort *port;
492             USBDevice *dev;
493             int n;
494 
495             n = (addr >> 1) & 7;
496             if (n >= NB_PORTS)
497                 return;
498             port = &s->ports[n];
499             dev = port->port.dev;
500             if (dev) {
501                 /* port reset */
502                 if ( (val & UHCI_PORT_RESET) &&
503                      !(port->ctrl & UHCI_PORT_RESET) ) {
504                     usb_send_msg(dev, USB_MSG_RESET);
505                 }
506             }
507             port->ctrl &= UHCI_PORT_READ_ONLY;
508             port->ctrl |= (val & ~UHCI_PORT_READ_ONLY);
509             /* some bits are reset when a '1' is written to them */
510             port->ctrl &= ~(val & UHCI_PORT_WRITE_CLEAR);
511         }
512         break;
513     }
514 }
515 
uhci_ioport_readw(void * opaque,uint32_t addr)516 static uint32_t uhci_ioport_readw(void *opaque, uint32_t addr)
517 {
518     UHCIState *s = opaque;
519     uint32_t val;
520 
521     addr &= 0x1f;
522     switch(addr) {
523     case 0x00:
524         val = s->cmd;
525         break;
526     case 0x02:
527         val = s->status;
528         break;
529     case 0x04:
530         val = s->intr;
531         break;
532     case 0x06:
533         val = s->frnum;
534         break;
535     case 0x10 ... 0x1f:
536         {
537             UHCIPort *port;
538             int n;
539             n = (addr >> 1) & 7;
540             if (n >= NB_PORTS)
541                 goto read_default;
542             port = &s->ports[n];
543             val = port->ctrl;
544         }
545         break;
546     default:
547     read_default:
548         val = 0xff7f; /* disabled port */
549         break;
550     }
551 
552     DPRINTF("uhci: readw port=0x%04x val=0x%04x\n", addr, val);
553 
554     return val;
555 }
556 
uhci_ioport_writel(void * opaque,uint32_t addr,uint32_t val)557 static void uhci_ioport_writel(void *opaque, uint32_t addr, uint32_t val)
558 {
559     UHCIState *s = opaque;
560 
561     addr &= 0x1f;
562     DPRINTF("uhci: writel port=0x%04x val=0x%08x\n", addr, val);
563 
564     switch(addr) {
565     case 0x08:
566         s->fl_base_addr = val & ~0xfff;
567         break;
568     }
569 }
570 
uhci_ioport_readl(void * opaque,uint32_t addr)571 static uint32_t uhci_ioport_readl(void *opaque, uint32_t addr)
572 {
573     UHCIState *s = opaque;
574     uint32_t val;
575 
576     addr &= 0x1f;
577     switch(addr) {
578     case 0x08:
579         val = s->fl_base_addr;
580         break;
581     default:
582         val = 0xffffffff;
583         break;
584     }
585     return val;
586 }
587 
588 /* signal resume if controller suspended */
uhci_resume(void * opaque)589 static void uhci_resume (void *opaque)
590 {
591     UHCIState *s = (UHCIState *)opaque;
592 
593     if (!s)
594         return;
595 
596     if (s->cmd & UHCI_CMD_EGSM) {
597         s->cmd |= UHCI_CMD_FGR;
598         s->status |= UHCI_STS_RD;
599         uhci_update_irq(s);
600     }
601 }
602 
uhci_attach(USBPort * port1)603 static void uhci_attach(USBPort *port1)
604 {
605     UHCIState *s = port1->opaque;
606     UHCIPort *port = &s->ports[port1->index];
607 
608     /* set connect status */
609     port->ctrl |= UHCI_PORT_CCS | UHCI_PORT_CSC;
610 
611     /* update speed */
612     if (port->port.dev->speed == USB_SPEED_LOW) {
613         port->ctrl |= UHCI_PORT_LSDA;
614     } else {
615         port->ctrl &= ~UHCI_PORT_LSDA;
616     }
617 
618     uhci_resume(s);
619 }
620 
uhci_detach(USBPort * port1)621 static void uhci_detach(USBPort *port1)
622 {
623     UHCIState *s = port1->opaque;
624     UHCIPort *port = &s->ports[port1->index];
625 
626     /* set connect status */
627     if (port->ctrl & UHCI_PORT_CCS) {
628         port->ctrl &= ~UHCI_PORT_CCS;
629         port->ctrl |= UHCI_PORT_CSC;
630     }
631     /* disable port */
632     if (port->ctrl & UHCI_PORT_EN) {
633         port->ctrl &= ~UHCI_PORT_EN;
634         port->ctrl |= UHCI_PORT_ENC;
635     }
636 
637     uhci_resume(s);
638 }
639 
uhci_wakeup(USBDevice * dev)640 static void uhci_wakeup(USBDevice *dev)
641 {
642     USBBus *bus = usb_bus_from_device(dev);
643     UHCIState *s = container_of(bus, UHCIState, bus);
644     UHCIPort *port = s->ports + dev->port->index;
645 
646     if (port->ctrl & UHCI_PORT_SUSPEND && !(port->ctrl & UHCI_PORT_RD)) {
647         port->ctrl |= UHCI_PORT_RD;
648         uhci_resume(s);
649     }
650 }
651 
uhci_broadcast_packet(UHCIState * s,USBPacket * p)652 static int uhci_broadcast_packet(UHCIState *s, USBPacket *p)
653 {
654     int i, ret;
655 
656     DPRINTF("uhci: packet enter. pid %s addr 0x%02x ep %d len %d\n",
657            pid2str(p->pid), p->devaddr, p->devep, p->len);
658     if (p->pid == USB_TOKEN_OUT || p->pid == USB_TOKEN_SETUP)
659         dump_data(p->data, p->len);
660 
661     ret = USB_RET_NODEV;
662     for (i = 0; i < NB_PORTS && ret == USB_RET_NODEV; i++) {
663         UHCIPort *port = &s->ports[i];
664         USBDevice *dev = port->port.dev;
665 
666         if (dev && (port->ctrl & UHCI_PORT_EN))
667             ret = dev->info->handle_packet(dev, p);
668     }
669 
670     DPRINTF("uhci: packet exit. ret %d len %d\n", ret, p->len);
671     if (p->pid == USB_TOKEN_IN && ret > 0)
672         dump_data(p->data, ret);
673 
674     return ret;
675 }
676 
677 static void uhci_async_complete(USBPacket * packet, void *opaque);
678 static void uhci_process_frame(UHCIState *s);
679 
680 /* return -1 if fatal error (frame must be stopped)
681           0 if TD successful
682           1 if TD unsuccessful or inactive
683 */
uhci_complete_td(UHCIState * s,UHCI_TD * td,UHCIAsync * async,uint32_t * int_mask)684 static int uhci_complete_td(UHCIState *s, UHCI_TD *td, UHCIAsync *async, uint32_t *int_mask)
685 {
686     int len = 0, max_len, err, ret;
687     uint8_t pid;
688 
689     max_len = ((td->token >> 21) + 1) & 0x7ff;
690     pid = td->token & 0xff;
691 
692     ret = async->packet.len;
693 
694     if (td->ctrl & TD_CTRL_IOS)
695         td->ctrl &= ~TD_CTRL_ACTIVE;
696 
697     if (ret < 0)
698         goto out;
699 
700     len = async->packet.len;
701     td->ctrl = (td->ctrl & ~0x7ff) | ((len - 1) & 0x7ff);
702 
703     /* The NAK bit may have been set by a previous frame, so clear it
704        here.  The docs are somewhat unclear, but win2k relies on this
705        behavior.  */
706     td->ctrl &= ~(TD_CTRL_ACTIVE | TD_CTRL_NAK);
707     if (td->ctrl & TD_CTRL_IOC)
708         *int_mask |= 0x01;
709 
710     if (pid == USB_TOKEN_IN) {
711         if (len > max_len) {
712             ret = USB_RET_BABBLE;
713             goto out;
714         }
715 
716         if (len > 0) {
717             /* write the data back */
718             cpu_physical_memory_write(td->buffer, async->buffer, len);
719         }
720 
721         if ((td->ctrl & TD_CTRL_SPD) && len < max_len) {
722             *int_mask |= 0x02;
723             /* short packet: do not update QH */
724             DPRINTF("uhci: short packet. td 0x%x token 0x%x\n", async->td, async->token);
725             return 1;
726         }
727     }
728 
729     /* success */
730     return 0;
731 
732 out:
733     switch(ret) {
734     case USB_RET_STALL:
735         td->ctrl |= TD_CTRL_STALL;
736         td->ctrl &= ~TD_CTRL_ACTIVE;
737         return 1;
738 
739     case USB_RET_BABBLE:
740         td->ctrl |= TD_CTRL_BABBLE | TD_CTRL_STALL;
741         td->ctrl &= ~TD_CTRL_ACTIVE;
742         /* frame interrupted */
743         return -1;
744 
745     case USB_RET_NAK:
746         td->ctrl |= TD_CTRL_NAK;
747         if (pid == USB_TOKEN_SETUP)
748             break;
749 	return 1;
750 
751     case USB_RET_NODEV:
752     default:
753 	break;
754     }
755 
756     /* Retry the TD if error count is not zero */
757 
758     td->ctrl |= TD_CTRL_TIMEOUT;
759     err = (td->ctrl >> TD_CTRL_ERROR_SHIFT) & 3;
760     if (err != 0) {
761         err--;
762         if (err == 0) {
763             td->ctrl &= ~TD_CTRL_ACTIVE;
764             s->status |= UHCI_STS_USBERR;
765             if (td->ctrl & TD_CTRL_IOC)
766                 *int_mask |= 0x01;
767             uhci_update_irq(s);
768         }
769     }
770     td->ctrl = (td->ctrl & ~(3 << TD_CTRL_ERROR_SHIFT)) |
771         (err << TD_CTRL_ERROR_SHIFT);
772     return 1;
773 }
774 
uhci_handle_td(UHCIState * s,uint32_t addr,UHCI_TD * td,uint32_t * int_mask)775 static int uhci_handle_td(UHCIState *s, uint32_t addr, UHCI_TD *td, uint32_t *int_mask)
776 {
777     UHCIAsync *async;
778     int len = 0, max_len;
779     uint8_t pid, isoc;
780     uint32_t token;
781 
782     /* Is active ? */
783     if (!(td->ctrl & TD_CTRL_ACTIVE))
784         return 1;
785 
786     /* token field is not unique for isochronous requests,
787      * so use the destination buffer
788      */
789     if (td->ctrl & TD_CTRL_IOS) {
790         token = td->buffer;
791         isoc = 1;
792     } else {
793         token = td->token;
794         isoc = 0;
795     }
796 
797     async = uhci_async_find_td(s, addr, token);
798     if (async) {
799         /* Already submitted */
800         async->valid = 32;
801 
802         if (!async->done)
803             return 1;
804 
805         uhci_async_unlink(s, async);
806         goto done;
807     }
808 
809     /* Allocate new packet */
810     async = uhci_async_alloc(s);
811     if (!async)
812         return 1;
813 
814     /* valid needs to be large enough to handle 10 frame delay
815      * for initial isochronous requests
816      */
817     async->valid = 32;
818     async->td    = addr;
819     async->token = token;
820     async->isoc  = isoc;
821 
822     max_len = ((td->token >> 21) + 1) & 0x7ff;
823     pid = td->token & 0xff;
824 
825     async->packet.pid     = pid;
826     async->packet.devaddr = (td->token >> 8) & 0x7f;
827     async->packet.devep   = (td->token >> 15) & 0xf;
828     async->packet.data    = async->buffer;
829     async->packet.len     = max_len;
830     async->packet.complete_cb     = uhci_async_complete;
831     async->packet.complete_opaque = s;
832 
833     switch(pid) {
834     case USB_TOKEN_OUT:
835     case USB_TOKEN_SETUP:
836         cpu_physical_memory_read(td->buffer, async->buffer, max_len);
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.len = len;
860 
861 done:
862     len = uhci_complete_td(s, td, async, int_mask);
863     uhci_async_free(s, async);
864     return len;
865 }
866 
uhci_async_complete(USBPacket * packet,void * opaque)867 static void uhci_async_complete(USBPacket *packet, void *opaque)
868 {
869     UHCIState *s = opaque;
870     UHCIAsync *async = (UHCIAsync *) packet;
871 
872     DPRINTF("uhci: async complete. td 0x%x token 0x%x\n", async->td, async->token);
873 
874     if (async->isoc) {
875         UHCI_TD td;
876         uint32_t link = async->td;
877         uint32_t int_mask = 0, val;
878 
879         cpu_physical_memory_read(link & ~0xf, (uint8_t *) &td, sizeof(td));
880         le32_to_cpus(&td.link);
881         le32_to_cpus(&td.ctrl);
882         le32_to_cpus(&td.token);
883         le32_to_cpus(&td.buffer);
884 
885         uhci_async_unlink(s, async);
886         uhci_complete_td(s, &td, async, &int_mask);
887         s->pending_int_mask |= int_mask;
888 
889         /* update the status bits of the TD */
890         val = cpu_to_le32(td.ctrl);
891         cpu_physical_memory_write((link & ~0xf) + 4,
892                                   (const uint8_t *)&val, sizeof(val));
893         uhci_async_free(s, async);
894     } else {
895         async->done = 1;
896         uhci_process_frame(s);
897     }
898 }
899 
is_valid(uint32_t link)900 static int is_valid(uint32_t link)
901 {
902     return (link & 1) == 0;
903 }
904 
is_qh(uint32_t link)905 static int is_qh(uint32_t link)
906 {
907     return (link & 2) != 0;
908 }
909 
depth_first(uint32_t link)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 
qhdb_reset(QhDb * db)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. */
qhdb_insert(QhDb * db,uint32_t addr)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 
uhci_process_frame(UHCIState * s)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     cpu_physical_memory_read(frame_addr, (uint8_t *)&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             cpu_physical_memory_read(link & ~0xf, (uint8_t *) &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         cpu_physical_memory_read(link & ~0xf, (uint8_t *) &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             cpu_physical_memory_write((link & ~0xf) + 4,
1014                                       (const uint8_t *)&val, sizeof(val));
1015         }
1016 
1017         if (ret < 0) {
1018             /* interrupted frame */
1019             break;
1020         }
1021 
1022         if (ret == 2 || ret == 1) {
1023             DPRINTF("uhci: TD 0x%x %s. link 0x%x ctrl 0x%x token 0x%x qh 0x%x\n",
1024                     link, ret == 2 ? "pend" : "skip",
1025                     td.link, td.ctrl, td.token, curr_qh);
1026 
1027             link = curr_qh ? qh.link : td.link;
1028             continue;
1029         }
1030 
1031         /* completed TD */
1032 
1033         DPRINTF("uhci: TD 0x%x done. link 0x%x ctrl 0x%x token 0x%x qh 0x%x\n",
1034                 link, td.link, td.ctrl, td.token, curr_qh);
1035 
1036         link = td.link;
1037 
1038         if (curr_qh) {
1039 	    /* update QH element link */
1040             qh.el_link = link;
1041             val = cpu_to_le32(qh.el_link);
1042             cpu_physical_memory_write((curr_qh & ~0xf) + 4,
1043                                           (const uint8_t *)&val, sizeof(val));
1044 
1045             if (!depth_first(link)) {
1046                /* done with this QH */
1047 
1048                DPRINTF("uhci: QH 0x%x done. link 0x%x elink 0x%x\n",
1049                        curr_qh, qh.link, qh.el_link);
1050 
1051                curr_qh = 0;
1052                link    = qh.link;
1053             }
1054         }
1055 
1056         /* go to the next entry */
1057     }
1058 
1059     s->pending_int_mask |= int_mask;
1060 }
1061 
uhci_frame_timer(void * opaque)1062 static void uhci_frame_timer(void *opaque)
1063 {
1064     UHCIState *s = opaque;
1065 
1066     /* prepare the timer for the next frame */
1067     s->expire_time += (get_ticks_per_sec() / FRAME_TIMER_FREQ);
1068 
1069     if (!(s->cmd & UHCI_CMD_RS)) {
1070         /* Full stop */
1071         qemu_del_timer(s->frame_timer);
1072         /* set hchalted bit in status - UHCI11D 2.1.2 */
1073         s->status |= UHCI_STS_HCHALTED;
1074 
1075         DPRINTF("uhci: halted\n");
1076         return;
1077     }
1078 
1079     /* Complete the previous frame */
1080     if (s->pending_int_mask) {
1081         s->status2 |= s->pending_int_mask;
1082         s->status  |= UHCI_STS_USBINT;
1083         uhci_update_irq(s);
1084     }
1085     s->pending_int_mask = 0;
1086 
1087     /* Start new frame */
1088     s->frnum = (s->frnum + 1) & 0x7ff;
1089 
1090     DPRINTF("uhci: new frame #%u\n" , s->frnum);
1091 
1092     uhci_async_validate_begin(s);
1093 
1094     uhci_process_frame(s);
1095 
1096     uhci_async_validate_end(s);
1097 
1098     qemu_mod_timer(s->frame_timer, s->expire_time);
1099 }
1100 
uhci_map(PCIDevice * pci_dev,int region_num,pcibus_t addr,pcibus_t size,int type)1101 static void uhci_map(PCIDevice *pci_dev, int region_num,
1102                     pcibus_t addr, pcibus_t size, int type)
1103 {
1104     UHCIState *s = (UHCIState *)pci_dev;
1105 
1106     register_ioport_write(addr, 32, 2, uhci_ioport_writew, s);
1107     register_ioport_read(addr, 32, 2, uhci_ioport_readw, s);
1108     register_ioport_write(addr, 32, 4, uhci_ioport_writel, s);
1109     register_ioport_read(addr, 32, 4, uhci_ioport_readl, s);
1110     register_ioport_write(addr, 32, 1, uhci_ioport_writeb, s);
1111     register_ioport_read(addr, 32, 1, uhci_ioport_readb, s);
1112 }
1113 
1114 static USBPortOps uhci_port_ops = {
1115     .attach = uhci_attach,
1116     .detach = uhci_detach,
1117     .wakeup = uhci_wakeup,
1118 };
1119 
usb_uhci_common_initfn(UHCIState * s)1120 static int usb_uhci_common_initfn(UHCIState *s)
1121 {
1122     uint8_t *pci_conf = s->dev.config;
1123     int i;
1124 
1125     pci_conf[PCI_REVISION_ID] = 0x01; // revision number
1126     pci_conf[PCI_CLASS_PROG] = 0x00;
1127     pci_config_set_class(pci_conf, PCI_CLASS_SERIAL_USB);
1128     /* TODO: reset value should be 0. */
1129     pci_conf[PCI_INTERRUPT_PIN] = 4; // interrupt pin 3
1130     pci_conf[0x60] = 0x10; // release number
1131 
1132     usb_bus_new(&s->bus, &s->dev.qdev);
1133     for(i = 0; i < NB_PORTS; i++) {
1134         usb_register_port(&s->bus, &s->ports[i].port, s, i, &uhci_port_ops,
1135                           USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL);
1136         usb_port_location(&s->ports[i].port, NULL, i+1);
1137     }
1138     s->frame_timer = qemu_new_timer(vm_clock, uhci_frame_timer, s);
1139     s->num_ports_vmstate = NB_PORTS;
1140 
1141     qemu_register_reset(uhci_reset, s);
1142 
1143     /* Use region 4 for consistency with real hardware.  BSD guests seem
1144        to rely on this.  */
1145     pci_register_bar(&s->dev, 4, 0x20,
1146                            PCI_BASE_ADDRESS_SPACE_IO, uhci_map);
1147 
1148     return 0;
1149 }
1150 
usb_uhci_piix3_initfn(PCIDevice * dev)1151 static int usb_uhci_piix3_initfn(PCIDevice *dev)
1152 {
1153     UHCIState *s = DO_UPCAST(UHCIState, dev, dev);
1154     uint8_t *pci_conf = s->dev.config;
1155 
1156     pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);
1157     pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_82371SB_2);
1158     return usb_uhci_common_initfn(s);
1159 }
1160 
usb_uhci_piix4_initfn(PCIDevice * dev)1161 static int usb_uhci_piix4_initfn(PCIDevice *dev)
1162 {
1163     UHCIState *s = DO_UPCAST(UHCIState, dev, dev);
1164     uint8_t *pci_conf = s->dev.config;
1165 
1166     pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);
1167     pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_82371AB_2);
1168     return usb_uhci_common_initfn(s);
1169 }
1170 
usb_uhci_vt82c686b_initfn(PCIDevice * dev)1171 static int usb_uhci_vt82c686b_initfn(PCIDevice *dev)
1172 {
1173     UHCIState *s = DO_UPCAST(UHCIState, dev, dev);
1174     uint8_t *pci_conf = s->dev.config;
1175 
1176     pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_VIA);
1177     pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_VIA_UHCI);
1178 
1179     /* USB misc control 1/2 */
1180     pci_set_long(pci_conf + 0x40,0x00001000);
1181     /* PM capability */
1182     pci_set_long(pci_conf + 0x80,0x00020001);
1183     /* USB legacy support  */
1184     pci_set_long(pci_conf + 0xc0,0x00002000);
1185 
1186     return usb_uhci_common_initfn(s);
1187 }
1188 
1189 static PCIDeviceInfo uhci_info[] = {
1190     {
1191         .qdev.name    = "piix3-usb-uhci",
1192         .qdev.size    = sizeof(UHCIState),
1193         .qdev.vmsd    = &vmstate_uhci,
1194         .init         = usb_uhci_piix3_initfn,
1195     },{
1196         .qdev.name    = "piix4-usb-uhci",
1197         .qdev.size    = sizeof(UHCIState),
1198         .qdev.vmsd    = &vmstate_uhci,
1199         .init         = usb_uhci_piix4_initfn,
1200     },{
1201         .qdev.name    = "vt82c686b-usb-uhci",
1202         .qdev.size    = sizeof(UHCIState),
1203         .qdev.vmsd    = &vmstate_uhci,
1204         .init         = usb_uhci_vt82c686b_initfn,
1205     },{
1206         /* end of list */
1207     }
1208 };
1209 
uhci_register(void)1210 static void uhci_register(void)
1211 {
1212     pci_qdev_register_many(uhci_info);
1213 }
1214 device_init(uhci_register);
1215 
usb_uhci_piix3_init(PCIBus * bus,int devfn)1216 void usb_uhci_piix3_init(PCIBus *bus, int devfn)
1217 {
1218     pci_create_simple(bus, devfn, "piix3-usb-uhci");
1219 }
1220 
usb_uhci_piix4_init(PCIBus * bus,int devfn)1221 void usb_uhci_piix4_init(PCIBus *bus, int devfn)
1222 {
1223     pci_create_simple(bus, devfn, "piix4-usb-uhci");
1224 }
1225 
usb_uhci_vt82c686b_init(PCIBus * bus,int devfn)1226 void usb_uhci_vt82c686b_init(PCIBus *bus, int devfn)
1227 {
1228     pci_create_simple(bus, devfn, "vt82c686b-usb-uhci");
1229 }
1230