APIC init fix + APIC get_irq fix (Juergen Keil)
[qemu] / hw / usb-ohci.c
1 /*
2  * QEMU USB OHCI Emulation
3  * Copyright (c) 2004 Gianni Tedesco
4  * Copyright (c) 2006 CodeSourcery
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * TODO:
21  *  o Isochronous transfers
22  *  o Allocate bandwidth in frames properly
23  *  o Disable timers when nothing needs to be done, or remove timer usage
24  *    all together.
25  *  o Handle unrecoverable errors properly
26  *  o BIOS work to boot from USB storage
27 */
28
29 #include "vl.h"
30
31 //#define DEBUG_OHCI
32 /* Dump packet contents.  */
33 //#define DEBUG_PACKET
34 /* This causes frames to occur 1000x slower */
35 //#define OHCI_TIME_WARP 1
36
37 #ifdef DEBUG_OHCI
38 #define dprintf printf
39 #else
40 #define dprintf(...)
41 #endif
42
43 /* Number of Downstream Ports on the root hub.  */
44
45 #define OHCI_MAX_PORTS 15
46
47 static int64_t usb_frame_time;
48 static int64_t usb_bit_time;
49
50 typedef struct OHCIPort {
51     USBPort port;
52     uint32_t ctrl;
53 } OHCIPort;
54
55 typedef struct {
56     struct PCIDevice pci_dev;
57     target_phys_addr_t mem_base;
58     int mem;
59     int num_ports;
60
61     QEMUTimer *eof_timer;
62     int64_t sof_time;
63
64     /* OHCI state */
65     /* Control partition */
66     uint32_t ctl, status;
67     uint32_t intr_status;
68     uint32_t intr;
69
70     /* memory pointer partition */
71     uint32_t hcca;
72     uint32_t ctrl_head, ctrl_cur;
73     uint32_t bulk_head, bulk_cur;
74     uint32_t per_cur;
75     uint32_t done;
76     int done_count;
77
78     /* Frame counter partition */
79     uint32_t fsmps:15;
80     uint32_t fit:1;
81     uint32_t fi:14;
82     uint32_t frt:1;
83     uint16_t frame_number;
84     uint16_t padding;
85     uint32_t pstart;
86     uint32_t lst;
87
88     /* Root Hub partition */
89     uint32_t rhdesc_a, rhdesc_b;
90     uint32_t rhstatus;
91     OHCIPort rhport[OHCI_MAX_PORTS];
92
93     /* Active packets.  */
94     uint32_t old_ctl;
95     USBPacket usb_packet;
96     uint8_t usb_buf[8192];
97     uint32_t async_td;
98     int async_complete;
99
100 } OHCIState;
101
102 /* Host Controller Communications Area */
103 struct ohci_hcca {
104     uint32_t intr[32];
105     uint16_t frame, pad;
106     uint32_t done;
107 };
108
109 /* Bitfields for the first word of an Endpoint Desciptor.  */
110 #define OHCI_ED_FA_SHIFT  0
111 #define OHCI_ED_FA_MASK   (0x7f<<OHCI_ED_FA_SHIFT)
112 #define OHCI_ED_EN_SHIFT  7
113 #define OHCI_ED_EN_MASK   (0xf<<OHCI_ED_EN_SHIFT)
114 #define OHCI_ED_D_SHIFT   11
115 #define OHCI_ED_D_MASK    (3<<OHCI_ED_D_SHIFT)
116 #define OHCI_ED_S         (1<<13)
117 #define OHCI_ED_K         (1<<14)
118 #define OHCI_ED_F         (1<<15)
119 #define OHCI_ED_MPS_SHIFT 7
120 #define OHCI_ED_MPS_MASK  (0xf<<OHCI_ED_FA_SHIFT)
121
122 /* Flags in the head field of an Endpoint Desciptor.  */
123 #define OHCI_ED_H         1
124 #define OHCI_ED_C         2
125
126 /* Bitfields for the first word of a Transfer Desciptor.  */
127 #define OHCI_TD_R         (1<<18)
128 #define OHCI_TD_DP_SHIFT  19
129 #define OHCI_TD_DP_MASK   (3<<OHCI_TD_DP_SHIFT)
130 #define OHCI_TD_DI_SHIFT  21
131 #define OHCI_TD_DI_MASK   (7<<OHCI_TD_DI_SHIFT)
132 #define OHCI_TD_T0        (1<<24)
133 #define OHCI_TD_T1        (1<<24)
134 #define OHCI_TD_EC_SHIFT  26
135 #define OHCI_TD_EC_MASK   (3<<OHCI_TD_EC_SHIFT)
136 #define OHCI_TD_CC_SHIFT  28
137 #define OHCI_TD_CC_MASK   (0xf<<OHCI_TD_CC_SHIFT)
138
139 #define OHCI_DPTR_MASK    0xfffffff0
140
141 #define OHCI_BM(val, field) \
142   (((val) & OHCI_##field##_MASK) >> OHCI_##field##_SHIFT)
143
144 #define OHCI_SET_BM(val, field, newval) do { \
145     val &= ~OHCI_##field##_MASK; \
146     val |= ((newval) << OHCI_##field##_SHIFT) & OHCI_##field##_MASK; \
147     } while(0)
148
149 /* endpoint descriptor */
150 struct ohci_ed {
151     uint32_t flags;
152     uint32_t tail;
153     uint32_t head;
154     uint32_t next;
155 };
156
157 /* General transfer descriptor */
158 struct ohci_td {
159     uint32_t flags;
160     uint32_t cbp;
161     uint32_t next;
162     uint32_t be;
163 };
164
165 #define USB_HZ                      12000000
166
167 /* OHCI Local stuff */
168 #define OHCI_CTL_CBSR         ((1<<0)|(1<<1))
169 #define OHCI_CTL_PLE          (1<<2)
170 #define OHCI_CTL_IE           (1<<3)
171 #define OHCI_CTL_CLE          (1<<4)
172 #define OHCI_CTL_BLE          (1<<5)
173 #define OHCI_CTL_HCFS         ((1<<6)|(1<<7))
174 #define  OHCI_USB_RESET       0x00
175 #define  OHCI_USB_RESUME      0x40
176 #define  OHCI_USB_OPERATIONAL 0x80
177 #define  OHCI_USB_SUSPEND     0xc0
178 #define OHCI_CTL_IR           (1<<8)
179 #define OHCI_CTL_RWC          (1<<9)
180 #define OHCI_CTL_RWE          (1<<10)
181
182 #define OHCI_STATUS_HCR       (1<<0)
183 #define OHCI_STATUS_CLF       (1<<1)
184 #define OHCI_STATUS_BLF       (1<<2)
185 #define OHCI_STATUS_OCR       (1<<3)
186 #define OHCI_STATUS_SOC       ((1<<6)|(1<<7))
187
188 #define OHCI_INTR_SO          (1<<0) /* Scheduling overrun */
189 #define OHCI_INTR_WD          (1<<1) /* HcDoneHead writeback */
190 #define OHCI_INTR_SF          (1<<2) /* Start of frame */
191 #define OHCI_INTR_RD          (1<<3) /* Resume detect */
192 #define OHCI_INTR_UE          (1<<4) /* Unrecoverable error */
193 #define OHCI_INTR_FNO         (1<<5) /* Frame number overflow */
194 #define OHCI_INTR_RHSC        (1<<6) /* Root hub status change */
195 #define OHCI_INTR_OC          (1<<30) /* Ownership change */
196 #define OHCI_INTR_MIE         (1<<31) /* Master Interrupt Enable */
197
198 #define OHCI_HCCA_SIZE        0x100
199 #define OHCI_HCCA_MASK        0xffffff00
200
201 #define OHCI_EDPTR_MASK       0xfffffff0
202
203 #define OHCI_FMI_FI           0x00003fff
204 #define OHCI_FMI_FSMPS        0xffff0000
205 #define OHCI_FMI_FIT          0x80000000
206
207 #define OHCI_FR_RT            (1<<31)
208
209 #define OHCI_LS_THRESH        0x628
210
211 #define OHCI_RHA_RW_MASK      0x00000000 /* Mask of supported features.  */
212 #define OHCI_RHA_PSM          (1<<8)
213 #define OHCI_RHA_NPS          (1<<9)
214 #define OHCI_RHA_DT           (1<<10)
215 #define OHCI_RHA_OCPM         (1<<11)
216 #define OHCI_RHA_NOCP         (1<<12)
217 #define OHCI_RHA_POTPGT_MASK  0xff000000
218
219 #define OHCI_RHS_LPS          (1<<0)
220 #define OHCI_RHS_OCI          (1<<1)
221 #define OHCI_RHS_DRWE         (1<<15)
222 #define OHCI_RHS_LPSC         (1<<16)
223 #define OHCI_RHS_OCIC         (1<<17)
224 #define OHCI_RHS_CRWE         (1<<31)
225
226 #define OHCI_PORT_CCS         (1<<0)
227 #define OHCI_PORT_PES         (1<<1)
228 #define OHCI_PORT_PSS         (1<<2)
229 #define OHCI_PORT_POCI        (1<<3)
230 #define OHCI_PORT_PRS         (1<<4)
231 #define OHCI_PORT_PPS         (1<<8)
232 #define OHCI_PORT_LSDA        (1<<9)
233 #define OHCI_PORT_CSC         (1<<16)
234 #define OHCI_PORT_PESC        (1<<17)
235 #define OHCI_PORT_PSSC        (1<<18)
236 #define OHCI_PORT_OCIC        (1<<19)
237 #define OHCI_PORT_PRSC        (1<<20)
238 #define OHCI_PORT_WTC         (OHCI_PORT_CSC|OHCI_PORT_PESC|OHCI_PORT_PSSC \
239                                |OHCI_PORT_OCIC|OHCI_PORT_PRSC)
240
241 #define OHCI_TD_DIR_SETUP     0x0
242 #define OHCI_TD_DIR_OUT       0x1
243 #define OHCI_TD_DIR_IN        0x2
244 #define OHCI_TD_DIR_RESERVED  0x3
245
246 #define OHCI_CC_NOERROR             0x0
247 #define OHCI_CC_CRC                 0x1
248 #define OHCI_CC_BITSTUFFING         0x2
249 #define OHCI_CC_DATATOGGLEMISMATCH  0x3
250 #define OHCI_CC_STALL               0x4
251 #define OHCI_CC_DEVICENOTRESPONDING 0x5
252 #define OHCI_CC_PIDCHECKFAILURE     0x6
253 #define OHCI_CC_UNDEXPETEDPID       0x7
254 #define OHCI_CC_DATAOVERRUN         0x8
255 #define OHCI_CC_DATAUNDERRUN        0x9
256 #define OHCI_CC_BUFFEROVERRUN       0xc
257 #define OHCI_CC_BUFFERUNDERRUN      0xd
258
259 /* Update IRQ levels */
260 static inline void ohci_intr_update(OHCIState *ohci)
261 {
262     int level = 0;
263
264     if ((ohci->intr & OHCI_INTR_MIE) &&
265         (ohci->intr_status & ohci->intr))
266         level = 1;
267
268     pci_set_irq(&ohci->pci_dev, 0, level);
269 }
270
271 /* Set an interrupt */
272 static inline void ohci_set_interrupt(OHCIState *ohci, uint32_t intr)
273 {
274     ohci->intr_status |= intr;
275     ohci_intr_update(ohci);
276 }
277
278 /* Attach or detach a device on a root hub port.  */
279 static void ohci_attach(USBPort *port1, USBDevice *dev)
280 {
281     OHCIState *s = port1->opaque;
282     OHCIPort *port = &s->rhport[port1->index];
283     uint32_t old_state = port->ctrl;
284
285     if (dev) {
286         if (port->port.dev) {
287             usb_attach(port1, NULL);
288         }
289         /* set connect status */
290         port->ctrl |= OHCI_PORT_CCS | OHCI_PORT_CSC;
291
292         /* update speed */
293         if (dev->speed == USB_SPEED_LOW)
294             port->ctrl |= OHCI_PORT_LSDA;
295         else
296             port->ctrl &= ~OHCI_PORT_LSDA;
297         port->port.dev = dev;
298         /* send the attach message */
299         usb_send_msg(dev, USB_MSG_ATTACH);
300         dprintf("usb-ohci: Attached port %d\n", port1->index);
301     } else {
302         /* set connect status */
303         if (port->ctrl & OHCI_PORT_CCS) {
304             port->ctrl &= ~OHCI_PORT_CCS;
305             port->ctrl |= OHCI_PORT_CSC;
306         }
307         /* disable port */
308         if (port->ctrl & OHCI_PORT_PES) {
309             port->ctrl &= ~OHCI_PORT_PES;
310             port->ctrl |= OHCI_PORT_PESC;
311         }
312         dev = port->port.dev;
313         if (dev) {
314             /* send the detach message */
315             usb_send_msg(dev, USB_MSG_DETACH);
316         }
317         port->port.dev = NULL;
318         dprintf("usb-ohci: Detached port %d\n", port1->index);
319     }
320
321     if (old_state != port->ctrl)
322         ohci_set_interrupt(s, OHCI_INTR_RHSC);
323 }
324
325 /* Reset the controller */
326 static void ohci_reset(OHCIState *ohci)
327 {
328     OHCIPort *port;
329     int i;
330
331     ohci->ctl = 0;
332     ohci->old_ctl = 0;
333     ohci->status = 0;
334     ohci->intr_status = 0;
335     ohci->intr = OHCI_INTR_MIE;
336
337     ohci->hcca = 0;
338     ohci->ctrl_head = ohci->ctrl_cur = 0;
339     ohci->bulk_head = ohci->bulk_cur = 0;
340     ohci->per_cur = 0;
341     ohci->done = 0;
342     ohci->done_count = 7;
343
344     /* FSMPS is marked TBD in OCHI 1.0, what gives ffs?
345      * I took the value linux sets ...
346      */
347     ohci->fsmps = 0x2778;
348     ohci->fi = 0x2edf;
349     ohci->fit = 0;
350     ohci->frt = 0;
351     ohci->frame_number = 0;
352     ohci->pstart = 0;
353     ohci->lst = OHCI_LS_THRESH;
354
355     ohci->rhdesc_a = OHCI_RHA_NPS | ohci->num_ports;
356     ohci->rhdesc_b = 0x0; /* Impl. specific */
357     ohci->rhstatus = 0;
358
359     for (i = 0; i < ohci->num_ports; i++)
360       {
361         port = &ohci->rhport[i];
362         port->ctrl = 0;
363         if (port->port.dev)
364             ohci_attach(&port->port, port->port.dev);
365       }
366     if (ohci->async_td) {
367         usb_cancel_packet(&ohci->usb_packet);
368         ohci->async_td = 0;
369     }
370     dprintf("usb-ohci: Reset %s\n", ohci->pci_dev.name);
371 }
372
373 /* Get an array of dwords from main memory */
374 static inline int get_dwords(uint32_t addr, uint32_t *buf, int num)
375 {
376     int i;
377
378     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
379         cpu_physical_memory_rw(addr, (uint8_t *)buf, sizeof(*buf), 0);
380         *buf = le32_to_cpu(*buf);
381     }
382
383     return 1;
384 }
385
386 /* Put an array of dwords in to main memory */
387 static inline int put_dwords(uint32_t addr, uint32_t *buf, int num)
388 {
389     int i;
390
391     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
392         uint32_t tmp = cpu_to_le32(*buf);
393         cpu_physical_memory_rw(addr, (uint8_t *)&tmp, sizeof(tmp), 1);
394     }
395
396     return 1;
397 }
398
399 static inline int ohci_read_ed(uint32_t addr, struct ohci_ed *ed)
400 {
401     return get_dwords(addr, (uint32_t *)ed, sizeof(*ed) >> 2);
402 }
403
404 static inline int ohci_read_td(uint32_t addr, struct ohci_td *td)
405 {
406     return get_dwords(addr, (uint32_t *)td, sizeof(*td) >> 2);
407 }
408
409 static inline int ohci_put_ed(uint32_t addr, struct ohci_ed *ed)
410 {
411     return put_dwords(addr, (uint32_t *)ed, sizeof(*ed) >> 2);
412 }
413
414 static inline int ohci_put_td(uint32_t addr, struct ohci_td *td)
415 {
416     return put_dwords(addr, (uint32_t *)td, sizeof(*td) >> 2);
417 }
418
419 /* Read/Write the contents of a TD from/to main memory.  */
420 static void ohci_copy_td(struct ohci_td *td, uint8_t *buf, int len, int write)
421 {
422     uint32_t ptr;
423     uint32_t n;
424
425     ptr = td->cbp;
426     n = 0x1000 - (ptr & 0xfff);
427     if (n > len)
428         n = len;
429     cpu_physical_memory_rw(ptr, buf, n, write);
430     if (n == len)
431         return;
432     ptr = td->be & ~0xfffu;
433     buf += n;
434     cpu_physical_memory_rw(ptr, buf, len - n, write);
435 }
436
437 static void ohci_process_lists(OHCIState *ohci);
438
439 static void ohci_async_complete_packet(USBPacket * packet, void *opaque)
440 {
441     OHCIState *ohci = opaque;
442 #ifdef DEBUG_PACKET
443     dprintf("Async packet complete\n");
444 #endif
445     ohci->async_complete = 1;
446     ohci_process_lists(ohci);
447 }
448
449 /* Service a transport descriptor.
450    Returns nonzero to terminate processing of this endpoint.  */
451
452 static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed)
453 {
454     int dir;
455     size_t len = 0;
456     char *str = NULL;
457     int pid;
458     int ret;
459     int i;
460     USBDevice *dev;
461     struct ohci_td td;
462     uint32_t addr;
463     int flag_r;
464     int completion;
465
466     addr = ed->head & OHCI_DPTR_MASK;
467     /* See if this TD has already been submitted to the device.  */
468     completion = (addr == ohci->async_td);
469     if (completion && !ohci->async_complete) {
470 #ifdef DEBUG_PACKET
471         dprintf("Skipping async TD\n");
472 #endif
473         return 1;
474     }
475     if (!ohci_read_td(addr, &td)) {
476         fprintf(stderr, "usb-ohci: TD read error at %x\n", addr);
477         return 0;
478     }
479
480     dir = OHCI_BM(ed->flags, ED_D);
481     switch (dir) {
482     case OHCI_TD_DIR_OUT:
483     case OHCI_TD_DIR_IN:
484         /* Same value.  */
485         break;
486     default:
487         dir = OHCI_BM(td.flags, TD_DP);
488         break;
489     }
490
491     switch (dir) {
492     case OHCI_TD_DIR_IN:
493         str = "in";
494         pid = USB_TOKEN_IN;
495         break;
496     case OHCI_TD_DIR_OUT:
497         str = "out";
498         pid = USB_TOKEN_OUT;
499         break;
500     case OHCI_TD_DIR_SETUP:
501         str = "setup";
502         pid = USB_TOKEN_SETUP;
503         break;
504     default:
505         fprintf(stderr, "usb-ohci: Bad direction\n");
506         return 1;
507     }
508     if (td.cbp && td.be) {
509         if ((td.cbp & 0xfffff000) != (td.be & 0xfffff000)) {
510             len = (td.be & 0xfff) + 0x1001 - (td.cbp & 0xfff);
511         } else {
512             len = (td.be - td.cbp) + 1;
513         }
514
515         if (len && dir != OHCI_TD_DIR_IN && !completion) {
516             ohci_copy_td(&td, ohci->usb_buf, len, 0);
517         }
518     }
519
520     flag_r = (td.flags & OHCI_TD_R) != 0;
521 #ifdef DEBUG_PACKET
522     dprintf(" TD @ 0x%.8x %u bytes %s r=%d cbp=0x%.8x be=0x%.8x\n",
523             addr, len, str, flag_r, td.cbp, td.be);
524
525     if (len >= 0 && dir != OHCI_TD_DIR_IN) {
526         dprintf("  data:");
527         for (i = 0; i < len; i++)
528             printf(" %.2x", ohci->usb_buf[i]);
529         dprintf("\n");
530     }
531 #endif
532     if (completion) {
533         ret = ohci->usb_packet.len;
534         ohci->async_td = 0;
535         ohci->async_complete = 0;
536     } else {
537         ret = USB_RET_NODEV;
538         for (i = 0; i < ohci->num_ports; i++) {
539             dev = ohci->rhport[i].port.dev;
540             if ((ohci->rhport[i].ctrl & OHCI_PORT_PES) == 0)
541                 continue;
542
543             if (ohci->async_td) {
544                 /* ??? The hardware should allow one active packet per
545                    endpoint.  We only allow one active packet per controller.
546                    This should be sufficient as long as devices respond in a
547                    timely manner.
548                  */
549 #ifdef DEBUG_PACKET
550                 dprintf("Too many pending packets\n");
551 #endif
552                 return 1;
553             }
554             ohci->usb_packet.pid = pid;
555             ohci->usb_packet.devaddr = OHCI_BM(ed->flags, ED_FA);
556             ohci->usb_packet.devep = OHCI_BM(ed->flags, ED_EN);
557             ohci->usb_packet.data = ohci->usb_buf;
558             ohci->usb_packet.len = len;
559             ohci->usb_packet.complete_cb = ohci_async_complete_packet;
560             ohci->usb_packet.complete_opaque = ohci;
561             ret = dev->handle_packet(dev, &ohci->usb_packet);
562             if (ret != USB_RET_NODEV)
563                 break;
564         }
565 #ifdef DEBUG_PACKET
566         dprintf("ret=%d\n", ret);
567 #endif
568         if (ret == USB_RET_ASYNC) {
569             ohci->async_td = addr;
570             return 1;
571         }
572     }
573     if (ret >= 0) {
574         if (dir == OHCI_TD_DIR_IN) {
575             ohci_copy_td(&td, ohci->usb_buf, ret, 1);
576 #ifdef DEBUG_PACKET
577             dprintf("  data:");
578             for (i = 0; i < ret; i++)
579                 printf(" %.2x", ohci->usb_buf[i]);
580             dprintf("\n");
581 #endif
582         } else {
583             ret = len;
584         }
585     }
586
587     /* Writeback */
588     if (ret == len || (dir == OHCI_TD_DIR_IN && ret >= 0 && flag_r)) {
589         /* Transmission succeeded.  */
590         if (ret == len) {
591             td.cbp = 0;
592         } else {
593             td.cbp += ret;
594             if ((td.cbp & 0xfff) + ret > 0xfff) {
595                 td.cbp &= 0xfff;
596                 td.cbp |= td.be & ~0xfff;
597             }
598         }
599         td.flags |= OHCI_TD_T1;
600         td.flags ^= OHCI_TD_T0;
601         OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_NOERROR);
602         OHCI_SET_BM(td.flags, TD_EC, 0);
603
604         ed->head &= ~OHCI_ED_C;
605         if (td.flags & OHCI_TD_T0)
606             ed->head |= OHCI_ED_C;
607     } else {
608         if (ret >= 0) {
609             dprintf("usb-ohci: Underrun\n");
610             OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAUNDERRUN);
611         } else {
612             switch (ret) {
613             case USB_RET_NODEV:
614                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DEVICENOTRESPONDING);
615             case USB_RET_NAK:
616                 dprintf("usb-ohci: got NAK\n");
617                 return 1;
618             case USB_RET_STALL:
619                 dprintf("usb-ohci: got STALL\n");
620                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_STALL);
621                 break;
622             case USB_RET_BABBLE:
623                 dprintf("usb-ohci: got BABBLE\n");
624                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAOVERRUN);
625                 break;
626             default:
627                 fprintf(stderr, "usb-ohci: Bad device response %d\n", ret);
628                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_UNDEXPETEDPID);
629                 OHCI_SET_BM(td.flags, TD_EC, 3);
630                 break;
631             }
632         }
633         ed->head |= OHCI_ED_H;
634     }
635
636     /* Retire this TD */
637     ed->head &= ~OHCI_DPTR_MASK;
638     ed->head |= td.next & OHCI_DPTR_MASK;
639     td.next = ohci->done;
640     ohci->done = addr;
641     i = OHCI_BM(td.flags, TD_DI);
642     if (i < ohci->done_count)
643         ohci->done_count = i;
644     ohci_put_td(addr, &td);
645     return OHCI_BM(td.flags, TD_CC) != OHCI_CC_NOERROR;
646 }
647
648 /* Service an endpoint list.  Returns nonzero if active TD were found.  */
649 static int ohci_service_ed_list(OHCIState *ohci, uint32_t head)
650 {
651     struct ohci_ed ed;
652     uint32_t next_ed;
653     uint32_t cur;
654     int active;
655
656     active = 0;
657
658     if (head == 0)
659         return 0;
660
661     for (cur = head; cur; cur = next_ed) {
662         if (!ohci_read_ed(cur, &ed)) {
663             fprintf(stderr, "usb-ohci: ED read error at %x\n", cur);
664             return 0;
665         }
666
667         next_ed = ed.next & OHCI_DPTR_MASK;
668
669         if ((ed.head & OHCI_ED_H) || (ed.flags & OHCI_ED_K)) {
670             uint32_t addr;
671             /* Cancel pending packets for ED that have been paused.  */
672             addr = ed.head & OHCI_DPTR_MASK;
673             if (ohci->async_td && addr == ohci->async_td) {
674                 usb_cancel_packet(&ohci->usb_packet);
675                 ohci->async_td = 0;
676             }
677             continue;
678         }
679
680         /* Skip isochronous endpoints.  */
681         if (ed.flags & OHCI_ED_F)
682           continue;
683
684         while ((ed.head & OHCI_DPTR_MASK) != ed.tail) {
685 #ifdef DEBUG_PACKET
686             dprintf("ED @ 0x%.8x fa=%u en=%u d=%u s=%u k=%u f=%u mps=%u "
687                     "h=%u c=%u\n  head=0x%.8x tailp=0x%.8x next=0x%.8x\n", cur,
688                     OHCI_BM(ed.flags, ED_FA), OHCI_BM(ed.flags, ED_EN),
689                     OHCI_BM(ed.flags, ED_D), (ed.flags & OHCI_ED_S)!= 0,
690                     (ed.flags & OHCI_ED_K) != 0, (ed.flags & OHCI_ED_F) != 0,
691                     OHCI_BM(ed.flags, ED_MPS), (ed.head & OHCI_ED_H) != 0,
692                     (ed.head & OHCI_ED_C) != 0, ed.head & OHCI_DPTR_MASK,
693                     ed.tail & OHCI_DPTR_MASK, ed.next & OHCI_DPTR_MASK);
694 #endif
695             active = 1;
696
697             if (ohci_service_td(ohci, &ed))
698                 break;
699         }
700
701         ohci_put_ed(cur, &ed);
702     }
703
704     return active;
705 }
706
707 /* Generate a SOF event, and set a timer for EOF */
708 static void ohci_sof(OHCIState *ohci)
709 {
710     ohci->sof_time = qemu_get_clock(vm_clock);
711     qemu_mod_timer(ohci->eof_timer, ohci->sof_time + usb_frame_time);
712     ohci_set_interrupt(ohci, OHCI_INTR_SF);
713 }
714
715 /* Process Control and Bulk lists.  */
716 static void ohci_process_lists(OHCIState *ohci)
717 {
718     if ((ohci->ctl & OHCI_CTL_CLE) && (ohci->status & OHCI_STATUS_CLF)) {
719         if (ohci->ctrl_cur && ohci->ctrl_cur != ohci->ctrl_head)
720           dprintf("usb-ohci: head %x, cur %x\n", ohci->ctrl_head, ohci->ctrl_cur);
721         if (!ohci_service_ed_list(ohci, ohci->ctrl_head)) {
722             ohci->ctrl_cur = 0;
723             ohci->status &= ~OHCI_STATUS_CLF;
724         }
725     }
726
727     if ((ohci->ctl & OHCI_CTL_BLE) && (ohci->status & OHCI_STATUS_BLF)) {
728         if (!ohci_service_ed_list(ohci, ohci->bulk_head)) {
729             ohci->bulk_cur = 0;
730             ohci->status &= ~OHCI_STATUS_BLF;
731         }
732     }
733 }
734
735 /* Do frame processing on frame boundary */
736 static void ohci_frame_boundary(void *opaque)
737 {
738     OHCIState *ohci = opaque;
739     struct ohci_hcca hcca;
740
741     cpu_physical_memory_rw(ohci->hcca, (uint8_t *)&hcca, sizeof(hcca), 0);
742
743     /* Process all the lists at the end of the frame */
744     if (ohci->ctl & OHCI_CTL_PLE) {
745         int n;
746
747         n = ohci->frame_number & 0x1f;
748         ohci_service_ed_list(ohci, le32_to_cpu(hcca.intr[n]));
749     }
750
751     /* Cancel all pending packets if either of the lists has been disabled.  */
752     if (ohci->async_td &&
753         ohci->old_ctl & (~ohci->ctl) & (OHCI_CTL_BLE | OHCI_CTL_CLE)) {
754         usb_cancel_packet(&ohci->usb_packet);
755         ohci->async_td = 0;
756     }
757     ohci->old_ctl = ohci->ctl;
758     ohci_process_lists(ohci);
759
760     /* Frame boundary, so do EOF stuf here */
761     ohci->frt = ohci->fit;
762
763     /* XXX: endianness */
764     ohci->frame_number = (ohci->frame_number + 1) & 0xffff;
765     hcca.frame = cpu_to_le32(ohci->frame_number);
766
767     if (ohci->done_count == 0 && !(ohci->intr_status & OHCI_INTR_WD)) {
768         if (!ohci->done)
769             abort();
770         if (ohci->intr & ohci->intr_status)
771             ohci->done |= 1;
772         hcca.done = cpu_to_le32(ohci->done);
773         ohci->done = 0;
774         ohci->done_count = 7;
775         ohci_set_interrupt(ohci, OHCI_INTR_WD);
776     }
777
778     if (ohci->done_count != 7 && ohci->done_count != 0)
779         ohci->done_count--;
780
781     /* Do SOF stuff here */
782     ohci_sof(ohci);
783
784     /* Writeback HCCA */
785     cpu_physical_memory_rw(ohci->hcca, (uint8_t *)&hcca, sizeof(hcca), 1);
786 }
787
788 /* Start sending SOF tokens across the USB bus, lists are processed in
789  * next frame
790  */
791 static int ohci_bus_start(OHCIState *ohci)
792 {
793     ohci->eof_timer = qemu_new_timer(vm_clock,
794                     ohci_frame_boundary,
795                     ohci);
796
797     if (ohci->eof_timer == NULL) {
798         fprintf(stderr, "usb-ohci: %s: qemu_new_timer failed\n",
799             ohci->pci_dev.name);
800         /* TODO: Signal unrecoverable error */
801         return 0;
802     }
803
804     dprintf("usb-ohci: %s: USB Operational\n", ohci->pci_dev.name);
805
806     ohci_sof(ohci);
807
808     return 1;
809 }
810
811 /* Stop sending SOF tokens on the bus */
812 static void ohci_bus_stop(OHCIState *ohci)
813 {
814     if (ohci->eof_timer)
815         qemu_del_timer(ohci->eof_timer);
816 }
817
818 /* Sets a flag in a port status register but only set it if the port is
819  * connected, if not set ConnectStatusChange flag. If flag is enabled
820  * return 1.
821  */
822 static int ohci_port_set_if_connected(OHCIState *ohci, int i, uint32_t val)
823 {
824     int ret = 1;
825
826     /* writing a 0 has no effect */
827     if (val == 0)
828         return 0;
829
830     /* If CurrentConnectStatus is cleared we set
831      * ConnectStatusChange
832      */
833     if (!(ohci->rhport[i].ctrl & OHCI_PORT_CCS)) {
834         ohci->rhport[i].ctrl |= OHCI_PORT_CSC;
835         if (ohci->rhstatus & OHCI_RHS_DRWE) {
836             /* TODO: CSC is a wakeup event */
837         }
838         return 0;
839     }
840
841     if (ohci->rhport[i].ctrl & val)
842         ret = 0;
843
844     /* set the bit */
845     ohci->rhport[i].ctrl |= val;
846
847     return ret;
848 }
849
850 /* Set the frame interval - frame interval toggle is manipulated by the hcd only */
851 static void ohci_set_frame_interval(OHCIState *ohci, uint16_t val)
852 {
853     val &= OHCI_FMI_FI;
854
855     if (val != ohci->fi) {
856         dprintf("usb-ohci: %s: FrameInterval = 0x%x (%u)\n",
857             ohci->pci_dev.name, ohci->fi, ohci->fi);
858     }
859
860     ohci->fi = val;
861 }
862
863 static void ohci_port_power(OHCIState *ohci, int i, int p)
864 {
865     if (p) {
866         ohci->rhport[i].ctrl |= OHCI_PORT_PPS;
867     } else {
868         ohci->rhport[i].ctrl &= ~(OHCI_PORT_PPS|
869                     OHCI_PORT_CCS|
870                     OHCI_PORT_PSS|
871                     OHCI_PORT_PRS);
872     }
873 }
874
875 /* Set HcControlRegister */
876 static void ohci_set_ctl(OHCIState *ohci, uint32_t val)
877 {
878     uint32_t old_state;
879     uint32_t new_state;
880
881     old_state = ohci->ctl & OHCI_CTL_HCFS;
882     ohci->ctl = val;
883     new_state = ohci->ctl & OHCI_CTL_HCFS;
884
885     /* no state change */
886     if (old_state == new_state)
887         return;
888
889     switch (new_state) {
890     case OHCI_USB_OPERATIONAL:
891         ohci_bus_start(ohci);
892         break;
893     case OHCI_USB_SUSPEND:
894         ohci_bus_stop(ohci);
895         dprintf("usb-ohci: %s: USB Suspended\n", ohci->pci_dev.name);
896         break;
897     case OHCI_USB_RESUME:
898         dprintf("usb-ohci: %s: USB Resume\n", ohci->pci_dev.name);
899         break;
900     case OHCI_USB_RESET:
901         dprintf("usb-ohci: %s: USB Reset\n", ohci->pci_dev.name);
902         break;
903     }
904 }
905
906 static uint32_t ohci_get_frame_remaining(OHCIState *ohci)
907 {
908     uint16_t fr;
909     int64_t tks;
910
911     if ((ohci->ctl & OHCI_CTL_HCFS) != OHCI_USB_OPERATIONAL)
912         return (ohci->frt << 31);
913
914     /* Being in USB operational state guarnatees sof_time was
915      * set already.
916      */
917     tks = qemu_get_clock(vm_clock) - ohci->sof_time;
918
919     /* avoid muldiv if possible */
920     if (tks >= usb_frame_time)
921         return (ohci->frt << 31);
922
923     tks = muldiv64(1, tks, usb_bit_time);
924     fr = (uint16_t)(ohci->fi - tks);
925
926     return (ohci->frt << 31) | fr;
927 }
928
929
930 /* Set root hub status */
931 static void ohci_set_hub_status(OHCIState *ohci, uint32_t val)
932 {
933     uint32_t old_state;
934
935     old_state = ohci->rhstatus;
936
937     /* write 1 to clear OCIC */
938     if (val & OHCI_RHS_OCIC)
939         ohci->rhstatus &= ~OHCI_RHS_OCIC;
940
941     if (val & OHCI_RHS_LPS) {
942         int i;
943
944         for (i = 0; i < ohci->num_ports; i++)
945             ohci_port_power(ohci, i, 0);
946         dprintf("usb-ohci: powered down all ports\n");
947     }
948
949     if (val & OHCI_RHS_LPSC) {
950         int i;
951
952         for (i = 0; i < ohci->num_ports; i++)
953             ohci_port_power(ohci, i, 1);
954         dprintf("usb-ohci: powered up all ports\n");
955     }
956
957     if (val & OHCI_RHS_DRWE)
958         ohci->rhstatus |= OHCI_RHS_DRWE;
959
960     if (val & OHCI_RHS_CRWE)
961         ohci->rhstatus &= ~OHCI_RHS_DRWE;
962
963     if (old_state != ohci->rhstatus)
964         ohci_set_interrupt(ohci, OHCI_INTR_RHSC);
965 }
966
967 /* Set root hub port status */
968 static void ohci_port_set_status(OHCIState *ohci, int portnum, uint32_t val)
969 {
970     uint32_t old_state;
971     OHCIPort *port;
972
973     port = &ohci->rhport[portnum];
974     old_state = port->ctrl;
975
976     /* Write to clear CSC, PESC, PSSC, OCIC, PRSC */
977     if (val & OHCI_PORT_WTC)
978         port->ctrl &= ~(val & OHCI_PORT_WTC);
979
980     if (val & OHCI_PORT_CCS)
981         port->ctrl &= ~OHCI_PORT_PES;
982
983     ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PES);
984
985     if (ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PSS))
986         dprintf("usb-ohci: port %d: SUSPEND\n", portnum);
987
988     if (ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PRS)) {
989         dprintf("usb-ohci: port %d: RESET\n", portnum);
990         usb_send_msg(port->port.dev, USB_MSG_RESET);
991         port->ctrl &= ~OHCI_PORT_PRS;
992         /* ??? Should this also set OHCI_PORT_PESC.  */
993         port->ctrl |= OHCI_PORT_PES | OHCI_PORT_PRSC;
994     }
995
996     /* Invert order here to ensure in ambiguous case, device is
997      * powered up...
998      */
999     if (val & OHCI_PORT_LSDA)
1000         ohci_port_power(ohci, portnum, 0);
1001     if (val & OHCI_PORT_PPS)
1002         ohci_port_power(ohci, portnum, 1);
1003
1004     if (old_state != port->ctrl)
1005         ohci_set_interrupt(ohci, OHCI_INTR_RHSC);
1006
1007     return;
1008 }
1009
1010 static uint32_t ohci_mem_read(void *ptr, target_phys_addr_t addr)
1011 {
1012     OHCIState *ohci = ptr;
1013
1014     addr -= ohci->mem_base;
1015
1016     /* Only aligned reads are allowed on OHCI */
1017     if (addr & 3) {
1018         fprintf(stderr, "usb-ohci: Mis-aligned read\n");
1019         return 0xffffffff;
1020     }
1021
1022     if (addr >= 0x54 && addr < 0x54 + ohci->num_ports * 4) {
1023         /* HcRhPortStatus */
1024         return ohci->rhport[(addr - 0x54) >> 2].ctrl | OHCI_PORT_PPS;
1025     }
1026
1027     switch (addr >> 2) {
1028     case 0: /* HcRevision */
1029         return 0x10;
1030
1031     case 1: /* HcControl */
1032         return ohci->ctl;
1033
1034     case 2: /* HcCommandStatus */
1035         return ohci->status;
1036
1037     case 3: /* HcInterruptStatus */
1038         return ohci->intr_status;
1039
1040     case 4: /* HcInterruptEnable */
1041     case 5: /* HcInterruptDisable */
1042         return ohci->intr;
1043
1044     case 6: /* HcHCCA */
1045         return ohci->hcca;
1046
1047     case 7: /* HcPeriodCurrentED */
1048         return ohci->per_cur;
1049
1050     case 8: /* HcControlHeadED */
1051         return ohci->ctrl_head;
1052
1053     case 9: /* HcControlCurrentED */
1054         return ohci->ctrl_cur;
1055
1056     case 10: /* HcBulkHeadED */
1057         return ohci->bulk_head;
1058
1059     case 11: /* HcBulkCurrentED */
1060         return ohci->bulk_cur;
1061
1062     case 12: /* HcDoneHead */
1063         return ohci->done;
1064
1065     case 13: /* HcFmInterval */
1066         return (ohci->fit << 31) | (ohci->fsmps << 16) | (ohci->fi);
1067
1068     case 14: /* HcFmRemaining */
1069         return ohci_get_frame_remaining(ohci);
1070
1071     case 15: /* HcFmNumber */
1072         return ohci->frame_number;
1073
1074     case 16: /* HcPeriodicStart */
1075         return ohci->pstart;
1076
1077     case 17: /* HcLSThreshold */
1078         return ohci->lst;
1079
1080     case 18: /* HcRhDescriptorA */
1081         return ohci->rhdesc_a;
1082
1083     case 19: /* HcRhDescriptorB */
1084         return ohci->rhdesc_b;
1085
1086     case 20: /* HcRhStatus */
1087         return ohci->rhstatus;
1088
1089     default:
1090         fprintf(stderr, "ohci_read: Bad offset %x\n", (int)addr);
1091         return 0xffffffff;
1092     }
1093 }
1094
1095 static void ohci_mem_write(void *ptr, target_phys_addr_t addr, uint32_t val)
1096 {
1097     OHCIState *ohci = ptr;
1098
1099     addr -= ohci->mem_base;
1100
1101     /* Only aligned reads are allowed on OHCI */
1102     if (addr & 3) {
1103         fprintf(stderr, "usb-ohci: Mis-aligned write\n");
1104         return;
1105     }
1106
1107     if (addr >= 0x54 && addr < 0x54 + ohci->num_ports * 4) {
1108         /* HcRhPortStatus */
1109         ohci_port_set_status(ohci, (addr - 0x54) >> 2, val);
1110         return;
1111     }
1112
1113     switch (addr >> 2) {
1114     case 1: /* HcControl */
1115         ohci_set_ctl(ohci, val);
1116         break;
1117
1118     case 2: /* HcCommandStatus */
1119         /* SOC is read-only */
1120         val = (val & ~OHCI_STATUS_SOC);
1121
1122         /* Bits written as '0' remain unchanged in the register */
1123         ohci->status |= val;
1124
1125         if (ohci->status & OHCI_STATUS_HCR)
1126             ohci_reset(ohci);
1127         break;
1128
1129     case 3: /* HcInterruptStatus */
1130         ohci->intr_status &= ~val;
1131         ohci_intr_update(ohci);
1132         break;
1133
1134     case 4: /* HcInterruptEnable */
1135         ohci->intr |= val;
1136         ohci_intr_update(ohci);
1137         break;
1138
1139     case 5: /* HcInterruptDisable */
1140         ohci->intr &= ~val;
1141         ohci_intr_update(ohci);
1142         break;
1143
1144     case 6: /* HcHCCA */
1145         ohci->hcca = val & OHCI_HCCA_MASK;
1146         break;
1147
1148     case 8: /* HcControlHeadED */
1149         ohci->ctrl_head = val & OHCI_EDPTR_MASK;
1150         break;
1151
1152     case 9: /* HcControlCurrentED */
1153         ohci->ctrl_cur = val & OHCI_EDPTR_MASK;
1154         break;
1155
1156     case 10: /* HcBulkHeadED */
1157         ohci->bulk_head = val & OHCI_EDPTR_MASK;
1158         break;
1159
1160     case 11: /* HcBulkCurrentED */
1161         ohci->bulk_cur = val & OHCI_EDPTR_MASK;
1162         break;
1163
1164     case 13: /* HcFmInterval */
1165         ohci->fsmps = (val & OHCI_FMI_FSMPS) >> 16;
1166         ohci->fit = (val & OHCI_FMI_FIT) >> 31;
1167         ohci_set_frame_interval(ohci, val);
1168         break;
1169
1170     case 16: /* HcPeriodicStart */
1171         ohci->pstart = val & 0xffff;
1172         break;
1173
1174     case 17: /* HcLSThreshold */
1175         ohci->lst = val & 0xffff;
1176         break;
1177
1178     case 18: /* HcRhDescriptorA */
1179         ohci->rhdesc_a &= ~OHCI_RHA_RW_MASK;
1180         ohci->rhdesc_a |= val & OHCI_RHA_RW_MASK;
1181         break;
1182
1183     case 19: /* HcRhDescriptorB */
1184         break;
1185
1186     case 20: /* HcRhStatus */
1187         ohci_set_hub_status(ohci, val);
1188         break;
1189
1190     default:
1191         fprintf(stderr, "ohci_write: Bad offset %x\n", (int)addr);
1192         break;
1193     }
1194 }
1195
1196 /* Only dword reads are defined on OHCI register space */
1197 static CPUReadMemoryFunc *ohci_readfn[3]={
1198     ohci_mem_read,
1199     ohci_mem_read,
1200     ohci_mem_read
1201 };
1202
1203 /* Only dword writes are defined on OHCI register space */
1204 static CPUWriteMemoryFunc *ohci_writefn[3]={
1205     ohci_mem_write,
1206     ohci_mem_write,
1207     ohci_mem_write
1208 };
1209
1210 static void ohci_mapfunc(PCIDevice *pci_dev, int i,
1211             uint32_t addr, uint32_t size, int type)
1212 {
1213     OHCIState *ohci = (OHCIState *)pci_dev;
1214     ohci->mem_base = addr;
1215     cpu_register_physical_memory(addr, size, ohci->mem);
1216 }
1217
1218 void usb_ohci_init(struct PCIBus *bus, int num_ports, int devfn)
1219 {
1220     OHCIState *ohci;
1221     int vid = 0x106b;
1222     int did = 0x003f;
1223     int i;
1224
1225
1226     if (usb_frame_time == 0) {
1227 #if OHCI_TIME_WARP
1228         usb_frame_time = ticks_per_sec;
1229         usb_bit_time = muldiv64(1, ticks_per_sec, USB_HZ/1000);
1230 #else
1231         usb_frame_time = muldiv64(1, ticks_per_sec, 1000);
1232         if (ticks_per_sec >= USB_HZ) {
1233             usb_bit_time = muldiv64(1, ticks_per_sec, USB_HZ);
1234         } else {
1235             usb_bit_time = 1;
1236         }
1237 #endif
1238         dprintf("usb-ohci: usb_bit_time=%lli usb_frame_time=%lli\n",
1239                 usb_frame_time, usb_bit_time);
1240     }
1241
1242     ohci = (OHCIState *)pci_register_device(bus, "OHCI USB", sizeof(*ohci),
1243                                             devfn, NULL, NULL);
1244     if (ohci == NULL) {
1245         fprintf(stderr, "usb-ohci: Failed to register PCI device\n");
1246         return;
1247     }
1248
1249     ohci->pci_dev.config[0x00] = vid & 0xff;
1250     ohci->pci_dev.config[0x01] = (vid >> 8) & 0xff;
1251     ohci->pci_dev.config[0x02] = did & 0xff;
1252     ohci->pci_dev.config[0x03] = (did >> 8) & 0xff;
1253     ohci->pci_dev.config[0x09] = 0x10; /* OHCI */
1254     ohci->pci_dev.config[0x0a] = 0x3;
1255     ohci->pci_dev.config[0x0b] = 0xc;
1256     ohci->pci_dev.config[0x3d] = 0x01; /* interrupt pin 1 */
1257
1258     ohci->mem = cpu_register_io_memory(0, ohci_readfn, ohci_writefn, ohci);
1259
1260     pci_register_io_region((struct PCIDevice *)ohci, 0, 256,
1261                            PCI_ADDRESS_SPACE_MEM, ohci_mapfunc);
1262
1263     ohci->num_ports = num_ports;
1264     for (i = 0; i < num_ports; i++) {
1265         qemu_register_usb_port(&ohci->rhport[i].port, ohci, i, ohci_attach);
1266     }
1267
1268     ohci->async_td = 0;
1269     ohci_reset(ohci);
1270 }