5fe25ce1f4e8de5bd721e1270ec155c88d0af7d4
[qemu] / hw / usb-musb.c
1 /*
2  * "Inventra" High-speed Dual-Role Controller (MUSB-HDRC), Mentor Graphics,
3  * USB2.0 OTG compliant core used in various chips.
4  *
5  * Copyright (C) 2008 Nokia Corporation
6  * Written by Andrzej Zaborowski <andrew@openedhand.com>
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License as
10  * published by the Free Software Foundation; either version 2 or
11  * (at your option) version 3 of the License.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Only host-mode and non-DMA accesses are currently supported.
23  */
24 #include "qemu-common.h"
25 #include "qemu-timer.h"
26 #include "usb.h"
27 #include "irq.h"
28 #include "hw.h"
29
30 /* Common USB registers */
31 #define MUSB_HDRC_FADDR         0x00    /* 8-bit */
32 #define MUSB_HDRC_POWER         0x01    /* 8-bit */
33
34 #define MUSB_HDRC_INTRTX        0x02    /* 16-bit */
35 #define MUSB_HDRC_INTRRX        0x04
36 #define MUSB_HDRC_INTRTXE       0x06
37 #define MUSB_HDRC_INTRRXE       0x08
38 #define MUSB_HDRC_INTRUSB       0x0a    /* 8 bit */
39 #define MUSB_HDRC_INTRUSBE      0x0b    /* 8 bit */
40 #define MUSB_HDRC_FRAME         0x0c    /* 16-bit */
41 #define MUSB_HDRC_INDEX         0x0e    /* 8 bit */
42 #define MUSB_HDRC_TESTMODE      0x0f    /* 8 bit */
43
44 /* Per-EP registers in indexed mode */
45 #define MUSB_HDRC_EP_IDX        0x10    /* 8-bit */
46
47 /* EP FIFOs */
48 #define MUSB_HDRC_FIFO          0x20
49
50 /* Additional Control Registers */
51 #define MUSB_HDRC_DEVCTL        0x60    /* 8 bit */
52
53 /* These are indexed */
54 #define MUSB_HDRC_TXFIFOSZ      0x62    /* 8 bit (see masks) */
55 #define MUSB_HDRC_RXFIFOSZ      0x63    /* 8 bit (see masks) */
56 #define MUSB_HDRC_TXFIFOADDR    0x64    /* 16 bit offset shifted right 3 */
57 #define MUSB_HDRC_RXFIFOADDR    0x66    /* 16 bit offset shifted right 3 */
58
59 /* Some more registers */
60 #define MUSB_HDRC_VCTRL         0x68    /* 8 bit */
61 #define MUSB_HDRC_HWVERS        0x6c    /* 8 bit */
62
63 /* Added in HDRC 1.9(?) & MHDRC 1.4 */
64 /* ULPI pass-through */
65 #define MUSB_HDRC_ULPI_VBUSCTL  0x70
66 #define MUSB_HDRC_ULPI_REGDATA  0x74
67 #define MUSB_HDRC_ULPI_REGADDR  0x75
68 #define MUSB_HDRC_ULPI_REGCTL   0x76
69
70 /* Extended config & PHY control */
71 #define MUSB_HDRC_ENDCOUNT      0x78    /* 8 bit */
72 #define MUSB_HDRC_DMARAMCFG     0x79    /* 8 bit */
73 #define MUSB_HDRC_PHYWAIT       0x7a    /* 8 bit */
74 #define MUSB_HDRC_PHYVPLEN      0x7b    /* 8 bit */
75 #define MUSB_HDRC_HS_EOF1       0x7c    /* 8 bit, units of 546.1 us */
76 #define MUSB_HDRC_FS_EOF1       0x7d    /* 8 bit, units of 533.3 ns */
77 #define MUSB_HDRC_LS_EOF1       0x7e    /* 8 bit, units of 1.067 us */
78
79 /* Per-EP BUSCTL registers */
80 #define MUSB_HDRC_BUSCTL        0x80
81
82 /* Per-EP registers in flat mode */
83 #define MUSB_HDRC_EP            0x100
84
85 /* offsets to registers in flat model */
86 #define MUSB_HDRC_TXMAXP        0x00    /* 16 bit apparently */
87 #define MUSB_HDRC_TXCSR         0x02    /* 16 bit apparently */
88 #define MUSB_HDRC_CSR0          MUSB_HDRC_TXCSR         /* re-used for EP0 */
89 #define MUSB_HDRC_RXMAXP        0x04    /* 16 bit apparently */
90 #define MUSB_HDRC_RXCSR         0x06    /* 16 bit apparently */
91 #define MUSB_HDRC_RXCOUNT       0x08    /* 16 bit apparently */
92 #define MUSB_HDRC_COUNT0        MUSB_HDRC_RXCOUNT       /* re-used for EP0 */
93 #define MUSB_HDRC_TXTYPE        0x0a    /* 8 bit apparently */
94 #define MUSB_HDRC_TYPE0         MUSB_HDRC_TXTYPE        /* re-used for EP0 */
95 #define MUSB_HDRC_TXINTERVAL    0x0b    /* 8 bit apparently */
96 #define MUSB_HDRC_NAKLIMIT0     MUSB_HDRC_TXINTERVAL    /* re-used for EP0 */
97 #define MUSB_HDRC_RXTYPE        0x0c    /* 8 bit apparently */
98 #define MUSB_HDRC_RXINTERVAL    0x0d    /* 8 bit apparently */
99 #define MUSB_HDRC_FIFOSIZE      0x0f    /* 8 bit apparently */
100 #define MUSB_HDRC_CONFIGDATA    MGC_O_HDRC_FIFOSIZE     /* re-used for EP0 */
101
102 /* "Bus control" registers */
103 #define MUSB_HDRC_TXFUNCADDR    0x00
104 #define MUSB_HDRC_TXHUBADDR     0x02
105 #define MUSB_HDRC_TXHUBPORT     0x03
106
107 #define MUSB_HDRC_RXFUNCADDR    0x04
108 #define MUSB_HDRC_RXHUBADDR     0x06
109 #define MUSB_HDRC_RXHUBPORT     0x07
110
111 /*
112  * MUSBHDRC Register bit masks
113  */
114
115 /* POWER */
116 #define MGC_M_POWER_ISOUPDATE           0x80
117 #define MGC_M_POWER_SOFTCONN            0x40
118 #define MGC_M_POWER_HSENAB              0x20
119 #define MGC_M_POWER_HSMODE              0x10
120 #define MGC_M_POWER_RESET               0x08
121 #define MGC_M_POWER_RESUME              0x04
122 #define MGC_M_POWER_SUSPENDM            0x02
123 #define MGC_M_POWER_ENSUSPEND           0x01
124
125 /* INTRUSB */
126 #define MGC_M_INTR_SUSPEND              0x01
127 #define MGC_M_INTR_RESUME               0x02
128 #define MGC_M_INTR_RESET                0x04
129 #define MGC_M_INTR_BABBLE               0x04
130 #define MGC_M_INTR_SOF                  0x08
131 #define MGC_M_INTR_CONNECT              0x10
132 #define MGC_M_INTR_DISCONNECT           0x20
133 #define MGC_M_INTR_SESSREQ              0x40
134 #define MGC_M_INTR_VBUSERROR            0x80    /* FOR SESSION END */
135 #define MGC_M_INTR_EP0                  0x01    /* FOR EP0 INTERRUPT */
136
137 /* DEVCTL */
138 #define MGC_M_DEVCTL_BDEVICE            0x80
139 #define MGC_M_DEVCTL_FSDEV              0x40
140 #define MGC_M_DEVCTL_LSDEV              0x20
141 #define MGC_M_DEVCTL_VBUS               0x18
142 #define MGC_S_DEVCTL_VBUS               3
143 #define MGC_M_DEVCTL_HM                 0x04
144 #define MGC_M_DEVCTL_HR                 0x02
145 #define MGC_M_DEVCTL_SESSION            0x01
146
147 /* TESTMODE */
148 #define MGC_M_TEST_FORCE_HOST           0x80
149 #define MGC_M_TEST_FIFO_ACCESS          0x40
150 #define MGC_M_TEST_FORCE_FS             0x20
151 #define MGC_M_TEST_FORCE_HS             0x10
152 #define MGC_M_TEST_PACKET               0x08
153 #define MGC_M_TEST_K                    0x04
154 #define MGC_M_TEST_J                    0x02
155 #define MGC_M_TEST_SE0_NAK              0x01
156
157 /* CSR0 */
158 #define MGC_M_CSR0_FLUSHFIFO            0x0100
159 #define MGC_M_CSR0_TXPKTRDY             0x0002
160 #define MGC_M_CSR0_RXPKTRDY             0x0001
161
162 /* CSR0 in Peripheral mode */
163 #define MGC_M_CSR0_P_SVDSETUPEND        0x0080
164 #define MGC_M_CSR0_P_SVDRXPKTRDY        0x0040
165 #define MGC_M_CSR0_P_SENDSTALL          0x0020
166 #define MGC_M_CSR0_P_SETUPEND           0x0010
167 #define MGC_M_CSR0_P_DATAEND            0x0008
168 #define MGC_M_CSR0_P_SENTSTALL          0x0004
169
170 /* CSR0 in Host mode */
171 #define MGC_M_CSR0_H_NO_PING            0x0800
172 #define MGC_M_CSR0_H_WR_DATATOGGLE      0x0400  /* set to allow setting: */
173 #define MGC_M_CSR0_H_DATATOGGLE         0x0200  /* data toggle control */
174 #define MGC_M_CSR0_H_NAKTIMEOUT         0x0080
175 #define MGC_M_CSR0_H_STATUSPKT          0x0040
176 #define MGC_M_CSR0_H_REQPKT             0x0020
177 #define MGC_M_CSR0_H_ERROR              0x0010
178 #define MGC_M_CSR0_H_SETUPPKT           0x0008
179 #define MGC_M_CSR0_H_RXSTALL            0x0004
180
181 /* CONFIGDATA */
182 #define MGC_M_CONFIGDATA_MPRXE          0x80    /* auto bulk pkt combining */
183 #define MGC_M_CONFIGDATA_MPTXE          0x40    /* auto bulk pkt splitting */
184 #define MGC_M_CONFIGDATA_BIGENDIAN      0x20
185 #define MGC_M_CONFIGDATA_HBRXE          0x10    /* HB-ISO for RX */
186 #define MGC_M_CONFIGDATA_HBTXE          0x08    /* HB-ISO for TX */
187 #define MGC_M_CONFIGDATA_DYNFIFO        0x04    /* dynamic FIFO sizing */
188 #define MGC_M_CONFIGDATA_SOFTCONE       0x02    /* SoftConnect */
189 #define MGC_M_CONFIGDATA_UTMIDW         0x01    /* Width, 0 => 8b, 1 => 16b */
190
191 /* TXCSR in Peripheral and Host mode */
192 #define MGC_M_TXCSR_AUTOSET             0x8000
193 #define MGC_M_TXCSR_ISO                 0x4000
194 #define MGC_M_TXCSR_MODE                0x2000
195 #define MGC_M_TXCSR_DMAENAB             0x1000
196 #define MGC_M_TXCSR_FRCDATATOG          0x0800
197 #define MGC_M_TXCSR_DMAMODE             0x0400
198 #define MGC_M_TXCSR_CLRDATATOG          0x0040
199 #define MGC_M_TXCSR_FLUSHFIFO           0x0008
200 #define MGC_M_TXCSR_FIFONOTEMPTY        0x0002
201 #define MGC_M_TXCSR_TXPKTRDY            0x0001
202
203 /* TXCSR in Peripheral mode */
204 #define MGC_M_TXCSR_P_INCOMPTX          0x0080
205 #define MGC_M_TXCSR_P_SENTSTALL         0x0020
206 #define MGC_M_TXCSR_P_SENDSTALL         0x0010
207 #define MGC_M_TXCSR_P_UNDERRUN          0x0004
208
209 /* TXCSR in Host mode */
210 #define MGC_M_TXCSR_H_WR_DATATOGGLE     0x0200
211 #define MGC_M_TXCSR_H_DATATOGGLE        0x0100
212 #define MGC_M_TXCSR_H_NAKTIMEOUT        0x0080
213 #define MGC_M_TXCSR_H_RXSTALL           0x0020
214 #define MGC_M_TXCSR_H_ERROR             0x0004
215
216 /* RXCSR in Peripheral and Host mode */
217 #define MGC_M_RXCSR_AUTOCLEAR           0x8000
218 #define MGC_M_RXCSR_DMAENAB             0x2000
219 #define MGC_M_RXCSR_DISNYET             0x1000
220 #define MGC_M_RXCSR_DMAMODE             0x0800
221 #define MGC_M_RXCSR_INCOMPRX            0x0100
222 #define MGC_M_RXCSR_CLRDATATOG          0x0080
223 #define MGC_M_RXCSR_FLUSHFIFO           0x0010
224 #define MGC_M_RXCSR_DATAERROR           0x0008
225 #define MGC_M_RXCSR_FIFOFULL            0x0002
226 #define MGC_M_RXCSR_RXPKTRDY            0x0001
227
228 /* RXCSR in Peripheral mode */
229 #define MGC_M_RXCSR_P_ISO               0x4000
230 #define MGC_M_RXCSR_P_SENTSTALL         0x0040
231 #define MGC_M_RXCSR_P_SENDSTALL         0x0020
232 #define MGC_M_RXCSR_P_OVERRUN           0x0004
233
234 /* RXCSR in Host mode */
235 #define MGC_M_RXCSR_H_AUTOREQ           0x4000
236 #define MGC_M_RXCSR_H_WR_DATATOGGLE     0x0400
237 #define MGC_M_RXCSR_H_DATATOGGLE        0x0200
238 #define MGC_M_RXCSR_H_RXSTALL           0x0040
239 #define MGC_M_RXCSR_H_REQPKT            0x0020
240 #define MGC_M_RXCSR_H_ERROR             0x0004
241
242 /* HUBADDR */
243 #define MGC_M_HUBADDR_MULTI_TT          0x80
244
245 /* ULPI: Added in HDRC 1.9(?) & MHDRC 1.4 */
246 #define MGC_M_ULPI_VBCTL_USEEXTVBUSIND  0x02
247 #define MGC_M_ULPI_VBCTL_USEEXTVBUS     0x01
248 #define MGC_M_ULPI_REGCTL_INT_ENABLE    0x08
249 #define MGC_M_ULPI_REGCTL_READNOTWRITE  0x04
250 #define MGC_M_ULPI_REGCTL_COMPLETE      0x02
251 #define MGC_M_ULPI_REGCTL_REG           0x01
252
253 /* #define MUSB_DEBUG */
254
255 #ifdef MUSB_DEBUG
256 #define TRACE(fmt,...) fprintf(stderr, "%s: " fmt "\n", __FUNCTION__, ##__VA_ARGS__)
257 #else
258 #define TRACE(...)
259 #endif
260
261
262 static void musb_attach(USBPort *port, USBDevice *dev);
263
264 struct musb_s {
265     qemu_irq *irqs;
266     USBPort port;
267
268     int idx;
269     uint8_t devctl;
270     uint8_t power;
271     uint8_t faddr;
272
273     uint8_t intr;
274     uint8_t mask;
275     uint16_t tx_intr;
276     uint16_t tx_mask;
277     uint16_t rx_intr;
278     uint16_t rx_mask;
279
280     int setup_len;
281     int session;
282
283     uint8_t buf[0x8000];
284
285     struct musb_ep_s {
286         uint16_t faddr[2];
287         uint8_t haddr[2];
288         uint8_t hport[2];
289         uint16_t csr[2];
290         uint16_t maxp[2];
291         uint16_t rxcount;
292         uint8_t type[2];
293         uint8_t interval[2];
294         uint8_t config;
295         uint8_t fifosize;
296         int timeout[2]; /* Always in microframes */
297
298         uint8_t *buf[2];
299         int fifolen[2];
300         int fifostart[2];
301         int fifoaddr[2];
302         USBPacket packey[2];
303         int status[2];
304         int ext_size[2];
305
306         /* For callbacks' use */
307         int epnum;
308         int interrupt[2];
309         struct musb_s *musb;
310         USBCallback *delayed_cb[2];
311         QEMUTimer *intv_timer[2];
312         /* Duplicating the world since 2008!...  probably we should have 32
313          * logical, single endpoints instead.  */
314     } ep[16];
315 };
316
317 static void musb_vbus_set(struct musb_s *s, int level)
318 {
319     if (level)
320         s->devctl |= 3 << MGC_S_DEVCTL_VBUS;
321     else
322         s->devctl &= ~MGC_M_DEVCTL_VBUS;
323
324     qemu_set_irq(s->irqs[musb_set_vbus], level);
325 }
326
327 static void musb_intr_set(struct musb_s *s, int line, int level)
328 {
329     if (!level) {
330         s->intr &= ~(1 << line);
331         qemu_irq_lower(s->irqs[line]);
332     } else if (s->mask & (1 << line)) {
333         s->intr |= 1 << line;
334         qemu_irq_raise(s->irqs[line]);
335     }
336 }
337
338 static void musb_tx_intr_set(struct musb_s *s, int line, int level)
339 {
340     if (!level) {
341         s->tx_intr &= ~(1 << line);
342         if (!s->tx_intr)
343             qemu_irq_lower(s->irqs[musb_irq_tx]);
344     } else if (s->tx_mask & (1 << line)) {
345         s->tx_intr |= 1 << line;
346         qemu_irq_raise(s->irqs[musb_irq_tx]);
347     }
348 }
349
350 static void musb_rx_intr_set(struct musb_s *s, int line, int level)
351 {
352     if (line) {
353         if (!level) {
354             s->rx_intr &= ~(1 << line);
355             if (!s->rx_intr)
356                 qemu_irq_lower(s->irqs[musb_irq_rx]);
357         } else if (s->rx_mask & (1 << line)) {
358             s->rx_intr |= 1 << line;
359             qemu_irq_raise(s->irqs[musb_irq_rx]);
360         }
361     } else
362         musb_tx_intr_set(s, line, level);
363 }
364
365 uint32_t musb_core_intr_get(struct musb_s *s)
366 {
367     return (s->rx_intr << 15) | s->tx_intr;
368 }
369
370 void musb_core_intr_clear(struct musb_s *s, uint32_t mask)
371 {
372     if (s->rx_intr) {
373         s->rx_intr &= mask >> 15;
374         if (!s->rx_intr)
375             qemu_irq_lower(s->irqs[musb_irq_rx]);
376     }
377
378     if (s->tx_intr) {
379         s->tx_intr &= mask & 0xffff;
380         if (!s->tx_intr)
381             qemu_irq_lower(s->irqs[musb_irq_tx]);
382     }
383 }
384
385 void musb_set_size(struct musb_s *s, int epnum, int size, int is_tx)
386 {
387     s->ep[epnum].ext_size[!is_tx] = size;
388     s->ep[epnum].fifostart[0] = 0;
389     s->ep[epnum].fifostart[1] = 0;
390     s->ep[epnum].fifolen[0] = 0;
391     s->ep[epnum].fifolen[1] = 0;
392 }
393
394 static void musb_session_update(struct musb_s *s, int prev_dev, int prev_sess)
395 {
396     int detect_prev = prev_dev && prev_sess;
397     int detect = !!s->port.dev && s->session;
398
399     if (detect && !detect_prev) {
400         /* Let's skip the ID pin sense and VBUS sense formalities and
401          * and signal a successful SRP directly.  This should work at least
402          * for the Linux driver stack.  */
403         musb_intr_set(s, musb_irq_connect, 1);
404
405         if (s->port.dev->speed == USB_SPEED_LOW) {
406             s->devctl &= ~MGC_M_DEVCTL_FSDEV;
407             s->devctl |= MGC_M_DEVCTL_LSDEV;
408         } else {
409             s->devctl |= MGC_M_DEVCTL_FSDEV;
410             s->devctl &= ~MGC_M_DEVCTL_LSDEV;
411         }
412
413         /* A-mode?  */
414         s->devctl &= ~MGC_M_DEVCTL_BDEVICE;
415
416         /* Host-mode bit?  */
417         s->devctl |= MGC_M_DEVCTL_HM;
418 #if 1
419         musb_vbus_set(s, 1);
420 #endif
421     } else if (!detect && detect_prev) {
422 #if 1
423         musb_vbus_set(s, 0);
424 #endif
425     }
426 }
427
428 /* Attach or detach a device on our only port.  */
429 static void musb_attach(USBPort *port, USBDevice *dev)
430 {
431     struct musb_s *s = (struct musb_s *) port->opaque;
432     USBDevice *curr;
433
434     port = &s->port;
435     curr = port->dev;
436
437     if (dev) {
438         if (curr) {
439             usb_attach(port, NULL);
440             /* TODO: signal some interrupts */
441         }
442
443         musb_intr_set(s, musb_irq_vbus_request, 1);
444
445         /* Send the attach message to device */
446         usb_send_msg(dev, USB_MSG_ATTACH);
447     } else if (curr) {
448         /* Send the detach message */
449         usb_send_msg(curr, USB_MSG_DETACH);
450
451         musb_intr_set(s, musb_irq_disconnect, 1);
452     }
453
454     port->dev = dev;
455
456     musb_session_update(s, !!curr, s->session);
457 }
458
459 static inline void musb_cb_tick0(void *opaque)
460 {
461     struct musb_ep_s *ep = (struct musb_ep_s *) opaque;
462
463     ep->delayed_cb[0](&ep->packey[0], opaque);
464 }
465
466 static inline void musb_cb_tick1(void *opaque)
467 {
468     struct musb_ep_s *ep = (struct musb_ep_s *) opaque;
469
470     ep->delayed_cb[1](&ep->packey[1], opaque);
471 }
472
473 #define musb_cb_tick    (dir ? musb_cb_tick1 : musb_cb_tick0)
474
475 static inline void musb_schedule_cb(USBPacket *packey, void *opaque, int dir)
476 {
477     struct musb_ep_s *ep = (struct musb_ep_s *) opaque;
478     int timeout = 0;
479
480     if (ep->status[dir] == USB_RET_NAK)
481         timeout = ep->timeout[dir];
482     else if (ep->interrupt[dir])
483         timeout = 8;
484     else
485         return musb_cb_tick(opaque);
486
487     if (!ep->intv_timer[dir])
488         ep->intv_timer[dir] = qemu_new_timer(vm_clock, musb_cb_tick, opaque);
489
490     qemu_mod_timer(ep->intv_timer[dir], qemu_get_clock(vm_clock) +
491                     muldiv64(timeout, ticks_per_sec, 8000));
492 }
493
494 static void musb_schedule0_cb(USBPacket *packey, void *opaque)
495 {
496     return musb_schedule_cb(packey, opaque, 0);
497 }
498
499 static void musb_schedule1_cb(USBPacket *packey, void *opaque)
500 {
501     return musb_schedule_cb(packey, opaque, 1);
502 }
503
504 static int musb_timeout(int ttype, int speed, int val)
505 {
506 #if 1
507     return val << 3;
508 #endif
509
510     switch (ttype) {
511     case USB_ENDPOINT_XFER_CONTROL:
512         if (val < 2)
513             return 0;
514         else if (speed == USB_SPEED_HIGH)
515             return 1 << (val - 1);
516         else
517             return 8 << (val - 1);
518
519     case USB_ENDPOINT_XFER_INT:
520         if (speed == USB_SPEED_HIGH)
521             if (val < 2)
522                 return 0;
523             else
524                 return 1 << (val - 1);
525         else
526             return val << 3;
527
528     case USB_ENDPOINT_XFER_BULK:
529     case USB_ENDPOINT_XFER_ISOC:
530         if (val < 2)
531             return 0;
532         else if (speed == USB_SPEED_HIGH)
533             return 1 << (val - 1);
534         else
535             return 8 << (val - 1);
536         /* TODO: what with low-speed Bulk and Isochronous?  */
537     }
538
539     cpu_abort(cpu_single_env, "bad interval\n");
540 }
541
542 static inline void musb_packet(struct musb_s *s, struct musb_ep_s *ep,
543                 int epnum, int pid, int len, USBCallback cb, int dir)
544 {
545     int ret;
546     int idx = epnum && dir;
547     int ttype;
548
549     /* ep->type[0,1] contains:
550      * in bits 7:6 the speed (0 - invalid, 1 - high, 2 - full, 3 - slow)
551      * in bits 5:4 the transfer type (BULK / INT)
552      * in bits 3:0 the EP num
553      */
554     ttype = epnum ? (ep->type[idx] >> 4) & 3 : 0;
555
556     ep->timeout[dir] = musb_timeout(ttype,
557                     ep->type[idx] >> 6, ep->interval[idx]);
558     ep->interrupt[dir] = ttype == USB_ENDPOINT_XFER_INT;
559     ep->delayed_cb[dir] = cb;
560     cb = dir ? musb_schedule1_cb : musb_schedule0_cb;
561
562     ep->packey[dir].pid = pid;
563     /* A wild guess on the FADDR semantics... */
564     ep->packey[dir].devaddr = ep->faddr[idx];
565     ep->packey[dir].devep = ep->type[idx] & 0xf;
566     ep->packey[dir].data = (void *) ep->buf[idx];
567     ep->packey[dir].len = len;
568     ep->packey[dir].complete_cb = cb;
569     ep->packey[dir].complete_opaque = ep;
570
571     if (s->port.dev)
572         ret = s->port.dev->handle_packet(s->port.dev, &ep->packey[dir]);
573     else
574         ret = USB_RET_NODEV;
575
576     if (ret == USB_RET_ASYNC) {
577         ep->status[dir] = len;
578         return;
579     }
580
581     ep->status[dir] = ret;
582     usb_packet_complete(&ep->packey[dir]);
583 }
584
585 static void musb_tx_packet_complete(USBPacket *packey, void *opaque)
586 {
587     /* Unfortunately we can't use packey->devep because that's the remote
588      * endpoint number and may be different than our local.  */
589     struct musb_ep_s *ep = (struct musb_ep_s *) opaque;
590     int epnum = ep->epnum;
591     struct musb_s *s = ep->musb;
592
593     ep->fifostart[0] = 0;
594     ep->fifolen[0] = 0;
595 #ifdef CLEAR_NAK
596     if (ep->status[0] != USB_RET_NAK) {
597 #endif
598         if (epnum)
599             ep->csr[0] &= ~(MGC_M_TXCSR_FIFONOTEMPTY | MGC_M_TXCSR_TXPKTRDY);
600         else
601             ep->csr[0] &= ~MGC_M_CSR0_TXPKTRDY;
602 #ifdef CLEAR_NAK
603     }
604 #endif
605
606     /* Clear all of the error bits first */
607     if (epnum)
608         ep->csr[0] &= ~(MGC_M_TXCSR_H_ERROR | MGC_M_TXCSR_H_RXSTALL |
609                         MGC_M_TXCSR_H_NAKTIMEOUT);
610     else
611         ep->csr[0] &= ~(MGC_M_CSR0_H_ERROR | MGC_M_CSR0_H_RXSTALL |
612                         MGC_M_CSR0_H_NAKTIMEOUT | MGC_M_CSR0_H_NO_PING);
613
614     if (ep->status[0] == USB_RET_STALL) {
615         /* Command not supported by target! */
616         ep->status[0] = 0;
617
618         if (epnum)
619             ep->csr[0] |= MGC_M_TXCSR_H_RXSTALL;
620         else
621             ep->csr[0] |= MGC_M_CSR0_H_RXSTALL;
622     }
623
624     if (ep->status[0] == USB_RET_NAK) {
625         ep->status[0] = 0;
626
627         /* NAK timeouts are only generated in Bulk transfers and
628          * Data-errors in Isochronous.  */
629         if (ep->interrupt[0]) {
630             return;
631         }
632
633         if (epnum)
634             ep->csr[0] |= MGC_M_TXCSR_H_NAKTIMEOUT;
635         else
636             ep->csr[0] |= MGC_M_CSR0_H_NAKTIMEOUT;
637     }
638
639     if (ep->status[0] < 0) {
640         if (ep->status[0] == USB_RET_BABBLE)
641             musb_intr_set(s, musb_irq_rst_babble, 1);
642
643         /* Pretend we've tried three times already and failed (in
644          * case of USB_TOKEN_SETUP).  */
645         if (epnum)
646             ep->csr[0] |= MGC_M_TXCSR_H_ERROR;
647         else
648             ep->csr[0] |= MGC_M_CSR0_H_ERROR;
649
650         musb_tx_intr_set(s, epnum, 1);
651         return;
652     }
653     /* TODO: check len for over/underruns of an OUT packet?  */
654
655 #ifdef SETUPLEN_HACK
656     if (!epnum && ep->packey[0].pid == USB_TOKEN_SETUP)
657         s->setup_len = ep->packey[0].data[6];
658 #endif
659
660     /* In DMA mode: if no error, assert DMA request for this EP,
661      * and skip the interrupt.  */
662     musb_tx_intr_set(s, epnum, 1);
663 }
664
665 static void musb_rx_packet_complete(USBPacket *packey, void *opaque)
666 {
667     /* Unfortunately we can't use packey->devep because that's the remote
668      * endpoint number and may be different than our local.  */
669     struct musb_ep_s *ep = (struct musb_ep_s *) opaque;
670     int epnum = ep->epnum;
671     struct musb_s *s = ep->musb;
672
673     ep->fifostart[1] = 0;
674     ep->fifolen[1] = 0;
675
676 #ifdef CLEAR_NAK
677     if (ep->status[1] != USB_RET_NAK) {
678 #endif
679         ep->csr[1] &= ~MGC_M_RXCSR_H_REQPKT;
680         if (!epnum)
681             ep->csr[0] &= ~MGC_M_CSR0_H_REQPKT;
682 #ifdef CLEAR_NAK
683     }
684 #endif
685
686     /* Clear all of the imaginable error bits first */
687     ep->csr[1] &= ~(MGC_M_RXCSR_H_ERROR | MGC_M_RXCSR_H_RXSTALL |
688                     MGC_M_RXCSR_DATAERROR);
689     if (!epnum)
690         ep->csr[0] &= ~(MGC_M_CSR0_H_ERROR | MGC_M_CSR0_H_RXSTALL |
691                         MGC_M_CSR0_H_NAKTIMEOUT | MGC_M_CSR0_H_NO_PING);
692
693     if (ep->status[1] == USB_RET_STALL) {
694         ep->status[1] = 0;
695         packey->len = 0;
696
697         ep->csr[1] |= MGC_M_RXCSR_H_RXSTALL;
698         if (!epnum)
699             ep->csr[0] |= MGC_M_CSR0_H_RXSTALL;
700     }
701
702     if (ep->status[1] == USB_RET_NAK) {
703         ep->status[1] = 0;
704
705         /* NAK timeouts are only generated in Bulk transfers and
706          * Data-errors in Isochronous.  */
707         if (ep->interrupt[1])
708             return musb_packet(s, ep, epnum, USB_TOKEN_IN,
709                             packey->len, musb_rx_packet_complete, 1);
710
711         ep->csr[1] |= MGC_M_RXCSR_DATAERROR;
712         if (!epnum)
713             ep->csr[0] |= MGC_M_CSR0_H_NAKTIMEOUT;
714     }
715
716     if (ep->status[1] < 0) {
717         if (ep->status[1] == USB_RET_BABBLE) {
718             musb_intr_set(s, musb_irq_rst_babble, 1);
719             return;
720         }
721
722         /* Pretend we've tried three times already and failed (in
723          * case of a control transfer).  */
724         ep->csr[1] |= MGC_M_RXCSR_H_ERROR;
725         if (!epnum)
726             ep->csr[0] |= MGC_M_CSR0_H_ERROR;
727
728         musb_rx_intr_set(s, epnum, 1);
729         return;
730     }
731     /* TODO: check len for over/underruns of an OUT packet?  */
732     /* TODO: perhaps make use of e->ext_size[1] here.  */
733
734     packey->len = ep->status[1];
735
736     if (!(ep->csr[1] & (MGC_M_RXCSR_H_RXSTALL | MGC_M_RXCSR_DATAERROR))) {
737         ep->csr[1] |= MGC_M_RXCSR_FIFOFULL | MGC_M_RXCSR_RXPKTRDY;
738         if (!epnum)
739             ep->csr[0] |= MGC_M_CSR0_RXPKTRDY;
740
741         ep->rxcount = packey->len; /* XXX: MIN(packey->len, ep->maxp[1]); */
742         /* In DMA mode: assert DMA request for this EP */
743     }
744
745     /* Only if DMA has not been asserted */
746     musb_rx_intr_set(s, epnum, 1);
747 }
748
749 static void musb_tx_rdy(struct musb_s *s, int epnum)
750 {
751     struct musb_ep_s *ep = s->ep + epnum;
752     int pid;
753     int total, valid = 0;
754     TRACE("start %d, len %d",  ep->fifostart[0], ep->fifolen[0] );
755     ep->fifostart[0] += ep->fifolen[0];
756     ep->fifolen[0] = 0;
757
758     /* XXX: how's the total size of the packet retrieved exactly in
759      * the generic case?  */
760     total = ep->maxp[0] & 0x3ff;
761
762     if (ep->ext_size[0]) {
763         total = ep->ext_size[0];
764         ep->ext_size[0] = 0;
765         valid = 1;
766     }
767
768     /* If the packet is not fully ready yet, wait for a next segment.  */
769     if (epnum && (ep->fifostart[0]) < total)
770         return;
771
772     if (!valid)
773         total = ep->fifostart[0];
774
775     pid = USB_TOKEN_OUT;
776     if (!epnum && (ep->csr[0] & MGC_M_CSR0_H_SETUPPKT)) {
777         pid = USB_TOKEN_SETUP;
778         if (total != 8)
779             printf("%s: illegal SETUPPKT length of %i bytes\n",
780                             __FUNCTION__, total);
781         /* Controller should retry SETUP packets three times on errors
782          * but it doesn't make sense for us to do that.  */
783     }
784
785     return musb_packet(s, ep, epnum, pid,
786                     total, musb_tx_packet_complete, 0);
787 }
788
789 static void musb_rx_req(struct musb_s *s, int epnum)
790 {
791     struct musb_ep_s *ep = s->ep + epnum;
792     int total;
793
794     /* If we already have a packet, which didn't fit into the
795      * 64 bytes of the FIFO, only move the FIFO start and return. (Obsolete) */
796     if (ep->packey[1].pid == USB_TOKEN_IN && ep->status[1] >= 0 &&
797                     (ep->fifostart[1]) + ep->rxcount <
798                     ep->packey[1].len) {
799         TRACE("0x%08x, %d",  ep->fifostart[1], ep->rxcount );
800         ep->fifostart[1] += ep->rxcount;
801         ep->fifolen[1] = 0;
802
803         ep->rxcount = MIN(ep->packey[0].len - (ep->fifostart[1]),
804                         ep->maxp[1]);
805
806         ep->csr[1] &= ~MGC_M_RXCSR_H_REQPKT;
807         if (!epnum)
808             ep->csr[0] &= ~MGC_M_CSR0_H_REQPKT;
809
810         /* Clear all of the error bits first */
811         ep->csr[1] &= ~(MGC_M_RXCSR_H_ERROR | MGC_M_RXCSR_H_RXSTALL |
812                         MGC_M_RXCSR_DATAERROR);
813         if (!epnum)
814             ep->csr[0] &= ~(MGC_M_CSR0_H_ERROR | MGC_M_CSR0_H_RXSTALL |
815                             MGC_M_CSR0_H_NAKTIMEOUT | MGC_M_CSR0_H_NO_PING);
816
817         ep->csr[1] |= MGC_M_RXCSR_FIFOFULL | MGC_M_RXCSR_RXPKTRDY;
818         if (!epnum)
819             ep->csr[0] |= MGC_M_CSR0_RXPKTRDY;
820         musb_rx_intr_set(s, epnum, 1);
821         return;
822     }
823
824     /* The driver sets maxp[1] to 64 or less because it knows the hardware
825      * FIFO is this deep.  Bigger packets get split in
826      * usb_generic_handle_packet but we can also do the splitting locally
827      * for performance.  It turns out we can also have a bigger FIFO and
828      * ignore the limit set in ep->maxp[1].  The Linux MUSB driver deals
829      * OK with single packets of even 32KB and we avoid splitting, however
830      * usb_msd.c sometimes sends a packet bigger than what Linux expects
831      * (e.g. 8192 bytes instead of 4096) and we get an OVERRUN.  Splitting
832      * hides this overrun from Linux.  Up to 4096 everything is fine
833      * though.  Currently this is disabled.
834      *
835      * XXX: mind ep->fifosize.  */
836     total = MIN(ep->maxp[1] & 0x3ff, sizeof(s->buf));
837
838 #ifdef SETUPLEN_HACK
839     /* Why should *we* do that instead of Linux?  */
840     if (!epnum) {
841         if (ep->packey[0].devaddr == 2)
842             total = MIN(s->setup_len, 8);
843         else
844             total = MIN(s->setup_len, 64);
845         s->setup_len -= total;
846     }
847 #endif
848
849     return musb_packet(s, ep, epnum, USB_TOKEN_IN,
850                     total, musb_rx_packet_complete, 1);
851 }
852
853 static uint8_t musb_read_fifo(struct musb_ep_s *ep)
854 {
855     uint8_t value;
856     if (ep->fifolen[1] >= 64) {
857         /* We have a FIFO underrun */
858         printf("%s: EP%d FIFO is now empty, stop reading\n",
859                 __FUNCTION__, ep->epnum);
860         return 0x00000000;
861     }
862     /* In DMA mode clear RXPKTRDY and set REQPKT automatically
863      * (if AUTOREQ is set) */
864
865     ep->csr[1] &= ~MGC_M_RXCSR_FIFOFULL;
866     value=ep->buf[1][ep->fifostart[1] + ep->fifolen[1] ++];
867     TRACE("EP%d 0x%02x, %d", ep->epnum, value, ep->fifolen[1] );
868     return value;
869 }
870
871 static void musb_write_fifo(struct musb_ep_s *ep, uint8_t value)
872 {
873     TRACE("EP%d = %02x", ep->epnum, value);
874     if (ep->fifolen[0] >= 64) {
875         /* We have a FIFO overrun */
876         printf("%s: EP%d FIFO exceeded 64 bytes, stop feeding data\n",
877                 __FUNCTION__, ep->epnum);
878         return;
879      }
880
881      ep->buf[0][ep->fifostart[0] + ep->fifolen[0] ++] = value;
882      ep->csr[0] |= MGC_M_TXCSR_FIFONOTEMPTY;
883 }
884
885 static void musb_ep_frame_cancel(struct musb_ep_s *ep, int dir)
886 {
887     if (ep->intv_timer[dir])
888         qemu_del_timer(ep->intv_timer[dir]);
889 }
890
891 /* Bus control */
892 static uint8_t musb_busctl_readb(void *opaque, int ep, int addr)
893 {
894     struct musb_s *s = (struct musb_s *) opaque;
895 //    TRACE("ADDR = 0x%08x", addr);
896
897     switch (addr) {
898     /* For USB2.0 HS hubs only */
899     case MUSB_HDRC_TXHUBADDR:
900         return s->ep[ep].haddr[0];
901     case MUSB_HDRC_TXHUBPORT:
902         return s->ep[ep].hport[0];
903     case MUSB_HDRC_RXHUBADDR:
904         return s->ep[ep].haddr[1];
905     case MUSB_HDRC_RXHUBPORT:
906         return s->ep[ep].hport[1];
907
908     default:
909         fprintf(stderr ,"%s: unknown register at %02x\n", __FUNCTION__, addr);
910         return 0x00;
911     };
912 }
913
914 static void musb_busctl_writeb(void *opaque, int ep, int addr, uint8_t value)
915 {
916     struct musb_s *s = (struct musb_s *) opaque;
917
918     switch (addr) {
919     case MUSB_HDRC_TXFUNCADDR:
920         s->ep[ep].faddr[0] = value;
921         break;
922     case MUSB_HDRC_RXFUNCADDR:
923         s->ep[ep].faddr[1] = value;
924         break;
925     case MUSB_HDRC_TXHUBADDR:
926         s->ep[ep].haddr[0] = value;
927         break;
928     case MUSB_HDRC_TXHUBPORT:
929         s->ep[ep].hport[0] = value;
930         break;
931     case MUSB_HDRC_RXHUBADDR:
932         s->ep[ep].haddr[1] = value;
933         break;
934     case MUSB_HDRC_RXHUBPORT:
935         s->ep[ep].hport[1] = value;
936         break;
937
938     default:
939         fprintf(stderr, "%s: unknown register at %02x\n", __FUNCTION__, addr);
940     };
941 }
942
943 static uint16_t musb_busctl_readh(void *opaque, int ep, int addr)
944 {
945     struct musb_s *s = (struct musb_s *) opaque;
946
947     switch (addr) {
948     case MUSB_HDRC_TXFUNCADDR:
949         return s->ep[ep].faddr[0];
950     case MUSB_HDRC_RXFUNCADDR:
951         return s->ep[ep].faddr[1];
952
953     default:
954         return musb_busctl_readb(s, ep, addr) |
955                 (musb_busctl_readb(s, ep, addr | 1) << 8);
956     };
957 }
958
959 static void musb_busctl_writeh(void *opaque, int ep, int addr, uint16_t value)
960 {
961     struct musb_s *s = (struct musb_s *) opaque;
962
963     switch (addr) {
964     case MUSB_HDRC_TXFUNCADDR:
965         s->ep[ep].faddr[0] = value;
966         break;
967     case MUSB_HDRC_RXFUNCADDR:
968         s->ep[ep].faddr[1] = value;
969         break;
970
971     default:
972         musb_busctl_writeb(s, ep, addr, value & 0xff);
973         musb_busctl_writeb(s, ep, addr | 1, value >> 8);
974     };
975 }
976
977 /* Endpoint control */
978 static uint8_t musb_ep_readb(void *opaque, int ep, int addr)
979 {
980     struct musb_s *s = (struct musb_s *) opaque;
981
982     switch (addr) {
983     case MUSB_HDRC_TXTYPE:
984         return s->ep[ep].type[0];
985     case MUSB_HDRC_TXINTERVAL:
986         return s->ep[ep].interval[0];
987     case MUSB_HDRC_RXTYPE:
988         return s->ep[ep].type[1];
989     case MUSB_HDRC_RXINTERVAL:
990         return s->ep[ep].interval[1];
991     case (MUSB_HDRC_FIFOSIZE & ~1):
992         return 0x00;
993     case MUSB_HDRC_FIFOSIZE:
994         return ep ? s->ep[ep].fifosize : s->ep[ep].config;
995     case MUSB_HDRC_RXCOUNT:
996         return s->ep[ep].rxcount;
997
998     default:
999         fprintf(stderr, "%s: unknown register at %02x\n", __FUNCTION__, addr);
1000         return 0x00;
1001     };
1002 }
1003
1004 static void musb_ep_writeb(void *opaque, int ep, int addr, uint8_t value)
1005 {
1006     struct musb_s *s = (struct musb_s *) opaque;
1007
1008     switch (addr) {
1009     case MUSB_HDRC_TXTYPE:
1010         s->ep[ep].type[0] = value;
1011         break;
1012     case MUSB_HDRC_TXINTERVAL:
1013         s->ep[ep].interval[0] = value;
1014         musb_ep_frame_cancel(&s->ep[ep], 0);
1015         break;
1016     case MUSB_HDRC_RXTYPE:
1017         s->ep[ep].type[1] = value;
1018         break;
1019     case MUSB_HDRC_RXINTERVAL:
1020         s->ep[ep].interval[1] = value;
1021         musb_ep_frame_cancel(&s->ep[ep], 1);
1022         break;
1023     case (MUSB_HDRC_FIFOSIZE & ~1):
1024         break;
1025     case MUSB_HDRC_FIFOSIZE:
1026         fprintf(stderr, "%s: somebody messes with fifosize (now %i bytes)\n",
1027                         __FUNCTION__, value);
1028         s->ep[ep].fifosize = value;
1029         break;
1030     default:
1031         fprintf(stderr, "%s: unknown register at %02x\n", __FUNCTION__, addr);
1032     };
1033 }
1034
1035 static uint16_t musb_ep_readh(void *opaque, int ep, int addr)
1036 {
1037     struct musb_s *s = (struct musb_s *) opaque;
1038     uint16_t ret;
1039
1040     switch (addr) {
1041     case MUSB_HDRC_TXMAXP:
1042         return s->ep[ep].maxp[0];
1043     case MUSB_HDRC_TXCSR:
1044         return s->ep[ep].csr[0];
1045     case MUSB_HDRC_RXMAXP:
1046         return s->ep[ep].maxp[1];
1047     case MUSB_HDRC_RXCSR:
1048         ret = s->ep[ep].csr[1];
1049
1050         /* TODO: This and other bits probably depend on
1051          * ep->csr[1] & MGC_M_RXCSR_AUTOCLEAR.  */
1052         if (s->ep[ep].csr[1] & MGC_M_RXCSR_AUTOCLEAR)
1053             s->ep[ep].csr[1] &= ~MGC_M_RXCSR_RXPKTRDY;
1054
1055         return ret;
1056     case MUSB_HDRC_RXCOUNT:
1057         return s->ep[ep].rxcount;
1058
1059     default:
1060         return musb_ep_readb(s, ep, addr) |
1061                 (musb_ep_readb(s, ep, addr | 1) << 8);
1062     };
1063 }
1064
1065 static void musb_ep_writeh(void *opaque, int ep, int addr, uint16_t value)
1066 {
1067     struct musb_s *s = (struct musb_s *) opaque;
1068
1069     switch (addr) {
1070     case MUSB_HDRC_TXMAXP:
1071         s->ep[ep].maxp[0] = value;
1072         break;
1073     case MUSB_HDRC_TXCSR:
1074         if (ep) {
1075             s->ep[ep].csr[0] &= value & 0xa6;
1076             s->ep[ep].csr[0] |= value & 0xff59;
1077         } else {
1078             s->ep[ep].csr[0] &= value & 0x85;
1079             s->ep[ep].csr[0] |= value & 0xf7a;
1080         }
1081
1082         musb_ep_frame_cancel(&s->ep[ep], 0);
1083
1084         if ((ep && (value & MGC_M_TXCSR_FLUSHFIFO)) ||
1085                         (!ep && (value & MGC_M_CSR0_FLUSHFIFO))) {
1086             s->ep[ep].fifolen[0] = 0;
1087             s->ep[ep].fifostart[0] = 0;
1088             if (ep)
1089                 s->ep[ep].csr[0] &=
1090                         ~(MGC_M_TXCSR_FIFONOTEMPTY | MGC_M_TXCSR_TXPKTRDY);
1091             else
1092                 s->ep[ep].csr[0] &=
1093                         ~(MGC_M_CSR0_TXPKTRDY | MGC_M_CSR0_RXPKTRDY);
1094         }
1095         if (
1096                         (ep &&
1097 #ifdef CLEAR_NAK
1098                          (value & MGC_M_TXCSR_TXPKTRDY) &&
1099                          !(value & MGC_M_TXCSR_H_NAKTIMEOUT)) ||
1100 #else
1101                          (value & MGC_M_TXCSR_TXPKTRDY)) ||
1102 #endif
1103                         (!ep &&
1104 #ifdef CLEAR_NAK
1105                          (value & MGC_M_CSR0_TXPKTRDY) &&
1106                          !(value & MGC_M_CSR0_H_NAKTIMEOUT)))
1107 #else
1108                          (value & MGC_M_CSR0_TXPKTRDY)))
1109 #endif
1110             musb_tx_rdy(s, ep);
1111         if (!ep &&
1112                         (value & MGC_M_CSR0_H_REQPKT) &&
1113 #ifdef CLEAR_NAK
1114                         !(value & (MGC_M_CSR0_H_NAKTIMEOUT |
1115                                         MGC_M_CSR0_RXPKTRDY)))
1116 #else
1117                         !(value & MGC_M_CSR0_RXPKTRDY))
1118 #endif
1119             musb_rx_req(s, ep);
1120         break;
1121
1122     case MUSB_HDRC_RXMAXP:
1123         s->ep[ep].maxp[1] = value;
1124         break;
1125     case MUSB_HDRC_RXCSR:
1126         /* (DMA mode only) */
1127         if (
1128                 (value & MGC_M_RXCSR_H_AUTOREQ) &&
1129                 !(value & MGC_M_RXCSR_RXPKTRDY) &&
1130                 (s->ep[ep].csr[1] & MGC_M_RXCSR_RXPKTRDY))
1131             value |= MGC_M_RXCSR_H_REQPKT;
1132
1133         s->ep[ep].csr[1] &= 0x102 | (value & 0x4d);
1134         s->ep[ep].csr[1] |= value & 0xfeb0;
1135
1136         musb_ep_frame_cancel(&s->ep[ep], 1);
1137
1138         if (value & MGC_M_RXCSR_FLUSHFIFO) {
1139             s->ep[ep].fifolen[1] = 0;
1140             s->ep[ep].fifostart[1] = 0;
1141             s->ep[ep].csr[1] &= ~(MGC_M_RXCSR_FIFOFULL | MGC_M_RXCSR_RXPKTRDY);
1142             /* If double buffering and we have two packets ready, flush
1143              * only the first one and set up the fifo at the second packet.  */
1144         }
1145 #ifdef CLEAR_NAK
1146         if ((value & MGC_M_RXCSR_H_REQPKT) && !(value & MGC_M_RXCSR_DATAERROR))
1147 #else
1148         if (value & MGC_M_RXCSR_H_REQPKT)
1149 #endif
1150             musb_rx_req(s, ep);
1151         break;
1152     case MUSB_HDRC_RXCOUNT:
1153         s->ep[ep].rxcount = value;
1154         break;
1155
1156     default:
1157         musb_ep_writeb(s, ep, addr, value & 0xff);
1158         musb_ep_writeb(s, ep, addr | 1, value >> 8);
1159     };
1160 }
1161
1162 /* Generic control */
1163 static uint32_t musb_readb(void *opaque, target_phys_addr_t addr)
1164 {
1165     struct musb_s *s = (struct musb_s *) opaque;
1166     int ep, i;
1167     uint8_t ret;
1168 //    TRACE("ADDR = 0x%08x", addr);
1169
1170     switch (addr) {
1171     case MUSB_HDRC_FADDR:
1172         return s->faddr;
1173     case MUSB_HDRC_POWER:
1174         return s->power;
1175     case MUSB_HDRC_INTRUSB:
1176         ret = s->intr;
1177         for (i = 0; i < sizeof(ret) * 8; i ++)
1178             if (ret & (1 << i))
1179                 musb_intr_set(s, i, 0);
1180         return ret;
1181     case MUSB_HDRC_INTRUSBE:
1182         return s->mask;
1183     case MUSB_HDRC_INDEX:
1184         return s->idx;
1185     case MUSB_HDRC_TESTMODE:
1186         return 0x00;
1187
1188     case MUSB_HDRC_EP_IDX ... (MUSB_HDRC_EP_IDX + 0xf):
1189         return musb_ep_readb(s, s->idx, addr & 0xf);
1190
1191     case MUSB_HDRC_DEVCTL:
1192         return s->devctl;
1193
1194     case MUSB_HDRC_TXFIFOSZ:
1195     case MUSB_HDRC_RXFIFOSZ:
1196     case MUSB_HDRC_VCTRL:
1197         /* TODO */
1198         return 0x00;
1199
1200     case MUSB_HDRC_HWVERS:
1201         return (1 << 10) | 400;
1202
1203     case (MUSB_HDRC_VCTRL | 1):
1204     case (MUSB_HDRC_HWVERS | 1):
1205     case (MUSB_HDRC_DEVCTL | 1):
1206         return 0x00;
1207
1208     case MUSB_HDRC_BUSCTL ... (MUSB_HDRC_BUSCTL + 0x7f):
1209         ep = (addr >> 3) & 0xf;
1210         return musb_busctl_readb(s, ep, addr & 0x7);
1211
1212     case MUSB_HDRC_EP ... (MUSB_HDRC_EP + 0xff):
1213         ep = (addr >> 4) & 0xf;
1214         return musb_ep_readb(s, ep, addr & 0xf);
1215
1216     case MUSB_HDRC_FIFO ... (MUSB_HDRC_FIFO + 0x3f):
1217         ep = ((addr - MUSB_HDRC_FIFO) >> 2) & 0xf;
1218         return musb_read_fifo(s->ep + ep);
1219
1220     default:
1221         fprintf(stderr, "%s: unknown register at %02x\n", __FUNCTION__, (int) addr);
1222         return 0x00;
1223     };
1224 }
1225
1226 static void musb_writeb(void *opaque, target_phys_addr_t addr, uint32_t value)
1227 {
1228     struct musb_s *s = (struct musb_s *) opaque;
1229     int ep;
1230 //    TRACE("ADDR = 0x%08x = %08x", addr, value);
1231
1232     switch (addr) {
1233     case MUSB_HDRC_FADDR:
1234         s->faddr = value & 0x7f;
1235         break;
1236     case MUSB_HDRC_POWER:
1237         s->power = (value & 0xef) | (s->power & 0x10);
1238         /* MGC_M_POWER_RESET is also read-only in Peripheral Mode */
1239         if ((value & MGC_M_POWER_RESET) && s->port.dev) {
1240             usb_send_msg(s->port.dev, USB_MSG_RESET);
1241             /* Negotiate high-speed operation if MGC_M_POWER_HSENAB is set.  */
1242             if ((value & MGC_M_POWER_HSENAB) &&
1243                             s->port.dev->speed == USB_SPEED_HIGH)
1244                 s->power |= MGC_M_POWER_HSMODE; /* Success */
1245             /* Restart frame counting.  */
1246         }
1247         if (value & MGC_M_POWER_SUSPENDM) {
1248             /* When all transfers finish, suspend and if MGC_M_POWER_ENSUSPEND
1249              * is set, also go into low power mode.  Frame counting stops.  */
1250             /* XXX: Cleared when the interrupt register is read */
1251         }
1252         if (value & MGC_M_POWER_RESUME) {
1253             /* Wait 20ms and signal resuming on the bus.  Frame counting
1254              * restarts.  */
1255         }
1256         break;
1257     case MUSB_HDRC_INTRUSB:
1258         break;
1259     case MUSB_HDRC_INTRUSBE:
1260         s->mask = value & 0xff;
1261         break;
1262     case MUSB_HDRC_INDEX:
1263         s->idx = value & 0xf;
1264         break;
1265     case MUSB_HDRC_TESTMODE:
1266         break;
1267
1268     case MUSB_HDRC_EP_IDX ... (MUSB_HDRC_EP_IDX + 0xf):
1269         musb_ep_writeb(s, s->idx, addr & 0xf, value);
1270         break;
1271
1272     case MUSB_HDRC_DEVCTL:
1273         s->session = !!(value & MGC_M_DEVCTL_SESSION);
1274         musb_session_update(s,
1275                         !!s->port.dev,
1276                         !!(s->devctl & MGC_M_DEVCTL_SESSION));
1277
1278         /* It seems this is the only R/W bit in this register?  */
1279         s->devctl &= ~MGC_M_DEVCTL_SESSION;
1280         s->devctl |= value & MGC_M_DEVCTL_SESSION;
1281         break;
1282
1283     case MUSB_HDRC_TXFIFOSZ:
1284     case MUSB_HDRC_RXFIFOSZ:
1285     case MUSB_HDRC_VCTRL:
1286         /* TODO */
1287         break;
1288
1289     case (MUSB_HDRC_VCTRL | 1):
1290     case (MUSB_HDRC_DEVCTL | 1):
1291         break;
1292
1293     case MUSB_HDRC_BUSCTL ... (MUSB_HDRC_BUSCTL + 0x7f):
1294         ep = (addr >> 3) & 0xf;
1295         musb_busctl_writeb(s, ep, addr & 0x7, value);
1296         break;
1297
1298     case MUSB_HDRC_EP ... (MUSB_HDRC_EP + 0xff):
1299         ep = (addr >> 4) & 0xf;
1300         musb_ep_writeb(s, ep, addr & 0xf, value);
1301         break;
1302
1303     case MUSB_HDRC_FIFO ... (MUSB_HDRC_FIFO + 0x3f):
1304         ep = ((addr - MUSB_HDRC_FIFO) >> 2) & 0xf;
1305         musb_write_fifo(s->ep + ep, value & 0xff);
1306         break;
1307
1308     default:
1309         fprintf(stderr, "%s: unknown register at %02x\n", __FUNCTION__, (int) addr);
1310     };
1311 }
1312
1313 static uint32_t musb_readh(void *opaque, target_phys_addr_t addr)
1314 {
1315     struct musb_s *s = (struct musb_s *) opaque;
1316     int ep, i;
1317     uint16_t ret;
1318 //    TRACE("ADDR = 0x%08x", addr);
1319
1320     switch (addr) {
1321     case MUSB_HDRC_INTRTX:
1322         ret = s->tx_intr;
1323         /* Auto clear */
1324         for (i = 0; i < sizeof(ret) * 8; i ++)
1325             if (ret & (1 << i))
1326                 musb_tx_intr_set(s, i, 0);
1327         return ret;
1328     case MUSB_HDRC_INTRRX:
1329         ret = s->rx_intr;
1330         /* Auto clear */
1331         for (i = 0; i < sizeof(ret) * 8; i ++)
1332             if (ret & (1 << i))
1333                 musb_rx_intr_set(s, i, 0);
1334         return ret;
1335     case MUSB_HDRC_INTRTXE:
1336         return s->tx_mask;
1337     case MUSB_HDRC_INTRRXE:
1338         return s->rx_mask;
1339
1340     case MUSB_HDRC_FRAME:
1341         /* TODO */
1342         return 0x0000;
1343     case MUSB_HDRC_TXFIFOADDR:
1344         return s->ep[s->idx].fifoaddr[0];
1345     case MUSB_HDRC_RXFIFOADDR:
1346         return s->ep[s->idx].fifoaddr[1];
1347
1348     case MUSB_HDRC_EP_IDX ... (MUSB_HDRC_EP_IDX + 0xf):
1349         return musb_ep_readh(s, s->idx, addr & 0xf);
1350
1351     case MUSB_HDRC_BUSCTL ... (MUSB_HDRC_BUSCTL + 0x7f):
1352         ep = (addr >> 3) & 0xf;
1353         return musb_busctl_readh(s, ep, addr & 0x7);
1354
1355     case MUSB_HDRC_EP ... (MUSB_HDRC_EP + 0xff):
1356         ep = (addr >> 4) & 0xf;
1357         return musb_ep_readh(s, ep, addr & 0xf);
1358
1359     case MUSB_HDRC_FIFO ... (MUSB_HDRC_FIFO + 0x3f):
1360         ep = ((addr - MUSB_HDRC_FIFO) >> 2) & 0xf;
1361         return (musb_read_fifo(s->ep + ep) | musb_read_fifo(s->ep + ep) << 8);
1362
1363     default:
1364         return musb_readb(s, addr) | (musb_readb(s, addr | 1) << 8);
1365     };
1366 }
1367
1368 static void musb_writeh(void *opaque, target_phys_addr_t addr, uint32_t value)
1369 {
1370     struct musb_s *s = (struct musb_s *) opaque;
1371     int ep;
1372     //TRACE("ADDR = 0x%08x = %08x", addr, value);
1373
1374     switch (addr) {
1375     case MUSB_HDRC_INTRTXE:
1376         s->tx_mask = value;
1377         /* XXX: the masks seem to apply on the raising edge like with
1378          * edge-triggered interrupts, thus no need to update.  I may be
1379          * wrong though.  */
1380         break;
1381     case MUSB_HDRC_INTRRXE:
1382         s->rx_mask = value;
1383         break;
1384
1385     case MUSB_HDRC_FRAME:
1386         /* TODO */
1387         break;
1388     case MUSB_HDRC_TXFIFOADDR:
1389         s->ep[s->idx].fifoaddr[0] = value;
1390         s->ep[s->idx].buf[0] =
1391                 s->buf + ((value << 3) & 0x7ff );
1392         //TRACE("TXFIFOADDR = 0x%08x, BUF %08x", value, s->ep[s->idx].buf[0]);
1393         break;
1394     case MUSB_HDRC_RXFIFOADDR:
1395         s->ep[s->idx].fifoaddr[1] = value;
1396         s->ep[s->idx].buf[1] =
1397                 s->buf + ((value << 3) & 0x7ff);
1398         //TRACE("RXFIFOADDR = 0x%08x, BUF %08x", value, s->ep[s->idx].buf[1]);
1399         break;
1400
1401     case MUSB_HDRC_EP_IDX ... (MUSB_HDRC_EP_IDX + 0xf):
1402         musb_ep_writeh(s, s->idx, addr & 0xf, value);
1403         break;
1404
1405     case MUSB_HDRC_BUSCTL ... (MUSB_HDRC_BUSCTL + 0x7f):
1406         ep = (addr >> 3) & 0xf;
1407         musb_busctl_writeh(s, ep, addr & 0x7, value);
1408         break;
1409
1410     case MUSB_HDRC_EP ... (MUSB_HDRC_EP + 0xff):
1411         ep = (addr >> 4) & 0xf;
1412         musb_ep_writeh(s, ep, addr & 0xf, value);
1413         break;
1414
1415     case MUSB_HDRC_FIFO ... (MUSB_HDRC_FIFO + 0x3f):
1416         ep = ((addr - MUSB_HDRC_FIFO) >> 2) & 0xf;
1417         musb_write_fifo(s->ep + ep, value & 0xff);
1418         musb_write_fifo(s->ep + ep, (value >> 8) & 0xff);
1419         break;
1420
1421     default:
1422         musb_writeb(s, addr, value & 0xff);
1423         musb_writeb(s, addr | 1, value >> 8);
1424     };
1425 }
1426
1427 static uint32_t musb_readw(void *opaque, target_phys_addr_t addr)
1428 {
1429     struct musb_s *s = (struct musb_s *) opaque;
1430     int ep;
1431
1432     switch (addr) {
1433     case MUSB_HDRC_FIFO ... (MUSB_HDRC_FIFO + 0x3f):
1434         ep = ((addr - MUSB_HDRC_FIFO) >> 2) & 0xf;
1435         return ( musb_read_fifo(s->ep + ep)       |
1436                  musb_read_fifo(s->ep + ep) << 8  |
1437                  musb_read_fifo(s->ep + ep) << 16 |
1438                  musb_read_fifo(s->ep + ep) << 24 );
1439     default:
1440         fprintf(stderr, "%s: unknown register at %02x\n", __FUNCTION__, (int) addr);
1441         return 0x00000000;
1442     };
1443 }
1444
1445 static void musb_writew(void *opaque, target_phys_addr_t addr, uint32_t value)
1446 {
1447     struct musb_s *s = (struct musb_s *) opaque;
1448     int ep;
1449 //    TRACE("ADDR = 0x%08x = %08x", addr, value);
1450
1451     switch (addr) {
1452     case MUSB_HDRC_FIFO ... (MUSB_HDRC_FIFO + 0x3f):
1453         ep = ((addr - MUSB_HDRC_FIFO) >> 2) & 0xf;
1454         musb_write_fifo(s->ep + ep, value & 0xff);
1455         musb_write_fifo(s->ep + ep, (value >> 8 ) & 0xff);
1456         musb_write_fifo(s->ep + ep, (value >> 16) & 0xff);
1457         musb_write_fifo(s->ep + ep, (value >> 24) & 0xff);
1458         break;
1459     default:
1460         fprintf(stderr, "%s: unknown register at %02x\n", __FUNCTION__, (int) addr);
1461     };
1462 }
1463
1464 CPUReadMemoryFunc *musb_read[] = {
1465     musb_readb,
1466     musb_readh,
1467     musb_readw,
1468 };
1469
1470 CPUWriteMemoryFunc *musb_write[] = {
1471     musb_writeb,
1472     musb_writeh,
1473     musb_writew,
1474 };
1475
1476 static void musb_save_state(QEMUFile *f, void *opaque)
1477 {
1478     struct musb_s *s = (struct musb_s *)opaque;
1479     int i, j;
1480     
1481     qemu_put_sbe32(f, s->idx);
1482     qemu_put_byte(f, s->devctl);
1483     qemu_put_byte(f, s->power);
1484     qemu_put_byte(f, s->faddr);
1485     qemu_put_byte(f, s->intr);
1486     qemu_put_byte(f, s->mask);
1487     qemu_put_be16(f, s->tx_intr);
1488     qemu_put_be16(f, s->tx_mask);
1489     qemu_put_be16(f, s->rx_intr);
1490     qemu_put_be16(f, s->rx_mask);
1491     qemu_put_sbe32(f, s->setup_len);
1492     qemu_put_sbe32(f, s->session);
1493     qemu_put_buffer(f, s->buf, sizeof(s->buf));
1494     for (i = 0; i < 16; i++) {
1495         qemu_put_be16(f, s->ep[i].rxcount);
1496         qemu_put_byte(f, s->ep[i].config);
1497         qemu_put_byte(f, s->ep[i].fifosize);
1498         for (j = 0; j < 2; j++) {
1499             qemu_put_be16(f, s->ep[i].faddr[j]);
1500             qemu_put_byte(f, s->ep[i].haddr[j]);
1501             qemu_put_byte(f, s->ep[i].hport[j]);
1502             qemu_put_be16(f, s->ep[i].csr[j]);
1503             qemu_put_be16(f, s->ep[i].maxp[j]);
1504             qemu_put_byte(f, s->ep[i].type[j]);
1505             qemu_put_byte(f, s->ep[i].interval[j]);
1506             qemu_put_sbe32(f, s->ep[i].timeout[j]);
1507             if (s->ep[i].buf[j])
1508                 qemu_put_be32(f, s->ep[i].buf[j] - s->buf);
1509             else
1510                 qemu_put_be32(f, 0xffffffff);
1511             qemu_put_sbe32(f, s->ep[i].fifolen[j]);
1512             qemu_put_sbe32(f, s->ep[i].fifostart[j]);
1513             qemu_put_sbe32(f, s->ep[i].fifoaddr[j]);
1514             qemu_put_sbe32(f, s->ep[i].packey[j].pid);
1515             qemu_put_byte(f, s->ep[i].packey[j].devaddr);
1516             qemu_put_byte(f, s->ep[i].packey[j].devep);
1517             qemu_put_sbe32(f, s->ep[i].packey[j].len);
1518             qemu_put_sbe32(f, s->ep[i].status[j]);
1519             qemu_put_sbe32(f, s->ep[i].ext_size[j]);
1520             qemu_put_sbe32(f, s->ep[i].interrupt[j]);
1521             if (s->ep[i].delayed_cb[j] == musb_rx_packet_complete)
1522                 qemu_put_byte(f, 1);
1523             else if (s->ep[i].delayed_cb[j] == musb_tx_packet_complete)
1524                 qemu_put_byte(f, 2);
1525             else
1526                 qemu_put_byte(f, 0);
1527             if (s->ep[i].intv_timer[j]) {
1528                 qemu_put_byte(f, 1);
1529                 qemu_put_timer(f, s->ep[i].intv_timer[j]);
1530             } else
1531                 qemu_put_byte(f, 0);
1532         }
1533     }
1534 }
1535
1536 static int musb_load_state(QEMUFile *f, void *opaque, int version_id)
1537 {
1538     struct musb_s *s = (struct musb_s *)opaque;
1539     int i, j;
1540     uint32_t x;
1541     
1542     if (version_id)
1543         return -EINVAL;
1544     
1545     s->idx = qemu_get_sbe32(f);
1546     s->devctl = qemu_get_byte(f);
1547     s->power = qemu_get_byte(f);
1548     s->faddr = qemu_get_byte(f);
1549     s->intr = qemu_get_byte(f);
1550     s->mask = qemu_get_byte(f);
1551     s->tx_intr = qemu_get_be16(f);
1552     s->tx_mask = qemu_get_be16(f);
1553     s->rx_intr = qemu_get_be16(f);
1554     s->rx_mask = qemu_get_be16(f);
1555     s->setup_len = qemu_get_sbe32(f);
1556     s->session = qemu_get_sbe32(f);
1557     qemu_get_buffer(f, s->buf, sizeof(s->buf));
1558     for (i = 0; i < 16; i++) {
1559         s->ep[i].rxcount = qemu_get_be16(f);
1560         s->ep[i].config = qemu_get_byte(f);
1561         s->ep[i].fifosize = qemu_get_byte(f);
1562         for (j = 0; j < 2; j++) {
1563             s->ep[i].faddr[j] = qemu_get_be16(f);
1564             s->ep[i].haddr[j] = qemu_get_byte(f);
1565             s->ep[i].hport[j] = qemu_get_byte(f);
1566             s->ep[i].csr[j] = qemu_get_be16(f);
1567             s->ep[i].maxp[j] = qemu_get_be16(f);
1568             s->ep[i].type[j] = qemu_get_byte(f);
1569             s->ep[i].interval[j] = qemu_get_byte(f);
1570             s->ep[i].timeout[j] = qemu_get_sbe32(f);
1571             x = qemu_get_be32(f);
1572             if (x != 0xffffffff)
1573                 s->ep[i].buf[j] = s->buf + x;
1574             else
1575                 s->ep[i].buf[j] = 0;
1576             s->ep[i].fifolen[j] = qemu_get_sbe32(f);
1577             s->ep[i].fifostart[j] = qemu_get_sbe32(f);
1578             s->ep[i].fifoaddr[j] = qemu_get_sbe32(f);
1579             s->ep[i].packey[j].pid = qemu_get_sbe32(f);
1580             s->ep[i].packey[j].devaddr = qemu_get_byte(f);
1581             s->ep[i].packey[j].devep = qemu_get_byte(f);
1582             s->ep[i].packey[j].data = s->ep[i].buf[j];
1583             s->ep[i].packey[j].len = qemu_get_sbe32(f);
1584             s->ep[i].packey[j].complete_opaque = &s->ep[i];
1585             s->ep[i].status[j] = qemu_get_sbe32(f);
1586             s->ep[i].ext_size[j] = qemu_get_sbe32(f);
1587             s->ep[i].interrupt[j] = qemu_get_sbe32(f);
1588             switch (qemu_get_byte(f)) {
1589                 case 0:
1590                     s->ep[i].delayed_cb[j] = 0;
1591                     s->ep[i].packey[j].complete_cb = 0;
1592                     break;
1593                 case 1:
1594                     s->ep[i].delayed_cb[j] = musb_rx_packet_complete;
1595                     s->ep[i].packey[j].complete_cb = musb_rx_packet_complete;
1596                     break;
1597                 case 2:
1598                     s->ep[i].delayed_cb[j] = musb_tx_packet_complete;
1599                     s->ep[i].packey[j].complete_cb = musb_tx_packet_complete;
1600                     break;
1601                 default:
1602                     fprintf(stderr, "%s: unknown delayed_cb\n", __FUNCTION__);
1603                     exit(-1);
1604                     break;
1605             }
1606             if (qemu_get_byte(f)) {
1607                 if (!s->ep[i].intv_timer[j]) {
1608                     s->ep[i].intv_timer[j] =
1609                         qemu_new_timer(vm_clock,
1610                                        j ? musb_cb_tick1 : musb_cb_tick0,
1611                                        &s->ep[i]);
1612                 }
1613                 qemu_get_timer(f, s->ep[i].intv_timer[j]);
1614             }
1615         }
1616     }
1617     
1618     /* TODO: restore interrupt status */
1619     
1620     return 0;
1621 }
1622
1623 struct musb_s *musb_init(qemu_irq *irqs)
1624 {
1625     struct musb_s *s = qemu_mallocz(sizeof(*s));
1626     int i;
1627     
1628     s->irqs = irqs;
1629     
1630     s->faddr = 0x00;
1631     s->power = MGC_M_POWER_HSENAB;
1632     s->tx_intr = 0x0000;
1633     s->rx_intr = 0x0000;
1634     s->tx_mask = 0xffff;
1635     s->rx_mask = 0xffff;
1636     s->intr = 0x00;
1637     s->mask = 0x06;
1638     s->idx = 0;
1639     
1640     /* TODO: _DW */
1641     s->ep[0].config = MGC_M_CONFIGDATA_SOFTCONE | MGC_M_CONFIGDATA_DYNFIFO;
1642     for (i = 0; i < 16; i ++) {
1643         s->ep[i].fifosize = 64;
1644         s->ep[i].maxp[0] = 0x40;
1645         s->ep[i].maxp[1] = 0x40;
1646         s->ep[i].musb = s;
1647         s->ep[i].epnum = i;
1648     }
1649     
1650     qemu_register_usb_port(&s->port, s, 0, musb_attach);
1651     register_savevm("musb", -1, 0, musb_save_state, musb_load_state, s);
1652     return s;
1653 }