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