xref: /openbmc/qemu/hw/usb/hcd-ohci.c (revision 84a3a53c)
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 static void ohci_roothub_reset(OHCIState *ohci)
443 {
444     OHCIPort *port;
445     int i;
446 
447     ohci_bus_stop(ohci);
448     ohci->rhdesc_a = OHCI_RHA_NPS | ohci->num_ports;
449     ohci->rhdesc_b = 0x0; /* Impl. specific */
450     ohci->rhstatus = 0;
451 
452     for (i = 0; i < ohci->num_ports; i++) {
453         port = &ohci->rhport[i];
454         port->ctrl = 0;
455         if (port->port.dev && port->port.dev->attached) {
456             usb_port_reset(&port->port);
457         }
458     }
459     if (ohci->async_td) {
460         usb_cancel_packet(&ohci->usb_packet);
461         ohci->async_td = 0;
462     }
463     ohci_stop_endpoints(ohci);
464 }
465 
466 /* Reset the controller */
467 static void ohci_soft_reset(OHCIState *ohci)
468 {
469     trace_usb_ohci_reset(ohci->name);
470 
471     ohci_bus_stop(ohci);
472     ohci->ctl = (ohci->ctl & OHCI_CTL_IR) | OHCI_USB_SUSPEND;
473     ohci->old_ctl = 0;
474     ohci->status = 0;
475     ohci->intr_status = 0;
476     ohci->intr = OHCI_INTR_MIE;
477 
478     ohci->hcca = 0;
479     ohci->ctrl_head = ohci->ctrl_cur = 0;
480     ohci->bulk_head = ohci->bulk_cur = 0;
481     ohci->per_cur = 0;
482     ohci->done = 0;
483     ohci->done_count = 7;
484 
485     /* FSMPS is marked TBD in OCHI 1.0, what gives ffs?
486      * I took the value linux sets ...
487      */
488     ohci->fsmps = 0x2778;
489     ohci->fi = 0x2edf;
490     ohci->fit = 0;
491     ohci->frt = 0;
492     ohci->frame_number = 0;
493     ohci->pstart = 0;
494     ohci->lst = OHCI_LS_THRESH;
495 }
496 
497 static void ohci_hard_reset(OHCIState *ohci)
498 {
499     ohci_soft_reset(ohci);
500     ohci->ctl = 0;
501     ohci_roothub_reset(ohci);
502 }
503 
504 /* Get an array of dwords from main memory */
505 static inline int get_dwords(OHCIState *ohci,
506                              dma_addr_t addr, uint32_t *buf, int num)
507 {
508     int i;
509 
510     addr += ohci->localmem_base;
511 
512     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
513         if (dma_memory_read(ohci->as, addr, buf, sizeof(*buf))) {
514             return -1;
515         }
516         *buf = le32_to_cpu(*buf);
517     }
518 
519     return 0;
520 }
521 
522 /* Put an array of dwords in to main memory */
523 static inline int put_dwords(OHCIState *ohci,
524                              dma_addr_t addr, uint32_t *buf, int num)
525 {
526     int i;
527 
528     addr += ohci->localmem_base;
529 
530     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
531         uint32_t tmp = cpu_to_le32(*buf);
532         if (dma_memory_write(ohci->as, addr, &tmp, sizeof(tmp))) {
533             return -1;
534         }
535     }
536 
537     return 0;
538 }
539 
540 /* Get an array of words from main memory */
541 static inline int get_words(OHCIState *ohci,
542                             dma_addr_t addr, uint16_t *buf, int num)
543 {
544     int i;
545 
546     addr += ohci->localmem_base;
547 
548     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
549         if (dma_memory_read(ohci->as, addr, buf, sizeof(*buf))) {
550             return -1;
551         }
552         *buf = le16_to_cpu(*buf);
553     }
554 
555     return 0;
556 }
557 
558 /* Put an array of words in to main memory */
559 static inline int put_words(OHCIState *ohci,
560                             dma_addr_t addr, uint16_t *buf, int num)
561 {
562     int i;
563 
564     addr += ohci->localmem_base;
565 
566     for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
567         uint16_t tmp = cpu_to_le16(*buf);
568         if (dma_memory_write(ohci->as, addr, &tmp, sizeof(tmp))) {
569             return -1;
570         }
571     }
572 
573     return 0;
574 }
575 
576 static inline int ohci_read_ed(OHCIState *ohci,
577                                dma_addr_t addr, struct ohci_ed *ed)
578 {
579     return get_dwords(ohci, addr, (uint32_t *)ed, sizeof(*ed) >> 2);
580 }
581 
582 static inline int ohci_read_td(OHCIState *ohci,
583                                dma_addr_t addr, struct ohci_td *td)
584 {
585     return get_dwords(ohci, addr, (uint32_t *)td, sizeof(*td) >> 2);
586 }
587 
588 static inline int ohci_read_iso_td(OHCIState *ohci,
589                                    dma_addr_t addr, struct ohci_iso_td *td)
590 {
591     return get_dwords(ohci, addr, (uint32_t *)td, 4) ||
592            get_words(ohci, addr + 16, td->offset, 8);
593 }
594 
595 static inline int ohci_read_hcca(OHCIState *ohci,
596                                  dma_addr_t addr, struct ohci_hcca *hcca)
597 {
598     return dma_memory_read(ohci->as, addr + ohci->localmem_base,
599                            hcca, sizeof(*hcca));
600 }
601 
602 static inline int ohci_put_ed(OHCIState *ohci,
603                               dma_addr_t addr, struct ohci_ed *ed)
604 {
605     /* ed->tail is under control of the HCD.
606      * Since just ed->head is changed by HC, just write back this
607      */
608 
609     return put_dwords(ohci, addr + ED_WBACK_OFFSET,
610                       (uint32_t *)((char *)ed + ED_WBACK_OFFSET),
611                       ED_WBACK_SIZE >> 2);
612 }
613 
614 static inline int ohci_put_td(OHCIState *ohci,
615                               dma_addr_t addr, struct ohci_td *td)
616 {
617     return put_dwords(ohci, addr, (uint32_t *)td, sizeof(*td) >> 2);
618 }
619 
620 static inline int ohci_put_iso_td(OHCIState *ohci,
621                                   dma_addr_t addr, struct ohci_iso_td *td)
622 {
623     return put_dwords(ohci, addr, (uint32_t *)td, 4) ||
624            put_words(ohci, addr + 16, td->offset, 8);
625 }
626 
627 static inline int ohci_put_hcca(OHCIState *ohci,
628                                 dma_addr_t addr, struct ohci_hcca *hcca)
629 {
630     return dma_memory_write(ohci->as,
631                             addr + ohci->localmem_base + HCCA_WRITEBACK_OFFSET,
632                             (char *)hcca + HCCA_WRITEBACK_OFFSET,
633                             HCCA_WRITEBACK_SIZE);
634 }
635 
636 /* Read/Write the contents of a TD from/to main memory.  */
637 static int ohci_copy_td(OHCIState *ohci, struct ohci_td *td,
638                         uint8_t *buf, int len, DMADirection dir)
639 {
640     dma_addr_t ptr, n;
641 
642     ptr = td->cbp;
643     n = 0x1000 - (ptr & 0xfff);
644     if (n > len)
645         n = len;
646 
647     if (dma_memory_rw(ohci->as, ptr + ohci->localmem_base, buf, n, dir)) {
648         return -1;
649     }
650     if (n == len) {
651         return 0;
652     }
653     ptr = td->be & ~0xfffu;
654     buf += n;
655     if (dma_memory_rw(ohci->as, ptr + ohci->localmem_base, buf,
656                       len - n, dir)) {
657         return -1;
658     }
659     return 0;
660 }
661 
662 /* Read/Write the contents of an ISO TD from/to main memory.  */
663 static int ohci_copy_iso_td(OHCIState *ohci,
664                             uint32_t start_addr, uint32_t end_addr,
665                             uint8_t *buf, int len, DMADirection dir)
666 {
667     dma_addr_t ptr, n;
668 
669     ptr = start_addr;
670     n = 0x1000 - (ptr & 0xfff);
671     if (n > len)
672         n = len;
673 
674     if (dma_memory_rw(ohci->as, ptr + ohci->localmem_base, buf, n, dir)) {
675         return -1;
676     }
677     if (n == len) {
678         return 0;
679     }
680     ptr = end_addr & ~0xfffu;
681     buf += n;
682     if (dma_memory_rw(ohci->as, ptr + ohci->localmem_base, buf,
683                       len - n, dir)) {
684         return -1;
685     }
686     return 0;
687 }
688 
689 static void ohci_process_lists(OHCIState *ohci, int completion);
690 
691 static void ohci_async_complete_packet(USBPort *port, USBPacket *packet)
692 {
693     OHCIState *ohci = container_of(packet, OHCIState, usb_packet);
694 
695     trace_usb_ohci_async_complete();
696     ohci->async_complete = true;
697     ohci_process_lists(ohci, 1);
698 }
699 
700 #define USUB(a, b) ((int16_t)((uint16_t)(a) - (uint16_t)(b)))
701 
702 static int ohci_service_iso_td(OHCIState *ohci, struct ohci_ed *ed,
703                                int completion)
704 {
705     int dir;
706     size_t len = 0;
707     const char *str = NULL;
708     int pid;
709     int ret;
710     int i;
711     USBDevice *dev;
712     USBEndpoint *ep;
713     struct ohci_iso_td iso_td;
714     uint32_t addr;
715     uint16_t starting_frame;
716     int16_t relative_frame_number;
717     int frame_count;
718     uint32_t start_offset, next_offset, end_offset = 0;
719     uint32_t start_addr, end_addr;
720 
721     addr = ed->head & OHCI_DPTR_MASK;
722 
723     if (ohci_read_iso_td(ohci, addr, &iso_td)) {
724         trace_usb_ohci_iso_td_read_failed(addr);
725         ohci_die(ohci);
726         return 0;
727     }
728 
729     starting_frame = OHCI_BM(iso_td.flags, TD_SF);
730     frame_count = OHCI_BM(iso_td.flags, TD_FC);
731     relative_frame_number = USUB(ohci->frame_number, starting_frame);
732 
733     trace_usb_ohci_iso_td_head(
734            ed->head & OHCI_DPTR_MASK, ed->tail & OHCI_DPTR_MASK,
735            iso_td.flags, iso_td.bp, iso_td.next, iso_td.be,
736            ohci->frame_number, starting_frame,
737            frame_count, relative_frame_number);
738     trace_usb_ohci_iso_td_head_offset(
739            iso_td.offset[0], iso_td.offset[1],
740            iso_td.offset[2], iso_td.offset[3],
741            iso_td.offset[4], iso_td.offset[5],
742            iso_td.offset[6], iso_td.offset[7]);
743 
744     if (relative_frame_number < 0) {
745         trace_usb_ohci_iso_td_relative_frame_number_neg(relative_frame_number);
746         return 1;
747     } else if (relative_frame_number > frame_count) {
748         /* ISO TD expired - retire the TD to the Done Queue and continue with
749            the next ISO TD of the same ED */
750         trace_usb_ohci_iso_td_relative_frame_number_big(relative_frame_number,
751                                                         frame_count);
752         OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_DATAOVERRUN);
753         ed->head &= ~OHCI_DPTR_MASK;
754         ed->head |= (iso_td.next & OHCI_DPTR_MASK);
755         iso_td.next = ohci->done;
756         ohci->done = addr;
757         i = OHCI_BM(iso_td.flags, TD_DI);
758         if (i < ohci->done_count)
759             ohci->done_count = i;
760         if (ohci_put_iso_td(ohci, addr, &iso_td)) {
761             ohci_die(ohci);
762             return 1;
763         }
764         return 0;
765     }
766 
767     dir = OHCI_BM(ed->flags, ED_D);
768     switch (dir) {
769     case OHCI_TD_DIR_IN:
770         str = "in";
771         pid = USB_TOKEN_IN;
772         break;
773     case OHCI_TD_DIR_OUT:
774         str = "out";
775         pid = USB_TOKEN_OUT;
776         break;
777     case OHCI_TD_DIR_SETUP:
778         str = "setup";
779         pid = USB_TOKEN_SETUP;
780         break;
781     default:
782         trace_usb_ohci_iso_td_bad_direction(dir);
783         return 1;
784     }
785 
786     if (!iso_td.bp || !iso_td.be) {
787         trace_usb_ohci_iso_td_bad_bp_be(iso_td.bp, iso_td.be);
788         return 1;
789     }
790 
791     start_offset = iso_td.offset[relative_frame_number];
792     next_offset = iso_td.offset[relative_frame_number + 1];
793 
794     if (!(OHCI_BM(start_offset, TD_PSW_CC) & 0xe) ||
795         ((relative_frame_number < frame_count) &&
796          !(OHCI_BM(next_offset, TD_PSW_CC) & 0xe))) {
797         trace_usb_ohci_iso_td_bad_cc_not_accessed(start_offset, next_offset);
798         return 1;
799     }
800 
801     if ((relative_frame_number < frame_count) && (start_offset > next_offset)) {
802         trace_usb_ohci_iso_td_bad_cc_overrun(start_offset, next_offset);
803         return 1;
804     }
805 
806     if ((start_offset & 0x1000) == 0) {
807         start_addr = (iso_td.bp & OHCI_PAGE_MASK) |
808             (start_offset & OHCI_OFFSET_MASK);
809     } else {
810         start_addr = (iso_td.be & OHCI_PAGE_MASK) |
811             (start_offset & OHCI_OFFSET_MASK);
812     }
813 
814     if (relative_frame_number < frame_count) {
815         end_offset = next_offset - 1;
816         if ((end_offset & 0x1000) == 0) {
817             end_addr = (iso_td.bp & OHCI_PAGE_MASK) |
818                 (end_offset & OHCI_OFFSET_MASK);
819         } else {
820             end_addr = (iso_td.be & OHCI_PAGE_MASK) |
821                 (end_offset & OHCI_OFFSET_MASK);
822         }
823     } else {
824         /* Last packet in the ISO TD */
825         end_addr = iso_td.be;
826     }
827 
828     if ((start_addr & OHCI_PAGE_MASK) != (end_addr & OHCI_PAGE_MASK)) {
829         len = (end_addr & OHCI_OFFSET_MASK) + 0x1001
830             - (start_addr & OHCI_OFFSET_MASK);
831     } else {
832         len = end_addr - start_addr + 1;
833     }
834 
835     if (len && dir != OHCI_TD_DIR_IN) {
836         if (ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, len,
837                              DMA_DIRECTION_TO_DEVICE)) {
838             ohci_die(ohci);
839             return 1;
840         }
841     }
842 
843     if (!completion) {
844         bool int_req = relative_frame_number == frame_count &&
845                        OHCI_BM(iso_td.flags, TD_DI) == 0;
846         dev = ohci_find_device(ohci, OHCI_BM(ed->flags, ED_FA));
847         ep = usb_ep_get(dev, pid, OHCI_BM(ed->flags, ED_EN));
848         usb_packet_setup(&ohci->usb_packet, pid, ep, 0, addr, false, int_req);
849         usb_packet_addbuf(&ohci->usb_packet, ohci->usb_buf, len);
850         usb_handle_packet(dev, &ohci->usb_packet);
851         if (ohci->usb_packet.status == USB_RET_ASYNC) {
852             usb_device_flush_ep_queue(dev, ep);
853             return 1;
854         }
855     }
856     if (ohci->usb_packet.status == USB_RET_SUCCESS) {
857         ret = ohci->usb_packet.actual_length;
858     } else {
859         ret = ohci->usb_packet.status;
860     }
861 
862     trace_usb_ohci_iso_td_so(start_offset, end_offset, start_addr, end_addr,
863                              str, len, ret);
864 
865     /* Writeback */
866     if (dir == OHCI_TD_DIR_IN && ret >= 0 && ret <= len) {
867         /* IN transfer succeeded */
868         if (ohci_copy_iso_td(ohci, start_addr, end_addr, ohci->usb_buf, ret,
869                              DMA_DIRECTION_FROM_DEVICE)) {
870             ohci_die(ohci);
871             return 1;
872         }
873         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
874                     OHCI_CC_NOERROR);
875         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, ret);
876     } else if (dir == OHCI_TD_DIR_OUT && ret == len) {
877         /* OUT transfer succeeded */
878         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
879                     OHCI_CC_NOERROR);
880         OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE, 0);
881     } else {
882         if (ret > (ssize_t) len) {
883             trace_usb_ohci_iso_td_data_overrun(ret, len);
884             OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
885                         OHCI_CC_DATAOVERRUN);
886             OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
887                         len);
888         } else if (ret >= 0) {
889             trace_usb_ohci_iso_td_data_underrun(ret);
890             OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
891                         OHCI_CC_DATAUNDERRUN);
892         } else {
893             switch (ret) {
894             case USB_RET_IOERROR:
895             case USB_RET_NODEV:
896                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
897                             OHCI_CC_DEVICENOTRESPONDING);
898                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
899                             0);
900                 break;
901             case USB_RET_NAK:
902             case USB_RET_STALL:
903                 trace_usb_ohci_iso_td_nak(ret);
904                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
905                             OHCI_CC_STALL);
906                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_SIZE,
907                             0);
908                 break;
909             default:
910                 trace_usb_ohci_iso_td_bad_response(ret);
911                 OHCI_SET_BM(iso_td.offset[relative_frame_number], TD_PSW_CC,
912                             OHCI_CC_UNDEXPETEDPID);
913                 break;
914             }
915         }
916     }
917 
918     if (relative_frame_number == frame_count) {
919         /* Last data packet of ISO TD - retire the TD to the Done Queue */
920         OHCI_SET_BM(iso_td.flags, TD_CC, OHCI_CC_NOERROR);
921         ed->head &= ~OHCI_DPTR_MASK;
922         ed->head |= (iso_td.next & OHCI_DPTR_MASK);
923         iso_td.next = ohci->done;
924         ohci->done = addr;
925         i = OHCI_BM(iso_td.flags, TD_DI);
926         if (i < ohci->done_count)
927             ohci->done_count = i;
928     }
929     if (ohci_put_iso_td(ohci, addr, &iso_td)) {
930         ohci_die(ohci);
931     }
932     return 1;
933 }
934 
935 #ifdef trace_event_get_state
936 static void ohci_td_pkt(const char *msg, const uint8_t *buf, size_t len)
937 {
938     bool print16 = !!trace_event_get_state(TRACE_USB_OHCI_TD_PKT_SHORT);
939     bool printall = !!trace_event_get_state(TRACE_USB_OHCI_TD_PKT_FULL);
940     const int width = 16;
941     int i;
942     char tmp[3 * width + 1];
943     char *p = tmp;
944 
945     if (!printall && !print16) {
946         return;
947     }
948 
949     for (i = 0; ; i++) {
950         if (i && (!(i % width) || (i == len))) {
951             if (!printall) {
952                 trace_usb_ohci_td_pkt_short(msg, tmp);
953                 break;
954             }
955             trace_usb_ohci_td_pkt_full(msg, tmp);
956             p = tmp;
957             *p = 0;
958         }
959         if (i == len) {
960             break;
961         }
962 
963         p += sprintf(p, " %.2x", buf[i]);
964     }
965 }
966 #else
967 static void ohci_td_pkt(const char *msg, const uint8_t *buf, size_t len)
968 {
969 }
970 #endif
971 
972 /* Service a transport descriptor.
973    Returns nonzero to terminate processing of this endpoint.  */
974 
975 static int ohci_service_td(OHCIState *ohci, struct ohci_ed *ed)
976 {
977     int dir;
978     size_t len = 0, pktlen = 0;
979     const char *str = NULL;
980     int pid;
981     int ret;
982     int i;
983     USBDevice *dev;
984     USBEndpoint *ep;
985     struct ohci_td td;
986     uint32_t addr;
987     int flag_r;
988     int completion;
989 
990     addr = ed->head & OHCI_DPTR_MASK;
991     /* See if this TD has already been submitted to the device.  */
992     completion = (addr == ohci->async_td);
993     if (completion && !ohci->async_complete) {
994         trace_usb_ohci_td_skip_async();
995         return 1;
996     }
997     if (ohci_read_td(ohci, addr, &td)) {
998         trace_usb_ohci_td_read_error(addr);
999         ohci_die(ohci);
1000         return 0;
1001     }
1002 
1003     dir = OHCI_BM(ed->flags, ED_D);
1004     switch (dir) {
1005     case OHCI_TD_DIR_OUT:
1006     case OHCI_TD_DIR_IN:
1007         /* Same value.  */
1008         break;
1009     default:
1010         dir = OHCI_BM(td.flags, TD_DP);
1011         break;
1012     }
1013 
1014     switch (dir) {
1015     case OHCI_TD_DIR_IN:
1016         str = "in";
1017         pid = USB_TOKEN_IN;
1018         break;
1019     case OHCI_TD_DIR_OUT:
1020         str = "out";
1021         pid = USB_TOKEN_OUT;
1022         break;
1023     case OHCI_TD_DIR_SETUP:
1024         str = "setup";
1025         pid = USB_TOKEN_SETUP;
1026         break;
1027     default:
1028         trace_usb_ohci_td_bad_direction(dir);
1029         return 1;
1030     }
1031     if (td.cbp && td.be) {
1032         if ((td.cbp & 0xfffff000) != (td.be & 0xfffff000)) {
1033             len = (td.be & 0xfff) + 0x1001 - (td.cbp & 0xfff);
1034         } else {
1035             len = (td.be - td.cbp) + 1;
1036         }
1037 
1038         pktlen = len;
1039         if (len && dir != OHCI_TD_DIR_IN) {
1040             /* The endpoint may not allow us to transfer it all now */
1041             pktlen = (ed->flags & OHCI_ED_MPS_MASK) >> OHCI_ED_MPS_SHIFT;
1042             if (pktlen > len) {
1043                 pktlen = len;
1044             }
1045             if (!completion) {
1046                 if (ohci_copy_td(ohci, &td, ohci->usb_buf, pktlen,
1047                                  DMA_DIRECTION_TO_DEVICE)) {
1048                     ohci_die(ohci);
1049                 }
1050             }
1051         }
1052     }
1053 
1054     flag_r = (td.flags & OHCI_TD_R) != 0;
1055     trace_usb_ohci_td_pkt_hdr(addr, (int64_t)pktlen, (int64_t)len, str,
1056                               flag_r, td.cbp, td.be);
1057     ohci_td_pkt("OUT", ohci->usb_buf, pktlen);
1058 
1059     if (completion) {
1060         ohci->async_td = 0;
1061         ohci->async_complete = false;
1062     } else {
1063         if (ohci->async_td) {
1064             /* ??? The hardware should allow one active packet per
1065                endpoint.  We only allow one active packet per controller.
1066                This should be sufficient as long as devices respond in a
1067                timely manner.
1068             */
1069             trace_usb_ohci_td_too_many_pending();
1070             return 1;
1071         }
1072         dev = ohci_find_device(ohci, OHCI_BM(ed->flags, ED_FA));
1073         ep = usb_ep_get(dev, pid, OHCI_BM(ed->flags, ED_EN));
1074         usb_packet_setup(&ohci->usb_packet, pid, ep, 0, addr, !flag_r,
1075                          OHCI_BM(td.flags, TD_DI) == 0);
1076         usb_packet_addbuf(&ohci->usb_packet, ohci->usb_buf, pktlen);
1077         usb_handle_packet(dev, &ohci->usb_packet);
1078         trace_usb_ohci_td_packet_status(ohci->usb_packet.status);
1079 
1080         if (ohci->usb_packet.status == USB_RET_ASYNC) {
1081             usb_device_flush_ep_queue(dev, ep);
1082             ohci->async_td = addr;
1083             return 1;
1084         }
1085     }
1086     if (ohci->usb_packet.status == USB_RET_SUCCESS) {
1087         ret = ohci->usb_packet.actual_length;
1088     } else {
1089         ret = ohci->usb_packet.status;
1090     }
1091 
1092     if (ret >= 0) {
1093         if (dir == OHCI_TD_DIR_IN) {
1094             if (ohci_copy_td(ohci, &td, ohci->usb_buf, ret,
1095                              DMA_DIRECTION_FROM_DEVICE)) {
1096                 ohci_die(ohci);
1097             }
1098             ohci_td_pkt("IN", ohci->usb_buf, pktlen);
1099         } else {
1100             ret = pktlen;
1101         }
1102     }
1103 
1104     /* Writeback */
1105     if (ret == pktlen || (dir == OHCI_TD_DIR_IN && ret >= 0 && flag_r)) {
1106         /* Transmission succeeded.  */
1107         if (ret == len) {
1108             td.cbp = 0;
1109         } else {
1110             if ((td.cbp & 0xfff) + ret > 0xfff) {
1111                 td.cbp = (td.be & ~0xfff) + ((td.cbp + ret) & 0xfff);
1112             } else {
1113                 td.cbp += ret;
1114             }
1115         }
1116         td.flags |= OHCI_TD_T1;
1117         td.flags ^= OHCI_TD_T0;
1118         OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_NOERROR);
1119         OHCI_SET_BM(td.flags, TD_EC, 0);
1120 
1121         if ((dir != OHCI_TD_DIR_IN) && (ret != len)) {
1122             /* Partial packet transfer: TD not ready to retire yet */
1123             goto exit_no_retire;
1124         }
1125 
1126         /* Setting ED_C is part of the TD retirement process */
1127         ed->head &= ~OHCI_ED_C;
1128         if (td.flags & OHCI_TD_T0)
1129             ed->head |= OHCI_ED_C;
1130     } else {
1131         if (ret >= 0) {
1132             trace_usb_ohci_td_underrun();
1133             OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAUNDERRUN);
1134         } else {
1135             switch (ret) {
1136             case USB_RET_IOERROR:
1137             case USB_RET_NODEV:
1138                 trace_usb_ohci_td_dev_error();
1139                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DEVICENOTRESPONDING);
1140                 break;
1141             case USB_RET_NAK:
1142                 trace_usb_ohci_td_nak();
1143                 return 1;
1144             case USB_RET_STALL:
1145                 trace_usb_ohci_td_stall();
1146                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_STALL);
1147                 break;
1148             case USB_RET_BABBLE:
1149                 trace_usb_ohci_td_babble();
1150                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_DATAOVERRUN);
1151                 break;
1152             default:
1153                 trace_usb_ohci_td_bad_device_response(ret);
1154                 OHCI_SET_BM(td.flags, TD_CC, OHCI_CC_UNDEXPETEDPID);
1155                 OHCI_SET_BM(td.flags, TD_EC, 3);
1156                 break;
1157             }
1158         }
1159         ed->head |= OHCI_ED_H;
1160     }
1161 
1162     /* Retire this TD */
1163     ed->head &= ~OHCI_DPTR_MASK;
1164     ed->head |= td.next & OHCI_DPTR_MASK;
1165     td.next = ohci->done;
1166     ohci->done = addr;
1167     i = OHCI_BM(td.flags, TD_DI);
1168     if (i < ohci->done_count)
1169         ohci->done_count = i;
1170 exit_no_retire:
1171     if (ohci_put_td(ohci, addr, &td)) {
1172         ohci_die(ohci);
1173         return 1;
1174     }
1175     return OHCI_BM(td.flags, TD_CC) != OHCI_CC_NOERROR;
1176 }
1177 
1178 /* Service an endpoint list.  Returns nonzero if active TD were found.  */
1179 static int ohci_service_ed_list(OHCIState *ohci, uint32_t head, int completion)
1180 {
1181     struct ohci_ed ed;
1182     uint32_t next_ed;
1183     uint32_t cur;
1184     int active;
1185 
1186     active = 0;
1187 
1188     if (head == 0)
1189         return 0;
1190 
1191     for (cur = head; cur; cur = next_ed) {
1192         if (ohci_read_ed(ohci, cur, &ed)) {
1193             trace_usb_ohci_ed_read_error(cur);
1194             ohci_die(ohci);
1195             return 0;
1196         }
1197 
1198         next_ed = ed.next & OHCI_DPTR_MASK;
1199 
1200         if ((ed.head & OHCI_ED_H) || (ed.flags & OHCI_ED_K)) {
1201             uint32_t addr;
1202             /* Cancel pending packets for ED that have been paused.  */
1203             addr = ed.head & OHCI_DPTR_MASK;
1204             if (ohci->async_td && addr == ohci->async_td) {
1205                 usb_cancel_packet(&ohci->usb_packet);
1206                 ohci->async_td = 0;
1207                 usb_device_ep_stopped(ohci->usb_packet.ep->dev,
1208                                       ohci->usb_packet.ep);
1209             }
1210             continue;
1211         }
1212 
1213         while ((ed.head & OHCI_DPTR_MASK) != ed.tail) {
1214             trace_usb_ohci_ed_pkt(cur, (ed.head & OHCI_ED_H) != 0,
1215                     (ed.head & OHCI_ED_C) != 0, ed.head & OHCI_DPTR_MASK,
1216                     ed.tail & OHCI_DPTR_MASK, ed.next & OHCI_DPTR_MASK);
1217             trace_usb_ohci_ed_pkt_flags(
1218                     OHCI_BM(ed.flags, ED_FA), OHCI_BM(ed.flags, ED_EN),
1219                     OHCI_BM(ed.flags, ED_D), (ed.flags & OHCI_ED_S)!= 0,
1220                     (ed.flags & OHCI_ED_K) != 0, (ed.flags & OHCI_ED_F) != 0,
1221                     OHCI_BM(ed.flags, ED_MPS));
1222 
1223             active = 1;
1224 
1225             if ((ed.flags & OHCI_ED_F) == 0) {
1226                 if (ohci_service_td(ohci, &ed))
1227                     break;
1228             } else {
1229                 /* Handle isochronous endpoints */
1230                 if (ohci_service_iso_td(ohci, &ed, completion))
1231                     break;
1232             }
1233         }
1234 
1235         if (ohci_put_ed(ohci, cur, &ed)) {
1236             ohci_die(ohci);
1237             return 0;
1238         }
1239     }
1240 
1241     return active;
1242 }
1243 
1244 /* set a timer for EOF */
1245 static void ohci_eof_timer(OHCIState *ohci)
1246 {
1247     ohci->sof_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1248     timer_mod(ohci->eof_timer, ohci->sof_time + usb_frame_time);
1249 }
1250 /* Set a timer for EOF and generate a SOF event */
1251 static void ohci_sof(OHCIState *ohci)
1252 {
1253     ohci_eof_timer(ohci);
1254     ohci_set_interrupt(ohci, OHCI_INTR_SF);
1255 }
1256 
1257 /* Process Control and Bulk lists.  */
1258 static void ohci_process_lists(OHCIState *ohci, int completion)
1259 {
1260     if ((ohci->ctl & OHCI_CTL_CLE) && (ohci->status & OHCI_STATUS_CLF)) {
1261         if (ohci->ctrl_cur && ohci->ctrl_cur != ohci->ctrl_head) {
1262             trace_usb_ohci_process_lists(ohci->ctrl_head, ohci->ctrl_cur);
1263         }
1264         if (!ohci_service_ed_list(ohci, ohci->ctrl_head, completion)) {
1265             ohci->ctrl_cur = 0;
1266             ohci->status &= ~OHCI_STATUS_CLF;
1267         }
1268     }
1269 
1270     if ((ohci->ctl & OHCI_CTL_BLE) && (ohci->status & OHCI_STATUS_BLF)) {
1271         if (!ohci_service_ed_list(ohci, ohci->bulk_head, completion)) {
1272             ohci->bulk_cur = 0;
1273             ohci->status &= ~OHCI_STATUS_BLF;
1274         }
1275     }
1276 }
1277 
1278 /* Do frame processing on frame boundary */
1279 static void ohci_frame_boundary(void *opaque)
1280 {
1281     OHCIState *ohci = opaque;
1282     struct ohci_hcca hcca;
1283 
1284     if (ohci_read_hcca(ohci, ohci->hcca, &hcca)) {
1285         trace_usb_ohci_hcca_read_error(ohci->hcca);
1286         ohci_die(ohci);
1287         return;
1288     }
1289 
1290     /* Process all the lists at the end of the frame */
1291     if (ohci->ctl & OHCI_CTL_PLE) {
1292         int n;
1293 
1294         n = ohci->frame_number & 0x1f;
1295         ohci_service_ed_list(ohci, le32_to_cpu(hcca.intr[n]), 0);
1296     }
1297 
1298     /* Cancel all pending packets if either of the lists has been disabled.  */
1299     if (ohci->old_ctl & (~ohci->ctl) & (OHCI_CTL_BLE | OHCI_CTL_CLE)) {
1300         if (ohci->async_td) {
1301             usb_cancel_packet(&ohci->usb_packet);
1302             ohci->async_td = 0;
1303         }
1304         ohci_stop_endpoints(ohci);
1305     }
1306     ohci->old_ctl = ohci->ctl;
1307     ohci_process_lists(ohci, 0);
1308 
1309     /* Stop if UnrecoverableError happened or ohci_sof will crash */
1310     if (ohci->intr_status & OHCI_INTR_UE) {
1311         return;
1312     }
1313 
1314     /* Frame boundary, so do EOF stuf here */
1315     ohci->frt = ohci->fit;
1316 
1317     /* Increment frame number and take care of endianness. */
1318     ohci->frame_number = (ohci->frame_number + 1) & 0xffff;
1319     hcca.frame = cpu_to_le16(ohci->frame_number);
1320 
1321     if (ohci->done_count == 0 && !(ohci->intr_status & OHCI_INTR_WD)) {
1322         if (!ohci->done)
1323             abort();
1324         if (ohci->intr & ohci->intr_status)
1325             ohci->done |= 1;
1326         hcca.done = cpu_to_le32(ohci->done);
1327         ohci->done = 0;
1328         ohci->done_count = 7;
1329         ohci_set_interrupt(ohci, OHCI_INTR_WD);
1330     }
1331 
1332     if (ohci->done_count != 7 && ohci->done_count != 0)
1333         ohci->done_count--;
1334 
1335     /* Do SOF stuff here */
1336     ohci_sof(ohci);
1337 
1338     /* Writeback HCCA */
1339     if (ohci_put_hcca(ohci, ohci->hcca, &hcca)) {
1340         ohci_die(ohci);
1341     }
1342 }
1343 
1344 /* Start sending SOF tokens across the USB bus, lists are processed in
1345  * next frame
1346  */
1347 static int ohci_bus_start(OHCIState *ohci)
1348 {
1349     ohci->eof_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
1350                     ohci_frame_boundary,
1351                     ohci);
1352 
1353     if (ohci->eof_timer == NULL) {
1354         trace_usb_ohci_bus_eof_timer_failed(ohci->name);
1355         ohci_die(ohci);
1356         return 0;
1357     }
1358 
1359     trace_usb_ohci_start(ohci->name);
1360 
1361     /* Delay the first SOF event by one frame time as
1362      * linux driver is not ready to receive it and
1363      * can meet some race conditions
1364      */
1365 
1366     ohci_eof_timer(ohci);
1367 
1368     return 1;
1369 }
1370 
1371 /* Stop sending SOF tokens on the bus */
1372 static void ohci_bus_stop(OHCIState *ohci)
1373 {
1374     trace_usb_ohci_stop(ohci->name);
1375     if (ohci->eof_timer) {
1376         timer_del(ohci->eof_timer);
1377         timer_free(ohci->eof_timer);
1378     }
1379     ohci->eof_timer = NULL;
1380 }
1381 
1382 /* Sets a flag in a port status register but only set it if the port is
1383  * connected, if not set ConnectStatusChange flag. If flag is enabled
1384  * return 1.
1385  */
1386 static int ohci_port_set_if_connected(OHCIState *ohci, int i, uint32_t val)
1387 {
1388     int ret = 1;
1389 
1390     /* writing a 0 has no effect */
1391     if (val == 0)
1392         return 0;
1393 
1394     /* If CurrentConnectStatus is cleared we set
1395      * ConnectStatusChange
1396      */
1397     if (!(ohci->rhport[i].ctrl & OHCI_PORT_CCS)) {
1398         ohci->rhport[i].ctrl |= OHCI_PORT_CSC;
1399         if (ohci->rhstatus & OHCI_RHS_DRWE) {
1400             /* TODO: CSC is a wakeup event */
1401         }
1402         return 0;
1403     }
1404 
1405     if (ohci->rhport[i].ctrl & val)
1406         ret = 0;
1407 
1408     /* set the bit */
1409     ohci->rhport[i].ctrl |= val;
1410 
1411     return ret;
1412 }
1413 
1414 /* Set the frame interval - frame interval toggle is manipulated by the hcd only */
1415 static void ohci_set_frame_interval(OHCIState *ohci, uint16_t val)
1416 {
1417     val &= OHCI_FMI_FI;
1418 
1419     if (val != ohci->fi) {
1420         trace_usb_ohci_set_frame_interval(ohci->name, ohci->fi, ohci->fi);
1421     }
1422 
1423     ohci->fi = val;
1424 }
1425 
1426 static void ohci_port_power(OHCIState *ohci, int i, int p)
1427 {
1428     if (p) {
1429         ohci->rhport[i].ctrl |= OHCI_PORT_PPS;
1430     } else {
1431         ohci->rhport[i].ctrl &= ~(OHCI_PORT_PPS|
1432                     OHCI_PORT_CCS|
1433                     OHCI_PORT_PSS|
1434                     OHCI_PORT_PRS);
1435     }
1436 }
1437 
1438 /* Set HcControlRegister */
1439 static void ohci_set_ctl(OHCIState *ohci, uint32_t val)
1440 {
1441     uint32_t old_state;
1442     uint32_t new_state;
1443 
1444     old_state = ohci->ctl & OHCI_CTL_HCFS;
1445     ohci->ctl = val;
1446     new_state = ohci->ctl & OHCI_CTL_HCFS;
1447 
1448     /* no state change */
1449     if (old_state == new_state)
1450         return;
1451 
1452     trace_usb_ohci_set_ctl(ohci->name, new_state);
1453     switch (new_state) {
1454     case OHCI_USB_OPERATIONAL:
1455         ohci_bus_start(ohci);
1456         break;
1457     case OHCI_USB_SUSPEND:
1458         ohci_bus_stop(ohci);
1459         /* clear pending SF otherwise linux driver loops in ohci_irq() */
1460         ohci->intr_status &= ~OHCI_INTR_SF;
1461         ohci_intr_update(ohci);
1462         break;
1463     case OHCI_USB_RESUME:
1464         trace_usb_ohci_resume(ohci->name);
1465         break;
1466     case OHCI_USB_RESET:
1467         ohci_roothub_reset(ohci);
1468         break;
1469     }
1470 }
1471 
1472 static uint32_t ohci_get_frame_remaining(OHCIState *ohci)
1473 {
1474     uint16_t fr;
1475     int64_t tks;
1476 
1477     if ((ohci->ctl & OHCI_CTL_HCFS) != OHCI_USB_OPERATIONAL)
1478         return (ohci->frt << 31);
1479 
1480     /* Being in USB operational state guarnatees sof_time was
1481      * set already.
1482      */
1483     tks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) - ohci->sof_time;
1484 
1485     /* avoid muldiv if possible */
1486     if (tks >= usb_frame_time)
1487         return (ohci->frt << 31);
1488 
1489     tks = muldiv64(1, tks, usb_bit_time);
1490     fr = (uint16_t)(ohci->fi - tks);
1491 
1492     return (ohci->frt << 31) | fr;
1493 }
1494 
1495 
1496 /* Set root hub status */
1497 static void ohci_set_hub_status(OHCIState *ohci, uint32_t val)
1498 {
1499     uint32_t old_state;
1500 
1501     old_state = ohci->rhstatus;
1502 
1503     /* write 1 to clear OCIC */
1504     if (val & OHCI_RHS_OCIC)
1505         ohci->rhstatus &= ~OHCI_RHS_OCIC;
1506 
1507     if (val & OHCI_RHS_LPS) {
1508         int i;
1509 
1510         for (i = 0; i < ohci->num_ports; i++)
1511             ohci_port_power(ohci, i, 0);
1512         trace_usb_ohci_hub_power_down();
1513     }
1514 
1515     if (val & OHCI_RHS_LPSC) {
1516         int i;
1517 
1518         for (i = 0; i < ohci->num_ports; i++)
1519             ohci_port_power(ohci, i, 1);
1520         trace_usb_ohci_hub_power_up();
1521     }
1522 
1523     if (val & OHCI_RHS_DRWE)
1524         ohci->rhstatus |= OHCI_RHS_DRWE;
1525 
1526     if (val & OHCI_RHS_CRWE)
1527         ohci->rhstatus &= ~OHCI_RHS_DRWE;
1528 
1529     if (old_state != ohci->rhstatus)
1530         ohci_set_interrupt(ohci, OHCI_INTR_RHSC);
1531 }
1532 
1533 /* Set root hub port status */
1534 static void ohci_port_set_status(OHCIState *ohci, int portnum, uint32_t val)
1535 {
1536     uint32_t old_state;
1537     OHCIPort *port;
1538 
1539     port = &ohci->rhport[portnum];
1540     old_state = port->ctrl;
1541 
1542     /* Write to clear CSC, PESC, PSSC, OCIC, PRSC */
1543     if (val & OHCI_PORT_WTC)
1544         port->ctrl &= ~(val & OHCI_PORT_WTC);
1545 
1546     if (val & OHCI_PORT_CCS)
1547         port->ctrl &= ~OHCI_PORT_PES;
1548 
1549     ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PES);
1550 
1551     if (ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PSS)) {
1552         trace_usb_ohci_port_suspend(portnum);
1553     }
1554 
1555     if (ohci_port_set_if_connected(ohci, portnum, val & OHCI_PORT_PRS)) {
1556         trace_usb_ohci_port_reset(portnum);
1557         usb_device_reset(port->port.dev);
1558         port->ctrl &= ~OHCI_PORT_PRS;
1559         /* ??? Should this also set OHCI_PORT_PESC.  */
1560         port->ctrl |= OHCI_PORT_PES | OHCI_PORT_PRSC;
1561     }
1562 
1563     /* Invert order here to ensure in ambiguous case, device is
1564      * powered up...
1565      */
1566     if (val & OHCI_PORT_LSDA)
1567         ohci_port_power(ohci, portnum, 0);
1568     if (val & OHCI_PORT_PPS)
1569         ohci_port_power(ohci, portnum, 1);
1570 
1571     if (old_state != port->ctrl)
1572         ohci_set_interrupt(ohci, OHCI_INTR_RHSC);
1573 }
1574 
1575 static uint64_t ohci_mem_read(void *opaque,
1576                               hwaddr addr,
1577                               unsigned size)
1578 {
1579     OHCIState *ohci = opaque;
1580     uint32_t retval;
1581 
1582     /* Only aligned reads are allowed on OHCI */
1583     if (addr & 3) {
1584         trace_usb_ohci_mem_read_unaligned(addr);
1585         return 0xffffffff;
1586     } else if (addr >= 0x54 && addr < 0x54 + ohci->num_ports * 4) {
1587         /* HcRhPortStatus */
1588         retval = ohci->rhport[(addr - 0x54) >> 2].ctrl | OHCI_PORT_PPS;
1589     } else {
1590         switch (addr >> 2) {
1591         case 0: /* HcRevision */
1592             retval = 0x10;
1593             break;
1594 
1595         case 1: /* HcControl */
1596             retval = ohci->ctl;
1597             break;
1598 
1599         case 2: /* HcCommandStatus */
1600             retval = ohci->status;
1601             break;
1602 
1603         case 3: /* HcInterruptStatus */
1604             retval = ohci->intr_status;
1605             break;
1606 
1607         case 4: /* HcInterruptEnable */
1608         case 5: /* HcInterruptDisable */
1609             retval = ohci->intr;
1610             break;
1611 
1612         case 6: /* HcHCCA */
1613             retval = ohci->hcca;
1614             break;
1615 
1616         case 7: /* HcPeriodCurrentED */
1617             retval = ohci->per_cur;
1618             break;
1619 
1620         case 8: /* HcControlHeadED */
1621             retval = ohci->ctrl_head;
1622             break;
1623 
1624         case 9: /* HcControlCurrentED */
1625             retval = ohci->ctrl_cur;
1626             break;
1627 
1628         case 10: /* HcBulkHeadED */
1629             retval = ohci->bulk_head;
1630             break;
1631 
1632         case 11: /* HcBulkCurrentED */
1633             retval = ohci->bulk_cur;
1634             break;
1635 
1636         case 12: /* HcDoneHead */
1637             retval = ohci->done;
1638             break;
1639 
1640         case 13: /* HcFmInterretval */
1641             retval = (ohci->fit << 31) | (ohci->fsmps << 16) | (ohci->fi);
1642             break;
1643 
1644         case 14: /* HcFmRemaining */
1645             retval = ohci_get_frame_remaining(ohci);
1646             break;
1647 
1648         case 15: /* HcFmNumber */
1649             retval = ohci->frame_number;
1650             break;
1651 
1652         case 16: /* HcPeriodicStart */
1653             retval = ohci->pstart;
1654             break;
1655 
1656         case 17: /* HcLSThreshold */
1657             retval = ohci->lst;
1658             break;
1659 
1660         case 18: /* HcRhDescriptorA */
1661             retval = ohci->rhdesc_a;
1662             break;
1663 
1664         case 19: /* HcRhDescriptorB */
1665             retval = ohci->rhdesc_b;
1666             break;
1667 
1668         case 20: /* HcRhStatus */
1669             retval = ohci->rhstatus;
1670             break;
1671 
1672         /* PXA27x specific registers */
1673         case 24: /* HcStatus */
1674             retval = ohci->hstatus & ohci->hmask;
1675             break;
1676 
1677         case 25: /* HcHReset */
1678             retval = ohci->hreset;
1679             break;
1680 
1681         case 26: /* HcHInterruptEnable */
1682             retval = ohci->hmask;
1683             break;
1684 
1685         case 27: /* HcHInterruptTest */
1686             retval = ohci->htest;
1687             break;
1688 
1689         default:
1690             trace_usb_ohci_mem_read_bad_offset(addr);
1691             retval = 0xffffffff;
1692         }
1693     }
1694 
1695     return retval;
1696 }
1697 
1698 static void ohci_mem_write(void *opaque,
1699                            hwaddr addr,
1700                            uint64_t val,
1701                            unsigned size)
1702 {
1703     OHCIState *ohci = opaque;
1704 
1705     /* Only aligned reads are allowed on OHCI */
1706     if (addr & 3) {
1707         trace_usb_ohci_mem_write_unaligned(addr);
1708         return;
1709     }
1710 
1711     if (addr >= 0x54 && addr < 0x54 + ohci->num_ports * 4) {
1712         /* HcRhPortStatus */
1713         ohci_port_set_status(ohci, (addr - 0x54) >> 2, val);
1714         return;
1715     }
1716 
1717     switch (addr >> 2) {
1718     case 1: /* HcControl */
1719         ohci_set_ctl(ohci, val);
1720         break;
1721 
1722     case 2: /* HcCommandStatus */
1723         /* SOC is read-only */
1724         val = (val & ~OHCI_STATUS_SOC);
1725 
1726         /* Bits written as '0' remain unchanged in the register */
1727         ohci->status |= val;
1728 
1729         if (ohci->status & OHCI_STATUS_HCR)
1730             ohci_soft_reset(ohci);
1731         break;
1732 
1733     case 3: /* HcInterruptStatus */
1734         ohci->intr_status &= ~val;
1735         ohci_intr_update(ohci);
1736         break;
1737 
1738     case 4: /* HcInterruptEnable */
1739         ohci->intr |= val;
1740         ohci_intr_update(ohci);
1741         break;
1742 
1743     case 5: /* HcInterruptDisable */
1744         ohci->intr &= ~val;
1745         ohci_intr_update(ohci);
1746         break;
1747 
1748     case 6: /* HcHCCA */
1749         ohci->hcca = val & OHCI_HCCA_MASK;
1750         break;
1751 
1752     case 7: /* HcPeriodCurrentED */
1753         /* Ignore writes to this read-only register, Linux does them */
1754         break;
1755 
1756     case 8: /* HcControlHeadED */
1757         ohci->ctrl_head = val & OHCI_EDPTR_MASK;
1758         break;
1759 
1760     case 9: /* HcControlCurrentED */
1761         ohci->ctrl_cur = val & OHCI_EDPTR_MASK;
1762         break;
1763 
1764     case 10: /* HcBulkHeadED */
1765         ohci->bulk_head = val & OHCI_EDPTR_MASK;
1766         break;
1767 
1768     case 11: /* HcBulkCurrentED */
1769         ohci->bulk_cur = val & OHCI_EDPTR_MASK;
1770         break;
1771 
1772     case 13: /* HcFmInterval */
1773         ohci->fsmps = (val & OHCI_FMI_FSMPS) >> 16;
1774         ohci->fit = (val & OHCI_FMI_FIT) >> 31;
1775         ohci_set_frame_interval(ohci, val);
1776         break;
1777 
1778     case 15: /* HcFmNumber */
1779         break;
1780 
1781     case 16: /* HcPeriodicStart */
1782         ohci->pstart = val & 0xffff;
1783         break;
1784 
1785     case 17: /* HcLSThreshold */
1786         ohci->lst = val & 0xffff;
1787         break;
1788 
1789     case 18: /* HcRhDescriptorA */
1790         ohci->rhdesc_a &= ~OHCI_RHA_RW_MASK;
1791         ohci->rhdesc_a |= val & OHCI_RHA_RW_MASK;
1792         break;
1793 
1794     case 19: /* HcRhDescriptorB */
1795         break;
1796 
1797     case 20: /* HcRhStatus */
1798         ohci_set_hub_status(ohci, val);
1799         break;
1800 
1801     /* PXA27x specific registers */
1802     case 24: /* HcStatus */
1803         ohci->hstatus &= ~(val & ohci->hmask);
1804         break;
1805 
1806     case 25: /* HcHReset */
1807         ohci->hreset = val & ~OHCI_HRESET_FSBIR;
1808         if (val & OHCI_HRESET_FSBIR)
1809             ohci_hard_reset(ohci);
1810         break;
1811 
1812     case 26: /* HcHInterruptEnable */
1813         ohci->hmask = val;
1814         break;
1815 
1816     case 27: /* HcHInterruptTest */
1817         ohci->htest = val;
1818         break;
1819 
1820     default:
1821         trace_usb_ohci_mem_write_bad_offset(addr);
1822         break;
1823     }
1824 }
1825 
1826 static void ohci_async_cancel_device(OHCIState *ohci, USBDevice *dev)
1827 {
1828     if (ohci->async_td &&
1829         usb_packet_is_inflight(&ohci->usb_packet) &&
1830         ohci->usb_packet.ep->dev == dev) {
1831         usb_cancel_packet(&ohci->usb_packet);
1832         ohci->async_td = 0;
1833     }
1834 }
1835 
1836 static const MemoryRegionOps ohci_mem_ops = {
1837     .read = ohci_mem_read,
1838     .write = ohci_mem_write,
1839     .endianness = DEVICE_LITTLE_ENDIAN,
1840 };
1841 
1842 static USBPortOps ohci_port_ops = {
1843     .attach = ohci_attach,
1844     .detach = ohci_detach,
1845     .child_detach = ohci_child_detach,
1846     .wakeup = ohci_wakeup,
1847     .complete = ohci_async_complete_packet,
1848 };
1849 
1850 static USBBusOps ohci_bus_ops = {
1851 };
1852 
1853 static void usb_ohci_init(OHCIState *ohci, DeviceState *dev,
1854                           int num_ports, dma_addr_t localmem_base,
1855                           char *masterbus, uint32_t firstport,
1856                           AddressSpace *as, Error **errp)
1857 {
1858     Error *err = NULL;
1859     int i;
1860 
1861     ohci->as = as;
1862 
1863     if (usb_frame_time == 0) {
1864 #ifdef OHCI_TIME_WARP
1865         usb_frame_time = get_ticks_per_sec();
1866         usb_bit_time = muldiv64(1, get_ticks_per_sec(), USB_HZ/1000);
1867 #else
1868         usb_frame_time = muldiv64(1, get_ticks_per_sec(), 1000);
1869         if (get_ticks_per_sec() >= USB_HZ) {
1870             usb_bit_time = muldiv64(1, get_ticks_per_sec(), USB_HZ);
1871         } else {
1872             usb_bit_time = 1;
1873         }
1874 #endif
1875         trace_usb_ohci_init_time(usb_frame_time, usb_bit_time);
1876     }
1877 
1878     ohci->num_ports = num_ports;
1879     if (masterbus) {
1880         USBPort *ports[OHCI_MAX_PORTS];
1881         for(i = 0; i < num_ports; i++) {
1882             ports[i] = &ohci->rhport[i].port;
1883         }
1884         usb_register_companion(masterbus, ports, num_ports,
1885                                firstport, ohci, &ohci_port_ops,
1886                                USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL,
1887                                &err);
1888         if (err) {
1889             error_propagate(errp, err);
1890             return;
1891         }
1892     } else {
1893         usb_bus_new(&ohci->bus, sizeof(ohci->bus), &ohci_bus_ops, dev);
1894         for (i = 0; i < num_ports; i++) {
1895             usb_register_port(&ohci->bus, &ohci->rhport[i].port,
1896                               ohci, i, &ohci_port_ops,
1897                               USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL);
1898         }
1899     }
1900 
1901     memory_region_init_io(&ohci->mem, OBJECT(dev), &ohci_mem_ops,
1902                           ohci, "ohci", 256);
1903     ohci->localmem_base = localmem_base;
1904 
1905     ohci->name = object_get_typename(OBJECT(dev));
1906     usb_packet_init(&ohci->usb_packet);
1907 
1908     ohci->async_td = 0;
1909 }
1910 
1911 #define TYPE_PCI_OHCI "pci-ohci"
1912 #define PCI_OHCI(obj) OBJECT_CHECK(OHCIPCIState, (obj), TYPE_PCI_OHCI)
1913 
1914 typedef struct {
1915     /*< private >*/
1916     PCIDevice parent_obj;
1917     /*< public >*/
1918 
1919     OHCIState state;
1920     char *masterbus;
1921     uint32_t num_ports;
1922     uint32_t firstport;
1923 } OHCIPCIState;
1924 
1925 /** A typical O/EHCI will stop operating, set itself into error state
1926  * (which can be queried by MMIO) and will set PERR in its config
1927  * space to signal that it got an error
1928  */
1929 static void ohci_die(OHCIState *ohci)
1930 {
1931     OHCIPCIState *dev = container_of(ohci, OHCIPCIState, state);
1932 
1933     trace_usb_ohci_die();
1934 
1935     ohci_set_interrupt(ohci, OHCI_INTR_UE);
1936     ohci_bus_stop(ohci);
1937     pci_set_word(dev->parent_obj.config + PCI_STATUS,
1938                  PCI_STATUS_DETECTED_PARITY);
1939 }
1940 
1941 static void usb_ohci_realize_pci(PCIDevice *dev, Error **errp)
1942 {
1943     Error *err = NULL;
1944     OHCIPCIState *ohci = PCI_OHCI(dev);
1945 
1946     dev->config[PCI_CLASS_PROG] = 0x10; /* OHCI */
1947     dev->config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin A */
1948 
1949     usb_ohci_init(&ohci->state, DEVICE(dev), ohci->num_ports, 0,
1950                   ohci->masterbus, ohci->firstport,
1951                   pci_get_address_space(dev), &err);
1952     if (err) {
1953         error_propagate(errp, err);
1954         return;
1955     }
1956 
1957     ohci->state.irq = pci_allocate_irq(dev);
1958     pci_register_bar(dev, 0, 0, &ohci->state.mem);
1959 }
1960 
1961 static void usb_ohci_exit(PCIDevice *dev)
1962 {
1963     OHCIPCIState *ohci = PCI_OHCI(dev);
1964     OHCIState *s = &ohci->state;
1965 
1966     trace_usb_ohci_exit(s->name);
1967     ohci_bus_stop(s);
1968 
1969     if (s->async_td) {
1970         usb_cancel_packet(&s->usb_packet);
1971         s->async_td = 0;
1972     }
1973     ohci_stop_endpoints(s);
1974 
1975     if (!ohci->masterbus) {
1976         usb_bus_release(&s->bus);
1977     }
1978 }
1979 
1980 static void usb_ohci_reset_pci(DeviceState *d)
1981 {
1982     PCIDevice *dev = PCI_DEVICE(d);
1983     OHCIPCIState *ohci = PCI_OHCI(dev);
1984     OHCIState *s = &ohci->state;
1985 
1986     ohci_hard_reset(s);
1987 }
1988 
1989 #define TYPE_SYSBUS_OHCI "sysbus-ohci"
1990 #define SYSBUS_OHCI(obj) OBJECT_CHECK(OHCISysBusState, (obj), TYPE_SYSBUS_OHCI)
1991 
1992 typedef struct {
1993     /*< private >*/
1994     SysBusDevice parent_obj;
1995     /*< public >*/
1996 
1997     OHCIState ohci;
1998     uint32_t num_ports;
1999     dma_addr_t dma_offset;
2000 } OHCISysBusState;
2001 
2002 static void ohci_realize_pxa(DeviceState *dev, Error **errp)
2003 {
2004     OHCISysBusState *s = SYSBUS_OHCI(dev);
2005     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
2006 
2007     /* Cannot fail as we pass NULL for masterbus */
2008     usb_ohci_init(&s->ohci, dev, s->num_ports, s->dma_offset, NULL, 0,
2009                   &address_space_memory, &error_abort);
2010     sysbus_init_irq(sbd, &s->ohci.irq);
2011     sysbus_init_mmio(sbd, &s->ohci.mem);
2012 }
2013 
2014 static void usb_ohci_reset_sysbus(DeviceState *dev)
2015 {
2016     OHCISysBusState *s = SYSBUS_OHCI(dev);
2017     OHCIState *ohci = &s->ohci;
2018 
2019     ohci_hard_reset(ohci);
2020 }
2021 
2022 static Property ohci_pci_properties[] = {
2023     DEFINE_PROP_STRING("masterbus", OHCIPCIState, masterbus),
2024     DEFINE_PROP_UINT32("num-ports", OHCIPCIState, num_ports, 3),
2025     DEFINE_PROP_UINT32("firstport", OHCIPCIState, firstport, 0),
2026     DEFINE_PROP_END_OF_LIST(),
2027 };
2028 
2029 static const VMStateDescription vmstate_ohci_state_port = {
2030     .name = "ohci-core/port",
2031     .version_id = 1,
2032     .minimum_version_id = 1,
2033     .fields = (VMStateField[]) {
2034         VMSTATE_UINT32(ctrl, OHCIPort),
2035         VMSTATE_END_OF_LIST()
2036     },
2037 };
2038 
2039 static bool ohci_eof_timer_needed(void *opaque)
2040 {
2041     OHCIState *ohci = opaque;
2042 
2043     return ohci->eof_timer != NULL;
2044 }
2045 
2046 static int ohci_eof_timer_pre_load(void *opaque)
2047 {
2048     OHCIState *ohci = opaque;
2049 
2050     ohci_bus_start(ohci);
2051 
2052     return 0;
2053 }
2054 
2055 static const VMStateDescription vmstate_ohci_eof_timer = {
2056     .name = "ohci-core/eof-timer",
2057     .version_id = 1,
2058     .minimum_version_id = 1,
2059     .pre_load = ohci_eof_timer_pre_load,
2060     .needed = ohci_eof_timer_needed,
2061     .fields = (VMStateField[]) {
2062         VMSTATE_TIMER_PTR(eof_timer, OHCIState),
2063         VMSTATE_END_OF_LIST()
2064     },
2065 };
2066 
2067 static const VMStateDescription vmstate_ohci_state = {
2068     .name = "ohci-core",
2069     .version_id = 1,
2070     .minimum_version_id = 1,
2071     .fields = (VMStateField[]) {
2072         VMSTATE_INT64(sof_time, OHCIState),
2073         VMSTATE_UINT32(ctl, OHCIState),
2074         VMSTATE_UINT32(status, OHCIState),
2075         VMSTATE_UINT32(intr_status, OHCIState),
2076         VMSTATE_UINT32(intr, OHCIState),
2077         VMSTATE_UINT32(hcca, OHCIState),
2078         VMSTATE_UINT32(ctrl_head, OHCIState),
2079         VMSTATE_UINT32(ctrl_cur, OHCIState),
2080         VMSTATE_UINT32(bulk_head, OHCIState),
2081         VMSTATE_UINT32(bulk_cur, OHCIState),
2082         VMSTATE_UINT32(per_cur, OHCIState),
2083         VMSTATE_UINT32(done, OHCIState),
2084         VMSTATE_INT32(done_count, OHCIState),
2085         VMSTATE_UINT16(fsmps, OHCIState),
2086         VMSTATE_UINT8(fit, OHCIState),
2087         VMSTATE_UINT16(fi, OHCIState),
2088         VMSTATE_UINT8(frt, OHCIState),
2089         VMSTATE_UINT16(frame_number, OHCIState),
2090         VMSTATE_UINT16(padding, OHCIState),
2091         VMSTATE_UINT32(pstart, OHCIState),
2092         VMSTATE_UINT32(lst, OHCIState),
2093         VMSTATE_UINT32(rhdesc_a, OHCIState),
2094         VMSTATE_UINT32(rhdesc_b, OHCIState),
2095         VMSTATE_UINT32(rhstatus, OHCIState),
2096         VMSTATE_STRUCT_ARRAY(rhport, OHCIState, OHCI_MAX_PORTS, 0,
2097                              vmstate_ohci_state_port, OHCIPort),
2098         VMSTATE_UINT32(hstatus, OHCIState),
2099         VMSTATE_UINT32(hmask, OHCIState),
2100         VMSTATE_UINT32(hreset, OHCIState),
2101         VMSTATE_UINT32(htest, OHCIState),
2102         VMSTATE_UINT32(old_ctl, OHCIState),
2103         VMSTATE_UINT8_ARRAY(usb_buf, OHCIState, 8192),
2104         VMSTATE_UINT32(async_td, OHCIState),
2105         VMSTATE_BOOL(async_complete, OHCIState),
2106         VMSTATE_END_OF_LIST()
2107     },
2108     .subsections = (const VMStateDescription*[]) {
2109         &vmstate_ohci_eof_timer,
2110         NULL
2111     }
2112 };
2113 
2114 static const VMStateDescription vmstate_ohci = {
2115     .name = "ohci",
2116     .version_id = 1,
2117     .minimum_version_id = 1,
2118     .fields = (VMStateField[]) {
2119         VMSTATE_PCI_DEVICE(parent_obj, OHCIPCIState),
2120         VMSTATE_STRUCT(state, OHCIPCIState, 1, vmstate_ohci_state, OHCIState),
2121         VMSTATE_END_OF_LIST()
2122     }
2123 };
2124 
2125 static void ohci_pci_class_init(ObjectClass *klass, void *data)
2126 {
2127     DeviceClass *dc = DEVICE_CLASS(klass);
2128     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
2129 
2130     k->realize = usb_ohci_realize_pci;
2131     k->exit = usb_ohci_exit;
2132     k->vendor_id = PCI_VENDOR_ID_APPLE;
2133     k->device_id = PCI_DEVICE_ID_APPLE_IPID_USB;
2134     k->class_id = PCI_CLASS_SERIAL_USB;
2135     set_bit(DEVICE_CATEGORY_USB, dc->categories);
2136     dc->desc = "Apple USB Controller";
2137     dc->props = ohci_pci_properties;
2138     dc->hotpluggable = false;
2139     dc->vmsd = &vmstate_ohci;
2140     dc->reset = usb_ohci_reset_pci;
2141 }
2142 
2143 static const TypeInfo ohci_pci_info = {
2144     .name          = TYPE_PCI_OHCI,
2145     .parent        = TYPE_PCI_DEVICE,
2146     .instance_size = sizeof(OHCIPCIState),
2147     .class_init    = ohci_pci_class_init,
2148 };
2149 
2150 static Property ohci_sysbus_properties[] = {
2151     DEFINE_PROP_UINT32("num-ports", OHCISysBusState, num_ports, 3),
2152     DEFINE_PROP_DMAADDR("dma-offset", OHCISysBusState, dma_offset, 3),
2153     DEFINE_PROP_END_OF_LIST(),
2154 };
2155 
2156 static void ohci_sysbus_class_init(ObjectClass *klass, void *data)
2157 {
2158     DeviceClass *dc = DEVICE_CLASS(klass);
2159 
2160     dc->realize = ohci_realize_pxa;
2161     set_bit(DEVICE_CATEGORY_USB, dc->categories);
2162     dc->desc = "OHCI USB Controller";
2163     dc->props = ohci_sysbus_properties;
2164     dc->reset = usb_ohci_reset_sysbus;
2165 }
2166 
2167 static const TypeInfo ohci_sysbus_info = {
2168     .name          = TYPE_SYSBUS_OHCI,
2169     .parent        = TYPE_SYS_BUS_DEVICE,
2170     .instance_size = sizeof(OHCISysBusState),
2171     .class_init    = ohci_sysbus_class_init,
2172 };
2173 
2174 static void ohci_register_types(void)
2175 {
2176     type_register_static(&ohci_pci_info);
2177     type_register_static(&ohci_sysbus_info);
2178 }
2179 
2180 type_init(ohci_register_types)
2181