xref: /openbmc/qemu/hw/usb/hcd-ohci.c (revision 786a4ea8)
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, see <http://www.gnu.org/licenses/>.
19  *
20  * TODO:
21  *  o Isochronous transfers
22  *  o Allocate bandwidth in frames properly
23  *  o Disable timers when nothing needs to be done, or remove timer usage
24  *    all together.
25  *  o BIOS work to boot from USB storage
26 */
27 
28 #include "hw/hw.h"
29 #include "qemu/timer.h"
30 #include "hw/usb.h"
31 #include "hw/pci/pci.h"
32 #include "hw/sysbus.h"
33 #include "hw/qdev-dma.h"
34 #include "trace.h"
35 
36 /* This causes frames to occur 1000x slower */
37 //#define OHCI_TIME_WARP 1
38 
39 /* Number of Downstream Ports on the root hub.  */
40 
41 #define OHCI_MAX_PORTS 15
42 
43 static int64_t usb_frame_time;
44 static int64_t usb_bit_time;
45 
46 typedef struct OHCIPort {
47     USBPort port;
48     uint32_t ctrl;
49 } OHCIPort;
50 
51 typedef struct {
52     USBBus bus;
53     qemu_irq irq;
54     MemoryRegion mem;
55     AddressSpace *as;
56     int num_ports;
57     const char *name;
58 
59     QEMUTimer *eof_timer;
60     int64_t sof_time;
61 
62     /* OHCI state */
63     /* Control partition */
64     uint32_t ctl, status;
65     uint32_t intr_status;
66     uint32_t intr;
67 
68     /* memory pointer partition */
69     uint32_t hcca;
70     uint32_t ctrl_head, ctrl_cur;
71     uint32_t bulk_head, bulk_cur;
72     uint32_t per_cur;
73     uint32_t done;
74     int32_t done_count;
75 
76     /* Frame counter partition */
77     uint16_t fsmps;
78     uint8_t fit;
79     uint16_t fi;
80     uint8_t frt;
81     uint16_t frame_number;
82     uint16_t padding;
83     uint32_t pstart;
84     uint32_t lst;
85 
86     /* Root Hub partition */
87     uint32_t rhdesc_a, rhdesc_b;
88     uint32_t rhstatus;
89     OHCIPort rhport[OHCI_MAX_PORTS];
90 
91     /* PXA27x Non-OHCI events */
92     uint32_t hstatus;
93     uint32_t hmask;
94     uint32_t hreset;
95     uint32_t htest;
96 
97     /* SM501 local memory offset */
98     dma_addr_t localmem_base;
99 
100     /* Active packets.  */
101     uint32_t old_ctl;
102     USBPacket usb_packet;
103     uint8_t usb_buf[8192];
104     uint32_t async_td;
105     bool async_complete;
106 
107 } OHCIState;
108 
109 /* Host Controller Communications Area */
110 struct ohci_hcca {
111     uint32_t intr[32];
112     uint16_t frame, pad;
113     uint32_t done;
114 };
115 #define HCCA_WRITEBACK_OFFSET   offsetof(struct ohci_hcca, frame)
116 #define HCCA_WRITEBACK_SIZE     8 /* frame, pad, done */
117 
118 #define ED_WBACK_OFFSET offsetof(struct ohci_ed, head)
119 #define ED_WBACK_SIZE   4
120 
121 static void ohci_bus_stop(OHCIState *ohci);
122 static void ohci_async_cancel_device(OHCIState *ohci, USBDevice *dev);
123 
124 /* Bitfields for the first word of an Endpoint Desciptor.  */
125 #define OHCI_ED_FA_SHIFT  0
126 #define OHCI_ED_FA_MASK   (0x7f<<OHCI_ED_FA_SHIFT)
127 #define OHCI_ED_EN_SHIFT  7
128 #define OHCI_ED_EN_MASK   (0xf<<OHCI_ED_EN_SHIFT)
129 #define OHCI_ED_D_SHIFT   11
130 #define OHCI_ED_D_MASK    (3<<OHCI_ED_D_SHIFT)
131 #define OHCI_ED_S         (1<<13)
132 #define OHCI_ED_K         (1<<14)
133 #define OHCI_ED_F         (1<<15)
134 #define OHCI_ED_MPS_SHIFT 16
135 #define OHCI_ED_MPS_MASK  (0x7ff<<OHCI_ED_MPS_SHIFT)
136 
137 /* Flags in the head field of an Endpoint Desciptor.  */
138 #define OHCI_ED_H         1
139 #define OHCI_ED_C         2
140 
141 /* Bitfields for the first word of a Transfer Desciptor.  */
142 #define OHCI_TD_R         (1<<18)
143 #define OHCI_TD_DP_SHIFT  19
144 #define OHCI_TD_DP_MASK   (3<<OHCI_TD_DP_SHIFT)
145 #define OHCI_TD_DI_SHIFT  21
146 #define OHCI_TD_DI_MASK   (7<<OHCI_TD_DI_SHIFT)
147 #define OHCI_TD_T0        (1<<24)
148 #define OHCI_TD_T1        (1<<25)
149 #define OHCI_TD_EC_SHIFT  26
150 #define OHCI_TD_EC_MASK   (3<<OHCI_TD_EC_SHIFT)
151 #define OHCI_TD_CC_SHIFT  28
152 #define OHCI_TD_CC_MASK   (0xf<<OHCI_TD_CC_SHIFT)
153 
154 /* Bitfields for the first word of an Isochronous Transfer Desciptor.  */
155 /* CC & DI - same as in the General Transfer Desciptor */
156 #define OHCI_TD_SF_SHIFT  0
157 #define OHCI_TD_SF_MASK   (0xffff<<OHCI_TD_SF_SHIFT)
158 #define OHCI_TD_FC_SHIFT  24
159 #define OHCI_TD_FC_MASK   (7<<OHCI_TD_FC_SHIFT)
160 
161 /* Isochronous Transfer Desciptor - Offset / PacketStatusWord */
162 #define OHCI_TD_PSW_CC_SHIFT 12
163 #define OHCI_TD_PSW_CC_MASK  (0xf<<OHCI_TD_PSW_CC_SHIFT)
164 #define OHCI_TD_PSW_SIZE_SHIFT 0
165 #define OHCI_TD_PSW_SIZE_MASK  (0xfff<<OHCI_TD_PSW_SIZE_SHIFT)
166 
167 #define OHCI_PAGE_MASK    0xfffff000
168 #define OHCI_OFFSET_MASK  0xfff
169 
170 #define OHCI_DPTR_MASK    0xfffffff0
171 
172 #define OHCI_BM(val, field) \
173   (((val) & OHCI_##field##_MASK) >> OHCI_##field##_SHIFT)
174 
175 #define OHCI_SET_BM(val, field, newval) do { \
176     val &= ~OHCI_##field##_MASK; \
177     val |= ((newval) << OHCI_##field##_SHIFT) & OHCI_##field##_MASK; \
178     } while(0)
179 
180 /* endpoint descriptor */
181 struct ohci_ed {
182     uint32_t flags;
183     uint32_t tail;
184     uint32_t head;
185     uint32_t next;
186 };
187 
188 /* General transfer descriptor */
189 struct ohci_td {
190     uint32_t flags;
191     uint32_t cbp;
192     uint32_t next;
193     uint32_t be;
194 };
195 
196 /* Isochronous transfer descriptor */
197 struct ohci_iso_td {
198     uint32_t flags;
199     uint32_t bp;
200     uint32_t next;
201     uint32_t be;
202     uint16_t offset[8];
203 };
204 
205 #define USB_HZ                      12000000
206 
207 /* OHCI Local stuff */
208 #define OHCI_CTL_CBSR         ((1<<0)|(1<<1))
209 #define OHCI_CTL_PLE          (1<<2)
210 #define OHCI_CTL_IE           (1<<3)
211 #define OHCI_CTL_CLE          (1<<4)
212 #define OHCI_CTL_BLE          (1<<5)
213 #define OHCI_CTL_HCFS         ((1<<6)|(1<<7))
214 #define  OHCI_USB_RESET       0x00
215 #define  OHCI_USB_RESUME      0x40
216 #define  OHCI_USB_OPERATIONAL 0x80
217 #define  OHCI_USB_SUSPEND     0xc0
218 #define OHCI_CTL_IR           (1<<8)
219 #define OHCI_CTL_RWC          (1<<9)
220 #define OHCI_CTL_RWE          (1<<10)
221 
222 #define OHCI_STATUS_HCR       (1<<0)
223 #define OHCI_STATUS_CLF       (1<<1)
224 #define OHCI_STATUS_BLF       (1<<2)
225 #define OHCI_STATUS_OCR       (1<<3)
226 #define OHCI_STATUS_SOC       ((1<<6)|(1<<7))
227 
228 #define OHCI_INTR_SO          (1U<<0) /* Scheduling overrun */
229 #define OHCI_INTR_WD          (1U<<1) /* HcDoneHead writeback */
230 #define OHCI_INTR_SF          (1U<<2) /* Start of frame */
231 #define OHCI_INTR_RD          (1U<<3) /* Resume detect */
232 #define OHCI_INTR_UE          (1U<<4) /* Unrecoverable error */
233 #define OHCI_INTR_FNO         (1U<<5) /* Frame number overflow */
234 #define OHCI_INTR_RHSC        (1U<<6) /* Root hub status change */
235 #define OHCI_INTR_OC          (1U<<30) /* Ownership change */
236 #define OHCI_INTR_MIE         (1U<<31) /* Master Interrupt Enable */
237 
238 #define OHCI_HCCA_SIZE        0x100
239 #define OHCI_HCCA_MASK        0xffffff00
240 
241 #define OHCI_EDPTR_MASK       0xfffffff0
242 
243 #define OHCI_FMI_FI           0x00003fff
244 #define OHCI_FMI_FSMPS        0xffff0000
245 #define OHCI_FMI_FIT          0x80000000
246 
247 #define OHCI_FR_RT            (1U<<31)
248 
249 #define OHCI_LS_THRESH        0x628
250 
251 #define OHCI_RHA_RW_MASK      0x00000000 /* Mask of supported features.  */
252 #define OHCI_RHA_PSM          (1<<8)
253 #define OHCI_RHA_NPS          (1<<9)
254 #define OHCI_RHA_DT           (1<<10)
255 #define OHCI_RHA_OCPM         (1<<11)
256 #define OHCI_RHA_NOCP         (1<<12)
257 #define OHCI_RHA_POTPGT_MASK  0xff000000
258 
259 #define OHCI_RHS_LPS          (1U<<0)
260 #define OHCI_RHS_OCI          (1U<<1)
261 #define OHCI_RHS_DRWE         (1U<<15)
262 #define OHCI_RHS_LPSC         (1U<<16)
263 #define OHCI_RHS_OCIC         (1U<<17)
264 #define OHCI_RHS_CRWE         (1U<<31)
265 
266 #define OHCI_PORT_CCS         (1<<0)
267 #define OHCI_PORT_PES         (1<<1)
268 #define OHCI_PORT_PSS         (1<<2)
269 #define OHCI_PORT_POCI        (1<<3)
270 #define OHCI_PORT_PRS         (1<<4)
271 #define OHCI_PORT_PPS         (1<<8)
272 #define OHCI_PORT_LSDA        (1<<9)
273 #define OHCI_PORT_CSC         (1<<16)
274 #define OHCI_PORT_PESC        (1<<17)
275 #define OHCI_PORT_PSSC        (1<<18)
276 #define OHCI_PORT_OCIC        (1<<19)
277 #define OHCI_PORT_PRSC        (1<<20)
278 #define OHCI_PORT_WTC         (OHCI_PORT_CSC|OHCI_PORT_PESC|OHCI_PORT_PSSC \
279                                |OHCI_PORT_OCIC|OHCI_PORT_PRSC)
280 
281 #define OHCI_TD_DIR_SETUP     0x0
282 #define OHCI_TD_DIR_OUT       0x1
283 #define OHCI_TD_DIR_IN        0x2
284 #define OHCI_TD_DIR_RESERVED  0x3
285 
286 #define OHCI_CC_NOERROR             0x0
287 #define OHCI_CC_CRC                 0x1
288 #define OHCI_CC_BITSTUFFING         0x2
289 #define OHCI_CC_DATATOGGLEMISMATCH  0x3
290 #define OHCI_CC_STALL               0x4
291 #define OHCI_CC_DEVICENOTRESPONDING 0x5
292 #define OHCI_CC_PIDCHECKFAILURE     0x6
293 #define OHCI_CC_UNDEXPETEDPID       0x7
294 #define OHCI_CC_DATAOVERRUN         0x8
295 #define OHCI_CC_DATAUNDERRUN        0x9
296 #define OHCI_CC_BUFFEROVERRUN       0xc
297 #define OHCI_CC_BUFFERUNDERRUN      0xd
298 
299 #define OHCI_HRESET_FSBIR       (1 << 0)
300 
301 static void ohci_die(OHCIState *ohci);
302 
303 /* Update IRQ levels */
304 static inline void ohci_intr_update(OHCIState *ohci)
305 {
306     int level = 0;
307 
308     if ((ohci->intr & OHCI_INTR_MIE) &&
309         (ohci->intr_status & ohci->intr))
310         level = 1;
311 
312     qemu_set_irq(ohci->irq, level);
313 }
314 
315 /* Set an interrupt */
316 static inline void ohci_set_interrupt(OHCIState *ohci, uint32_t intr)
317 {
318     ohci->intr_status |= intr;
319     ohci_intr_update(ohci);
320 }
321 
322 /* Attach or detach a device on a root hub port.  */
323 static void ohci_attach(USBPort *port1)
324 {
325     OHCIState *s = port1->opaque;
326     OHCIPort *port = &s->rhport[port1->index];
327     uint32_t old_state = port->ctrl;
328 
329     /* set connect status */
330     port->ctrl |= OHCI_PORT_CCS | OHCI_PORT_CSC;
331 
332     /* update speed */
333     if (port->port.dev->speed == USB_SPEED_LOW) {
334         port->ctrl |= OHCI_PORT_LSDA;
335     } else {
336         port->ctrl &= ~OHCI_PORT_LSDA;
337     }
338 
339     /* notify of remote-wakeup */
340     if ((s->ctl & OHCI_CTL_HCFS) == OHCI_USB_SUSPEND) {
341         ohci_set_interrupt(s, OHCI_INTR_RD);
342     }
343 
344     trace_usb_ohci_port_attach(port1->index);
345 
346     if (old_state != port->ctrl) {
347         ohci_set_interrupt(s, OHCI_INTR_RHSC);
348     }
349 }
350 
351 static void ohci_detach(USBPort *port1)
352 {
353     OHCIState *s = port1->opaque;
354     OHCIPort *port = &s->rhport[port1->index];
355     uint32_t old_state = port->ctrl;
356 
357     ohci_async_cancel_device(s, port1->dev);
358 
359     /* set connect status */
360     if (port->ctrl & OHCI_PORT_CCS) {
361         port->ctrl &= ~OHCI_PORT_CCS;
362         port->ctrl |= OHCI_PORT_CSC;
363     }
364     /* disable port */
365     if (port->ctrl & OHCI_PORT_PES) {
366         port->ctrl &= ~OHCI_PORT_PES;
367         port->ctrl |= OHCI_PORT_PESC;
368     }
369     trace_usb_ohci_port_detach(port1->index);
370 
371     if (old_state != port->ctrl) {
372         ohci_set_interrupt(s, OHCI_INTR_RHSC);
373     }
374 }
375 
376 static void ohci_wakeup(USBPort *port1)
377 {
378     OHCIState *s = port1->opaque;
379     OHCIPort *port = &s->rhport[port1->index];
380     uint32_t intr = 0;
381     if (port->ctrl & OHCI_PORT_PSS) {
382         trace_usb_ohci_port_wakeup(port1->index);
383         port->ctrl |= OHCI_PORT_PSSC;
384         port->ctrl &= ~OHCI_PORT_PSS;
385         intr = OHCI_INTR_RHSC;
386     }
387     /* Note that the controller can be suspended even if this port is not */
388     if ((s->ctl & OHCI_CTL_HCFS) == OHCI_USB_SUSPEND) {
389         trace_usb_ohci_remote_wakeup(s->name);
390         /* This is the one state transition the controller can do by itself */
391         s->ctl &= ~OHCI_CTL_HCFS;
392         s->ctl |= OHCI_USB_RESUME;
393         /* In suspend mode only ResumeDetected is possible, not RHSC:
394          * see the OHCI spec 5.1.2.3.
395          */
396         intr = OHCI_INTR_RD;
397     }
398     ohci_set_interrupt(s, intr);
399 }
400 
401 static void ohci_child_detach(USBPort *port1, USBDevice *child)
402 {
403     OHCIState *s = port1->opaque;
404 
405     ohci_async_cancel_device(s, child);
406 }
407 
408 static USBDevice *ohci_find_device(OHCIState *ohci, uint8_t addr)
409 {
410     USBDevice *dev;
411     int i;
412 
413     for (i = 0; i < ohci->num_ports; i++) {
414         if ((ohci->rhport[i].ctrl & OHCI_PORT_PES) == 0) {
415             continue;
416         }
417         dev = usb_find_device(&ohci->rhport[i].port, addr);
418         if (dev != NULL) {
419             return dev;
420         }
421     }
422     return NULL;
423 }
424 
425 static void ohci_stop_endpoints(OHCIState *ohci)
426 {
427     USBDevice *dev;
428     int i, j;
429 
430     for (i = 0; i < ohci->num_ports; i++) {
431         dev = ohci->rhport[i].port.dev;
432         if (dev && dev->attached) {
433             usb_device_ep_stopped(dev, &dev->ep_ctl);
434             for (j = 0; j < USB_MAX_ENDPOINTS; j++) {
435                 usb_device_ep_stopped(dev, &dev->ep_in[j]);
436                 usb_device_ep_stopped(dev, &dev->ep_out[j]);
437             }
438         }
439     }
440 }
441 
442 /* Reset the controller */
443 static void ohci_reset(void *opaque)
444 {
445     OHCIState *ohci = opaque;
446     OHCIPort *port;
447     int i;
448 
449     ohci_bus_stop(ohci);
450     ohci->ctl = 0;
451     ohci->old_ctl = 0;
452     ohci->status = 0;
453     ohci->intr_status = 0;
454     ohci->intr = OHCI_INTR_MIE;
455 
456     ohci->hcca = 0;
457     ohci->ctrl_head = ohci->ctrl_cur = 0;
458     ohci->bulk_head = ohci->bulk_cur = 0;
459     ohci->per_cur = 0;
460     ohci->done = 0;
461     ohci->done_count = 7;
462 
463     /* FSMPS is marked TBD in OCHI 1.0, what gives ffs?
464      * I took the value linux sets ...
465      */
466     ohci->fsmps = 0x2778;
467     ohci->fi = 0x2edf;
468     ohci->fit = 0;
469     ohci->frt = 0;
470     ohci->frame_number = 0;
471     ohci->pstart = 0;
472     ohci->lst = OHCI_LS_THRESH;
473 
474     ohci->rhdesc_a = OHCI_RHA_NPS | ohci->num_ports;
475     ohci->rhdesc_b = 0x0; /* Impl. specific */
476     ohci->rhstatus = 0;
477 
478     for (i = 0; i < ohci->num_ports; i++)
479       {
480         port = &ohci->rhport[i];
481         port->ctrl = 0;
482         if (port->port.dev && port->port.dev->attached) {
483             usb_port_reset(&port->port);
484         }
485       }
486     if (ohci->async_td) {
487         usb_cancel_packet(&ohci->usb_packet);
488         ohci->async_td = 0;
489     }
490     ohci_stop_endpoints(ohci);
491     trace_usb_ohci_reset(ohci->name);
492 }
493 
494 /* Get an array of dwords from main memory */
495 static inline int get_dwords(OHCIState *ohci,
496                              dma_addr_t addr, uint32_t *buf, int num)
497 {
498     int i;
499 
500     addr += ohci->localmem_base;
501 
502     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
503         if (dma_memory_read(ohci->as, addr, buf, sizeof(*buf))) {
504             return -1;
505         }
506         *buf = le32_to_cpu(*buf);
507     }
508 
509     return 0;
510 }
511 
512 /* Put an array of dwords in to main memory */
513 static inline int put_dwords(OHCIState *ohci,
514                              dma_addr_t addr, uint32_t *buf, int num)
515 {
516     int i;
517 
518     addr += ohci->localmem_base;
519 
520     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
521         uint32_t tmp = cpu_to_le32(*buf);
522         if (dma_memory_write(ohci->as, addr, &tmp, sizeof(tmp))) {
523             return -1;
524         }
525     }
526 
527     return 0;
528 }
529 
530 /* Get an array of words from main memory */
531 static inline int get_words(OHCIState *ohci,
532                             dma_addr_t addr, uint16_t *buf, int num)
533 {
534     int i;
535 
536     addr += ohci->localmem_base;
537 
538     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
539         if (dma_memory_read(ohci->as, addr, buf, sizeof(*buf))) {
540             return -1;
541         }
542         *buf = le16_to_cpu(*buf);
543     }
544 
545     return 0;
546 }
547 
548 /* Put an array of words in to main memory */
549 static inline int put_words(OHCIState *ohci,
550                             dma_addr_t addr, uint16_t *buf, int num)
551 {
552     int i;
553 
554     addr += ohci->localmem_base;
555 
556     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
557         uint16_t tmp = cpu_to_le16(*buf);
558         if (dma_memory_write(ohci->as, addr, &tmp, sizeof(tmp))) {
559             return -1;
560         }
561     }
562 
563     return 0;
564 }
565 
566 static inline int ohci_read_ed(OHCIState *ohci,
567                                dma_addr_t addr, struct ohci_ed *ed)
568 {
569     return get_dwords(ohci, addr, (uint32_t *)ed, sizeof(*ed) >> 2);
570 }
571 
572 static inline int ohci_read_td(OHCIState *ohci,
573                                dma_addr_t addr, struct ohci_td *td)
574 {
575     return get_dwords(ohci, addr, (uint32_t *)td, sizeof(*td) >> 2);
576 }
577 
578 static inline int ohci_read_iso_td(OHCIState *ohci,
579                                    dma_addr_t addr, struct ohci_iso_td *td)
580 {
581     return get_dwords(ohci, addr, (uint32_t *)td, 4) ||
582            get_words(ohci, addr + 16, td->offset, 8);
583 }
584 
585 static inline int ohci_read_hcca(OHCIState *ohci,
586                                  dma_addr_t addr, struct ohci_hcca *hcca)
587 {
588     return dma_memory_read(ohci->as, addr + ohci->localmem_base,
589                            hcca, sizeof(*hcca));
590 }
591 
592 static inline int ohci_put_ed(OHCIState *ohci,
593                               dma_addr_t addr, struct ohci_ed *ed)
594 {
595     /* ed->tail is under control of the HCD.
596      * Since just ed->head is changed by HC, just write back this
597      */
598 
599     return put_dwords(ohci, addr + ED_WBACK_OFFSET,
600                       (uint32_t *)((char *)ed + ED_WBACK_OFFSET),
601                       ED_WBACK_SIZE >> 2);
602 }
603 
604 static inline int ohci_put_td(OHCIState *ohci,
605                               dma_addr_t addr, struct ohci_td *td)
606 {
607     return put_dwords(ohci, addr, (uint32_t *)td, sizeof(*td) >> 2);
608 }
609 
610 static inline int ohci_put_iso_td(OHCIState *ohci,
611                                   dma_addr_t addr, struct ohci_iso_td *td)
612 {
613     return put_dwords(ohci, addr, (uint32_t *)td, 4) ||
614            put_words(ohci, addr + 16, td->offset, 8);
615 }
616 
617 static inline int ohci_put_hcca(OHCIState *ohci,
618                                 dma_addr_t addr, struct ohci_hcca *hcca)
619 {
620     return dma_memory_write(ohci->as,
621                             addr + ohci->localmem_base + HCCA_WRITEBACK_OFFSET,
622                             (char *)hcca + HCCA_WRITEBACK_OFFSET,
623                             HCCA_WRITEBACK_SIZE);
624 }
625 
626 /* Read/Write the contents of a TD from/to main memory.  */
627 static int ohci_copy_td(OHCIState *ohci, struct ohci_td *td,
628                         uint8_t *buf, int len, DMADirection dir)
629 {
630     dma_addr_t ptr, n;
631 
632     ptr = td->cbp;
633     n = 0x1000 - (ptr & 0xfff);
634     if (n > len)
635         n = len;
636 
637     if (dma_memory_rw(ohci->as, ptr + ohci->localmem_base, buf, n, dir)) {
638         return -1;
639     }
640     if (n == len) {
641         return 0;
642     }
643     ptr = td->be & ~0xfffu;
644     buf += n;
645     if (dma_memory_rw(ohci->as, ptr + ohci->localmem_base, buf,
646                       len - n, dir)) {
647         return -1;
648     }
649     return 0;
650 }
651 
652 /* Read/Write the contents of an ISO TD from/to main memory.  */
653 static int ohci_copy_iso_td(OHCIState *ohci,
654                             uint32_t start_addr, uint32_t end_addr,
655                             uint8_t *buf, int len, DMADirection dir)
656 {
657     dma_addr_t ptr, n;
658 
659     ptr = start_addr;
660     n = 0x1000 - (ptr & 0xfff);
661     if (n > len)
662         n = len;
663 
664     if (dma_memory_rw(ohci->as, ptr + ohci->localmem_base, buf, n, dir)) {
665         return -1;
666     }
667     if (n == len) {
668         return 0;
669     }
670     ptr = end_addr & ~0xfffu;
671     buf += n;
672     if (dma_memory_rw(ohci->as, ptr + ohci->localmem_base, buf,
673                       len - n, dir)) {
674         return -1;
675     }
676     return 0;
677 }
678 
679 static void ohci_process_lists(OHCIState *ohci, int completion);
680 
681 static void ohci_async_complete_packet(USBPort *port, USBPacket *packet)
682 {
683     OHCIState *ohci = container_of(packet, OHCIState, usb_packet);
684 
685     trace_usb_ohci_async_complete();
686     ohci->async_complete = true;
687     ohci_process_lists(ohci, 1);
688 }
689 
690 #define USUB(a, b) ((int16_t)((uint16_t)(a) - (uint16_t)(b)))
691 
692 static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed,
693                                int completion)
694 {
695     int dir;
696     size_t len = 0;
697     const char *str = NULL;
698     int pid;
699     int ret;
700     int i;
701     USBDevice *dev;
702     USBEndpoint *ep;
703     struct ohci_iso_td iso_td;
704     uint32_t addr;
705     uint16_t starting_frame;
706     int16_t relative_frame_number;
707     int frame_count;
708     uint32_t start_offset, next_offset, end_offset = 0;
709     uint32_t start_addr, end_addr;
710 
711     addr = ed->head & OHCI_DPTR_MASK;
712 
713     if (ohci_read_iso_td(ohci, addr, &iso_td)) {
714         trace_usb_ohci_iso_td_read_failed(addr);
715         ohci_die(ohci);
716         return 0;
717     }
718 
719     starting_frame = OHCI_BM(iso_td.flags, TD_SF);
720     frame_count = OHCI_BM(iso_td.flags, TD_FC);
721     relative_frame_number = USUB(ohci->frame_number, starting_frame);
722 
723     trace_usb_ohci_iso_td_head(
724            ed->head & OHCI_DPTR_MASK, ed->tail & OHCI_DPTR_MASK,
725            iso_td.flags, iso_td.bp, iso_td.next, iso_td.be,
726            ohci->frame_number, starting_frame,
727            frame_count, relative_frame_number);
728     trace_usb_ohci_iso_td_head_offset(
729            iso_td.offset[0], iso_td.offset[1],
730            iso_td.offset[2], iso_td.offset[3],
731            iso_td.offset[4], iso_td.offset[5],
732            iso_td.offset[6], iso_td.offset[7]);
733 
734     if (relative_frame_number < 0) {
735         trace_usb_ohci_iso_td_relative_frame_number_neg(relative_frame_number);
736         return 1;
737     } else if (relative_frame_number > frame_count) {
738         /* ISO TD expired - retire the TD to the Done Queue and continue with
739            the next ISO TD of the same ED */
740         trace_usb_ohci_iso_td_relative_frame_number_big(relative_frame_number,
741                                                         frame_count);
742         OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_DATAOVERRUN);
743         ed->head &= ~OHCI_DPTR_MASK;
744         ed->head |= (iso_td.next & OHCI_DPTR_MASK);
745         iso_td.next = ohci->done;
746         ohci->done = addr;
747         i = OHCI_BM(iso_td.flags, TD_DI);
748         if (i < ohci->done_count)
749             ohci->done_count = i;
750         if (ohci_put_iso_td(ohci, addr, &iso_td)) {
751             ohci_die(ohci);
752             return 1;
753         }
754         return 0;
755     }
756 
757     dir = OHCI_BM(ed->flags, ED_D);
758     switch (dir) {
759     case OHCI_TD_DIR_IN:
760         str = "in";
761         pid = USB_TOKEN_IN;
762         break;
763     case OHCI_TD_DIR_OUT:
764         str = "out";
765         pid = USB_TOKEN_OUT;
766         break;
767     case OHCI_TD_DIR_SETUP:
768         str = "setup";
769         pid = USB_TOKEN_SETUP;
770         break;
771     default:
772         trace_usb_ohci_iso_td_bad_direction(dir);
773         return 1;
774     }
775 
776     if (!iso_td.bp || !iso_td.be) {
777         trace_usb_ohci_iso_td_bad_bp_be(iso_td.bp, iso_td.be);
778         return 1;
779     }
780 
781     start_offset = iso_td.offset[relative_frame_number];
782     next_offset = iso_td.offset[relative_frame_number + 1];
783 
784     if (!(OHCI_BM(start_offset, TD_PSW_CC) & 0xe) ||
785         ((relative_frame_number < frame_count) &&
786          !(OHCI_BM(next_offset, TD_PSW_CC) & 0xe))) {
787         trace_usb_ohci_iso_td_bad_cc_not_accessed(start_offset, next_offset);
788         return 1;
789     }
790 
791     if ((relative_frame_number < frame_count) && (start_offset > next_offset)) {
792         trace_usb_ohci_iso_td_bad_cc_overrun(start_offset, next_offset);
793         return 1;
794     }
795 
796     if ((start_offset & 0x1000) == 0) {
797         start_addr = (iso_td.bp & OHCI_PAGE_MASK) |
798             (start_offset & OHCI_OFFSET_MASK);
799     } else {
800         start_addr = (iso_td.be & OHCI_PAGE_MASK) |
801             (start_offset & OHCI_OFFSET_MASK);
802     }
803 
804     if (relative_frame_number < frame_count) {
805         end_offset = next_offset - 1;
806         if ((end_offset & 0x1000) == 0) {
807             end_addr = (iso_td.bp & OHCI_PAGE_MASK) |
808                 (end_offset & OHCI_OFFSET_MASK);
809         } else {
810             end_addr = (iso_td.be & OHCI_PAGE_MASK) |
811                 (end_offset & OHCI_OFFSET_MASK);
812         }
813     } else {
814         /* Last packet in the ISO TD */
815         end_addr = iso_td.be;
816     }
817 
818     if ((start_addr & OHCI_PAGE_MASK) != (end_addr & OHCI_PAGE_MASK)) {
819         len = (end_addr & OHCI_OFFSET_MASK) + 0x1001
820             - (start_addr & OHCI_OFFSET_MASK);
821     } else {
822         len = end_addr - start_addr + 1;
823     }
824 
825     if (len && dir != OHCI_TD_DIR_IN) {
826         if (ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, len,
827                              DMA_DIRECTION_TO_DEVICE)) {
828             ohci_die(ohci);
829             return 1;
830         }
831     }
832 
833     if (!completion) {
834         bool int_req = relative_frame_number == frame_count &&
835                        OHCI_BM(iso_td.flags, TD_DI) == 0;
836         dev = ohci_find_device(ohci, OHCI_BM(ed->flags, ED_FA));
837         ep = usb_ep_get(dev, pid, OHCI_BM(ed->flags, ED_EN));
838         usb_packet_setup(&ohci->usb_packet, pid, ep, 0, addr, false, int_req);
839         usb_packet_addbuf(&ohci->usb_packet, ohci->usb_buf, len);
840         usb_handle_packet(dev, &ohci->usb_packet);
841         if (ohci->usb_packet.status == USB_RET_ASYNC) {
842             usb_device_flush_ep_queue(dev, ep);
843             return 1;
844         }
845     }
846     if (ohci->usb_packet.status == USB_RET_SUCCESS) {
847         ret = ohci->usb_packet.actual_length;
848     } else {
849         ret = ohci->usb_packet.status;
850     }
851 
852     trace_usb_ohci_iso_td_so(start_offset, end_offset, start_addr, end_addr,
853                              str, len, ret);
854 
855     /* Writeback */
856     if (dir == OHCI_TD_DIR_IN && ret >= 0 && ret <= len) {
857         /* IN transfer succeeded */
858         if (ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, ret,
859                              DMA_DIRECTION_FROM_DEVICE)) {
860             ohci_die(ohci);
861             return 1;
862         }
863         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
864                     OHCI_CC_NOERROR);
865         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, ret);
866     } else if (dir == OHCI_TD_DIR_OUT && ret == len) {
867         /* OUT transfer succeeded */
868         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
869                     OHCI_CC_NOERROR);
870         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, 0);
871     } else {
872         if (ret > (ssize_t) len) {
873             trace_usb_ohci_iso_td_data_overrun(ret, len);
874             OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
875                         OHCI_CC_DATAOVERRUN);
876             OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
877                         len);
878         } else if (ret >= 0) {
879             trace_usb_ohci_iso_td_data_underrun(ret);
880             OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
881                         OHCI_CC_DATAUNDERRUN);
882         } else {
883             switch (ret) {
884             case USB_RET_IOERROR:
885             case USB_RET_NODEV:
886                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
887                             OHCI_CC_DEVICENOTRESPONDING);
888                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
889                             0);
890                 break;
891             case USB_RET_NAK:
892             case USB_RET_STALL:
893                 trace_usb_ohci_iso_td_nak(ret);
894                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
895                             OHCI_CC_STALL);
896                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
897                             0);
898                 break;
899             default:
900                 trace_usb_ohci_iso_td_bad_response(ret);
901                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
902                             OHCI_CC_UNDEXPETEDPID);
903                 break;
904             }
905         }
906     }
907 
908     if (relative_frame_number == frame_count) {
909         /* Last data packet of ISO TD - retire the TD to the Done Queue */
910         OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_NOERROR);
911         ed->head &= ~OHCI_DPTR_MASK;
912         ed->head |= (iso_td.next & OHCI_DPTR_MASK);
913         iso_td.next = ohci->done;
914         ohci->done = addr;
915         i = OHCI_BM(iso_td.flags, TD_DI);
916         if (i < ohci->done_count)
917             ohci->done_count = i;
918     }
919     if (ohci_put_iso_td(ohci, addr, &iso_td)) {
920         ohci_die(ohci);
921     }
922     return 1;
923 }
924 
925 #ifdef trace_event_get_state
926 static void ohci_td_pkt(const char *msg, const uint8_t *buf, size_t len)
927 {
928     bool print16 = !!trace_event_get_state(TRACE_USB_OHCI_TD_PKT_SHORT);
929     bool printall = !!trace_event_get_state(TRACE_USB_OHCI_TD_PKT_FULL);
930     const int width = 16;
931     int i;
932     char tmp[3 * width + 1];
933     char *p = tmp;
934 
935     if (!printall && !print16) {
936         return;
937     }
938 
939     for (i = 0; ; i++) {
940         if (i && (!(i % width) || (i == len))) {
941             if (!printall) {
942                 trace_usb_ohci_td_pkt_short(msg, tmp);
943                 break;
944             }
945             trace_usb_ohci_td_pkt_full(msg, tmp);
946             p = tmp;
947             *p = 0;
948         }
949         if (i == len) {
950             break;
951         }
952 
953         p += sprintf(p, " %.2x", buf[i]);
954     }
955 }
956 #else
957 static void ohci_td_pkt(const char *msg, const uint8_t *buf, size_t len)
958 {
959 }
960 #endif
961 
962 /* Service a transport descriptor.
963    Returns nonzero to terminate processing of this endpoint.  */
964 
965 static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed)
966 {
967     int dir;
968     size_t len = 0, pktlen = 0;
969     const char *str = NULL;
970     int pid;
971     int ret;
972     int i;
973     USBDevice *dev;
974     USBEndpoint *ep;
975     struct ohci_td td;
976     uint32_t addr;
977     int flag_r;
978     int completion;
979 
980     addr = ed->head & OHCI_DPTR_MASK;
981     /* See if this TD has already been submitted to the device.  */
982     completion = (addr == ohci->async_td);
983     if (completion && !ohci->async_complete) {
984         trace_usb_ohci_td_skip_async();
985         return 1;
986     }
987     if (ohci_read_td(ohci, addr, &td)) {
988         trace_usb_ohci_td_read_error(addr);
989         ohci_die(ohci);
990         return 0;
991     }
992 
993     dir = OHCI_BM(ed->flags, ED_D);
994     switch (dir) {
995     case OHCI_TD_DIR_OUT:
996     case OHCI_TD_DIR_IN:
997         /* Same value.  */
998         break;
999     default:
1000         dir = OHCI_BM(td.flags, TD_DP);
1001         break;
1002     }
1003 
1004     switch (dir) {
1005     case OHCI_TD_DIR_IN:
1006         str = "in";
1007         pid = USB_TOKEN_IN;
1008         break;
1009     case OHCI_TD_DIR_OUT:
1010         str = "out";
1011         pid = USB_TOKEN_OUT;
1012         break;
1013     case OHCI_TD_DIR_SETUP:
1014         str = "setup";
1015         pid = USB_TOKEN_SETUP;
1016         break;
1017     default:
1018         trace_usb_ohci_td_bad_direction(dir);
1019         return 1;
1020     }
1021     if (td.cbp && td.be) {
1022         if ((td.cbp & 0xfffff000) != (td.be & 0xfffff000)) {
1023             len = (td.be & 0xfff) + 0x1001 - (td.cbp & 0xfff);
1024         } else {
1025             len = (td.be - td.cbp) + 1;
1026         }
1027 
1028         pktlen = len;
1029         if (len && dir != OHCI_TD_DIR_IN) {
1030             /* The endpoint may not allow us to transfer it all now */
1031             pktlen = (ed->flags & OHCI_ED_MPS_MASK) >> OHCI_ED_MPS_SHIFT;
1032             if (pktlen > len) {
1033                 pktlen = len;
1034             }
1035             if (!completion) {
1036                 if (ohci_copy_td(ohci, &td, ohci->usb_buf, pktlen,
1037                                  DMA_DIRECTION_TO_DEVICE)) {
1038                     ohci_die(ohci);
1039                 }
1040             }
1041         }
1042     }
1043 
1044     flag_r = (td.flags & OHCI_TD_R) != 0;
1045     trace_usb_ohci_td_pkt_hdr(addr, (int64_t)pktlen, (int64_t)len, str,
1046                               flag_r, td.cbp, td.be);
1047     ohci_td_pkt("OUT", ohci->usb_buf, pktlen);
1048 
1049     if (completion) {
1050         ohci->async_td = 0;
1051         ohci->async_complete = false;
1052     } else {
1053         if (ohci->async_td) {
1054             /* ??? The hardware should allow one active packet per
1055                endpoint.  We only allow one active packet per controller.
1056                This should be sufficient as long as devices respond in a
1057                timely manner.
1058             */
1059             trace_usb_ohci_td_too_many_pending();
1060             return 1;
1061         }
1062         dev = ohci_find_device(ohci, OHCI_BM(ed->flags, ED_FA));
1063         ep = usb_ep_get(dev, pid, OHCI_BM(ed->flags, ED_EN));
1064         usb_packet_setup(&ohci->usb_packet, pid, ep, 0, addr, !flag_r,
1065                          OHCI_BM(td.flags, TD_DI) == 0);
1066         usb_packet_addbuf(&ohci->usb_packet, ohci->usb_buf, pktlen);
1067         usb_handle_packet(dev, &ohci->usb_packet);
1068         trace_usb_ohci_td_packet_status(ohci->usb_packet.status);
1069 
1070         if (ohci->usb_packet.status == USB_RET_ASYNC) {
1071             usb_device_flush_ep_queue(dev, ep);
1072             ohci->async_td = addr;
1073             return 1;
1074         }
1075     }
1076     if (ohci->usb_packet.status == USB_RET_SUCCESS) {
1077         ret = ohci->usb_packet.actual_length;
1078     } else {
1079         ret = ohci->usb_packet.status;
1080     }
1081 
1082     if (ret >= 0) {
1083         if (dir == OHCI_TD_DIR_IN) {
1084             if (ohci_copy_td(ohci, &td, ohci->usb_buf, ret,
1085                              DMA_DIRECTION_FROM_DEVICE)) {
1086                 ohci_die(ohci);
1087             }
1088             ohci_td_pkt("IN", ohci->usb_buf, pktlen);
1089         } else {
1090             ret = pktlen;
1091         }
1092     }
1093 
1094     /* Writeback */
1095     if (ret == pktlen || (dir == OHCI_TD_DIR_IN && ret >= 0 && flag_r)) {
1096         /* Transmission succeeded.  */
1097         if (ret == len) {
1098             td.cbp = 0;
1099         } else {
1100             if ((td.cbp & 0xfff) + ret > 0xfff) {
1101                 td.cbp = (td.be & ~0xfff) + ((td.cbp + ret) & 0xfff);
1102             } else {
1103                 td.cbp += ret;
1104             }
1105         }
1106         td.flags |= OHCI_TD_T1;
1107         td.flags ^= OHCI_TD_T0;
1108         OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_NOERROR);
1109         OHCI_SET_BM(td.flags, TD_EC, 0);
1110 
1111         if ((dir != OHCI_TD_DIR_IN) && (ret != len)) {
1112             /* Partial packet transfer: TD not ready to retire yet */
1113             goto exit_no_retire;
1114         }
1115 
1116         /* Setting ED_C is part of the TD retirement process */
1117         ed->head &= ~OHCI_ED_C;
1118         if (td.flags & OHCI_TD_T0)
1119             ed->head |= OHCI_ED_C;
1120     } else {
1121         if (ret >= 0) {
1122             trace_usb_ohci_td_underrun();
1123             OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAUNDERRUN);
1124         } else {
1125             switch (ret) {
1126             case USB_RET_IOERROR:
1127             case USB_RET_NODEV:
1128                 trace_usb_ohci_td_dev_error();
1129                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DEVICENOTRESPONDING);
1130                 break;
1131             case USB_RET_NAK:
1132                 trace_usb_ohci_td_nak();
1133                 return 1;
1134             case USB_RET_STALL:
1135                 trace_usb_ohci_td_stall();
1136                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_STALL);
1137                 break;
1138             case USB_RET_BABBLE:
1139                 trace_usb_ohci_td_babble();
1140                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAOVERRUN);
1141                 break;
1142             default:
1143                 trace_usb_ohci_td_bad_device_response(ret);
1144                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_UNDEXPETEDPID);
1145                 OHCI_SET_BM(td.flags, TD_EC, 3);
1146                 break;
1147             }
1148         }
1149         ed->head |= OHCI_ED_H;
1150     }
1151 
1152     /* Retire this TD */
1153     ed->head &= ~OHCI_DPTR_MASK;
1154     ed->head |= td.next & OHCI_DPTR_MASK;
1155     td.next = ohci->done;
1156     ohci->done = addr;
1157     i = OHCI_BM(td.flags, TD_DI);
1158     if (i < ohci->done_count)
1159         ohci->done_count = i;
1160 exit_no_retire:
1161     if (ohci_put_td(ohci, addr, &td)) {
1162         ohci_die(ohci);
1163         return 1;
1164     }
1165     return OHCI_BM(td.flags, TD_CC) != OHCI_CC_NOERROR;
1166 }
1167 
1168 /* Service an endpoint list.  Returns nonzero if active TD were found.  */
1169 static int ohci_service_ed_list(OHCIState *ohci, uint32_t head, int completion)
1170 {
1171     struct ohci_ed ed;
1172     uint32_t next_ed;
1173     uint32_t cur;
1174     int active;
1175 
1176     active = 0;
1177 
1178     if (head == 0)
1179         return 0;
1180 
1181     for (cur = head; cur; cur = next_ed) {
1182         if (ohci_read_ed(ohci, cur, &ed)) {
1183             trace_usb_ohci_ed_read_error(cur);
1184             ohci_die(ohci);
1185             return 0;
1186         }
1187 
1188         next_ed = ed.next & OHCI_DPTR_MASK;
1189 
1190         if ((ed.head & OHCI_ED_H) || (ed.flags & OHCI_ED_K)) {
1191             uint32_t addr;
1192             /* Cancel pending packets for ED that have been paused.  */
1193             addr = ed.head & OHCI_DPTR_MASK;
1194             if (ohci->async_td && addr == ohci->async_td) {
1195                 usb_cancel_packet(&ohci->usb_packet);
1196                 ohci->async_td = 0;
1197                 usb_device_ep_stopped(ohci->usb_packet.ep->dev,
1198                                       ohci->usb_packet.ep);
1199             }
1200             continue;
1201         }
1202 
1203         while ((ed.head & OHCI_DPTR_MASK) != ed.tail) {
1204             trace_usb_ohci_ed_pkt(cur, (ed.head & OHCI_ED_H) != 0,
1205                     (ed.head & OHCI_ED_C) != 0, ed.head & OHCI_DPTR_MASK,
1206                     ed.tail & OHCI_DPTR_MASK, ed.next & OHCI_DPTR_MASK);
1207             trace_usb_ohci_ed_pkt_flags(
1208                     OHCI_BM(ed.flags, ED_FA), OHCI_BM(ed.flags, ED_EN),
1209                     OHCI_BM(ed.flags, ED_D), (ed.flags & OHCI_ED_S)!= 0,
1210                     (ed.flags & OHCI_ED_K) != 0, (ed.flags & OHCI_ED_F) != 0,
1211                     OHCI_BM(ed.flags, ED_MPS));
1212 
1213             active = 1;
1214 
1215             if ((ed.flags & OHCI_ED_F) == 0) {
1216                 if (ohci_service_td(ohci, &ed))
1217                     break;
1218             } else {
1219                 /* Handle isochronous endpoints */
1220                 if (ohci_service_iso_td(ohci, &ed, completion))
1221                     break;
1222             }
1223         }
1224 
1225         if (ohci_put_ed(ohci, cur, &ed)) {
1226             ohci_die(ohci);
1227             return 0;
1228         }
1229     }
1230 
1231     return active;
1232 }
1233 
1234 /* Generate a SOF event, and set a timer for EOF */
1235 static void ohci_sof(OHCIState *ohci)
1236 {
1237     ohci->sof_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1238     timer_mod(ohci->eof_timer, ohci->sof_time + usb_frame_time);
1239     ohci_set_interrupt(ohci, OHCI_INTR_SF);
1240 }
1241 
1242 /* Process Control and Bulk lists.  */
1243 static void ohci_process_lists(OHCIState *ohci, int completion)
1244 {
1245     if ((ohci->ctl & OHCI_CTL_CLE) && (ohci->status & OHCI_STATUS_CLF)) {
1246         if (ohci->ctrl_cur && ohci->ctrl_cur != ohci->ctrl_head) {
1247             trace_usb_ohci_process_lists(ohci->ctrl_head, ohci->ctrl_cur);
1248         }
1249         if (!ohci_service_ed_list(ohci, ohci->ctrl_head, completion)) {
1250             ohci->ctrl_cur = 0;
1251             ohci->status &= ~OHCI_STATUS_CLF;
1252         }
1253     }
1254 
1255     if ((ohci->ctl & OHCI_CTL_BLE) && (ohci->status & OHCI_STATUS_BLF)) {
1256         if (!ohci_service_ed_list(ohci, ohci->bulk_head, completion)) {
1257             ohci->bulk_cur = 0;
1258             ohci->status &= ~OHCI_STATUS_BLF;
1259         }
1260     }
1261 }
1262 
1263 /* Do frame processing on frame boundary */
1264 static void ohci_frame_boundary(void *opaque)
1265 {
1266     OHCIState *ohci = opaque;
1267     struct ohci_hcca hcca;
1268 
1269     if (ohci_read_hcca(ohci, ohci->hcca, &hcca)) {
1270         trace_usb_ohci_hcca_read_error(ohci->hcca);
1271         ohci_die(ohci);
1272         return;
1273     }
1274 
1275     /* Process all the lists at the end of the frame */
1276     if (ohci->ctl & OHCI_CTL_PLE) {
1277         int n;
1278 
1279         n = ohci->frame_number & 0x1f;
1280         ohci_service_ed_list(ohci, le32_to_cpu(hcca.intr[n]), 0);
1281     }
1282 
1283     /* Cancel all pending packets if either of the lists has been disabled.  */
1284     if (ohci->old_ctl & (~ohci->ctl) & (OHCI_CTL_BLE | OHCI_CTL_CLE)) {
1285         if (ohci->async_td) {
1286             usb_cancel_packet(&ohci->usb_packet);
1287             ohci->async_td = 0;
1288         }
1289         ohci_stop_endpoints(ohci);
1290     }
1291     ohci->old_ctl = ohci->ctl;
1292     ohci_process_lists(ohci, 0);
1293 
1294     /* Stop if UnrecoverableError happened or ohci_sof will crash */
1295     if (ohci->intr_status & OHCI_INTR_UE) {
1296         return;
1297     }
1298 
1299     /* Frame boundary, so do EOF stuf here */
1300     ohci->frt = ohci->fit;
1301 
1302     /* Increment frame number and take care of endianness. */
1303     ohci->frame_number = (ohci->frame_number + 1) & 0xffff;
1304     hcca.frame = cpu_to_le16(ohci->frame_number);
1305 
1306     if (ohci->done_count == 0 && !(ohci->intr_status & OHCI_INTR_WD)) {
1307         if (!ohci->done)
1308             abort();
1309         if (ohci->intr & ohci->intr_status)
1310             ohci->done |= 1;
1311         hcca.done = cpu_to_le32(ohci->done);
1312         ohci->done = 0;
1313         ohci->done_count = 7;
1314         ohci_set_interrupt(ohci, OHCI_INTR_WD);
1315     }
1316 
1317     if (ohci->done_count != 7 && ohci->done_count != 0)
1318         ohci->done_count--;
1319 
1320     /* Do SOF stuff here */
1321     ohci_sof(ohci);
1322 
1323     /* Writeback HCCA */
1324     if (ohci_put_hcca(ohci, ohci->hcca, &hcca)) {
1325         ohci_die(ohci);
1326     }
1327 }
1328 
1329 /* Start sending SOF tokens across the USB bus, lists are processed in
1330  * next frame
1331  */
1332 static int ohci_bus_start(OHCIState *ohci)
1333 {
1334     ohci->eof_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
1335                     ohci_frame_boundary,
1336                     ohci);
1337 
1338     if (ohci->eof_timer == NULL) {
1339         trace_usb_ohci_bus_eof_timer_failed(ohci->name);
1340         ohci_die(ohci);
1341         return 0;
1342     }
1343 
1344     trace_usb_ohci_start(ohci->name);
1345 
1346     ohci_sof(ohci);
1347 
1348     return 1;
1349 }
1350 
1351 /* Stop sending SOF tokens on the bus */
1352 static void ohci_bus_stop(OHCIState *ohci)
1353 {
1354     trace_usb_ohci_stop(ohci->name);
1355     if (ohci->eof_timer) {
1356         timer_del(ohci->eof_timer);
1357         timer_free(ohci->eof_timer);
1358     }
1359     ohci->eof_timer = NULL;
1360 }
1361 
1362 /* Sets a flag in a port status register but only set it if the port is
1363  * connected, if not set ConnectStatusChange flag. If flag is enabled
1364  * return 1.
1365  */
1366 static int ohci_port_set_if_connected(OHCIState *ohci, int i, uint32_t val)
1367 {
1368     int ret = 1;
1369 
1370     /* writing a 0 has no effect */
1371     if (val == 0)
1372         return 0;
1373 
1374     /* If CurrentConnectStatus is cleared we set
1375      * ConnectStatusChange
1376      */
1377     if (!(ohci->rhport[i].ctrl & OHCI_PORT_CCS)) {
1378         ohci->rhport[i].ctrl |= OHCI_PORT_CSC;
1379         if (ohci->rhstatus & OHCI_RHS_DRWE) {
1380             /* TODO: CSC is a wakeup event */
1381         }
1382         return 0;
1383     }
1384 
1385     if (ohci->rhport[i].ctrl & val)
1386         ret = 0;
1387 
1388     /* set the bit */
1389     ohci->rhport[i].ctrl |= val;
1390 
1391     return ret;
1392 }
1393 
1394 /* Set the frame interval - frame interval toggle is manipulated by the hcd only */
1395 static void ohci_set_frame_interval(OHCIState *ohci, uint16_t val)
1396 {
1397     val &= OHCI_FMI_FI;
1398 
1399     if (val != ohci->fi) {
1400         trace_usb_ohci_set_frame_interval(ohci->name, ohci->fi, ohci->fi);
1401     }
1402 
1403     ohci->fi = val;
1404 }
1405 
1406 static void ohci_port_power(OHCIState *ohci, int i, int p)
1407 {
1408     if (p) {
1409         ohci->rhport[i].ctrl |= OHCI_PORT_PPS;
1410     } else {
1411         ohci->rhport[i].ctrl &= ~(OHCI_PORT_PPS|
1412                     OHCI_PORT_CCS|
1413                     OHCI_PORT_PSS|
1414                     OHCI_PORT_PRS);
1415     }
1416 }
1417 
1418 /* Set HcControlRegister */
1419 static void ohci_set_ctl(OHCIState *ohci, uint32_t val)
1420 {
1421     uint32_t old_state;
1422     uint32_t new_state;
1423 
1424     old_state = ohci->ctl & OHCI_CTL_HCFS;
1425     ohci->ctl = val;
1426     new_state = ohci->ctl & OHCI_CTL_HCFS;
1427 
1428     /* no state change */
1429     if (old_state == new_state)
1430         return;
1431 
1432     trace_usb_ohci_set_ctl(ohci->name, new_state);
1433     switch (new_state) {
1434     case OHCI_USB_OPERATIONAL:
1435         ohci_bus_start(ohci);
1436         break;
1437     case OHCI_USB_SUSPEND:
1438         ohci_bus_stop(ohci);
1439         break;
1440     case OHCI_USB_RESUME:
1441         trace_usb_ohci_resume(ohci->name);
1442         break;
1443     case OHCI_USB_RESET:
1444         ohci_reset(ohci);
1445         break;
1446     }
1447 }
1448 
1449 static uint32_t ohci_get_frame_remaining(OHCIState *ohci)
1450 {
1451     uint16_t fr;
1452     int64_t tks;
1453 
1454     if ((ohci->ctl & OHCI_CTL_HCFS) != OHCI_USB_OPERATIONAL)
1455         return (ohci->frt << 31);
1456 
1457     /* Being in USB operational state guarnatees sof_time was
1458      * set already.
1459      */
1460     tks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) - ohci->sof_time;
1461 
1462     /* avoid muldiv if possible */
1463     if (tks >= usb_frame_time)
1464         return (ohci->frt << 31);
1465 
1466     tks = muldiv64(1, tks, usb_bit_time);
1467     fr = (uint16_t)(ohci->fi - tks);
1468 
1469     return (ohci->frt << 31) | fr;
1470 }
1471 
1472 
1473 /* Set root hub status */
1474 static void ohci_set_hub_status(OHCIState *ohci, uint32_t val)
1475 {
1476     uint32_t old_state;
1477 
1478     old_state = ohci->rhstatus;
1479 
1480     /* write 1 to clear OCIC */
1481     if (val & OHCI_RHS_OCIC)
1482         ohci->rhstatus &= ~OHCI_RHS_OCIC;
1483 
1484     if (val & OHCI_RHS_LPS) {
1485         int i;
1486 
1487         for (i = 0; i < ohci->num_ports; i++)
1488             ohci_port_power(ohci, i, 0);
1489         trace_usb_ohci_hub_power_down();
1490     }
1491 
1492     if (val & OHCI_RHS_LPSC) {
1493         int i;
1494 
1495         for (i = 0; i < ohci->num_ports; i++)
1496             ohci_port_power(ohci, i, 1);
1497         trace_usb_ohci_hub_power_up();
1498     }
1499 
1500     if (val & OHCI_RHS_DRWE)
1501         ohci->rhstatus |= OHCI_RHS_DRWE;
1502 
1503     if (val & OHCI_RHS_CRWE)
1504         ohci->rhstatus &= ~OHCI_RHS_DRWE;
1505 
1506     if (old_state != ohci->rhstatus)
1507         ohci_set_interrupt(ohci, OHCI_INTR_RHSC);
1508 }
1509 
1510 /* Set root hub port status */
1511 static void ohci_port_set_status(OHCIState *ohci, int portnum, uint32_t val)
1512 {
1513     uint32_t old_state;
1514     OHCIPort *port;
1515 
1516     port = &ohci->rhport[portnum];
1517     old_state = port->ctrl;
1518 
1519     /* Write to clear CSC, PESC, PSSC, OCIC, PRSC */
1520     if (val & OHCI_PORT_WTC)
1521         port->ctrl &= ~(val & OHCI_PORT_WTC);
1522 
1523     if (val & OHCI_PORT_CCS)
1524         port->ctrl &= ~OHCI_PORT_PES;
1525 
1526     ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PES);
1527 
1528     if (ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PSS)) {
1529         trace_usb_ohci_port_suspend(portnum);
1530     }
1531 
1532     if (ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PRS)) {
1533         trace_usb_ohci_port_reset(portnum);
1534         usb_device_reset(port->port.dev);
1535         port->ctrl &= ~OHCI_PORT_PRS;
1536         /* ??? Should this also set OHCI_PORT_PESC.  */
1537         port->ctrl |= OHCI_PORT_PES | OHCI_PORT_PRSC;
1538     }
1539 
1540     /* Invert order here to ensure in ambiguous case, device is
1541      * powered up...
1542      */
1543     if (val & OHCI_PORT_LSDA)
1544         ohci_port_power(ohci, portnum, 0);
1545     if (val & OHCI_PORT_PPS)
1546         ohci_port_power(ohci, portnum, 1);
1547 
1548     if (old_state != port->ctrl)
1549         ohci_set_interrupt(ohci, OHCI_INTR_RHSC);
1550 }
1551 
1552 static uint64_t ohci_mem_read(void *opaque,
1553                               hwaddr addr,
1554                               unsigned size)
1555 {
1556     OHCIState *ohci = opaque;
1557     uint32_t retval;
1558 
1559     /* Only aligned reads are allowed on OHCI */
1560     if (addr & 3) {
1561         trace_usb_ohci_mem_read_unaligned(addr);
1562         return 0xffffffff;
1563     } else if (addr >= 0x54 && addr < 0x54 + ohci->num_ports * 4) {
1564         /* HcRhPortStatus */
1565         retval = ohci->rhport[(addr - 0x54) >> 2].ctrl | OHCI_PORT_PPS;
1566     } else {
1567         switch (addr >> 2) {
1568         case 0: /* HcRevision */
1569             retval = 0x10;
1570             break;
1571 
1572         case 1: /* HcControl */
1573             retval = ohci->ctl;
1574             break;
1575 
1576         case 2: /* HcCommandStatus */
1577             retval = ohci->status;
1578             break;
1579 
1580         case 3: /* HcInterruptStatus */
1581             retval = ohci->intr_status;
1582             break;
1583 
1584         case 4: /* HcInterruptEnable */
1585         case 5: /* HcInterruptDisable */
1586             retval = ohci->intr;
1587             break;
1588 
1589         case 6: /* HcHCCA */
1590             retval = ohci->hcca;
1591             break;
1592 
1593         case 7: /* HcPeriodCurrentED */
1594             retval = ohci->per_cur;
1595             break;
1596 
1597         case 8: /* HcControlHeadED */
1598             retval = ohci->ctrl_head;
1599             break;
1600 
1601         case 9: /* HcControlCurrentED */
1602             retval = ohci->ctrl_cur;
1603             break;
1604 
1605         case 10: /* HcBulkHeadED */
1606             retval = ohci->bulk_head;
1607             break;
1608 
1609         case 11: /* HcBulkCurrentED */
1610             retval = ohci->bulk_cur;
1611             break;
1612 
1613         case 12: /* HcDoneHead */
1614             retval = ohci->done;
1615             break;
1616 
1617         case 13: /* HcFmInterretval */
1618             retval = (ohci->fit << 31) | (ohci->fsmps << 16) | (ohci->fi);
1619             break;
1620 
1621         case 14: /* HcFmRemaining */
1622             retval = ohci_get_frame_remaining(ohci);
1623             break;
1624 
1625         case 15: /* HcFmNumber */
1626             retval = ohci->frame_number;
1627             break;
1628 
1629         case 16: /* HcPeriodicStart */
1630             retval = ohci->pstart;
1631             break;
1632 
1633         case 17: /* HcLSThreshold */
1634             retval = ohci->lst;
1635             break;
1636 
1637         case 18: /* HcRhDescriptorA */
1638             retval = ohci->rhdesc_a;
1639             break;
1640 
1641         case 19: /* HcRhDescriptorB */
1642             retval = ohci->rhdesc_b;
1643             break;
1644 
1645         case 20: /* HcRhStatus */
1646             retval = ohci->rhstatus;
1647             break;
1648 
1649         /* PXA27x specific registers */
1650         case 24: /* HcStatus */
1651             retval = ohci->hstatus & ohci->hmask;
1652             break;
1653 
1654         case 25: /* HcHReset */
1655             retval = ohci->hreset;
1656             break;
1657 
1658         case 26: /* HcHInterruptEnable */
1659             retval = ohci->hmask;
1660             break;
1661 
1662         case 27: /* HcHInterruptTest */
1663             retval = ohci->htest;
1664             break;
1665 
1666         default:
1667             trace_usb_ohci_mem_read_bad_offset(addr);
1668             retval = 0xffffffff;
1669         }
1670     }
1671 
1672     return retval;
1673 }
1674 
1675 static void ohci_mem_write(void *opaque,
1676                            hwaddr addr,
1677                            uint64_t val,
1678                            unsigned size)
1679 {
1680     OHCIState *ohci = opaque;
1681 
1682     /* Only aligned reads are allowed on OHCI */
1683     if (addr & 3) {
1684         trace_usb_ohci_mem_write_unaligned(addr);
1685         return;
1686     }
1687 
1688     if (addr >= 0x54 && addr < 0x54 + ohci->num_ports * 4) {
1689         /* HcRhPortStatus */
1690         ohci_port_set_status(ohci, (addr - 0x54) >> 2, val);
1691         return;
1692     }
1693 
1694     switch (addr >> 2) {
1695     case 1: /* HcControl */
1696         ohci_set_ctl(ohci, val);
1697         break;
1698 
1699     case 2: /* HcCommandStatus */
1700         /* SOC is read-only */
1701         val = (val & ~OHCI_STATUS_SOC);
1702 
1703         /* Bits written as '0' remain unchanged in the register */
1704         ohci->status |= val;
1705 
1706         if (ohci->status & OHCI_STATUS_HCR)
1707             ohci_reset(ohci);
1708         break;
1709 
1710     case 3: /* HcInterruptStatus */
1711         ohci->intr_status &= ~val;
1712         ohci_intr_update(ohci);
1713         break;
1714 
1715     case 4: /* HcInterruptEnable */
1716         ohci->intr |= val;
1717         ohci_intr_update(ohci);
1718         break;
1719 
1720     case 5: /* HcInterruptDisable */
1721         ohci->intr &= ~val;
1722         ohci_intr_update(ohci);
1723         break;
1724 
1725     case 6: /* HcHCCA */
1726         ohci->hcca = val & OHCI_HCCA_MASK;
1727         break;
1728 
1729     case 7: /* HcPeriodCurrentED */
1730         /* Ignore writes to this read-only register, Linux does them */
1731         break;
1732 
1733     case 8: /* HcControlHeadED */
1734         ohci->ctrl_head = val & OHCI_EDPTR_MASK;
1735         break;
1736 
1737     case 9: /* HcControlCurrentED */
1738         ohci->ctrl_cur = val & OHCI_EDPTR_MASK;
1739         break;
1740 
1741     case 10: /* HcBulkHeadED */
1742         ohci->bulk_head = val & OHCI_EDPTR_MASK;
1743         break;
1744 
1745     case 11: /* HcBulkCurrentED */
1746         ohci->bulk_cur = val & OHCI_EDPTR_MASK;
1747         break;
1748 
1749     case 13: /* HcFmInterval */
1750         ohci->fsmps = (val & OHCI_FMI_FSMPS) >> 16;
1751         ohci->fit = (val & OHCI_FMI_FIT) >> 31;
1752         ohci_set_frame_interval(ohci, val);
1753         break;
1754 
1755     case 15: /* HcFmNumber */
1756         break;
1757 
1758     case 16: /* HcPeriodicStart */
1759         ohci->pstart = val & 0xffff;
1760         break;
1761 
1762     case 17: /* HcLSThreshold */
1763         ohci->lst = val & 0xffff;
1764         break;
1765 
1766     case 18: /* HcRhDescriptorA */
1767         ohci->rhdesc_a &= ~OHCI_RHA_RW_MASK;
1768         ohci->rhdesc_a |= val & OHCI_RHA_RW_MASK;
1769         break;
1770 
1771     case 19: /* HcRhDescriptorB */
1772         break;
1773 
1774     case 20: /* HcRhStatus */
1775         ohci_set_hub_status(ohci, val);
1776         break;
1777 
1778     /* PXA27x specific registers */
1779     case 24: /* HcStatus */
1780         ohci->hstatus &= ~(val & ohci->hmask);
1781         break;
1782 
1783     case 25: /* HcHReset */
1784         ohci->hreset = val & ~OHCI_HRESET_FSBIR;
1785         if (val & OHCI_HRESET_FSBIR)
1786             ohci_reset(ohci);
1787         break;
1788 
1789     case 26: /* HcHInterruptEnable */
1790         ohci->hmask = val;
1791         break;
1792 
1793     case 27: /* HcHInterruptTest */
1794         ohci->htest = val;
1795         break;
1796 
1797     default:
1798         trace_usb_ohci_mem_write_bad_offset(addr);
1799         break;
1800     }
1801 }
1802 
1803 static void ohci_async_cancel_device(OHCIState *ohci, USBDevice *dev)
1804 {
1805     if (ohci->async_td &&
1806         usb_packet_is_inflight(&ohci->usb_packet) &&
1807         ohci->usb_packet.ep->dev == dev) {
1808         usb_cancel_packet(&ohci->usb_packet);
1809         ohci->async_td = 0;
1810     }
1811 }
1812 
1813 static const MemoryRegionOps ohci_mem_ops = {
1814     .read = ohci_mem_read,
1815     .write = ohci_mem_write,
1816     .endianness = DEVICE_LITTLE_ENDIAN,
1817 };
1818 
1819 static USBPortOps ohci_port_ops = {
1820     .attach = ohci_attach,
1821     .detach = ohci_detach,
1822     .child_detach = ohci_child_detach,
1823     .wakeup = ohci_wakeup,
1824     .complete = ohci_async_complete_packet,
1825 };
1826 
1827 static USBBusOps ohci_bus_ops = {
1828 };
1829 
1830 static void usb_ohci_init(OHCIState *ohci, DeviceState *dev,
1831                           int num_ports, dma_addr_t localmem_base,
1832                           char *masterbus, uint32_t firstport,
1833                           AddressSpace *as, Error **errp)
1834 {
1835     Error *err = NULL;
1836     int i;
1837 
1838     ohci->as = as;
1839 
1840     if (usb_frame_time == 0) {
1841 #ifdef OHCI_TIME_WARP
1842         usb_frame_time = get_ticks_per_sec();
1843         usb_bit_time = muldiv64(1, get_ticks_per_sec(), USB_HZ/1000);
1844 #else
1845         usb_frame_time = muldiv64(1, get_ticks_per_sec(), 1000);
1846         if (get_ticks_per_sec() >= USB_HZ) {
1847             usb_bit_time = muldiv64(1, get_ticks_per_sec(), USB_HZ);
1848         } else {
1849             usb_bit_time = 1;
1850         }
1851 #endif
1852         trace_usb_ohci_init_time(usb_frame_time, usb_bit_time);
1853     }
1854 
1855     ohci->num_ports = num_ports;
1856     if (masterbus) {
1857         USBPort *ports[OHCI_MAX_PORTS];
1858         for(i = 0; i < num_ports; i++) {
1859             ports[i] = &ohci->rhport[i].port;
1860         }
1861         usb_register_companion(masterbus, ports, num_ports,
1862                                firstport, ohci, &ohci_port_ops,
1863                                USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL,
1864                                &err);
1865         if (err) {
1866             error_propagate(errp, err);
1867             return;
1868         }
1869     } else {
1870         usb_bus_new(&ohci->bus, sizeof(ohci->bus), &ohci_bus_ops, dev);
1871         for (i = 0; i < num_ports; i++) {
1872             usb_register_port(&ohci->bus, &ohci->rhport[i].port,
1873                               ohci, i, &ohci_port_ops,
1874                               USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL);
1875         }
1876     }
1877 
1878     memory_region_init_io(&ohci->mem, OBJECT(dev), &ohci_mem_ops,
1879                           ohci, "ohci", 256);
1880     ohci->localmem_base = localmem_base;
1881 
1882     ohci->name = object_get_typename(OBJECT(dev));
1883     usb_packet_init(&ohci->usb_packet);
1884 
1885     ohci->async_td = 0;
1886 }
1887 
1888 #define TYPE_PCI_OHCI "pci-ohci"
1889 #define PCI_OHCI(obj) OBJECT_CHECK(OHCIPCIState, (obj), TYPE_PCI_OHCI)
1890 
1891 typedef struct {
1892     /*< private >*/
1893     PCIDevice parent_obj;
1894     /*< public >*/
1895 
1896     OHCIState state;
1897     char *masterbus;
1898     uint32_t num_ports;
1899     uint32_t firstport;
1900 } OHCIPCIState;
1901 
1902 /** A typical O/EHCI will stop operating, set itself into error state
1903  * (which can be queried by MMIO) and will set PERR in its config
1904  * space to signal that it got an error
1905  */
1906 static void ohci_die(OHCIState *ohci)
1907 {
1908     OHCIPCIState *dev = container_of(ohci, OHCIPCIState, state);
1909 
1910     trace_usb_ohci_die();
1911 
1912     ohci_set_interrupt(ohci, OHCI_INTR_UE);
1913     ohci_bus_stop(ohci);
1914     pci_set_word(dev->parent_obj.config + PCI_STATUS,
1915                  PCI_STATUS_DETECTED_PARITY);
1916 }
1917 
1918 static void usb_ohci_realize_pci(PCIDevice *dev, Error **errp)
1919 {
1920     Error *err = NULL;
1921     OHCIPCIState *ohci = PCI_OHCI(dev);
1922 
1923     dev->config[PCI_CLASS_PROG] = 0x10; /* OHCI */
1924     dev->config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin A */
1925 
1926     usb_ohci_init(&ohci->state, DEVICE(dev), ohci->num_ports, 0,
1927                   ohci->masterbus, ohci->firstport,
1928                   pci_get_address_space(dev), &err);
1929     if (err) {
1930         error_propagate(errp, err);
1931         return;
1932     }
1933 
1934     ohci->state.irq = pci_allocate_irq(dev);
1935     pci_register_bar(dev, 0, 0, &ohci->state.mem);
1936 }
1937 
1938 static void usb_ohci_exit(PCIDevice *dev)
1939 {
1940     OHCIPCIState *ohci = PCI_OHCI(dev);
1941     OHCIState *s = &ohci->state;
1942 
1943     trace_usb_ohci_exit(s->name);
1944     ohci_bus_stop(s);
1945 
1946     if (s->async_td) {
1947         usb_cancel_packet(&s->usb_packet);
1948         s->async_td = 0;
1949     }
1950     ohci_stop_endpoints(s);
1951 
1952     if (!ohci->masterbus) {
1953         usb_bus_release(&s->bus);
1954     }
1955 }
1956 
1957 static void usb_ohci_reset_pci(DeviceState *d)
1958 {
1959     PCIDevice *dev = PCI_DEVICE(d);
1960     OHCIPCIState *ohci = PCI_OHCI(dev);
1961     OHCIState *s = &ohci->state;
1962 
1963     ohci_reset(s);
1964 }
1965 
1966 #define TYPE_SYSBUS_OHCI "sysbus-ohci"
1967 #define SYSBUS_OHCI(obj) OBJECT_CHECK(OHCISysBusState, (obj), TYPE_SYSBUS_OHCI)
1968 
1969 typedef struct {
1970     /*< private >*/
1971     SysBusDevice parent_obj;
1972     /*< public >*/
1973 
1974     OHCIState ohci;
1975     uint32_t num_ports;
1976     dma_addr_t dma_offset;
1977 } OHCISysBusState;
1978 
1979 static void ohci_realize_pxa(DeviceState *dev, Error **errp)
1980 {
1981     OHCISysBusState *s = SYSBUS_OHCI(dev);
1982     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
1983 
1984     /* Cannot fail as we pass NULL for masterbus */
1985     usb_ohci_init(&s->ohci, dev, s->num_ports, s->dma_offset, NULL, 0,
1986                   &address_space_memory, &error_abort);
1987     sysbus_init_irq(sbd, &s->ohci.irq);
1988     sysbus_init_mmio(sbd, &s->ohci.mem);
1989 }
1990 
1991 static void usb_ohci_reset_sysbus(DeviceState *dev)
1992 {
1993     OHCISysBusState *s = SYSBUS_OHCI(dev);
1994     OHCIState *ohci = &s->ohci;
1995 
1996     ohci_reset(ohci);
1997 }
1998 
1999 static Property ohci_pci_properties[] = {
2000     DEFINE_PROP_STRING("masterbus", OHCIPCIState, masterbus),
2001     DEFINE_PROP_UINT32("num-ports", OHCIPCIState, num_ports, 3),
2002     DEFINE_PROP_UINT32("firstport", OHCIPCIState, firstport, 0),
2003     DEFINE_PROP_END_OF_LIST(),
2004 };
2005 
2006 static const VMStateDescription vmstate_ohci_state_port = {
2007     .name = "ohci-core/port",
2008     .version_id = 1,
2009     .minimum_version_id = 1,
2010     .fields = (VMStateField[]) {
2011         VMSTATE_UINT32(ctrl, OHCIPort),
2012         VMSTATE_END_OF_LIST()
2013     },
2014 };
2015 
2016 static bool ohci_eof_timer_needed(void *opaque)
2017 {
2018     OHCIState *ohci = opaque;
2019 
2020     return ohci->eof_timer != NULL;
2021 }
2022 
2023 static int ohci_eof_timer_pre_load(void *opaque)
2024 {
2025     OHCIState *ohci = opaque;
2026 
2027     ohci_bus_start(ohci);
2028 
2029     return 0;
2030 }
2031 
2032 static const VMStateDescription vmstate_ohci_eof_timer = {
2033     .name = "ohci-core/eof-timer",
2034     .version_id = 1,
2035     .minimum_version_id = 1,
2036     .pre_load = ohci_eof_timer_pre_load,
2037     .fields = (VMStateField[]) {
2038         VMSTATE_TIMER_PTR(eof_timer, OHCIState),
2039         VMSTATE_END_OF_LIST()
2040     },
2041 };
2042 
2043 static const VMStateDescription vmstate_ohci_state = {
2044     .name = "ohci-core",
2045     .version_id = 1,
2046     .minimum_version_id = 1,
2047     .fields = (VMStateField[]) {
2048         VMSTATE_INT64(sof_time, OHCIState),
2049         VMSTATE_UINT32(ctl, OHCIState),
2050         VMSTATE_UINT32(status, OHCIState),
2051         VMSTATE_UINT32(intr_status, OHCIState),
2052         VMSTATE_UINT32(intr, OHCIState),
2053         VMSTATE_UINT32(hcca, OHCIState),
2054         VMSTATE_UINT32(ctrl_head, OHCIState),
2055         VMSTATE_UINT32(ctrl_cur, OHCIState),
2056         VMSTATE_UINT32(bulk_head, OHCIState),
2057         VMSTATE_UINT32(bulk_cur, OHCIState),
2058         VMSTATE_UINT32(per_cur, OHCIState),
2059         VMSTATE_UINT32(done, OHCIState),
2060         VMSTATE_INT32(done_count, OHCIState),
2061         VMSTATE_UINT16(fsmps, OHCIState),
2062         VMSTATE_UINT8(fit, OHCIState),
2063         VMSTATE_UINT16(fi, OHCIState),
2064         VMSTATE_UINT8(frt, OHCIState),
2065         VMSTATE_UINT16(frame_number, OHCIState),
2066         VMSTATE_UINT16(padding, OHCIState),
2067         VMSTATE_UINT32(pstart, OHCIState),
2068         VMSTATE_UINT32(lst, OHCIState),
2069         VMSTATE_UINT32(rhdesc_a, OHCIState),
2070         VMSTATE_UINT32(rhdesc_b, OHCIState),
2071         VMSTATE_UINT32(rhstatus, OHCIState),
2072         VMSTATE_STRUCT_ARRAY(rhport, OHCIState, OHCI_MAX_PORTS, 0,
2073                              vmstate_ohci_state_port, OHCIPort),
2074         VMSTATE_UINT32(hstatus, OHCIState),
2075         VMSTATE_UINT32(hmask, OHCIState),
2076         VMSTATE_UINT32(hreset, OHCIState),
2077         VMSTATE_UINT32(htest, OHCIState),
2078         VMSTATE_UINT32(old_ctl, OHCIState),
2079         VMSTATE_UINT8_ARRAY(usb_buf, OHCIState, 8192),
2080         VMSTATE_UINT32(async_td, OHCIState),
2081         VMSTATE_BOOL(async_complete, OHCIState),
2082         VMSTATE_END_OF_LIST()
2083     },
2084     .subsections = (VMStateSubsection []) {
2085         {
2086             .vmsd = &vmstate_ohci_eof_timer,
2087             .needed = ohci_eof_timer_needed,
2088         } , {
2089             /* empty */
2090         }
2091     }
2092 };
2093 
2094 static const VMStateDescription vmstate_ohci = {
2095     .name = "ohci",
2096     .version_id = 1,
2097     .minimum_version_id = 1,
2098     .fields = (VMStateField[]) {
2099         VMSTATE_PCI_DEVICE(parent_obj, OHCIPCIState),
2100         VMSTATE_STRUCT(state, OHCIPCIState, 1, vmstate_ohci_state, OHCIState),
2101         VMSTATE_END_OF_LIST()
2102     }
2103 };
2104 
2105 static void ohci_pci_class_init(ObjectClass *klass, void *data)
2106 {
2107     DeviceClass *dc = DEVICE_CLASS(klass);
2108     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
2109 
2110     k->realize = usb_ohci_realize_pci;
2111     k->exit = usb_ohci_exit;
2112     k->vendor_id = PCI_VENDOR_ID_APPLE;
2113     k->device_id = PCI_DEVICE_ID_APPLE_IPID_USB;
2114     k->class_id = PCI_CLASS_SERIAL_USB;
2115     set_bit(DEVICE_CATEGORY_USB, dc->categories);
2116     dc->desc = "Apple USB Controller";
2117     dc->props = ohci_pci_properties;
2118     dc->hotpluggable = false;
2119     dc->vmsd = &vmstate_ohci;
2120     dc->reset = usb_ohci_reset_pci;
2121 }
2122 
2123 static const TypeInfo ohci_pci_info = {
2124     .name          = TYPE_PCI_OHCI,
2125     .parent        = TYPE_PCI_DEVICE,
2126     .instance_size = sizeof(OHCIPCIState),
2127     .class_init    = ohci_pci_class_init,
2128 };
2129 
2130 static Property ohci_sysbus_properties[] = {
2131     DEFINE_PROP_UINT32("num-ports", OHCISysBusState, num_ports, 3),
2132     DEFINE_PROP_DMAADDR("dma-offset", OHCISysBusState, dma_offset, 3),
2133     DEFINE_PROP_END_OF_LIST(),
2134 };
2135 
2136 static void ohci_sysbus_class_init(ObjectClass *klass, void *data)
2137 {
2138     DeviceClass *dc = DEVICE_CLASS(klass);
2139 
2140     dc->realize = ohci_realize_pxa;
2141     set_bit(DEVICE_CATEGORY_USB, dc->categories);
2142     dc->desc = "OHCI USB Controller";
2143     dc->props = ohci_sysbus_properties;
2144     dc->reset = usb_ohci_reset_sysbus;
2145 }
2146 
2147 static const TypeInfo ohci_sysbus_info = {
2148     .name          = TYPE_SYSBUS_OHCI,
2149     .parent        = TYPE_SYS_BUS_DEVICE,
2150     .instance_size = sizeof(OHCISysBusState),
2151     .class_init    = ohci_sysbus_class_init,
2152 };
2153 
2154 static void ohci_register_types(void)
2155 {
2156     type_register_static(&ohci_pci_info);
2157     type_register_static(&ohci_sysbus_info);
2158 }
2159 
2160 type_init(ohci_register_types)
2161