279e82e364d646fe569484a5191f553901f6cc5c
[qemu] / hw / usb-ohci.c
1 /*
2  * QEMU USB OHCI Emulation
3  * Copyright (c) 2004 Gianni Tedesco
4  * Copyright (c) 2006 CodeSourcery
5  * Copyright (c) 2006 Openedhand Ltd.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA  02110-1301 USA
20  *
21  * TODO:
22  *  o Isochronous transfers
23  *  o Allocate bandwidth in frames properly
24  *  o Disable timers when nothing needs to be done, or remove timer usage
25  *    all together.
26  *  o Handle unrecoverable errors properly
27  *  o BIOS work to boot from USB storage
28 */
29
30 #include "hw.h"
31 #include "qemu-timer.h"
32 #include "usb.h"
33 #include "pci.h"
34 #include "pxa.h"
35 #include "omap.h"
36 #include "devices.h"
37
38 //#define DEBUG_OHCI
39 /* Dump packet contents.  */
40 //#define DEBUG_PACKET
41 //#define DEBUG_ISOCH
42 /* This causes frames to occur 1000x slower */
43 //#define OHCI_TIME_WARP 1
44
45 #ifdef DEBUG_OHCI
46 #define dprintf printf
47 #else
48 #define dprintf(...)
49 #endif
50
51 /* Number of Downstream Ports on the root hub.  */
52
53 #define OHCI_MAX_PORTS 15
54
55 static int64_t usb_frame_time;
56 static int64_t usb_bit_time;
57
58 typedef struct OHCIPort {
59     USBPort port;
60     uint32_t ctrl;
61 } OHCIPort;
62
63 enum ohci_type {
64     OHCI_TYPE_PCI,
65     OHCI_TYPE_PXA,
66     OHCI_TYPE_OMAP,
67     OHCI_TYPE_SM501,
68 };
69
70 typedef struct {
71     qemu_irq irq;
72     enum ohci_type type;
73     int mem;
74     int num_ports;
75     const char *name;
76
77     QEMUTimer *eof_timer;
78     int64_t sof_time;
79
80     /* OHCI state */
81     /* Control partition */
82     uint32_t ctl, status;
83     uint32_t intr_status;
84     uint32_t intr;
85
86     /* memory pointer partition */
87     uint32_t hcca;
88     uint32_t ctrl_head, ctrl_cur;
89     uint32_t bulk_head, bulk_cur;
90     uint32_t per_cur;
91     uint32_t done;
92     int done_count;
93
94     /* Frame counter partition */
95     uint32_t fsmps:15;
96     uint32_t fit:1;
97     uint32_t fi:14;
98     uint32_t frt:1;
99     uint16_t frame_number;
100     uint16_t padding;
101     uint32_t pstart;
102     uint32_t lst;
103
104     /* Root Hub partition */
105     uint32_t rhdesc_a, rhdesc_b;
106     uint32_t rhstatus;
107     OHCIPort rhport[OHCI_MAX_PORTS];
108
109     /* PXA27x Non-OHCI events */
110     uint32_t hstatus;
111     uint32_t hmask;
112     uint32_t hreset;
113     uint32_t htest;
114
115     /* SM501 local memory offset */
116     target_phys_addr_t localmem_base;
117
118     /* Active packets.  */
119     uint32_t old_ctl;
120     USBPacket usb_packet;
121     uint8_t usb_buf[8192];
122     uint32_t async_td;
123     int async_complete;
124
125 } OHCIState;
126
127 /* Host Controller Communications Area */
128 struct ohci_hcca {
129     uint32_t intr[32];
130     uint16_t frame, pad;
131     uint32_t done;
132 };
133
134 static void ohci_bus_stop(OHCIState *ohci);
135
136 /* Bitfields for the first word of an Endpoint Desciptor.  */
137 #define OHCI_ED_FA_SHIFT  0
138 #define OHCI_ED_FA_MASK   (0x7f<<OHCI_ED_FA_SHIFT)
139 #define OHCI_ED_EN_SHIFT  7
140 #define OHCI_ED_EN_MASK   (0xf<<OHCI_ED_EN_SHIFT)
141 #define OHCI_ED_D_SHIFT   11
142 #define OHCI_ED_D_MASK    (3<<OHCI_ED_D_SHIFT)
143 #define OHCI_ED_S         (1<<13)
144 #define OHCI_ED_K         (1<<14)
145 #define OHCI_ED_F         (1<<15)
146 #define OHCI_ED_MPS_SHIFT 16
147 #define OHCI_ED_MPS_MASK  (0x7ff<<OHCI_ED_MPS_SHIFT)
148
149 /* Flags in the head field of an Endpoint Desciptor.  */
150 #define OHCI_ED_H         1
151 #define OHCI_ED_C         2
152
153 /* Bitfields for the first word of a Transfer Desciptor.  */
154 #define OHCI_TD_R         (1<<18)
155 #define OHCI_TD_DP_SHIFT  19
156 #define OHCI_TD_DP_MASK   (3<<OHCI_TD_DP_SHIFT)
157 #define OHCI_TD_DI_SHIFT  21
158 #define OHCI_TD_DI_MASK   (7<<OHCI_TD_DI_SHIFT)
159 #define OHCI_TD_T0        (1<<24)
160 #define OHCI_TD_T1        (1<<24)
161 #define OHCI_TD_EC_SHIFT  26
162 #define OHCI_TD_EC_MASK   (3<<OHCI_TD_EC_SHIFT)
163 #define OHCI_TD_CC_SHIFT  28
164 #define OHCI_TD_CC_MASK   (0xf<<OHCI_TD_CC_SHIFT)
165
166 /* Bitfields for the first word of an Isochronous Transfer Desciptor.  */
167 /* CC & DI - same as in the General Transfer Desciptor */
168 #define OHCI_TD_SF_SHIFT  0
169 #define OHCI_TD_SF_MASK   (0xffff<<OHCI_TD_SF_SHIFT)
170 #define OHCI_TD_FC_SHIFT  24
171 #define OHCI_TD_FC_MASK   (7<<OHCI_TD_FC_SHIFT)
172
173 /* Isochronous Transfer Desciptor - Offset / PacketStatusWord */
174 #define OHCI_TD_PSW_CC_SHIFT 12
175 #define OHCI_TD_PSW_CC_MASK  (0xf<<OHCI_TD_PSW_CC_SHIFT)
176 #define OHCI_TD_PSW_SIZE_SHIFT 0
177 #define OHCI_TD_PSW_SIZE_MASK  (0xfff<<OHCI_TD_PSW_SIZE_SHIFT)
178
179 #define OHCI_PAGE_MASK    0xfffff000
180 #define OHCI_OFFSET_MASK  0xfff
181
182 #define OHCI_DPTR_MASK    0xfffffff0
183
184 #define OHCI_BM(val, field) \
185   (((val) & OHCI_##field##_MASK) >> OHCI_##field##_SHIFT)
186
187 #define OHCI_SET_BM(val, field, newval) do { \
188     val &= ~OHCI_##field##_MASK; \
189     val |= ((newval) << OHCI_##field##_SHIFT) & OHCI_##field##_MASK; \
190     } while(0)
191
192 /* endpoint descriptor */
193 struct ohci_ed {
194     uint32_t flags;
195     uint32_t tail;
196     uint32_t head;
197     uint32_t next;
198 };
199
200 /* General transfer descriptor */
201 struct ohci_td {
202     uint32_t flags;
203     uint32_t cbp;
204     uint32_t next;
205     uint32_t be;
206 };
207
208 /* Isochronous transfer descriptor */
209 struct ohci_iso_td {
210     uint32_t flags;
211     uint32_t bp;
212     uint32_t next;
213     uint32_t be;
214     uint16_t offset[8];
215 };
216
217 #define USB_HZ                      12000000
218
219 /* OHCI Local stuff */
220 #define OHCI_CTL_CBSR         ((1<<0)|(1<<1))
221 #define OHCI_CTL_PLE          (1<<2)
222 #define OHCI_CTL_IE           (1<<3)
223 #define OHCI_CTL_CLE          (1<<4)
224 #define OHCI_CTL_BLE          (1<<5)
225 #define OHCI_CTL_HCFS         ((1<<6)|(1<<7))
226 #define  OHCI_USB_RESET       0x00
227 #define  OHCI_USB_RESUME      0x40
228 #define  OHCI_USB_OPERATIONAL 0x80
229 #define  OHCI_USB_SUSPEND     0xc0
230 #define OHCI_CTL_IR           (1<<8)
231 #define OHCI_CTL_RWC          (1<<9)
232 #define OHCI_CTL_RWE          (1<<10)
233
234 #define OHCI_STATUS_HCR       (1<<0)
235 #define OHCI_STATUS_CLF       (1<<1)
236 #define OHCI_STATUS_BLF       (1<<2)
237 #define OHCI_STATUS_OCR       (1<<3)
238 #define OHCI_STATUS_SOC       ((1<<6)|(1<<7))
239
240 #define OHCI_INTR_SO          (1<<0) /* Scheduling overrun */
241 #define OHCI_INTR_WD          (1<<1) /* HcDoneHead writeback */
242 #define OHCI_INTR_SF          (1<<2) /* Start of frame */
243 #define OHCI_INTR_RD          (1<<3) /* Resume detect */
244 #define OHCI_INTR_UE          (1<<4) /* Unrecoverable error */
245 #define OHCI_INTR_FNO         (1<<5) /* Frame number overflow */
246 #define OHCI_INTR_RHSC        (1<<6) /* Root hub status change */
247 #define OHCI_INTR_OC          (1<<30) /* Ownership change */
248 #define OHCI_INTR_MIE         (1<<31) /* Master Interrupt Enable */
249
250 #define OHCI_HCCA_SIZE        0x100
251 #define OHCI_HCCA_MASK        0xffffff00
252
253 #define OHCI_EDPTR_MASK       0xfffffff0
254
255 #define OHCI_FMI_FI           0x00003fff
256 #define OHCI_FMI_FSMPS        0xffff0000
257 #define OHCI_FMI_FIT          0x80000000
258
259 #define OHCI_FR_RT            (1<<31)
260
261 #define OHCI_LS_THRESH        0x628
262
263 #define OHCI_RHA_RW_MASK      0x00000000 /* Mask of supported features.  */
264 #define OHCI_RHA_PSM          (1<<8)
265 #define OHCI_RHA_NPS          (1<<9)
266 #define OHCI_RHA_DT           (1<<10)
267 #define OHCI_RHA_OCPM         (1<<11)
268 #define OHCI_RHA_NOCP         (1<<12)
269 #define OHCI_RHA_POTPGT_MASK  0xff000000
270
271 #define OHCI_RHS_LPS          (1<<0)
272 #define OHCI_RHS_OCI          (1<<1)
273 #define OHCI_RHS_DRWE         (1<<15)
274 #define OHCI_RHS_LPSC         (1<<16)
275 #define OHCI_RHS_OCIC         (1<<17)
276 #define OHCI_RHS_CRWE         (1<<31)
277
278 #define OHCI_PORT_CCS         (1<<0)
279 #define OHCI_PORT_PES         (1<<1)
280 #define OHCI_PORT_PSS         (1<<2)
281 #define OHCI_PORT_POCI        (1<<3)
282 #define OHCI_PORT_PRS         (1<<4)
283 #define OHCI_PORT_PPS         (1<<8)
284 #define OHCI_PORT_LSDA        (1<<9)
285 #define OHCI_PORT_CSC         (1<<16)
286 #define OHCI_PORT_PESC        (1<<17)
287 #define OHCI_PORT_PSSC        (1<<18)
288 #define OHCI_PORT_OCIC        (1<<19)
289 #define OHCI_PORT_PRSC        (1<<20)
290 #define OHCI_PORT_WTC         (OHCI_PORT_CSC|OHCI_PORT_PESC|OHCI_PORT_PSSC \
291                                |OHCI_PORT_OCIC|OHCI_PORT_PRSC)
292
293 #define OHCI_TD_DIR_SETUP     0x0
294 #define OHCI_TD_DIR_OUT       0x1
295 #define OHCI_TD_DIR_IN        0x2
296 #define OHCI_TD_DIR_RESERVED  0x3
297
298 #define OHCI_CC_NOERROR             0x0
299 #define OHCI_CC_CRC                 0x1
300 #define OHCI_CC_BITSTUFFING         0x2
301 #define OHCI_CC_DATATOGGLEMISMATCH  0x3
302 #define OHCI_CC_STALL               0x4
303 #define OHCI_CC_DEVICENOTRESPONDING 0x5
304 #define OHCI_CC_PIDCHECKFAILURE     0x6
305 #define OHCI_CC_UNDEXPETEDPID       0x7
306 #define OHCI_CC_DATAOVERRUN         0x8
307 #define OHCI_CC_DATAUNDERRUN        0x9
308 #define OHCI_CC_BUFFEROVERRUN       0xc
309 #define OHCI_CC_BUFFERUNDERRUN      0xd
310
311 #define OHCI_HRESET_FSBIR       (1 << 0)
312
313 /* Update IRQ levels */
314 static inline void ohci_intr_update(OHCIState *ohci)
315 {
316     int level = 0;
317
318     if ((ohci->intr & OHCI_INTR_MIE) &&
319         (ohci->intr_status & ohci->intr))
320         level = 1;
321
322     qemu_set_irq(ohci->irq, level);
323 }
324
325 /* Set an interrupt */
326 static inline void ohci_set_interrupt(OHCIState *ohci, uint32_t intr)
327 {
328     ohci->intr_status |= intr;
329     ohci_intr_update(ohci);
330 }
331
332 /* Attach or detach a device on a root hub port.  */
333 static void ohci_attach(USBPort *port1, USBDevice *dev)
334 {
335     OHCIState *s = port1->opaque;
336     OHCIPort *port = &s->rhport[port1->index];
337     uint32_t old_state = port->ctrl;
338
339     if (dev) {
340         if (port->port.dev) {
341             usb_attach(port1, NULL);
342         }
343         /* set connect status */
344         port->ctrl |= OHCI_PORT_CCS | OHCI_PORT_CSC;
345
346         /* update speed */
347         if (dev->speed == USB_SPEED_LOW)
348             port->ctrl |= OHCI_PORT_LSDA;
349         else
350             port->ctrl &= ~OHCI_PORT_LSDA;
351         port->port.dev = dev;
352
353         /* notify of remote-wakeup */
354         if ((s->ctl & OHCI_CTL_HCFS) == OHCI_USB_SUSPEND)
355             ohci_set_interrupt(s, OHCI_INTR_RD);
356
357         /* send the attach message */
358         usb_send_msg(dev, USB_MSG_ATTACH);
359         dprintf("usb-ohci: Attached port %d\n", port1->index);
360     } else {
361         /* set connect status */
362         if (port->ctrl & OHCI_PORT_CCS) {
363             port->ctrl &= ~OHCI_PORT_CCS;
364             port->ctrl |= OHCI_PORT_CSC;
365         }
366         /* disable port */
367         if (port->ctrl & OHCI_PORT_PES) {
368             port->ctrl &= ~OHCI_PORT_PES;
369             port->ctrl |= OHCI_PORT_PESC;
370         }
371         dev = port->port.dev;
372         if (dev) {
373             /* send the detach message */
374             usb_send_msg(dev, USB_MSG_DETACH);
375         }
376         port->port.dev = NULL;
377         dprintf("usb-ohci: Detached port %d\n", port1->index);
378     }
379
380     if (old_state != port->ctrl)
381         ohci_set_interrupt(s, OHCI_INTR_RHSC);
382 }
383
384 /* Reset the controller */
385 static void ohci_reset(void *opaque)
386 {
387     OHCIState *ohci = opaque;
388     OHCIPort *port;
389     int i;
390
391     ohci_bus_stop(ohci);
392     ohci->ctl = 0;
393     ohci->old_ctl = 0;
394     ohci->status = 0;
395     ohci->intr_status = 0;
396     ohci->intr = OHCI_INTR_MIE;
397
398     ohci->hcca = 0;
399     ohci->ctrl_head = ohci->ctrl_cur = 0;
400     ohci->bulk_head = ohci->bulk_cur = 0;
401     ohci->per_cur = 0;
402     ohci->done = 0;
403     ohci->done_count = 7;
404
405     /* FSMPS is marked TBD in OCHI 1.0, what gives ffs?
406      * I took the value linux sets ...
407      */
408     ohci->fsmps = 0x2778;
409     ohci->fi = 0x2edf;
410     ohci->fit = 0;
411     ohci->frt = 0;
412     ohci->frame_number = 0;
413     ohci->pstart = 0;
414     ohci->lst = OHCI_LS_THRESH;
415
416     ohci->rhdesc_a = OHCI_RHA_NPS | ohci->num_ports;
417     ohci->rhdesc_b = 0x0; /* Impl. specific */
418     ohci->rhstatus = 0;
419
420     for (i = 0; i < ohci->num_ports; i++)
421       {
422         port = &ohci->rhport[i];
423         port->ctrl = 0;
424         if (port->port.dev)
425             ohci_attach(&port->port, port->port.dev);
426       }
427     if (ohci->async_td) {
428         usb_cancel_packet(&ohci->usb_packet);
429         ohci->async_td = 0;
430     }
431     dprintf("usb-ohci: Reset %s\n", ohci->name);
432 }
433
434 /* Get an array of dwords from main memory */
435 static inline int get_dwords(OHCIState *ohci,
436                              uint32_t addr, uint32_t *buf, int num)
437 {
438     int i;
439
440     addr += ohci->localmem_base;
441
442     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
443         cpu_physical_memory_rw(addr, (uint8_t *)buf, sizeof(*buf), 0);
444         *buf = le32_to_cpu(*buf);
445     }
446
447     return 1;
448 }
449
450 /* Put an array of dwords in to main memory */
451 static inline int put_dwords(OHCIState *ohci,
452                              uint32_t addr, uint32_t *buf, int num)
453 {
454     int i;
455
456     addr += ohci->localmem_base;
457
458     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
459         uint32_t tmp = cpu_to_le32(*buf);
460         cpu_physical_memory_rw(addr, (uint8_t *)&tmp, sizeof(tmp), 1);
461     }
462
463     return 1;
464 }
465
466 /* Get an array of words from main memory */
467 static inline int get_words(OHCIState *ohci,
468                             uint32_t addr, uint16_t *buf, int num)
469 {
470     int i;
471
472     addr += ohci->localmem_base;
473
474     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
475         cpu_physical_memory_rw(addr, (uint8_t *)buf, sizeof(*buf), 0);
476         *buf = le16_to_cpu(*buf);
477     }
478
479     return 1;
480 }
481
482 /* Put an array of words in to main memory */
483 static inline int put_words(OHCIState *ohci,
484                             uint32_t addr, uint16_t *buf, int num)
485 {
486     int i;
487
488     addr += ohci->localmem_base;
489
490     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
491         uint16_t tmp = cpu_to_le16(*buf);
492         cpu_physical_memory_rw(addr, (uint8_t *)&tmp, sizeof(tmp), 1);
493     }
494
495     return 1;
496 }
497
498 static inline int ohci_read_ed(OHCIState *ohci,
499                                uint32_t addr, struct ohci_ed *ed)
500 {
501     return get_dwords(ohci, addr, (uint32_t *)ed, sizeof(*ed) >> 2);
502 }
503
504 static inline int ohci_read_td(OHCIState *ohci,
505                                uint32_t addr, struct ohci_td *td)
506 {
507     return get_dwords(ohci, addr, (uint32_t *)td, sizeof(*td) >> 2);
508 }
509
510 static inline int ohci_read_iso_td(OHCIState *ohci,
511                                    uint32_t addr, struct ohci_iso_td *td)
512 {
513     return (get_dwords(ohci, addr, (uint32_t *)td, 4) &&
514             get_words(ohci, addr + 16, td->offset, 8));
515 }
516
517 static inline int ohci_read_hcca(OHCIState *ohci,
518                                  uint32_t addr, struct ohci_hcca *hcca)
519 {
520     cpu_physical_memory_rw(addr + ohci->localmem_base,
521                            (uint8_t *)hcca, sizeof(*hcca), 0);
522     return 1;
523 }
524
525 static inline int ohci_put_ed(OHCIState *ohci,
526                               uint32_t addr, struct ohci_ed *ed)
527 {
528     return put_dwords(ohci, addr, (uint32_t *)ed, sizeof(*ed) >> 2);
529 }
530
531 static inline int ohci_put_td(OHCIState *ohci,
532                               uint32_t addr, struct ohci_td *td)
533 {
534     return put_dwords(ohci, addr, (uint32_t *)td, sizeof(*td) >> 2);
535 }
536
537 static inline int ohci_put_iso_td(OHCIState *ohci,
538                                   uint32_t addr, struct ohci_iso_td *td)
539 {
540     return (put_dwords(ohci, addr, (uint32_t *)td, 4) &&
541             put_words(ohci, addr + 16, td->offset, 8));
542 }
543
544 static inline int ohci_put_hcca(OHCIState *ohci,
545                                 uint32_t addr, struct ohci_hcca *hcca)
546 {
547     cpu_physical_memory_rw(addr + ohci->localmem_base,
548                            (uint8_t *)hcca, sizeof(*hcca), 1);
549     return 1;
550 }
551
552 /* Read/Write the contents of a TD from/to main memory.  */
553 static void ohci_copy_td(OHCIState *ohci, struct ohci_td *td,
554                          uint8_t *buf, int len, int write)
555 {
556     uint32_t ptr;
557     uint32_t n;
558
559     ptr = td->cbp;
560     n = 0x1000 - (ptr & 0xfff);
561     if (n > len)
562         n = len;
563     cpu_physical_memory_rw(ptr + ohci->localmem_base, buf, n, write);
564     if (n == len)
565         return;
566     ptr = td->be & ~0xfffu;
567     buf += n;
568     cpu_physical_memory_rw(ptr + ohci->localmem_base, buf, len - n, write);
569 }
570
571 /* Read/Write the contents of an ISO TD from/to main memory.  */
572 static void ohci_copy_iso_td(OHCIState *ohci,
573                              uint32_t start_addr, uint32_t end_addr,
574                              uint8_t *buf, int len, int write)
575 {
576     uint32_t ptr;
577     uint32_t n;
578
579     ptr = start_addr;
580     n = 0x1000 - (ptr & 0xfff);
581     if (n > len)
582         n = len;
583     cpu_physical_memory_rw(ptr + ohci->localmem_base, buf, n, write);
584     if (n == len)
585         return;
586     ptr = end_addr & ~0xfffu;
587     buf += n;
588     cpu_physical_memory_rw(ptr + ohci->localmem_base, buf, len - n, write);
589 }
590
591 static void ohci_process_lists(OHCIState *ohci, int completion);
592
593 static void ohci_async_complete_packet(USBPacket *packet, void *opaque)
594 {
595     OHCIState *ohci = opaque;
596 #ifdef DEBUG_PACKET
597     dprintf("Async packet complete\n");
598 #endif
599     ohci->async_complete = 1;
600     ohci_process_lists(ohci, 1);
601 }
602
603 #define USUB(a, b) ((int16_t)((uint16_t)(a) - (uint16_t)(b)))
604
605 static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed,
606                                int completion)
607 {
608     int dir;
609     size_t len = 0;
610     const char *str = NULL;
611     int pid;
612     int ret;
613     int i;
614     USBDevice *dev;
615     struct ohci_iso_td iso_td;
616     uint32_t addr;
617     uint16_t starting_frame;
618     int16_t relative_frame_number;
619     int frame_count;
620     uint32_t start_offset, next_offset, end_offset = 0;
621     uint32_t start_addr, end_addr;
622
623     addr = ed->head & OHCI_DPTR_MASK;
624
625     if (!ohci_read_iso_td(ohci, addr, &iso_td)) {
626         printf("usb-ohci: ISO_TD read error at %x\n", addr);
627         return 0;
628     }
629
630     starting_frame = OHCI_BM(iso_td.flags, TD_SF);
631     frame_count = OHCI_BM(iso_td.flags, TD_FC);
632     relative_frame_number = USUB(ohci->frame_number, starting_frame); 
633
634 #ifdef DEBUG_ISOCH
635     printf("--- ISO_TD ED head 0x%.8x tailp 0x%.8x\n"
636            "0x%.8x 0x%.8x 0x%.8x 0x%.8x\n"
637            "0x%.8x 0x%.8x 0x%.8x 0x%.8x\n"
638            "0x%.8x 0x%.8x 0x%.8x 0x%.8x\n"
639            "frame_number 0x%.8x starting_frame 0x%.8x\n"
640            "frame_count  0x%.8x relative %d\n"
641            "di 0x%.8x cc 0x%.8x\n",
642            ed->head & OHCI_DPTR_MASK, ed->tail & OHCI_DPTR_MASK,
643            iso_td.flags, iso_td.bp, iso_td.next, iso_td.be,
644            iso_td.offset[0], iso_td.offset[1], iso_td.offset[2], iso_td.offset[3],
645            iso_td.offset[4], iso_td.offset[5], iso_td.offset[6], iso_td.offset[7],
646            ohci->frame_number, starting_frame, 
647            frame_count, relative_frame_number,         
648            OHCI_BM(iso_td.flags, TD_DI), OHCI_BM(iso_td.flags, TD_CC));
649 #endif
650
651     if (relative_frame_number < 0) {
652         dprintf("usb-ohci: ISO_TD R=%d < 0\n", relative_frame_number);
653         return 1;
654     } else if (relative_frame_number > frame_count) {
655         /* ISO TD expired - retire the TD to the Done Queue and continue with
656            the next ISO TD of the same ED */
657         dprintf("usb-ohci: ISO_TD R=%d > FC=%d\n", relative_frame_number, 
658                frame_count);
659         OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_DATAOVERRUN);
660         ed->head &= ~OHCI_DPTR_MASK;
661         ed->head |= (iso_td.next & OHCI_DPTR_MASK);
662         iso_td.next = ohci->done;
663         ohci->done = addr;
664         i = OHCI_BM(iso_td.flags, TD_DI);
665         if (i < ohci->done_count)
666             ohci->done_count = i;
667         ohci_put_iso_td(ohci, addr, &iso_td);
668         return 0;
669     }
670
671     dir = OHCI_BM(ed->flags, ED_D);
672     switch (dir) {
673     case OHCI_TD_DIR_IN:
674         str = "in";
675         pid = USB_TOKEN_IN;
676         break;
677     case OHCI_TD_DIR_OUT:
678         str = "out";
679         pid = USB_TOKEN_OUT;
680         break;
681     case OHCI_TD_DIR_SETUP:
682         str = "setup";
683         pid = USB_TOKEN_SETUP;
684         break;
685     default:
686         printf("usb-ohci: Bad direction %d\n", dir);
687         return 1;
688     }
689
690     if (!iso_td.bp || !iso_td.be) {
691         printf("usb-ohci: ISO_TD bp 0x%.8x be 0x%.8x\n", iso_td.bp, iso_td.be);
692         return 1;
693     }
694
695     start_offset = iso_td.offset[relative_frame_number];
696     next_offset = iso_td.offset[relative_frame_number + 1];
697
698     if (!(OHCI_BM(start_offset, TD_PSW_CC) & 0xe) || 
699         ((relative_frame_number < frame_count) && 
700          !(OHCI_BM(next_offset, TD_PSW_CC) & 0xe))) {
701         printf("usb-ohci: ISO_TD cc != not accessed 0x%.8x 0x%.8x\n",
702                start_offset, next_offset);
703         return 1;
704     }
705
706     if ((relative_frame_number < frame_count) && (start_offset > next_offset)) {
707         printf("usb-ohci: ISO_TD start_offset=0x%.8x > next_offset=0x%.8x\n",
708                 start_offset, next_offset);
709         return 1;
710     }
711
712     if ((start_offset & 0x1000) == 0) {
713         start_addr = (iso_td.bp & OHCI_PAGE_MASK) |
714             (start_offset & OHCI_OFFSET_MASK);
715     } else {
716         start_addr = (iso_td.be & OHCI_PAGE_MASK) |
717             (start_offset & OHCI_OFFSET_MASK);
718     }
719
720     if (relative_frame_number < frame_count) {
721         end_offset = next_offset - 1;
722         if ((end_offset & 0x1000) == 0) {
723             end_addr = (iso_td.bp & OHCI_PAGE_MASK) |
724                 (end_offset & OHCI_OFFSET_MASK);
725         } else {
726             end_addr = (iso_td.be & OHCI_PAGE_MASK) |
727                 (end_offset & OHCI_OFFSET_MASK);
728         }
729     } else {
730         /* Last packet in the ISO TD */
731         end_addr = iso_td.be;
732     }
733
734     if ((start_addr & OHCI_PAGE_MASK) != (end_addr & OHCI_PAGE_MASK)) {
735         len = (end_addr & OHCI_OFFSET_MASK) + 0x1001
736             - (start_addr & OHCI_OFFSET_MASK);
737     } else {
738         len = end_addr - start_addr + 1;
739     }
740
741     if (len && dir != OHCI_TD_DIR_IN) {
742         ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, len, 0);
743     }
744
745     if (completion) {
746         ret = ohci->usb_packet.len;
747     } else {
748         ret = USB_RET_NODEV;
749         for (i = 0; i < ohci->num_ports; i++) {
750             dev = ohci->rhport[i].port.dev;
751             if ((ohci->rhport[i].ctrl & OHCI_PORT_PES) == 0)
752                 continue;
753             ohci->usb_packet.pid = pid;
754             ohci->usb_packet.devaddr = OHCI_BM(ed->flags, ED_FA);
755             ohci->usb_packet.devep = OHCI_BM(ed->flags, ED_EN);
756             ohci->usb_packet.data = ohci->usb_buf;
757             ohci->usb_packet.len = len;
758             ohci->usb_packet.complete_cb = ohci_async_complete_packet;
759             ohci->usb_packet.complete_opaque = ohci;
760             ret = dev->handle_packet(dev, &ohci->usb_packet);
761             if (ret != USB_RET_NODEV)
762                 break;
763         }
764     
765         if (ret == USB_RET_ASYNC) {
766             return 1;
767         }
768     }
769
770 #ifdef DEBUG_ISOCH
771     printf("so 0x%.8x eo 0x%.8x\nsa 0x%.8x ea 0x%.8x\ndir %s len %zu ret %d\n",
772            start_offset, end_offset, start_addr, end_addr, str, len, ret);
773 #endif
774
775     /* Writeback */
776     if (dir == OHCI_TD_DIR_IN && ret >= 0 && ret <= len) {
777         /* IN transfer succeeded */
778         ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, ret, 1);
779         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
780                     OHCI_CC_NOERROR);
781         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, ret);
782     } else if (dir == OHCI_TD_DIR_OUT && ret == len) {
783         /* OUT transfer succeeded */
784         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
785                     OHCI_CC_NOERROR);
786         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, 0);
787     } else {
788         if (ret > (ssize_t) len) {
789             printf("usb-ohci: DataOverrun %d > %zu\n", ret, len);
790             OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
791                         OHCI_CC_DATAOVERRUN);
792             OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
793                         len);
794         } else if (ret >= 0) {
795             printf("usb-ohci: DataUnderrun %d\n", ret);
796             OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
797                         OHCI_CC_DATAUNDERRUN);
798         } else {
799             switch (ret) {
800             case USB_RET_NODEV:
801                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
802                             OHCI_CC_DEVICENOTRESPONDING);
803                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
804                             0);
805                 break;
806             case USB_RET_NAK:
807             case USB_RET_STALL:
808                 printf("usb-ohci: got NAK/STALL %d\n", ret);
809                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
810                             OHCI_CC_STALL);
811                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
812                             0);
813                 break;
814             default:
815                 printf("usb-ohci: Bad device response %d\n", ret);
816                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
817                             OHCI_CC_UNDEXPETEDPID);
818                 break;
819             }
820         }
821     }
822
823     if (relative_frame_number == frame_count) {
824         /* Last data packet of ISO TD - retire the TD to the Done Queue */
825         OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_NOERROR);
826         ed->head &= ~OHCI_DPTR_MASK;
827         ed->head |= (iso_td.next & OHCI_DPTR_MASK);
828         iso_td.next = ohci->done;
829         ohci->done = addr;
830         i = OHCI_BM(iso_td.flags, TD_DI);
831         if (i < ohci->done_count)
832             ohci->done_count = i;
833     }
834     ohci_put_iso_td(ohci, addr, &iso_td);
835     return 1;
836 }
837
838 /* Service a transport descriptor.
839    Returns nonzero to terminate processing of this endpoint.  */
840
841 static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed)
842 {
843     int dir;
844     size_t len = 0;
845     const char *str = NULL;
846     int pid;
847     int ret;
848     int i;
849     USBDevice *dev;
850     struct ohci_td td;
851     uint32_t addr;
852     int flag_r;
853     int completion;
854
855     addr = ed->head & OHCI_DPTR_MASK;
856     /* See if this TD has already been submitted to the device.  */
857     completion = (addr == ohci->async_td);
858     if (completion && !ohci->async_complete) {
859 #ifdef DEBUG_PACKET
860         dprintf("Skipping async TD\n");
861 #endif
862         return 1;
863     }
864     if (!ohci_read_td(ohci, addr, &td)) {
865         fprintf(stderr, "usb-ohci: TD read error at %x\n", addr);
866         return 0;
867     }
868
869     dir = OHCI_BM(ed->flags, ED_D);
870     switch (dir) {
871     case OHCI_TD_DIR_OUT:
872     case OHCI_TD_DIR_IN:
873         /* Same value.  */
874         break;
875     default:
876         dir = OHCI_BM(td.flags, TD_DP);
877         break;
878     }
879
880     switch (dir) {
881     case OHCI_TD_DIR_IN:
882         str = "in";
883         pid = USB_TOKEN_IN;
884         break;
885     case OHCI_TD_DIR_OUT:
886         str = "out";
887         pid = USB_TOKEN_OUT;
888         break;
889     case OHCI_TD_DIR_SETUP:
890         str = "setup";
891         pid = USB_TOKEN_SETUP;
892         break;
893     default:
894         fprintf(stderr, "usb-ohci: Bad direction\n");
895         return 1;
896     }
897     if (td.cbp && td.be) {
898         if ((td.cbp & 0xfffff000) != (td.be & 0xfffff000)) {
899             len = (td.be & 0xfff) + 0x1001 - (td.cbp & 0xfff);
900         } else {
901             len = (td.be - td.cbp) + 1;
902         }
903
904         if (len && dir != OHCI_TD_DIR_IN && !completion) {
905             ohci_copy_td(ohci, &td, ohci->usb_buf, len, 0);
906         }
907     }
908
909     flag_r = (td.flags & OHCI_TD_R) != 0;
910 #ifdef DEBUG_PACKET
911     dprintf(" TD @ 0x%.8x %u bytes %s r=%d cbp=0x%.8x be=0x%.8x\n",
912             addr, len, str, flag_r, td.cbp, td.be);
913
914     if (len > 0 && dir != OHCI_TD_DIR_IN) {
915         dprintf("  data:");
916         for (i = 0; i < len; i++)
917             printf(" %.2x", ohci->usb_buf[i]);
918         dprintf("\n");
919     }
920 #endif
921     if (completion) {
922         ret = ohci->usb_packet.len;
923         ohci->async_td = 0;
924         ohci->async_complete = 0;
925     } else {
926         ret = USB_RET_NODEV;
927         for (i = 0; i < ohci->num_ports; i++) {
928             dev = ohci->rhport[i].port.dev;
929             if ((ohci->rhport[i].ctrl & OHCI_PORT_PES) == 0)
930                 continue;
931
932             if (ohci->async_td) {
933                 /* ??? The hardware should allow one active packet per
934                    endpoint.  We only allow one active packet per controller.
935                    This should be sufficient as long as devices respond in a
936                    timely manner.
937                  */
938 #ifdef DEBUG_PACKET
939                 dprintf("Too many pending packets\n");
940 #endif
941                 return 1;
942             }
943             ohci->usb_packet.pid = pid;
944             ohci->usb_packet.devaddr = OHCI_BM(ed->flags, ED_FA);
945             ohci->usb_packet.devep = OHCI_BM(ed->flags, ED_EN);
946             ohci->usb_packet.data = ohci->usb_buf;
947             ohci->usb_packet.len = len;
948             ohci->usb_packet.complete_cb = ohci_async_complete_packet;
949             ohci->usb_packet.complete_opaque = ohci;
950             ret = dev->handle_packet(dev, &ohci->usb_packet);
951             if (ret != USB_RET_NODEV)
952                 break;
953         }
954 #ifdef DEBUG_PACKET
955         dprintf("ret=%d\n", ret);
956 #endif
957         if (ret == USB_RET_ASYNC) {
958             ohci->async_td = addr;
959             return 1;
960         }
961     }
962     if (ret >= 0) {
963         if (dir == OHCI_TD_DIR_IN) {
964             ohci_copy_td(ohci, &td, ohci->usb_buf, ret, 1);
965 #ifdef DEBUG_PACKET
966             dprintf("  data:");
967             for (i = 0; i < ret; i++)
968                 printf(" %.2x", ohci->usb_buf[i]);
969             dprintf("\n");
970 #endif
971         } else {
972             ret = len;
973         }
974     }
975
976     /* Writeback */
977     if (ret == len || (dir == OHCI_TD_DIR_IN && ret >= 0 && flag_r)) {
978         /* Transmission succeeded.  */
979         if (ret == len) {
980             td.cbp = 0;
981         } else {
982             td.cbp += ret;
983             if ((td.cbp & 0xfff) + ret > 0xfff) {
984                 td.cbp &= 0xfff;
985                 td.cbp |= td.be & ~0xfff;
986             }
987         }
988         td.flags |= OHCI_TD_T1;
989         td.flags ^= OHCI_TD_T0;
990         OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_NOERROR);
991         OHCI_SET_BM(td.flags, TD_EC, 0);
992
993         ed->head &= ~OHCI_ED_C;
994         if (td.flags & OHCI_TD_T0)
995             ed->head |= OHCI_ED_C;
996     } else {
997         if (ret >= 0) {
998             dprintf("usb-ohci: Underrun\n");
999             OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAUNDERRUN);
1000         } else {
1001             switch (ret) {
1002             case USB_RET_NODEV:
1003                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DEVICENOTRESPONDING);
1004             case USB_RET_NAK:
1005                 dprintf("usb-ohci: got NAK\n");
1006                 return 1;
1007             case USB_RET_STALL:
1008                 dprintf("usb-ohci: got STALL\n");
1009                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_STALL);
1010                 break;
1011             case USB_RET_BABBLE:
1012                 dprintf("usb-ohci: got BABBLE\n");
1013                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAOVERRUN);
1014                 break;
1015             default:
1016                 fprintf(stderr, "usb-ohci: Bad device response %d\n", ret);
1017                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_UNDEXPETEDPID);
1018                 OHCI_SET_BM(td.flags, TD_EC, 3);
1019                 break;
1020             }
1021         }
1022         ed->head |= OHCI_ED_H;
1023     }
1024
1025     /* Retire this TD */
1026     ed->head &= ~OHCI_DPTR_MASK;
1027     ed->head |= td.next & OHCI_DPTR_MASK;
1028     td.next = ohci->done;
1029     ohci->done = addr;
1030     i = OHCI_BM(td.flags, TD_DI);
1031     if (i < ohci->done_count)
1032         ohci->done_count = i;
1033     ohci_put_td(ohci, addr, &td);
1034     return OHCI_BM(td.flags, TD_CC) != OHCI_CC_NOERROR;
1035 }
1036
1037 /* Service an endpoint list.  Returns nonzero if active TD were found.  */
1038 static int ohci_service_ed_list(OHCIState *ohci, uint32_t head, int completion)
1039 {
1040     struct ohci_ed ed;
1041     uint32_t next_ed;
1042     uint32_t cur;
1043     int active;
1044
1045     active = 0;
1046
1047     if (head == 0)
1048         return 0;
1049
1050     for (cur = head; cur; cur = next_ed) {
1051         if (!ohci_read_ed(ohci, cur, &ed)) {
1052             fprintf(stderr, "usb-ohci: ED read error at %x\n", cur);
1053             return 0;
1054         }
1055
1056         next_ed = ed.next & OHCI_DPTR_MASK;
1057
1058         if ((ed.head & OHCI_ED_H) || (ed.flags & OHCI_ED_K)) {
1059             uint32_t addr;
1060             /* Cancel pending packets for ED that have been paused.  */
1061             addr = ed.head & OHCI_DPTR_MASK;
1062             if (ohci->async_td && addr == ohci->async_td) {
1063                 usb_cancel_packet(&ohci->usb_packet);
1064                 ohci->async_td = 0;
1065             }
1066             continue;
1067         }
1068
1069         while ((ed.head & OHCI_DPTR_MASK) != ed.tail) {
1070 #ifdef DEBUG_PACKET
1071             dprintf("ED @ 0x%.8x fa=%u en=%u d=%u s=%u k=%u f=%u mps=%u "
1072                     "h=%u c=%u\n  head=0x%.8x tailp=0x%.8x next=0x%.8x\n", cur,
1073                     OHCI_BM(ed.flags, ED_FA), OHCI_BM(ed.flags, ED_EN),
1074                     OHCI_BM(ed.flags, ED_D), (ed.flags & OHCI_ED_S)!= 0,
1075                     (ed.flags & OHCI_ED_K) != 0, (ed.flags & OHCI_ED_F) != 0,
1076                     OHCI_BM(ed.flags, ED_MPS), (ed.head & OHCI_ED_H) != 0,
1077                     (ed.head & OHCI_ED_C) != 0, ed.head & OHCI_DPTR_MASK,
1078                     ed.tail & OHCI_DPTR_MASK, ed.next & OHCI_DPTR_MASK);
1079 #endif
1080             active = 1;
1081
1082             if ((ed.flags & OHCI_ED_F) == 0) {
1083                 if (ohci_service_td(ohci, &ed))
1084                     break;
1085             } else {
1086                 /* Handle isochronous endpoints */
1087                 if (ohci_service_iso_td(ohci, &ed, completion))
1088                     break;
1089             }
1090         }
1091
1092         ohci_put_ed(ohci, cur, &ed);
1093     }
1094
1095     return active;
1096 }
1097
1098 /* Generate a SOF event, and set a timer for EOF */
1099 static void ohci_sof(OHCIState *ohci)
1100 {
1101     ohci->sof_time = qemu_get_clock(vm_clock);
1102     qemu_mod_timer(ohci->eof_timer, ohci->sof_time + usb_frame_time);
1103     ohci_set_interrupt(ohci, OHCI_INTR_SF);
1104 }
1105
1106 /* Process Control and Bulk lists.  */
1107 static void ohci_process_lists(OHCIState *ohci, int completion)
1108 {
1109     if ((ohci->ctl & OHCI_CTL_CLE) && (ohci->status & OHCI_STATUS_CLF)) {
1110         if (ohci->ctrl_cur && ohci->ctrl_cur != ohci->ctrl_head)
1111           dprintf("usb-ohci: head %x, cur %x\n",
1112                           ohci->ctrl_head, ohci->ctrl_cur);
1113         if (!ohci_service_ed_list(ohci, ohci->ctrl_head, completion)) {
1114             ohci->ctrl_cur = 0;
1115             ohci->status &= ~OHCI_STATUS_CLF;
1116         }
1117     }
1118
1119     if ((ohci->ctl & OHCI_CTL_BLE) && (ohci->status & OHCI_STATUS_BLF)) {
1120         if (!ohci_service_ed_list(ohci, ohci->bulk_head, completion)) {
1121             ohci->bulk_cur = 0;
1122             ohci->status &= ~OHCI_STATUS_BLF;
1123         }
1124     }
1125 }
1126
1127 /* Do frame processing on frame boundary */
1128 static void ohci_frame_boundary(void *opaque)
1129 {
1130     OHCIState *ohci = opaque;
1131     struct ohci_hcca hcca;
1132
1133     ohci_read_hcca(ohci, ohci->hcca, &hcca);
1134
1135     /* Process all the lists at the end of the frame */
1136     if (ohci->ctl & OHCI_CTL_PLE) {
1137         int n;
1138
1139         n = ohci->frame_number & 0x1f;
1140         ohci_service_ed_list(ohci, le32_to_cpu(hcca.intr[n]), 0);
1141     }
1142
1143     /* Cancel all pending packets if either of the lists has been disabled.  */
1144     if (ohci->async_td &&
1145         ohci->old_ctl & (~ohci->ctl) & (OHCI_CTL_BLE | OHCI_CTL_CLE)) {
1146         usb_cancel_packet(&ohci->usb_packet);
1147         ohci->async_td = 0;
1148     }
1149     ohci->old_ctl = ohci->ctl;
1150     ohci_process_lists(ohci, 0);
1151
1152     /* Frame boundary, so do EOF stuf here */
1153     ohci->frt = ohci->fit;
1154
1155     /* XXX: endianness */
1156     ohci->frame_number = (ohci->frame_number + 1) & 0xffff;
1157     hcca.frame = cpu_to_le32(ohci->frame_number);
1158
1159     if (ohci->done_count == 0 && !(ohci->intr_status & OHCI_INTR_WD)) {
1160         if (!ohci->done)
1161             abort();
1162         if (ohci->intr & ohci->intr_status)
1163             ohci->done |= 1;
1164         hcca.done = cpu_to_le32(ohci->done);
1165         ohci->done = 0;
1166         ohci->done_count = 7;
1167         ohci_set_interrupt(ohci, OHCI_INTR_WD);
1168     }
1169
1170     if (ohci->done_count != 7 && ohci->done_count != 0)
1171         ohci->done_count--;
1172
1173     /* Do SOF stuff here */
1174     ohci_sof(ohci);
1175
1176     /* Writeback HCCA */
1177     ohci_put_hcca(ohci, ohci->hcca, &hcca);
1178 }
1179
1180 /* Start sending SOF tokens across the USB bus, lists are processed in
1181  * next frame
1182  */
1183 static int ohci_bus_start(OHCIState *ohci)
1184 {
1185     ohci->eof_timer = qemu_new_timer(vm_clock,
1186                     ohci_frame_boundary,
1187                     ohci);
1188
1189     if (ohci->eof_timer == NULL) {
1190         fprintf(stderr, "usb-ohci: %s: qemu_new_timer failed\n", ohci->name);
1191         /* TODO: Signal unrecoverable error */
1192         return 0;
1193     }
1194
1195     dprintf("usb-ohci: %s: USB Operational\n", ohci->name);
1196
1197     ohci_sof(ohci);
1198
1199     return 1;
1200 }
1201
1202 /* Stop sending SOF tokens on the bus */
1203 static void ohci_bus_stop(OHCIState *ohci)
1204 {
1205     if (ohci->eof_timer)
1206         qemu_del_timer(ohci->eof_timer);
1207     ohci->eof_timer = NULL;
1208 }
1209
1210 /* Sets a flag in a port status register but only set it if the port is
1211  * connected, if not set ConnectStatusChange flag. If flag is enabled
1212  * return 1.
1213  */
1214 static int ohci_port_set_if_connected(OHCIState *ohci, int i, uint32_t val)
1215 {
1216     int ret = 1;
1217
1218     /* writing a 0 has no effect */
1219     if (val == 0)
1220         return 0;
1221
1222     /* If CurrentConnectStatus is cleared we set
1223      * ConnectStatusChange
1224      */
1225     if (!(ohci->rhport[i].ctrl & OHCI_PORT_CCS)) {
1226         ohci->rhport[i].ctrl |= OHCI_PORT_CSC;
1227         if (ohci->rhstatus & OHCI_RHS_DRWE) {
1228             /* TODO: CSC is a wakeup event */
1229         }
1230         return 0;
1231     }
1232
1233     if (ohci->rhport[i].ctrl & val)
1234         ret = 0;
1235
1236     /* set the bit */
1237     ohci->rhport[i].ctrl |= val;
1238
1239     return ret;
1240 }
1241
1242 /* Set the frame interval - frame interval toggle is manipulated by the hcd only */
1243 static void ohci_set_frame_interval(OHCIState *ohci, uint16_t val)
1244 {
1245     val &= OHCI_FMI_FI;
1246
1247     if (val != ohci->fi) {
1248         dprintf("usb-ohci: %s: FrameInterval = 0x%x (%u)\n",
1249             ohci->name, ohci->fi, ohci->fi);
1250     }
1251
1252     ohci->fi = val;
1253 }
1254
1255 static void ohci_port_power(OHCIState *ohci, int i, int p)
1256 {
1257     if (p) {
1258         ohci->rhport[i].ctrl |= OHCI_PORT_PPS;
1259     } else {
1260         ohci->rhport[i].ctrl &= ~(OHCI_PORT_PPS|
1261                     OHCI_PORT_CCS|
1262                     OHCI_PORT_PSS|
1263                     OHCI_PORT_PRS);
1264     }
1265 }
1266
1267 /* Set HcControlRegister */
1268 static void ohci_set_ctl(OHCIState *ohci, uint32_t val)
1269 {
1270     uint32_t old_state;
1271     uint32_t new_state;
1272
1273     old_state = ohci->ctl & OHCI_CTL_HCFS;
1274     ohci->ctl = val;
1275     new_state = ohci->ctl & OHCI_CTL_HCFS;
1276
1277     /* no state change */
1278     if (old_state == new_state)
1279         return;
1280
1281     switch (new_state) {
1282     case OHCI_USB_OPERATIONAL:
1283         ohci_bus_start(ohci);
1284         break;
1285     case OHCI_USB_SUSPEND:
1286         ohci_bus_stop(ohci);
1287         dprintf("usb-ohci: %s: USB Suspended\n", ohci->name);
1288         break;
1289     case OHCI_USB_RESUME:
1290         dprintf("usb-ohci: %s: USB Resume\n", ohci->name);
1291         break;
1292     case OHCI_USB_RESET:
1293         ohci_reset(ohci);
1294         dprintf("usb-ohci: %s: USB Reset\n", ohci->name);
1295         break;
1296     }
1297 }
1298
1299 static uint32_t ohci_get_frame_remaining(OHCIState *ohci)
1300 {
1301     uint16_t fr;
1302     int64_t tks;
1303
1304     if ((ohci->ctl & OHCI_CTL_HCFS) != OHCI_USB_OPERATIONAL)
1305         return (ohci->frt << 31);
1306
1307     /* Being in USB operational state guarnatees sof_time was
1308      * set already.
1309      */
1310     tks = qemu_get_clock(vm_clock) - ohci->sof_time;
1311
1312     /* avoid muldiv if possible */
1313     if (tks >= usb_frame_time)
1314         return (ohci->frt << 31);
1315
1316     tks = muldiv64(1, tks, usb_bit_time);
1317     fr = (uint16_t)(ohci->fi - tks);
1318
1319     return (ohci->frt << 31) | fr;
1320 }
1321
1322
1323 /* Set root hub status */
1324 static void ohci_set_hub_status(OHCIState *ohci, uint32_t val)
1325 {
1326     uint32_t old_state;
1327
1328     old_state = ohci->rhstatus;
1329
1330     /* write 1 to clear OCIC */
1331     if (val & OHCI_RHS_OCIC)
1332         ohci->rhstatus &= ~OHCI_RHS_OCIC;
1333
1334     if (val & OHCI_RHS_LPS) {
1335         int i;
1336
1337         for (i = 0; i < ohci->num_ports; i++)
1338             ohci_port_power(ohci, i, 0);
1339         dprintf("usb-ohci: powered down all ports\n");
1340     }
1341
1342     if (val & OHCI_RHS_LPSC) {
1343         int i;
1344
1345         for (i = 0; i < ohci->num_ports; i++)
1346             ohci_port_power(ohci, i, 1);
1347         dprintf("usb-ohci: powered up all ports\n");
1348     }
1349
1350     if (val & OHCI_RHS_DRWE)
1351         ohci->rhstatus |= OHCI_RHS_DRWE;
1352
1353     if (val & OHCI_RHS_CRWE)
1354         ohci->rhstatus &= ~OHCI_RHS_DRWE;
1355
1356     if (old_state != ohci->rhstatus)
1357         ohci_set_interrupt(ohci, OHCI_INTR_RHSC);
1358 }
1359
1360 /* Set root hub port status */
1361 static void ohci_port_set_status(OHCIState *ohci, int portnum, uint32_t val)
1362 {
1363     uint32_t old_state;
1364     OHCIPort *port;
1365
1366     port = &ohci->rhport[portnum];
1367     old_state = port->ctrl;
1368
1369     /* Write to clear CSC, PESC, PSSC, OCIC, PRSC */
1370     if (val & OHCI_PORT_WTC)
1371         port->ctrl &= ~(val & OHCI_PORT_WTC);
1372
1373     if (val & OHCI_PORT_CCS)
1374         port->ctrl &= ~OHCI_PORT_PES;
1375
1376     ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PES);
1377
1378     if (ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PSS))
1379         dprintf("usb-ohci: port %d: SUSPEND\n", portnum);
1380
1381     if (ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PRS)) {
1382         dprintf("usb-ohci: port %d: RESET\n", portnum);
1383         usb_send_msg(port->port.dev, USB_MSG_RESET);
1384         port->ctrl &= ~OHCI_PORT_PRS;
1385         /* ??? Should this also set OHCI_PORT_PESC.  */
1386         port->ctrl |= OHCI_PORT_PES | OHCI_PORT_PRSC;
1387     }
1388
1389     /* Invert order here to ensure in ambiguous case, device is
1390      * powered up...
1391      */
1392     if (val & OHCI_PORT_LSDA)
1393         ohci_port_power(ohci, portnum, 0);
1394     if (val & OHCI_PORT_PPS)
1395         ohci_port_power(ohci, portnum, 1);
1396
1397     if (old_state != port->ctrl)
1398         ohci_set_interrupt(ohci, OHCI_INTR_RHSC);
1399
1400     return;
1401 }
1402
1403 static uint32_t ohci_mem_read(void *ptr, target_phys_addr_t addr)
1404 {
1405     OHCIState *ohci = ptr;
1406     uint32_t retval;
1407
1408     /* Only aligned reads are allowed on OHCI */
1409     if (addr & 3) {
1410         fprintf(stderr, "usb-ohci: Mis-aligned read\n");
1411         return 0xffffffff;
1412     } else if (addr >= 0x54 && addr < 0x54 + ohci->num_ports * 4) {
1413         /* HcRhPortStatus */
1414         retval = ohci->rhport[(addr - 0x54) >> 2].ctrl | OHCI_PORT_PPS;
1415     } else {
1416         switch (addr >> 2) {
1417         case 0: /* HcRevision */
1418             retval = 0x10;
1419             break;
1420
1421         case 1: /* HcControl */
1422             retval = ohci->ctl;
1423             break;
1424
1425         case 2: /* HcCommandStatus */
1426             retval = ohci->status;
1427             break;
1428
1429         case 3: /* HcInterruptStatus */
1430             retval = ohci->intr_status;
1431             break;
1432
1433         case 4: /* HcInterruptEnable */
1434         case 5: /* HcInterruptDisable */
1435             retval = ohci->intr;
1436             break;
1437
1438         case 6: /* HcHCCA */
1439             retval = ohci->hcca;
1440             break;
1441
1442         case 7: /* HcPeriodCurrentED */
1443             retval = ohci->per_cur;
1444             break;
1445
1446         case 8: /* HcControlHeadED */
1447             retval = ohci->ctrl_head;
1448             break;
1449
1450         case 9: /* HcControlCurrentED */
1451             retval = ohci->ctrl_cur;
1452             break;
1453
1454         case 10: /* HcBulkHeadED */
1455             retval = ohci->bulk_head;
1456             break;
1457
1458         case 11: /* HcBulkCurrentED */
1459             retval = ohci->bulk_cur;
1460             break;
1461
1462         case 12: /* HcDoneHead */
1463             retval = ohci->done;
1464             break;
1465
1466         case 13: /* HcFmInterretval */
1467             retval = (ohci->fit << 31) | (ohci->fsmps << 16) | (ohci->fi);
1468             break;
1469
1470         case 14: /* HcFmRemaining */
1471             retval = ohci_get_frame_remaining(ohci);
1472             break;
1473
1474         case 15: /* HcFmNumber */
1475             retval = ohci->frame_number;
1476             break;
1477
1478         case 16: /* HcPeriodicStart */
1479             retval = ohci->pstart;
1480             break;
1481
1482         case 17: /* HcLSThreshold */
1483             retval = ohci->lst;
1484             break;
1485
1486         case 18: /* HcRhDescriptorA */
1487             retval = ohci->rhdesc_a;
1488             break;
1489
1490         case 19: /* HcRhDescriptorB */
1491             retval = ohci->rhdesc_b;
1492             break;
1493
1494         case 20: /* HcRhStatus */
1495             retval = ohci->rhstatus;
1496             break;
1497
1498         /* PXA27x specific registers */
1499         case 24: /* HcStatus */
1500             retval = ohci->hstatus & ohci->hmask;
1501             break;
1502
1503         case 25: /* HcHReset */
1504             retval = ohci->hreset;
1505             break;
1506
1507         case 26: /* HcHInterruptEnable */
1508             retval = ohci->hmask;
1509             break;
1510
1511         case 27: /* HcHInterruptTest */
1512             retval = ohci->htest;
1513             break;
1514
1515         default:
1516             fprintf(stderr, "ohci_read: Bad offset %x\n", (int)addr);
1517             retval = 0xffffffff;
1518         }
1519     }
1520
1521 #ifdef TARGET_WORDS_BIGENDIAN
1522     retval = bswap32(retval);
1523 #endif
1524     return retval;
1525 }
1526
1527 static void ohci_mem_write(void *ptr, target_phys_addr_t addr, uint32_t val)
1528 {
1529     OHCIState *ohci = ptr;
1530
1531 #ifdef TARGET_WORDS_BIGENDIAN
1532     val = bswap32(val);
1533 #endif
1534
1535     /* Only aligned reads are allowed on OHCI */
1536     if (addr & 3) {
1537         fprintf(stderr, "usb-ohci: Mis-aligned write\n");
1538         return;
1539     }
1540
1541     if (addr >= 0x54 && addr < 0x54 + ohci->num_ports * 4) {
1542         /* HcRhPortStatus */
1543         ohci_port_set_status(ohci, (addr - 0x54) >> 2, val);
1544         return;
1545     }
1546
1547     switch (addr >> 2) {
1548     case 1: /* HcControl */
1549         ohci_set_ctl(ohci, val);
1550         break;
1551
1552     case 2: /* HcCommandStatus */
1553         /* SOC is read-only */
1554         val = (val & ~OHCI_STATUS_SOC);
1555
1556         /* Bits written as '0' remain unchanged in the register */
1557         ohci->status |= val;
1558
1559         if (ohci->status & OHCI_STATUS_HCR)
1560             ohci_reset(ohci);
1561         break;
1562
1563     case 3: /* HcInterruptStatus */
1564         ohci->intr_status &= ~val;
1565         ohci_intr_update(ohci);
1566         break;
1567
1568     case 4: /* HcInterruptEnable */
1569         ohci->intr |= val;
1570         ohci_intr_update(ohci);
1571         break;
1572
1573     case 5: /* HcInterruptDisable */
1574         ohci->intr &= ~val;
1575         ohci_intr_update(ohci);
1576         break;
1577
1578     case 6: /* HcHCCA */
1579         ohci->hcca = val & OHCI_HCCA_MASK;
1580         break;
1581
1582     case 8: /* HcControlHeadED */
1583         ohci->ctrl_head = val & OHCI_EDPTR_MASK;
1584         break;
1585
1586     case 9: /* HcControlCurrentED */
1587         ohci->ctrl_cur = val & OHCI_EDPTR_MASK;
1588         break;
1589
1590     case 10: /* HcBulkHeadED */
1591         ohci->bulk_head = val & OHCI_EDPTR_MASK;
1592         break;
1593
1594     case 11: /* HcBulkCurrentED */
1595         ohci->bulk_cur = val & OHCI_EDPTR_MASK;
1596         break;
1597
1598     case 13: /* HcFmInterval */
1599         ohci->fsmps = (val & OHCI_FMI_FSMPS) >> 16;
1600         ohci->fit = (val & OHCI_FMI_FIT) >> 31;
1601         ohci_set_frame_interval(ohci, val);
1602         break;
1603
1604     case 15: /* HcFmNumber */
1605         break;
1606
1607     case 16: /* HcPeriodicStart */
1608         ohci->pstart = val & 0xffff;
1609         break;
1610
1611     case 17: /* HcLSThreshold */
1612         ohci->lst = val & 0xffff;
1613         break;
1614
1615     case 18: /* HcRhDescriptorA */
1616         ohci->rhdesc_a &= ~OHCI_RHA_RW_MASK;
1617         ohci->rhdesc_a |= val & OHCI_RHA_RW_MASK;
1618         break;
1619
1620     case 19: /* HcRhDescriptorB */
1621         break;
1622
1623     case 20: /* HcRhStatus */
1624         ohci_set_hub_status(ohci, val);
1625         break;
1626
1627     /* PXA27x specific registers */
1628     case 24: /* HcStatus */
1629         ohci->hstatus &= ~(val & ohci->hmask);
1630
1631     case 25: /* HcHReset */
1632         ohci->hreset = val & ~OHCI_HRESET_FSBIR;
1633         if (val & OHCI_HRESET_FSBIR)
1634             ohci_reset(ohci);
1635         break;
1636
1637     case 26: /* HcHInterruptEnable */
1638         ohci->hmask = val;
1639         break;
1640
1641     case 27: /* HcHInterruptTest */
1642         ohci->htest = val;
1643         break;
1644
1645     default:
1646         fprintf(stderr, "ohci_write: Bad offset %x\n", (int)addr);
1647         break;
1648     }
1649 }
1650
1651 /* Only dword reads are defined on OHCI register space */
1652 static CPUReadMemoryFunc *ohci_readfn[3]={
1653     ohci_mem_read,
1654     ohci_mem_read,
1655     ohci_mem_read
1656 };
1657
1658 /* Only dword writes are defined on OHCI register space */
1659 static CPUWriteMemoryFunc *ohci_writefn[3]={
1660     ohci_mem_write,
1661     ohci_mem_write,
1662     ohci_mem_write
1663 };
1664
1665 static void usb_ohci_init(OHCIState *ohci, int num_ports, int devfn,
1666                           qemu_irq irq, enum ohci_type type,
1667                           const char *name, uint32_t localmem_base)
1668 {
1669     int i;
1670
1671     if (usb_frame_time == 0) {
1672 #ifdef OHCI_TIME_WARP
1673         usb_frame_time = ticks_per_sec;
1674         usb_bit_time = muldiv64(1, ticks_per_sec, USB_HZ/1000);
1675 #else
1676         usb_frame_time = muldiv64(1, ticks_per_sec, 1000);
1677         if (ticks_per_sec >= USB_HZ) {
1678             usb_bit_time = muldiv64(1, ticks_per_sec, USB_HZ);
1679         } else {
1680             usb_bit_time = 1;
1681         }
1682 #endif
1683         dprintf("usb-ohci: usb_bit_time=%lli usb_frame_time=%lli\n",
1684                 usb_frame_time, usb_bit_time);
1685     }
1686
1687     ohci->mem = cpu_register_io_memory(0, ohci_readfn, ohci_writefn, ohci);
1688     ohci->localmem_base = localmem_base;
1689     ohci->name = name;
1690
1691     ohci->irq = irq;
1692     ohci->type = type;
1693
1694     ohci->num_ports = num_ports;
1695     for (i = 0; i < num_ports; i++) {
1696         qemu_register_usb_port(&ohci->rhport[i].port, ohci, i, ohci_attach);
1697     }
1698
1699     ohci->async_td = 0;
1700     qemu_register_reset(ohci_reset, ohci);
1701     ohci_reset(ohci);
1702 }
1703
1704 typedef struct {
1705     PCIDevice pci_dev;
1706     OHCIState state;
1707 } OHCIPCIState;
1708
1709 static void ohci_mapfunc(PCIDevice *pci_dev, int i,
1710             uint32_t addr, uint32_t size, int type)
1711 {
1712     OHCIPCIState *ohci = (OHCIPCIState *)pci_dev;
1713     cpu_register_physical_memory(addr, size, ohci->state.mem);
1714 }
1715
1716 void usb_ohci_init_pci(struct PCIBus *bus, int num_ports, int devfn)
1717 {
1718     OHCIPCIState *ohci;
1719
1720     ohci = (OHCIPCIState *)pci_register_device(bus, "OHCI USB", sizeof(*ohci),
1721                                                devfn, NULL, NULL);
1722     if (ohci == NULL) {
1723         fprintf(stderr, "usb-ohci: Failed to register PCI device\n");
1724         return;
1725     }
1726
1727     pci_config_set_vendor_id(ohci->pci_dev.config, PCI_VENDOR_ID_APPLE);
1728     pci_config_set_device_id(ohci->pci_dev.config,
1729                              PCI_DEVICE_ID_APPLE_IPID_USB);
1730     ohci->pci_dev.config[0x09] = 0x10; /* OHCI */
1731     pci_config_set_class(ohci->pci_dev.config, PCI_CLASS_SERIAL_USB);
1732     ohci->pci_dev.config[0x3d] = 0x01; /* interrupt pin 1 */
1733
1734     usb_ohci_init(&ohci->state, num_ports, devfn, ohci->pci_dev.irq[0],
1735                   OHCI_TYPE_PCI, ohci->pci_dev.name, 0);
1736
1737     pci_register_io_region((struct PCIDevice *)ohci, 0, 256,
1738                            PCI_ADDRESS_SPACE_MEM, ohci_mapfunc);
1739 }
1740
1741 void usb_ohci_init_pxa(target_phys_addr_t base, int num_ports, int devfn,
1742                        qemu_irq irq)
1743 {
1744     OHCIState *ohci = (OHCIState *)qemu_mallocz(sizeof(OHCIState));
1745
1746     usb_ohci_init(ohci, num_ports, devfn, irq,
1747                   OHCI_TYPE_PXA, "OHCI USB", 0);
1748
1749     cpu_register_physical_memory(base, 0x1000, ohci->mem);
1750 }
1751
1752 void usb_ohci_init_omap(target_phys_addr_t base, uint32_t region_size,
1753                        int num_ports, qemu_irq irq)
1754 {
1755     OHCIState *ohci = (OHCIState *)qemu_mallocz(sizeof(OHCIState));
1756     
1757     usb_ohci_init(ohci, num_ports, -1, irq, OHCI_TYPE_OMAP, "OHCI USB" ,0);
1758
1759     cpu_register_physical_memory(base, 0x1000, ohci->mem);
1760 }
1761
1762 void usb_ohci_init_sm501(uint32_t mmio_base, uint32_t localmem_base,
1763                          int num_ports, int devfn, qemu_irq irq)
1764 {
1765     OHCIState *ohci = (OHCIState *)qemu_mallocz(sizeof(OHCIState));
1766
1767     usb_ohci_init(ohci, num_ports, devfn, irq,
1768                   OHCI_TYPE_SM501, "OHCI USB", localmem_base);
1769
1770     cpu_register_physical_memory(mmio_base, 0x1000, ohci->mem);
1771 }
1772