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