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