musb_host: refactor musb_save_toggle() (take 2)
[safe/jmp/linux-2.6] / drivers / usb / musb / musb_host.c
1 /*
2  * MUSB OTG driver host support
3  *
4  * Copyright 2005 Mentor Graphics Corporation
5  * Copyright (C) 2005-2006 by Texas Instruments
6  * Copyright (C) 2006-2007 Nokia Corporation
7  * Copyright (C) 2008-2009 MontaVista Software, Inc. <source@mvista.com>
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * version 2 as published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
21  * 02110-1301 USA
22  *
23  * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
24  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
26  * NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
29  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
30  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  *
34  */
35
36 #include <linux/module.h>
37 #include <linux/kernel.h>
38 #include <linux/delay.h>
39 #include <linux/sched.h>
40 #include <linux/slab.h>
41 #include <linux/errno.h>
42 #include <linux/init.h>
43 #include <linux/list.h>
44
45 #include "musb_core.h"
46 #include "musb_host.h"
47
48
49 /* MUSB HOST status 22-mar-2006
50  *
51  * - There's still lots of partial code duplication for fault paths, so
52  *   they aren't handled as consistently as they need to be.
53  *
54  * - PIO mostly behaved when last tested.
55  *     + including ep0, with all usbtest cases 9, 10
56  *     + usbtest 14 (ep0out) doesn't seem to run at all
57  *     + double buffered OUT/TX endpoints saw stalls(!) with certain usbtest
58  *       configurations, but otherwise double buffering passes basic tests.
59  *     + for 2.6.N, for N > ~10, needs API changes for hcd framework.
60  *
61  * - DMA (CPPI) ... partially behaves, not currently recommended
62  *     + about 1/15 the speed of typical EHCI implementations (PCI)
63  *     + RX, all too often reqpkt seems to misbehave after tx
64  *     + TX, no known issues (other than evident silicon issue)
65  *
66  * - DMA (Mentor/OMAP) ...has at least toggle update problems
67  *
68  * - [23-feb-2009] minimal traffic scheduling to avoid bulk RX packet
69  *   starvation ... nothing yet for TX, interrupt, or bulk.
70  *
71  * - Not tested with HNP, but some SRP paths seem to behave.
72  *
73  * NOTE 24-August-2006:
74  *
75  * - Bulk traffic finally uses both sides of hardware ep1, freeing up an
76  *   extra endpoint for periodic use enabling hub + keybd + mouse.  That
77  *   mostly works, except that with "usbnet" it's easy to trigger cases
78  *   with "ping" where RX loses.  (a) ping to davinci, even "ping -f",
79  *   fine; but (b) ping _from_ davinci, even "ping -c 1", ICMP RX loses
80  *   although ARP RX wins.  (That test was done with a full speed link.)
81  */
82
83
84 /*
85  * NOTE on endpoint usage:
86  *
87  * CONTROL transfers all go through ep0.  BULK ones go through dedicated IN
88  * and OUT endpoints ... hardware is dedicated for those "async" queue(s).
89  * (Yes, bulk _could_ use more of the endpoints than that, and would even
90  * benefit from it.)
91  *
92  * INTERUPPT and ISOCHRONOUS transfers are scheduled to the other endpoints.
93  * So far that scheduling is both dumb and optimistic:  the endpoint will be
94  * "claimed" until its software queue is no longer refilled.  No multiplexing
95  * of transfers between endpoints, or anything clever.
96  */
97
98
99 static void musb_ep_program(struct musb *musb, u8 epnum,
100                         struct urb *urb, int is_out,
101                         u8 *buf, u32 offset, u32 len);
102
103 /*
104  * Clear TX fifo. Needed to avoid BABBLE errors.
105  */
106 static void musb_h_tx_flush_fifo(struct musb_hw_ep *ep)
107 {
108         void __iomem    *epio = ep->regs;
109         u16             csr;
110         u16             lastcsr = 0;
111         int             retries = 1000;
112
113         csr = musb_readw(epio, MUSB_TXCSR);
114         while (csr & MUSB_TXCSR_FIFONOTEMPTY) {
115                 if (csr != lastcsr)
116                         DBG(3, "Host TX FIFONOTEMPTY csr: %02x\n", csr);
117                 lastcsr = csr;
118                 csr |= MUSB_TXCSR_FLUSHFIFO;
119                 musb_writew(epio, MUSB_TXCSR, csr);
120                 csr = musb_readw(epio, MUSB_TXCSR);
121                 if (WARN(retries-- < 1,
122                                 "Could not flush host TX%d fifo: csr: %04x\n",
123                                 ep->epnum, csr))
124                         return;
125                 mdelay(1);
126         }
127 }
128
129 static void musb_h_ep0_flush_fifo(struct musb_hw_ep *ep)
130 {
131         void __iomem    *epio = ep->regs;
132         u16             csr;
133         int             retries = 5;
134
135         /* scrub any data left in the fifo */
136         do {
137                 csr = musb_readw(epio, MUSB_TXCSR);
138                 if (!(csr & (MUSB_CSR0_TXPKTRDY | MUSB_CSR0_RXPKTRDY)))
139                         break;
140                 musb_writew(epio, MUSB_TXCSR, MUSB_CSR0_FLUSHFIFO);
141                 csr = musb_readw(epio, MUSB_TXCSR);
142                 udelay(10);
143         } while (--retries);
144
145         WARN(!retries, "Could not flush host TX%d fifo: csr: %04x\n",
146                         ep->epnum, csr);
147
148         /* and reset for the next transfer */
149         musb_writew(epio, MUSB_TXCSR, 0);
150 }
151
152 /*
153  * Start transmit. Caller is responsible for locking shared resources.
154  * musb must be locked.
155  */
156 static inline void musb_h_tx_start(struct musb_hw_ep *ep)
157 {
158         u16     txcsr;
159
160         /* NOTE: no locks here; caller should lock and select EP */
161         if (ep->epnum) {
162                 txcsr = musb_readw(ep->regs, MUSB_TXCSR);
163                 txcsr |= MUSB_TXCSR_TXPKTRDY | MUSB_TXCSR_H_WZC_BITS;
164                 musb_writew(ep->regs, MUSB_TXCSR, txcsr);
165         } else {
166                 txcsr = MUSB_CSR0_H_SETUPPKT | MUSB_CSR0_TXPKTRDY;
167                 musb_writew(ep->regs, MUSB_CSR0, txcsr);
168         }
169
170 }
171
172 static inline void musb_h_tx_dma_start(struct musb_hw_ep *ep)
173 {
174         u16     txcsr;
175
176         /* NOTE: no locks here; caller should lock and select EP */
177         txcsr = musb_readw(ep->regs, MUSB_TXCSR);
178         txcsr |= MUSB_TXCSR_DMAENAB | MUSB_TXCSR_H_WZC_BITS;
179         if (is_cppi_enabled())
180                 txcsr |= MUSB_TXCSR_DMAMODE;
181         musb_writew(ep->regs, MUSB_TXCSR, txcsr);
182 }
183
184 /*
185  * Start the URB at the front of an endpoint's queue
186  * end must be claimed from the caller.
187  *
188  * Context: controller locked, irqs blocked
189  */
190 static void
191 musb_start_urb(struct musb *musb, int is_in, struct musb_qh *qh)
192 {
193         u16                     frame;
194         u32                     len;
195         void __iomem            *mbase =  musb->mregs;
196         struct urb              *urb = next_urb(qh);
197         void                    *buf = urb->transfer_buffer;
198         u32                     offset = 0;
199         struct musb_hw_ep       *hw_ep = qh->hw_ep;
200         unsigned                pipe = urb->pipe;
201         u8                      address = usb_pipedevice(pipe);
202         int                     epnum = hw_ep->epnum;
203
204         /* initialize software qh state */
205         qh->offset = 0;
206         qh->segsize = 0;
207
208         /* gather right source of data */
209         switch (qh->type) {
210         case USB_ENDPOINT_XFER_CONTROL:
211                 /* control transfers always start with SETUP */
212                 is_in = 0;
213                 hw_ep->out_qh = qh;
214                 musb->ep0_stage = MUSB_EP0_START;
215                 buf = urb->setup_packet;
216                 len = 8;
217                 break;
218         case USB_ENDPOINT_XFER_ISOC:
219                 qh->iso_idx = 0;
220                 qh->frame = 0;
221                 offset = urb->iso_frame_desc[0].offset;
222                 len = urb->iso_frame_desc[0].length;
223                 break;
224         default:                /* bulk, interrupt */
225                 /* actual_length may be nonzero on retry paths */
226                 buf = urb->transfer_buffer + urb->actual_length;
227                 len = urb->transfer_buffer_length - urb->actual_length;
228         }
229
230         DBG(4, "qh %p urb %p dev%d ep%d%s%s, hw_ep %d, %p/%d\n",
231                         qh, urb, address, qh->epnum,
232                         is_in ? "in" : "out",
233                         ({char *s; switch (qh->type) {
234                         case USB_ENDPOINT_XFER_CONTROL: s = ""; break;
235                         case USB_ENDPOINT_XFER_BULK:    s = "-bulk"; break;
236                         case USB_ENDPOINT_XFER_ISOC:    s = "-iso"; break;
237                         default:                        s = "-intr"; break;
238                         }; s; }),
239                         epnum, buf + offset, len);
240
241         /* Configure endpoint */
242         if (is_in || hw_ep->is_shared_fifo)
243                 hw_ep->in_qh = qh;
244         else
245                 hw_ep->out_qh = qh;
246         musb_ep_program(musb, epnum, urb, !is_in, buf, offset, len);
247
248         /* transmit may have more work: start it when it is time */
249         if (is_in)
250                 return;
251
252         /* determine if the time is right for a periodic transfer */
253         switch (qh->type) {
254         case USB_ENDPOINT_XFER_ISOC:
255         case USB_ENDPOINT_XFER_INT:
256                 DBG(3, "check whether there's still time for periodic Tx\n");
257                 frame = musb_readw(mbase, MUSB_FRAME);
258                 /* FIXME this doesn't implement that scheduling policy ...
259                  * or handle framecounter wrapping
260                  */
261                 if ((urb->transfer_flags & URB_ISO_ASAP)
262                                 || (frame >= urb->start_frame)) {
263                         /* REVISIT the SOF irq handler shouldn't duplicate
264                          * this code; and we don't init urb->start_frame...
265                          */
266                         qh->frame = 0;
267                         goto start;
268                 } else {
269                         qh->frame = urb->start_frame;
270                         /* enable SOF interrupt so we can count down */
271                         DBG(1, "SOF for %d\n", epnum);
272 #if 1 /* ifndef CONFIG_ARCH_DAVINCI */
273                         musb_writeb(mbase, MUSB_INTRUSBE, 0xff);
274 #endif
275                 }
276                 break;
277         default:
278 start:
279                 DBG(4, "Start TX%d %s\n", epnum,
280                         hw_ep->tx_channel ? "dma" : "pio");
281
282                 if (!hw_ep->tx_channel)
283                         musb_h_tx_start(hw_ep);
284                 else if (is_cppi_enabled() || tusb_dma_omap())
285                         musb_h_tx_dma_start(hw_ep);
286         }
287 }
288
289 /* caller owns controller lock, irqs are blocked */
290 static void
291 __musb_giveback(struct musb *musb, struct urb *urb, int status)
292 __releases(musb->lock)
293 __acquires(musb->lock)
294 {
295         DBG(({ int level; switch (status) {
296                                 case 0:
297                                         level = 4;
298                                         break;
299                                 /* common/boring faults */
300                                 case -EREMOTEIO:
301                                 case -ESHUTDOWN:
302                                 case -ECONNRESET:
303                                 case -EPIPE:
304                                         level = 3;
305                                         break;
306                                 default:
307                                         level = 2;
308                                         break;
309                                 }; level; }),
310                         "complete %p %pF (%d), dev%d ep%d%s, %d/%d\n",
311                         urb, urb->complete, status,
312                         usb_pipedevice(urb->pipe),
313                         usb_pipeendpoint(urb->pipe),
314                         usb_pipein(urb->pipe) ? "in" : "out",
315                         urb->actual_length, urb->transfer_buffer_length
316                         );
317
318         usb_hcd_unlink_urb_from_ep(musb_to_hcd(musb), urb);
319         spin_unlock(&musb->lock);
320         usb_hcd_giveback_urb(musb_to_hcd(musb), urb, status);
321         spin_lock(&musb->lock);
322 }
323
324 /* For bulk/interrupt endpoints only */
325 static inline void musb_save_toggle(struct musb_qh *qh, int is_in,
326                                     struct urb *urb)
327 {
328         void __iomem            *epio = qh->hw_ep->regs;
329         u16                     csr;
330
331         /*
332          * FIXME: the current Mentor DMA code seems to have
333          * problems getting toggle correct.
334          */
335
336         if (is_in)
337                 csr = musb_readw(epio, MUSB_RXCSR) & MUSB_RXCSR_H_DATATOGGLE;
338         else
339                 csr = musb_readw(epio, MUSB_TXCSR) & MUSB_TXCSR_H_DATATOGGLE;
340
341         usb_settoggle(urb->dev, qh->epnum, !is_in, csr ? 1 : 0);
342 }
343
344 /* caller owns controller lock, irqs are blocked */
345 static struct musb_qh *
346 musb_giveback(struct musb_qh *qh, struct urb *urb, int status)
347 {
348         struct musb_hw_ep       *ep = qh->hw_ep;
349         struct musb             *musb = ep->musb;
350         int                     is_in = usb_pipein(urb->pipe);
351         int                     ready = qh->is_ready;
352
353         /* save toggle eagerly, for paranoia */
354         switch (qh->type) {
355         case USB_ENDPOINT_XFER_BULK:
356         case USB_ENDPOINT_XFER_INT:
357                 musb_save_toggle(qh, is_in, urb);
358                 break;
359         case USB_ENDPOINT_XFER_ISOC:
360                 if (status == 0 && urb->error_count)
361                         status = -EXDEV;
362                 break;
363         }
364
365         qh->is_ready = 0;
366         __musb_giveback(musb, urb, status);
367         qh->is_ready = ready;
368
369         /* reclaim resources (and bandwidth) ASAP; deschedule it, and
370          * invalidate qh as soon as list_empty(&hep->urb_list)
371          */
372         if (list_empty(&qh->hep->urb_list)) {
373                 struct list_head        *head;
374
375                 if (is_in)
376                         ep->rx_reinit = 1;
377                 else
378                         ep->tx_reinit = 1;
379
380                 /* clobber old pointers to this qh */
381                 if (is_in || ep->is_shared_fifo)
382                         ep->in_qh = NULL;
383                 else
384                         ep->out_qh = NULL;
385                 qh->hep->hcpriv = NULL;
386
387                 switch (qh->type) {
388
389                 case USB_ENDPOINT_XFER_CONTROL:
390                 case USB_ENDPOINT_XFER_BULK:
391                         /* fifo policy for these lists, except that NAKing
392                          * should rotate a qh to the end (for fairness).
393                          */
394                         if (qh->mux == 1) {
395                                 head = qh->ring.prev;
396                                 list_del(&qh->ring);
397                                 kfree(qh);
398                                 qh = first_qh(head);
399                                 break;
400                         }
401
402                 case USB_ENDPOINT_XFER_ISOC:
403                 case USB_ENDPOINT_XFER_INT:
404                         /* this is where periodic bandwidth should be
405                          * de-allocated if it's tracked and allocated;
406                          * and where we'd update the schedule tree...
407                          */
408                         kfree(qh);
409                         qh = NULL;
410                         break;
411                 }
412         }
413         return qh;
414 }
415
416 /*
417  * Advance this hardware endpoint's queue, completing the specified urb and
418  * advancing to either the next urb queued to that qh, or else invalidating
419  * that qh and advancing to the next qh scheduled after the current one.
420  *
421  * Context: caller owns controller lock, irqs are blocked
422  */
423 static void
424 musb_advance_schedule(struct musb *musb, struct urb *urb,
425                 struct musb_hw_ep *hw_ep, int is_in)
426 {
427         struct musb_qh  *qh;
428
429         if (is_in || hw_ep->is_shared_fifo)
430                 qh = hw_ep->in_qh;
431         else
432                 qh = hw_ep->out_qh;
433
434         if (urb->status == -EINPROGRESS)
435                 qh = musb_giveback(qh, urb, 0);
436         else
437                 qh = musb_giveback(qh, urb, urb->status);
438
439         if (qh != NULL && qh->is_ready) {
440                 DBG(4, "... next ep%d %cX urb %p\n",
441                                 hw_ep->epnum, is_in ? 'R' : 'T',
442                                 next_urb(qh));
443                 musb_start_urb(musb, is_in, qh);
444         }
445 }
446
447 static u16 musb_h_flush_rxfifo(struct musb_hw_ep *hw_ep, u16 csr)
448 {
449         /* we don't want fifo to fill itself again;
450          * ignore dma (various models),
451          * leave toggle alone (may not have been saved yet)
452          */
453         csr |= MUSB_RXCSR_FLUSHFIFO | MUSB_RXCSR_RXPKTRDY;
454         csr &= ~(MUSB_RXCSR_H_REQPKT
455                 | MUSB_RXCSR_H_AUTOREQ
456                 | MUSB_RXCSR_AUTOCLEAR);
457
458         /* write 2x to allow double buffering */
459         musb_writew(hw_ep->regs, MUSB_RXCSR, csr);
460         musb_writew(hw_ep->regs, MUSB_RXCSR, csr);
461
462         /* flush writebuffer */
463         return musb_readw(hw_ep->regs, MUSB_RXCSR);
464 }
465
466 /*
467  * PIO RX for a packet (or part of it).
468  */
469 static bool
470 musb_host_packet_rx(struct musb *musb, struct urb *urb, u8 epnum, u8 iso_err)
471 {
472         u16                     rx_count;
473         u8                      *buf;
474         u16                     csr;
475         bool                    done = false;
476         u32                     length;
477         int                     do_flush = 0;
478         struct musb_hw_ep       *hw_ep = musb->endpoints + epnum;
479         void __iomem            *epio = hw_ep->regs;
480         struct musb_qh          *qh = hw_ep->in_qh;
481         int                     pipe = urb->pipe;
482         void                    *buffer = urb->transfer_buffer;
483
484         /* musb_ep_select(mbase, epnum); */
485         rx_count = musb_readw(epio, MUSB_RXCOUNT);
486         DBG(3, "RX%d count %d, buffer %p len %d/%d\n", epnum, rx_count,
487                         urb->transfer_buffer, qh->offset,
488                         urb->transfer_buffer_length);
489
490         /* unload FIFO */
491         if (usb_pipeisoc(pipe)) {
492                 int                                     status = 0;
493                 struct usb_iso_packet_descriptor        *d;
494
495                 if (iso_err) {
496                         status = -EILSEQ;
497                         urb->error_count++;
498                 }
499
500                 d = urb->iso_frame_desc + qh->iso_idx;
501                 buf = buffer + d->offset;
502                 length = d->length;
503                 if (rx_count > length) {
504                         if (status == 0) {
505                                 status = -EOVERFLOW;
506                                 urb->error_count++;
507                         }
508                         DBG(2, "** OVERFLOW %d into %d\n", rx_count, length);
509                         do_flush = 1;
510                 } else
511                         length = rx_count;
512                 urb->actual_length += length;
513                 d->actual_length = length;
514
515                 d->status = status;
516
517                 /* see if we are done */
518                 done = (++qh->iso_idx >= urb->number_of_packets);
519         } else {
520                 /* non-isoch */
521                 buf = buffer + qh->offset;
522                 length = urb->transfer_buffer_length - qh->offset;
523                 if (rx_count > length) {
524                         if (urb->status == -EINPROGRESS)
525                                 urb->status = -EOVERFLOW;
526                         DBG(2, "** OVERFLOW %d into %d\n", rx_count, length);
527                         do_flush = 1;
528                 } else
529                         length = rx_count;
530                 urb->actual_length += length;
531                 qh->offset += length;
532
533                 /* see if we are done */
534                 done = (urb->actual_length == urb->transfer_buffer_length)
535                         || (rx_count < qh->maxpacket)
536                         || (urb->status != -EINPROGRESS);
537                 if (done
538                                 && (urb->status == -EINPROGRESS)
539                                 && (urb->transfer_flags & URB_SHORT_NOT_OK)
540                                 && (urb->actual_length
541                                         < urb->transfer_buffer_length))
542                         urb->status = -EREMOTEIO;
543         }
544
545         musb_read_fifo(hw_ep, length, buf);
546
547         csr = musb_readw(epio, MUSB_RXCSR);
548         csr |= MUSB_RXCSR_H_WZC_BITS;
549         if (unlikely(do_flush))
550                 musb_h_flush_rxfifo(hw_ep, csr);
551         else {
552                 /* REVISIT this assumes AUTOCLEAR is never set */
553                 csr &= ~(MUSB_RXCSR_RXPKTRDY | MUSB_RXCSR_H_REQPKT);
554                 if (!done)
555                         csr |= MUSB_RXCSR_H_REQPKT;
556                 musb_writew(epio, MUSB_RXCSR, csr);
557         }
558
559         return done;
560 }
561
562 /* we don't always need to reinit a given side of an endpoint...
563  * when we do, use tx/rx reinit routine and then construct a new CSR
564  * to address data toggle, NYET, and DMA or PIO.
565  *
566  * it's possible that driver bugs (especially for DMA) or aborting a
567  * transfer might have left the endpoint busier than it should be.
568  * the busy/not-empty tests are basically paranoia.
569  */
570 static void
571 musb_rx_reinit(struct musb *musb, struct musb_qh *qh, struct musb_hw_ep *ep)
572 {
573         u16     csr;
574
575         /* NOTE:  we know the "rx" fifo reinit never triggers for ep0.
576          * That always uses tx_reinit since ep0 repurposes TX register
577          * offsets; the initial SETUP packet is also a kind of OUT.
578          */
579
580         /* if programmed for Tx, put it in RX mode */
581         if (ep->is_shared_fifo) {
582                 csr = musb_readw(ep->regs, MUSB_TXCSR);
583                 if (csr & MUSB_TXCSR_MODE) {
584                         musb_h_tx_flush_fifo(ep);
585                         csr = musb_readw(ep->regs, MUSB_TXCSR);
586                         musb_writew(ep->regs, MUSB_TXCSR,
587                                     csr | MUSB_TXCSR_FRCDATATOG);
588                 }
589
590                 /*
591                  * Clear the MODE bit (and everything else) to enable Rx.
592                  * NOTE: we mustn't clear the DMAMODE bit before DMAENAB.
593                  */
594                 if (csr & MUSB_TXCSR_DMAMODE)
595                         musb_writew(ep->regs, MUSB_TXCSR, MUSB_TXCSR_DMAMODE);
596                 musb_writew(ep->regs, MUSB_TXCSR, 0);
597
598         /* scrub all previous state, clearing toggle */
599         } else {
600                 csr = musb_readw(ep->regs, MUSB_RXCSR);
601                 if (csr & MUSB_RXCSR_RXPKTRDY)
602                         WARNING("rx%d, packet/%d ready?\n", ep->epnum,
603                                 musb_readw(ep->regs, MUSB_RXCOUNT));
604
605                 musb_h_flush_rxfifo(ep, MUSB_RXCSR_CLRDATATOG);
606         }
607
608         /* target addr and (for multipoint) hub addr/port */
609         if (musb->is_multipoint) {
610                 musb_write_rxfunaddr(ep->target_regs, qh->addr_reg);
611                 musb_write_rxhubaddr(ep->target_regs, qh->h_addr_reg);
612                 musb_write_rxhubport(ep->target_regs, qh->h_port_reg);
613
614         } else
615                 musb_writeb(musb->mregs, MUSB_FADDR, qh->addr_reg);
616
617         /* protocol/endpoint, interval/NAKlimit, i/o size */
618         musb_writeb(ep->regs, MUSB_RXTYPE, qh->type_reg);
619         musb_writeb(ep->regs, MUSB_RXINTERVAL, qh->intv_reg);
620         /* NOTE: bulk combining rewrites high bits of maxpacket */
621         musb_writew(ep->regs, MUSB_RXMAXP, qh->maxpacket);
622
623         ep->rx_reinit = 0;
624 }
625
626 static bool musb_tx_dma_program(struct dma_controller *dma,
627                 struct musb_hw_ep *hw_ep, struct musb_qh *qh,
628                 struct urb *urb, u32 offset, u32 length)
629 {
630         struct dma_channel      *channel = hw_ep->tx_channel;
631         void __iomem            *epio = hw_ep->regs;
632         u16                     pkt_size = qh->maxpacket;
633         u16                     csr;
634         u8                      mode;
635
636 #ifdef  CONFIG_USB_INVENTRA_DMA
637         if (length > channel->max_len)
638                 length = channel->max_len;
639
640         csr = musb_readw(epio, MUSB_TXCSR);
641         if (length > pkt_size) {
642                 mode = 1;
643                 csr |= MUSB_TXCSR_AUTOSET
644                         | MUSB_TXCSR_DMAMODE
645                         | MUSB_TXCSR_DMAENAB;
646         } else {
647                 mode = 0;
648                 csr &= ~(MUSB_TXCSR_AUTOSET | MUSB_TXCSR_DMAMODE);
649                 csr |= MUSB_TXCSR_DMAENAB; /* against programmer's guide */
650         }
651         channel->desired_mode = mode;
652         musb_writew(epio, MUSB_TXCSR, csr);
653 #else
654         if (!is_cppi_enabled() && !tusb_dma_omap())
655                 return false;
656
657         channel->actual_len = 0;
658
659         /*
660          * TX uses "RNDIS" mode automatically but needs help
661          * to identify the zero-length-final-packet case.
662          */
663         mode = (urb->transfer_flags & URB_ZERO_PACKET) ? 1 : 0;
664 #endif
665
666         qh->segsize = length;
667
668         if (!dma->channel_program(channel, pkt_size, mode,
669                         urb->transfer_dma + offset, length)) {
670                 dma->channel_release(channel);
671                 hw_ep->tx_channel = NULL;
672
673                 csr = musb_readw(epio, MUSB_TXCSR);
674                 csr &= ~(MUSB_TXCSR_AUTOSET | MUSB_TXCSR_DMAENAB);
675                 musb_writew(epio, MUSB_TXCSR, csr | MUSB_TXCSR_H_WZC_BITS);
676                 return false;
677         }
678         return true;
679 }
680
681 /*
682  * Program an HDRC endpoint as per the given URB
683  * Context: irqs blocked, controller lock held
684  */
685 static void musb_ep_program(struct musb *musb, u8 epnum,
686                         struct urb *urb, int is_out,
687                         u8 *buf, u32 offset, u32 len)
688 {
689         struct dma_controller   *dma_controller;
690         struct dma_channel      *dma_channel;
691         u8                      dma_ok;
692         void __iomem            *mbase = musb->mregs;
693         struct musb_hw_ep       *hw_ep = musb->endpoints + epnum;
694         void __iomem            *epio = hw_ep->regs;
695         struct musb_qh          *qh;
696         u16                     packet_sz;
697
698         if (!is_out || hw_ep->is_shared_fifo)
699                 qh = hw_ep->in_qh;
700         else
701                 qh = hw_ep->out_qh;
702
703         packet_sz = qh->maxpacket;
704
705         DBG(3, "%s hw%d urb %p spd%d dev%d ep%d%s "
706                                 "h_addr%02x h_port%02x bytes %d\n",
707                         is_out ? "-->" : "<--",
708                         epnum, urb, urb->dev->speed,
709                         qh->addr_reg, qh->epnum, is_out ? "out" : "in",
710                         qh->h_addr_reg, qh->h_port_reg,
711                         len);
712
713         musb_ep_select(mbase, epnum);
714
715         /* candidate for DMA? */
716         dma_controller = musb->dma_controller;
717         if (is_dma_capable() && epnum && dma_controller) {
718                 dma_channel = is_out ? hw_ep->tx_channel : hw_ep->rx_channel;
719                 if (!dma_channel) {
720                         dma_channel = dma_controller->channel_alloc(
721                                         dma_controller, hw_ep, is_out);
722                         if (is_out)
723                                 hw_ep->tx_channel = dma_channel;
724                         else
725                                 hw_ep->rx_channel = dma_channel;
726                 }
727         } else
728                 dma_channel = NULL;
729
730         /* make sure we clear DMAEnab, autoSet bits from previous run */
731
732         /* OUT/transmit/EP0 or IN/receive? */
733         if (is_out) {
734                 u16     csr;
735                 u16     int_txe;
736                 u16     load_count;
737
738                 csr = musb_readw(epio, MUSB_TXCSR);
739
740                 /* disable interrupt in case we flush */
741                 int_txe = musb_readw(mbase, MUSB_INTRTXE);
742                 musb_writew(mbase, MUSB_INTRTXE, int_txe & ~(1 << epnum));
743
744                 /* general endpoint setup */
745                 if (epnum) {
746                         /* flush all old state, set default */
747                         musb_h_tx_flush_fifo(hw_ep);
748
749                         /*
750                          * We must not clear the DMAMODE bit before or in
751                          * the same cycle with the DMAENAB bit, so we clear
752                          * the latter first...
753                          */
754                         csr &= ~(MUSB_TXCSR_H_NAKTIMEOUT
755                                         | MUSB_TXCSR_AUTOSET
756                                         | MUSB_TXCSR_DMAENAB
757                                         | MUSB_TXCSR_FRCDATATOG
758                                         | MUSB_TXCSR_H_RXSTALL
759                                         | MUSB_TXCSR_H_ERROR
760                                         | MUSB_TXCSR_TXPKTRDY
761                                         );
762                         csr |= MUSB_TXCSR_MODE;
763
764                         if (usb_gettoggle(urb->dev, qh->epnum, 1))
765                                 csr |= MUSB_TXCSR_H_WR_DATATOGGLE
766                                         | MUSB_TXCSR_H_DATATOGGLE;
767                         else
768                                 csr |= MUSB_TXCSR_CLRDATATOG;
769
770                         musb_writew(epio, MUSB_TXCSR, csr);
771                         /* REVISIT may need to clear FLUSHFIFO ... */
772                         csr &= ~MUSB_TXCSR_DMAMODE;
773                         musb_writew(epio, MUSB_TXCSR, csr);
774                         csr = musb_readw(epio, MUSB_TXCSR);
775                 } else {
776                         /* endpoint 0: just flush */
777                         musb_h_ep0_flush_fifo(hw_ep);
778                 }
779
780                 /* target addr and (for multipoint) hub addr/port */
781                 if (musb->is_multipoint) {
782                         musb_write_txfunaddr(mbase, epnum, qh->addr_reg);
783                         musb_write_txhubaddr(mbase, epnum, qh->h_addr_reg);
784                         musb_write_txhubport(mbase, epnum, qh->h_port_reg);
785 /* FIXME if !epnum, do the same for RX ... */
786                 } else
787                         musb_writeb(mbase, MUSB_FADDR, qh->addr_reg);
788
789                 /* protocol/endpoint/interval/NAKlimit */
790                 if (epnum) {
791                         musb_writeb(epio, MUSB_TXTYPE, qh->type_reg);
792                         if (can_bulk_split(musb, qh->type))
793                                 musb_writew(epio, MUSB_TXMAXP,
794                                         packet_sz
795                                         | ((hw_ep->max_packet_sz_tx /
796                                                 packet_sz) - 1) << 11);
797                         else
798                                 musb_writew(epio, MUSB_TXMAXP,
799                                         packet_sz);
800                         musb_writeb(epio, MUSB_TXINTERVAL, qh->intv_reg);
801                 } else {
802                         musb_writeb(epio, MUSB_NAKLIMIT0, qh->intv_reg);
803                         if (musb->is_multipoint)
804                                 musb_writeb(epio, MUSB_TYPE0,
805                                                 qh->type_reg);
806                 }
807
808                 if (can_bulk_split(musb, qh->type))
809                         load_count = min((u32) hw_ep->max_packet_sz_tx,
810                                                 len);
811                 else
812                         load_count = min((u32) packet_sz, len);
813
814                 if (dma_channel && musb_tx_dma_program(dma_controller,
815                                         hw_ep, qh, urb, offset, len))
816                         load_count = 0;
817
818                 if (load_count) {
819                         /* PIO to load FIFO */
820                         qh->segsize = load_count;
821                         musb_write_fifo(hw_ep, load_count, buf);
822                 }
823
824                 /* re-enable interrupt */
825                 musb_writew(mbase, MUSB_INTRTXE, int_txe);
826
827         /* IN/receive */
828         } else {
829                 u16     csr;
830
831                 if (hw_ep->rx_reinit) {
832                         musb_rx_reinit(musb, qh, hw_ep);
833
834                         /* init new state: toggle and NYET, maybe DMA later */
835                         if (usb_gettoggle(urb->dev, qh->epnum, 0))
836                                 csr = MUSB_RXCSR_H_WR_DATATOGGLE
837                                         | MUSB_RXCSR_H_DATATOGGLE;
838                         else
839                                 csr = 0;
840                         if (qh->type == USB_ENDPOINT_XFER_INT)
841                                 csr |= MUSB_RXCSR_DISNYET;
842
843                 } else {
844                         csr = musb_readw(hw_ep->regs, MUSB_RXCSR);
845
846                         if (csr & (MUSB_RXCSR_RXPKTRDY
847                                         | MUSB_RXCSR_DMAENAB
848                                         | MUSB_RXCSR_H_REQPKT))
849                                 ERR("broken !rx_reinit, ep%d csr %04x\n",
850                                                 hw_ep->epnum, csr);
851
852                         /* scrub any stale state, leaving toggle alone */
853                         csr &= MUSB_RXCSR_DISNYET;
854                 }
855
856                 /* kick things off */
857
858                 if ((is_cppi_enabled() || tusb_dma_omap()) && dma_channel) {
859                         /* candidate for DMA */
860                         if (dma_channel) {
861                                 dma_channel->actual_len = 0L;
862                                 qh->segsize = len;
863
864                                 /* AUTOREQ is in a DMA register */
865                                 musb_writew(hw_ep->regs, MUSB_RXCSR, csr);
866                                 csr = musb_readw(hw_ep->regs,
867                                                 MUSB_RXCSR);
868
869                                 /* unless caller treats short rx transfers as
870                                  * errors, we dare not queue multiple transfers.
871                                  */
872                                 dma_ok = dma_controller->channel_program(
873                                                 dma_channel, packet_sz,
874                                                 !(urb->transfer_flags
875                                                         & URB_SHORT_NOT_OK),
876                                                 urb->transfer_dma + offset,
877                                                 qh->segsize);
878                                 if (!dma_ok) {
879                                         dma_controller->channel_release(
880                                                         dma_channel);
881                                         hw_ep->rx_channel = NULL;
882                                         dma_channel = NULL;
883                                 } else
884                                         csr |= MUSB_RXCSR_DMAENAB;
885                         }
886                 }
887
888                 csr |= MUSB_RXCSR_H_REQPKT;
889                 DBG(7, "RXCSR%d := %04x\n", epnum, csr);
890                 musb_writew(hw_ep->regs, MUSB_RXCSR, csr);
891                 csr = musb_readw(hw_ep->regs, MUSB_RXCSR);
892         }
893 }
894
895
896 /*
897  * Service the default endpoint (ep0) as host.
898  * Return true until it's time to start the status stage.
899  */
900 static bool musb_h_ep0_continue(struct musb *musb, u16 len, struct urb *urb)
901 {
902         bool                     more = false;
903         u8                      *fifo_dest = NULL;
904         u16                     fifo_count = 0;
905         struct musb_hw_ep       *hw_ep = musb->control_ep;
906         struct musb_qh          *qh = hw_ep->in_qh;
907         struct usb_ctrlrequest  *request;
908
909         switch (musb->ep0_stage) {
910         case MUSB_EP0_IN:
911                 fifo_dest = urb->transfer_buffer + urb->actual_length;
912                 fifo_count = min_t(size_t, len, urb->transfer_buffer_length -
913                                    urb->actual_length);
914                 if (fifo_count < len)
915                         urb->status = -EOVERFLOW;
916
917                 musb_read_fifo(hw_ep, fifo_count, fifo_dest);
918
919                 urb->actual_length += fifo_count;
920                 if (len < qh->maxpacket) {
921                         /* always terminate on short read; it's
922                          * rarely reported as an error.
923                          */
924                 } else if (urb->actual_length <
925                                 urb->transfer_buffer_length)
926                         more = true;
927                 break;
928         case MUSB_EP0_START:
929                 request = (struct usb_ctrlrequest *) urb->setup_packet;
930
931                 if (!request->wLength) {
932                         DBG(4, "start no-DATA\n");
933                         break;
934                 } else if (request->bRequestType & USB_DIR_IN) {
935                         DBG(4, "start IN-DATA\n");
936                         musb->ep0_stage = MUSB_EP0_IN;
937                         more = true;
938                         break;
939                 } else {
940                         DBG(4, "start OUT-DATA\n");
941                         musb->ep0_stage = MUSB_EP0_OUT;
942                         more = true;
943                 }
944                 /* FALLTHROUGH */
945         case MUSB_EP0_OUT:
946                 fifo_count = min_t(size_t, qh->maxpacket,
947                                    urb->transfer_buffer_length -
948                                    urb->actual_length);
949                 if (fifo_count) {
950                         fifo_dest = (u8 *) (urb->transfer_buffer
951                                         + urb->actual_length);
952                         DBG(3, "Sending %d byte%s to ep0 fifo %p\n",
953                                         fifo_count,
954                                         (fifo_count == 1) ? "" : "s",
955                                         fifo_dest);
956                         musb_write_fifo(hw_ep, fifo_count, fifo_dest);
957
958                         urb->actual_length += fifo_count;
959                         more = true;
960                 }
961                 break;
962         default:
963                 ERR("bogus ep0 stage %d\n", musb->ep0_stage);
964                 break;
965         }
966
967         return more;
968 }
969
970 /*
971  * Handle default endpoint interrupt as host. Only called in IRQ time
972  * from musb_interrupt().
973  *
974  * called with controller irqlocked
975  */
976 irqreturn_t musb_h_ep0_irq(struct musb *musb)
977 {
978         struct urb              *urb;
979         u16                     csr, len;
980         int                     status = 0;
981         void __iomem            *mbase = musb->mregs;
982         struct musb_hw_ep       *hw_ep = musb->control_ep;
983         void __iomem            *epio = hw_ep->regs;
984         struct musb_qh          *qh = hw_ep->in_qh;
985         bool                    complete = false;
986         irqreturn_t             retval = IRQ_NONE;
987
988         /* ep0 only has one queue, "in" */
989         urb = next_urb(qh);
990
991         musb_ep_select(mbase, 0);
992         csr = musb_readw(epio, MUSB_CSR0);
993         len = (csr & MUSB_CSR0_RXPKTRDY)
994                         ? musb_readb(epio, MUSB_COUNT0)
995                         : 0;
996
997         DBG(4, "<== csr0 %04x, qh %p, count %d, urb %p, stage %d\n",
998                 csr, qh, len, urb, musb->ep0_stage);
999
1000         /* if we just did status stage, we are done */
1001         if (MUSB_EP0_STATUS == musb->ep0_stage) {
1002                 retval = IRQ_HANDLED;
1003                 complete = true;
1004         }
1005
1006         /* prepare status */
1007         if (csr & MUSB_CSR0_H_RXSTALL) {
1008                 DBG(6, "STALLING ENDPOINT\n");
1009                 status = -EPIPE;
1010
1011         } else if (csr & MUSB_CSR0_H_ERROR) {
1012                 DBG(2, "no response, csr0 %04x\n", csr);
1013                 status = -EPROTO;
1014
1015         } else if (csr & MUSB_CSR0_H_NAKTIMEOUT) {
1016                 DBG(2, "control NAK timeout\n");
1017
1018                 /* NOTE:  this code path would be a good place to PAUSE a
1019                  * control transfer, if another one is queued, so that
1020                  * ep0 is more likely to stay busy.  That's already done
1021                  * for bulk RX transfers.
1022                  *
1023                  * if (qh->ring.next != &musb->control), then
1024                  * we have a candidate... NAKing is *NOT* an error
1025                  */
1026                 musb_writew(epio, MUSB_CSR0, 0);
1027                 retval = IRQ_HANDLED;
1028         }
1029
1030         if (status) {
1031                 DBG(6, "aborting\n");
1032                 retval = IRQ_HANDLED;
1033                 if (urb)
1034                         urb->status = status;
1035                 complete = true;
1036
1037                 /* use the proper sequence to abort the transfer */
1038                 if (csr & MUSB_CSR0_H_REQPKT) {
1039                         csr &= ~MUSB_CSR0_H_REQPKT;
1040                         musb_writew(epio, MUSB_CSR0, csr);
1041                         csr &= ~MUSB_CSR0_H_NAKTIMEOUT;
1042                         musb_writew(epio, MUSB_CSR0, csr);
1043                 } else {
1044                         musb_h_ep0_flush_fifo(hw_ep);
1045                 }
1046
1047                 musb_writeb(epio, MUSB_NAKLIMIT0, 0);
1048
1049                 /* clear it */
1050                 musb_writew(epio, MUSB_CSR0, 0);
1051         }
1052
1053         if (unlikely(!urb)) {
1054                 /* stop endpoint since we have no place for its data, this
1055                  * SHOULD NEVER HAPPEN! */
1056                 ERR("no URB for end 0\n");
1057
1058                 musb_h_ep0_flush_fifo(hw_ep);
1059                 goto done;
1060         }
1061
1062         if (!complete) {
1063                 /* call common logic and prepare response */
1064                 if (musb_h_ep0_continue(musb, len, urb)) {
1065                         /* more packets required */
1066                         csr = (MUSB_EP0_IN == musb->ep0_stage)
1067                                 ?  MUSB_CSR0_H_REQPKT : MUSB_CSR0_TXPKTRDY;
1068                 } else {
1069                         /* data transfer complete; perform status phase */
1070                         if (usb_pipeout(urb->pipe)
1071                                         || !urb->transfer_buffer_length)
1072                                 csr = MUSB_CSR0_H_STATUSPKT
1073                                         | MUSB_CSR0_H_REQPKT;
1074                         else
1075                                 csr = MUSB_CSR0_H_STATUSPKT
1076                                         | MUSB_CSR0_TXPKTRDY;
1077
1078                         /* flag status stage */
1079                         musb->ep0_stage = MUSB_EP0_STATUS;
1080
1081                         DBG(5, "ep0 STATUS, csr %04x\n", csr);
1082
1083                 }
1084                 musb_writew(epio, MUSB_CSR0, csr);
1085                 retval = IRQ_HANDLED;
1086         } else
1087                 musb->ep0_stage = MUSB_EP0_IDLE;
1088
1089         /* call completion handler if done */
1090         if (complete)
1091                 musb_advance_schedule(musb, urb, hw_ep, 1);
1092 done:
1093         return retval;
1094 }
1095
1096
1097 #ifdef CONFIG_USB_INVENTRA_DMA
1098
1099 /* Host side TX (OUT) using Mentor DMA works as follows:
1100         submit_urb ->
1101                 - if queue was empty, Program Endpoint
1102                 - ... which starts DMA to fifo in mode 1 or 0
1103
1104         DMA Isr (transfer complete) -> TxAvail()
1105                 - Stop DMA (~DmaEnab)   (<--- Alert ... currently happens
1106                                         only in musb_cleanup_urb)
1107                 - TxPktRdy has to be set in mode 0 or for
1108                         short packets in mode 1.
1109 */
1110
1111 #endif
1112
1113 /* Service a Tx-Available or dma completion irq for the endpoint */
1114 void musb_host_tx(struct musb *musb, u8 epnum)
1115 {
1116         int                     pipe;
1117         bool                    done = false;
1118         u16                     tx_csr;
1119         size_t                  length = 0;
1120         size_t                  offset = 0;
1121         struct urb              *urb;
1122         struct musb_hw_ep       *hw_ep = musb->endpoints + epnum;
1123         void __iomem            *epio = hw_ep->regs;
1124         struct musb_qh          *qh = hw_ep->is_shared_fifo ? hw_ep->in_qh
1125                                                             : hw_ep->out_qh;
1126         u32                     status = 0;
1127         void __iomem            *mbase = musb->mregs;
1128         struct dma_channel      *dma;
1129
1130         urb = next_urb(qh);
1131
1132         musb_ep_select(mbase, epnum);
1133         tx_csr = musb_readw(epio, MUSB_TXCSR);
1134
1135         /* with CPPI, DMA sometimes triggers "extra" irqs */
1136         if (!urb) {
1137                 DBG(4, "extra TX%d ready, csr %04x\n", epnum, tx_csr);
1138                 return;
1139         }
1140
1141         pipe = urb->pipe;
1142         dma = is_dma_capable() ? hw_ep->tx_channel : NULL;
1143         DBG(4, "OUT/TX%d end, csr %04x%s\n", epnum, tx_csr,
1144                         dma ? ", dma" : "");
1145
1146         /* check for errors */
1147         if (tx_csr & MUSB_TXCSR_H_RXSTALL) {
1148                 /* dma was disabled, fifo flushed */
1149                 DBG(3, "TX end %d stall\n", epnum);
1150
1151                 /* stall; record URB status */
1152                 status = -EPIPE;
1153
1154         } else if (tx_csr & MUSB_TXCSR_H_ERROR) {
1155                 /* (NON-ISO) dma was disabled, fifo flushed */
1156                 DBG(3, "TX 3strikes on ep=%d\n", epnum);
1157
1158                 status = -ETIMEDOUT;
1159
1160         } else if (tx_csr & MUSB_TXCSR_H_NAKTIMEOUT) {
1161                 DBG(6, "TX end=%d device not responding\n", epnum);
1162
1163                 /* NOTE:  this code path would be a good place to PAUSE a
1164                  * transfer, if there's some other (nonperiodic) tx urb
1165                  * that could use this fifo.  (dma complicates it...)
1166                  * That's already done for bulk RX transfers.
1167                  *
1168                  * if (bulk && qh->ring.next != &musb->out_bulk), then
1169                  * we have a candidate... NAKing is *NOT* an error
1170                  */
1171                 musb_ep_select(mbase, epnum);
1172                 musb_writew(epio, MUSB_TXCSR,
1173                                 MUSB_TXCSR_H_WZC_BITS
1174                                 | MUSB_TXCSR_TXPKTRDY);
1175                 return;
1176         }
1177
1178         if (status) {
1179                 if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) {
1180                         dma->status = MUSB_DMA_STATUS_CORE_ABORT;
1181                         (void) musb->dma_controller->channel_abort(dma);
1182                 }
1183
1184                 /* do the proper sequence to abort the transfer in the
1185                  * usb core; the dma engine should already be stopped.
1186                  */
1187                 musb_h_tx_flush_fifo(hw_ep);
1188                 tx_csr &= ~(MUSB_TXCSR_AUTOSET
1189                                 | MUSB_TXCSR_DMAENAB
1190                                 | MUSB_TXCSR_H_ERROR
1191                                 | MUSB_TXCSR_H_RXSTALL
1192                                 | MUSB_TXCSR_H_NAKTIMEOUT
1193                                 );
1194
1195                 musb_ep_select(mbase, epnum);
1196                 musb_writew(epio, MUSB_TXCSR, tx_csr);
1197                 /* REVISIT may need to clear FLUSHFIFO ... */
1198                 musb_writew(epio, MUSB_TXCSR, tx_csr);
1199                 musb_writeb(epio, MUSB_TXINTERVAL, 0);
1200
1201                 done = true;
1202         }
1203
1204         /* second cppi case */
1205         if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) {
1206                 DBG(4, "extra TX%d ready, csr %04x\n", epnum, tx_csr);
1207                 return;
1208         }
1209
1210         if (is_dma_capable() && dma && !status) {
1211                 /*
1212                  * DMA has completed.  But if we're using DMA mode 1 (multi
1213                  * packet DMA), we need a terminal TXPKTRDY interrupt before
1214                  * we can consider this transfer completed, lest we trash
1215                  * its last packet when writing the next URB's data.  So we
1216                  * switch back to mode 0 to get that interrupt; we'll come
1217                  * back here once it happens.
1218                  */
1219                 if (tx_csr & MUSB_TXCSR_DMAMODE) {
1220                         /*
1221                          * We shouldn't clear DMAMODE with DMAENAB set; so
1222                          * clear them in a safe order.  That should be OK
1223                          * once TXPKTRDY has been set (and I've never seen
1224                          * it being 0 at this moment -- DMA interrupt latency
1225                          * is significant) but if it hasn't been then we have
1226                          * no choice but to stop being polite and ignore the
1227                          * programmer's guide... :-)
1228                          *
1229                          * Note that we must write TXCSR with TXPKTRDY cleared
1230                          * in order not to re-trigger the packet send (this bit
1231                          * can't be cleared by CPU), and there's another caveat:
1232                          * TXPKTRDY may be set shortly and then cleared in the
1233                          * double-buffered FIFO mode, so we do an extra TXCSR
1234                          * read for debouncing...
1235                          */
1236                         tx_csr &= musb_readw(epio, MUSB_TXCSR);
1237                         if (tx_csr & MUSB_TXCSR_TXPKTRDY) {
1238                                 tx_csr &= ~(MUSB_TXCSR_DMAENAB |
1239                                             MUSB_TXCSR_TXPKTRDY);
1240                                 musb_writew(epio, MUSB_TXCSR,
1241                                             tx_csr | MUSB_TXCSR_H_WZC_BITS);
1242                         }
1243                         tx_csr &= ~(MUSB_TXCSR_DMAMODE |
1244                                     MUSB_TXCSR_TXPKTRDY);
1245                         musb_writew(epio, MUSB_TXCSR,
1246                                     tx_csr | MUSB_TXCSR_H_WZC_BITS);
1247
1248                         /*
1249                          * There is no guarantee that we'll get an interrupt
1250                          * after clearing DMAMODE as we might have done this
1251                          * too late (after TXPKTRDY was cleared by controller).
1252                          * Re-read TXCSR as we have spoiled its previous value.
1253                          */
1254                         tx_csr = musb_readw(epio, MUSB_TXCSR);
1255                 }
1256
1257                 /*
1258                  * We may get here from a DMA completion or TXPKTRDY interrupt.
1259                  * In any case, we must check the FIFO status here and bail out
1260                  * only if the FIFO still has data -- that should prevent the
1261                  * "missed" TXPKTRDY interrupts and deal with double-buffered
1262                  * FIFO mode too...
1263                  */
1264                 if (tx_csr & (MUSB_TXCSR_FIFONOTEMPTY | MUSB_TXCSR_TXPKTRDY)) {
1265                         DBG(2, "DMA complete but packet still in FIFO, "
1266                             "CSR %04x\n", tx_csr);
1267                         return;
1268                 }
1269         }
1270
1271         if (!status || dma || usb_pipeisoc(pipe)) {
1272                 if (dma)
1273                         length = dma->actual_len;
1274                 else
1275                         length = qh->segsize;
1276                 qh->offset += length;
1277
1278                 if (usb_pipeisoc(pipe)) {
1279                         struct usb_iso_packet_descriptor        *d;
1280
1281                         d = urb->iso_frame_desc + qh->iso_idx;
1282                         d->actual_length = length;
1283                         d->status = status;
1284                         if (++qh->iso_idx >= urb->number_of_packets) {
1285                                 done = true;
1286                         } else {
1287                                 d++;
1288                                 offset = d->offset;
1289                                 length = d->length;
1290                         }
1291                 } else if (dma) {
1292                         done = true;
1293                 } else {
1294                         /* see if we need to send more data, or ZLP */
1295                         if (qh->segsize < qh->maxpacket)
1296                                 done = true;
1297                         else if (qh->offset == urb->transfer_buffer_length
1298                                         && !(urb->transfer_flags
1299                                                 & URB_ZERO_PACKET))
1300                                 done = true;
1301                         if (!done) {
1302                                 offset = qh->offset;
1303                                 length = urb->transfer_buffer_length - offset;
1304                         }
1305                 }
1306         }
1307
1308         /* urb->status != -EINPROGRESS means request has been faulted,
1309          * so we must abort this transfer after cleanup
1310          */
1311         if (urb->status != -EINPROGRESS) {
1312                 done = true;
1313                 if (status == 0)
1314                         status = urb->status;
1315         }
1316
1317         if (done) {
1318                 /* set status */
1319                 urb->status = status;
1320                 urb->actual_length = qh->offset;
1321                 musb_advance_schedule(musb, urb, hw_ep, USB_DIR_OUT);
1322                 return;
1323         } else  if (usb_pipeisoc(pipe) && dma) {
1324                 if (musb_tx_dma_program(musb->dma_controller, hw_ep, qh, urb,
1325                                 offset, length))
1326                         return;
1327         } else  if (tx_csr & MUSB_TXCSR_DMAENAB) {
1328                 DBG(1, "not complete, but DMA enabled?\n");
1329                 return;
1330         }
1331
1332         /*
1333          * PIO: start next packet in this URB.
1334          *
1335          * REVISIT: some docs say that when hw_ep->tx_double_buffered,
1336          * (and presumably, FIFO is not half-full) we should write *two*
1337          * packets before updating TXCSR; other docs disagree...
1338          */
1339         if (length > qh->maxpacket)
1340                 length = qh->maxpacket;
1341         musb_write_fifo(hw_ep, length, urb->transfer_buffer + offset);
1342         qh->segsize = length;
1343
1344         musb_ep_select(mbase, epnum);
1345         musb_writew(epio, MUSB_TXCSR,
1346                         MUSB_TXCSR_H_WZC_BITS | MUSB_TXCSR_TXPKTRDY);
1347 }
1348
1349
1350 #ifdef CONFIG_USB_INVENTRA_DMA
1351
1352 /* Host side RX (IN) using Mentor DMA works as follows:
1353         submit_urb ->
1354                 - if queue was empty, ProgramEndpoint
1355                 - first IN token is sent out (by setting ReqPkt)
1356         LinuxIsr -> RxReady()
1357         /\      => first packet is received
1358         |       - Set in mode 0 (DmaEnab, ~ReqPkt)
1359         |               -> DMA Isr (transfer complete) -> RxReady()
1360         |                   - Ack receive (~RxPktRdy), turn off DMA (~DmaEnab)
1361         |                   - if urb not complete, send next IN token (ReqPkt)
1362         |                          |            else complete urb.
1363         |                          |
1364         ---------------------------
1365  *
1366  * Nuances of mode 1:
1367  *      For short packets, no ack (+RxPktRdy) is sent automatically
1368  *      (even if AutoClear is ON)
1369  *      For full packets, ack (~RxPktRdy) and next IN token (+ReqPkt) is sent
1370  *      automatically => major problem, as collecting the next packet becomes
1371  *      difficult. Hence mode 1 is not used.
1372  *
1373  * REVISIT
1374  *      All we care about at this driver level is that
1375  *       (a) all URBs terminate with REQPKT cleared and fifo(s) empty;
1376  *       (b) termination conditions are: short RX, or buffer full;
1377  *       (c) fault modes include
1378  *           - iff URB_SHORT_NOT_OK, short RX status is -EREMOTEIO.
1379  *             (and that endpoint's dma queue stops immediately)
1380  *           - overflow (full, PLUS more bytes in the terminal packet)
1381  *
1382  *      So for example, usb-storage sets URB_SHORT_NOT_OK, and would
1383  *      thus be a great candidate for using mode 1 ... for all but the
1384  *      last packet of one URB's transfer.
1385  */
1386
1387 #endif
1388
1389 /* Schedule next QH from musb->in_bulk and move the current qh to
1390  * the end; avoids starvation for other endpoints.
1391  */
1392 static void musb_bulk_rx_nak_timeout(struct musb *musb, struct musb_hw_ep *ep)
1393 {
1394         struct dma_channel      *dma;
1395         struct urb              *urb;
1396         void __iomem            *mbase = musb->mregs;
1397         void __iomem            *epio = ep->regs;
1398         struct musb_qh          *cur_qh, *next_qh;
1399         u16                     rx_csr;
1400
1401         musb_ep_select(mbase, ep->epnum);
1402         dma = is_dma_capable() ? ep->rx_channel : NULL;
1403
1404         /* clear nak timeout bit */
1405         rx_csr = musb_readw(epio, MUSB_RXCSR);
1406         rx_csr |= MUSB_RXCSR_H_WZC_BITS;
1407         rx_csr &= ~MUSB_RXCSR_DATAERROR;
1408         musb_writew(epio, MUSB_RXCSR, rx_csr);
1409
1410         cur_qh = first_qh(&musb->in_bulk);
1411         if (cur_qh) {
1412                 urb = next_urb(cur_qh);
1413                 if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) {
1414                         dma->status = MUSB_DMA_STATUS_CORE_ABORT;
1415                         musb->dma_controller->channel_abort(dma);
1416                         urb->actual_length += dma->actual_len;
1417                         dma->actual_len = 0L;
1418                 }
1419                 musb_save_toggle(cur_qh, 1, urb);
1420
1421                 /* move cur_qh to end of queue */
1422                 list_move_tail(&cur_qh->ring, &musb->in_bulk);
1423
1424                 /* get the next qh from musb->in_bulk */
1425                 next_qh = first_qh(&musb->in_bulk);
1426
1427                 /* set rx_reinit and schedule the next qh */
1428                 ep->rx_reinit = 1;
1429                 musb_start_urb(musb, 1, next_qh);
1430         }
1431 }
1432
1433 /*
1434  * Service an RX interrupt for the given IN endpoint; docs cover bulk, iso,
1435  * and high-bandwidth IN transfer cases.
1436  */
1437 void musb_host_rx(struct musb *musb, u8 epnum)
1438 {
1439         struct urb              *urb;
1440         struct musb_hw_ep       *hw_ep = musb->endpoints + epnum;
1441         void __iomem            *epio = hw_ep->regs;
1442         struct musb_qh          *qh = hw_ep->in_qh;
1443         size_t                  xfer_len;
1444         void __iomem            *mbase = musb->mregs;
1445         int                     pipe;
1446         u16                     rx_csr, val;
1447         bool                    iso_err = false;
1448         bool                    done = false;
1449         u32                     status;
1450         struct dma_channel      *dma;
1451
1452         musb_ep_select(mbase, epnum);
1453
1454         urb = next_urb(qh);
1455         dma = is_dma_capable() ? hw_ep->rx_channel : NULL;
1456         status = 0;
1457         xfer_len = 0;
1458
1459         rx_csr = musb_readw(epio, MUSB_RXCSR);
1460         val = rx_csr;
1461
1462         if (unlikely(!urb)) {
1463                 /* REVISIT -- THIS SHOULD NEVER HAPPEN ... but, at least
1464                  * usbtest #11 (unlinks) triggers it regularly, sometimes
1465                  * with fifo full.  (Only with DMA??)
1466                  */
1467                 DBG(3, "BOGUS RX%d ready, csr %04x, count %d\n", epnum, val,
1468                         musb_readw(epio, MUSB_RXCOUNT));
1469                 musb_h_flush_rxfifo(hw_ep, MUSB_RXCSR_CLRDATATOG);
1470                 return;
1471         }
1472
1473         pipe = urb->pipe;
1474
1475         DBG(5, "<== hw %d rxcsr %04x, urb actual %d (+dma %zu)\n",
1476                 epnum, rx_csr, urb->actual_length,
1477                 dma ? dma->actual_len : 0);
1478
1479         /* check for errors, concurrent stall & unlink is not really
1480          * handled yet! */
1481         if (rx_csr & MUSB_RXCSR_H_RXSTALL) {
1482                 DBG(3, "RX end %d STALL\n", epnum);
1483
1484                 /* stall; record URB status */
1485                 status = -EPIPE;
1486
1487         } else if (rx_csr & MUSB_RXCSR_H_ERROR) {
1488                 DBG(3, "end %d RX proto error\n", epnum);
1489
1490                 status = -EPROTO;
1491                 musb_writeb(epio, MUSB_RXINTERVAL, 0);
1492
1493         } else if (rx_csr & MUSB_RXCSR_DATAERROR) {
1494
1495                 if (USB_ENDPOINT_XFER_ISOC != qh->type) {
1496                         DBG(6, "RX end %d NAK timeout\n", epnum);
1497
1498                         /* NOTE: NAKing is *NOT* an error, so we want to
1499                          * continue.  Except ... if there's a request for
1500                          * another QH, use that instead of starving it.
1501                          *
1502                          * Devices like Ethernet and serial adapters keep
1503                          * reads posted at all times, which will starve
1504                          * other devices without this logic.
1505                          */
1506                         if (usb_pipebulk(urb->pipe)
1507                                         && qh->mux == 1
1508                                         && !list_is_singular(&musb->in_bulk)) {
1509                                 musb_bulk_rx_nak_timeout(musb, hw_ep);
1510                                 return;
1511                         }
1512                         musb_ep_select(mbase, epnum);
1513                         rx_csr |= MUSB_RXCSR_H_WZC_BITS;
1514                         rx_csr &= ~MUSB_RXCSR_DATAERROR;
1515                         musb_writew(epio, MUSB_RXCSR, rx_csr);
1516
1517                         goto finish;
1518                 } else {
1519                         DBG(4, "RX end %d ISO data error\n", epnum);
1520                         /* packet error reported later */
1521                         iso_err = true;
1522                 }
1523         }
1524
1525         /* faults abort the transfer */
1526         if (status) {
1527                 /* clean up dma and collect transfer count */
1528                 if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) {
1529                         dma->status = MUSB_DMA_STATUS_CORE_ABORT;
1530                         (void) musb->dma_controller->channel_abort(dma);
1531                         xfer_len = dma->actual_len;
1532                 }
1533                 musb_h_flush_rxfifo(hw_ep, MUSB_RXCSR_CLRDATATOG);
1534                 musb_writeb(epio, MUSB_RXINTERVAL, 0);
1535                 done = true;
1536                 goto finish;
1537         }
1538
1539         if (unlikely(dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY)) {
1540                 /* SHOULD NEVER HAPPEN ... but at least DaVinci has done it */
1541                 ERR("RX%d dma busy, csr %04x\n", epnum, rx_csr);
1542                 goto finish;
1543         }
1544
1545         /* thorough shutdown for now ... given more precise fault handling
1546          * and better queueing support, we might keep a DMA pipeline going
1547          * while processing this irq for earlier completions.
1548          */
1549
1550         /* FIXME this is _way_ too much in-line logic for Mentor DMA */
1551
1552 #ifndef CONFIG_USB_INVENTRA_DMA
1553         if (rx_csr & MUSB_RXCSR_H_REQPKT)  {
1554                 /* REVISIT this happened for a while on some short reads...
1555                  * the cleanup still needs investigation... looks bad...
1556                  * and also duplicates dma cleanup code above ... plus,
1557                  * shouldn't this be the "half full" double buffer case?
1558                  */
1559                 if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) {
1560                         dma->status = MUSB_DMA_STATUS_CORE_ABORT;
1561                         (void) musb->dma_controller->channel_abort(dma);
1562                         xfer_len = dma->actual_len;
1563                         done = true;
1564                 }
1565
1566                 DBG(2, "RXCSR%d %04x, reqpkt, len %zu%s\n", epnum, rx_csr,
1567                                 xfer_len, dma ? ", dma" : "");
1568                 rx_csr &= ~MUSB_RXCSR_H_REQPKT;
1569
1570                 musb_ep_select(mbase, epnum);
1571                 musb_writew(epio, MUSB_RXCSR,
1572                                 MUSB_RXCSR_H_WZC_BITS | rx_csr);
1573         }
1574 #endif
1575         if (dma && (rx_csr & MUSB_RXCSR_DMAENAB)) {
1576                 xfer_len = dma->actual_len;
1577
1578                 val &= ~(MUSB_RXCSR_DMAENAB
1579                         | MUSB_RXCSR_H_AUTOREQ
1580                         | MUSB_RXCSR_AUTOCLEAR
1581                         | MUSB_RXCSR_RXPKTRDY);
1582                 musb_writew(hw_ep->regs, MUSB_RXCSR, val);
1583
1584 #ifdef CONFIG_USB_INVENTRA_DMA
1585                 if (usb_pipeisoc(pipe)) {
1586                         struct usb_iso_packet_descriptor *d;
1587
1588                         d = urb->iso_frame_desc + qh->iso_idx;
1589                         d->actual_length = xfer_len;
1590
1591                         /* even if there was an error, we did the dma
1592                          * for iso_frame_desc->length
1593                          */
1594                         if (d->status != EILSEQ && d->status != -EOVERFLOW)
1595                                 d->status = 0;
1596
1597                         if (++qh->iso_idx >= urb->number_of_packets)
1598                                 done = true;
1599                         else
1600                                 done = false;
1601
1602                 } else  {
1603                 /* done if urb buffer is full or short packet is recd */
1604                 done = (urb->actual_length + xfer_len >=
1605                                 urb->transfer_buffer_length
1606                         || dma->actual_len < qh->maxpacket);
1607                 }
1608
1609                 /* send IN token for next packet, without AUTOREQ */
1610                 if (!done) {
1611                         val |= MUSB_RXCSR_H_REQPKT;
1612                         musb_writew(epio, MUSB_RXCSR,
1613                                 MUSB_RXCSR_H_WZC_BITS | val);
1614                 }
1615
1616                 DBG(4, "ep %d dma %s, rxcsr %04x, rxcount %d\n", epnum,
1617                         done ? "off" : "reset",
1618                         musb_readw(epio, MUSB_RXCSR),
1619                         musb_readw(epio, MUSB_RXCOUNT));
1620 #else
1621                 done = true;
1622 #endif
1623         } else if (urb->status == -EINPROGRESS) {
1624                 /* if no errors, be sure a packet is ready for unloading */
1625                 if (unlikely(!(rx_csr & MUSB_RXCSR_RXPKTRDY))) {
1626                         status = -EPROTO;
1627                         ERR("Rx interrupt with no errors or packet!\n");
1628
1629                         /* FIXME this is another "SHOULD NEVER HAPPEN" */
1630
1631 /* SCRUB (RX) */
1632                         /* do the proper sequence to abort the transfer */
1633                         musb_ep_select(mbase, epnum);
1634                         val &= ~MUSB_RXCSR_H_REQPKT;
1635                         musb_writew(epio, MUSB_RXCSR, val);
1636                         goto finish;
1637                 }
1638
1639                 /* we are expecting IN packets */
1640 #ifdef CONFIG_USB_INVENTRA_DMA
1641                 if (dma) {
1642                         struct dma_controller   *c;
1643                         u16                     rx_count;
1644                         int                     ret, length;
1645                         dma_addr_t              buf;
1646
1647                         rx_count = musb_readw(epio, MUSB_RXCOUNT);
1648
1649                         DBG(2, "RX%d count %d, buffer 0x%x len %d/%d\n",
1650                                         epnum, rx_count,
1651                                         urb->transfer_dma
1652                                                 + urb->actual_length,
1653                                         qh->offset,
1654                                         urb->transfer_buffer_length);
1655
1656                         c = musb->dma_controller;
1657
1658                         if (usb_pipeisoc(pipe)) {
1659                                 int status = 0;
1660                                 struct usb_iso_packet_descriptor *d;
1661
1662                                 d = urb->iso_frame_desc + qh->iso_idx;
1663
1664                                 if (iso_err) {
1665                                         status = -EILSEQ;
1666                                         urb->error_count++;
1667                                 }
1668                                 if (rx_count > d->length) {
1669                                         if (status == 0) {
1670                                                 status = -EOVERFLOW;
1671                                                 urb->error_count++;
1672                                         }
1673                                         DBG(2, "** OVERFLOW %d into %d\n",\
1674                                             rx_count, d->length);
1675
1676                                         length = d->length;
1677                                 } else
1678                                         length = rx_count;
1679                                 d->status = status;
1680                                 buf = urb->transfer_dma + d->offset;
1681                         } else {
1682                                 length = rx_count;
1683                                 buf = urb->transfer_dma +
1684                                                 urb->actual_length;
1685                         }
1686
1687                         dma->desired_mode = 0;
1688 #ifdef USE_MODE1
1689                         /* because of the issue below, mode 1 will
1690                          * only rarely behave with correct semantics.
1691                          */
1692                         if ((urb->transfer_flags &
1693                                                 URB_SHORT_NOT_OK)
1694                                 && (urb->transfer_buffer_length -
1695                                                 urb->actual_length)
1696                                         > qh->maxpacket)
1697                                 dma->desired_mode = 1;
1698                         if (rx_count < hw_ep->max_packet_sz_rx) {
1699                                 length = rx_count;
1700                                 dma->bDesiredMode = 0;
1701                         } else {
1702                                 length = urb->transfer_buffer_length;
1703                         }
1704 #endif
1705
1706 /* Disadvantage of using mode 1:
1707  *      It's basically usable only for mass storage class; essentially all
1708  *      other protocols also terminate transfers on short packets.
1709  *
1710  * Details:
1711  *      An extra IN token is sent at the end of the transfer (due to AUTOREQ)
1712  *      If you try to use mode 1 for (transfer_buffer_length - 512), and try
1713  *      to use the extra IN token to grab the last packet using mode 0, then
1714  *      the problem is that you cannot be sure when the device will send the
1715  *      last packet and RxPktRdy set. Sometimes the packet is recd too soon
1716  *      such that it gets lost when RxCSR is re-set at the end of the mode 1
1717  *      transfer, while sometimes it is recd just a little late so that if you
1718  *      try to configure for mode 0 soon after the mode 1 transfer is
1719  *      completed, you will find rxcount 0. Okay, so you might think why not
1720  *      wait for an interrupt when the pkt is recd. Well, you won't get any!
1721  */
1722
1723                         val = musb_readw(epio, MUSB_RXCSR);
1724                         val &= ~MUSB_RXCSR_H_REQPKT;
1725
1726                         if (dma->desired_mode == 0)
1727                                 val &= ~MUSB_RXCSR_H_AUTOREQ;
1728                         else
1729                                 val |= MUSB_RXCSR_H_AUTOREQ;
1730                         val |= MUSB_RXCSR_AUTOCLEAR | MUSB_RXCSR_DMAENAB;
1731
1732                         musb_writew(epio, MUSB_RXCSR,
1733                                 MUSB_RXCSR_H_WZC_BITS | val);
1734
1735                         /* REVISIT if when actual_length != 0,
1736                          * transfer_buffer_length needs to be
1737                          * adjusted first...
1738                          */
1739                         ret = c->channel_program(
1740                                 dma, qh->maxpacket,
1741                                 dma->desired_mode, buf, length);
1742
1743                         if (!ret) {
1744                                 c->channel_release(dma);
1745                                 hw_ep->rx_channel = NULL;
1746                                 dma = NULL;
1747                                 /* REVISIT reset CSR */
1748                         }
1749                 }
1750 #endif  /* Mentor DMA */
1751
1752                 if (!dma) {
1753                         done = musb_host_packet_rx(musb, urb,
1754                                         epnum, iso_err);
1755                         DBG(6, "read %spacket\n", done ? "last " : "");
1756                 }
1757         }
1758
1759 finish:
1760         urb->actual_length += xfer_len;
1761         qh->offset += xfer_len;
1762         if (done) {
1763                 if (urb->status == -EINPROGRESS)
1764                         urb->status = status;
1765                 musb_advance_schedule(musb, urb, hw_ep, USB_DIR_IN);
1766         }
1767 }
1768
1769 /* schedule nodes correspond to peripheral endpoints, like an OHCI QH.
1770  * the software schedule associates multiple such nodes with a given
1771  * host side hardware endpoint + direction; scheduling may activate
1772  * that hardware endpoint.
1773  */
1774 static int musb_schedule(
1775         struct musb             *musb,
1776         struct musb_qh          *qh,
1777         int                     is_in)
1778 {
1779         int                     idle;
1780         int                     best_diff;
1781         int                     best_end, epnum;
1782         struct musb_hw_ep       *hw_ep = NULL;
1783         struct list_head        *head = NULL;
1784
1785         /* use fixed hardware for control and bulk */
1786         if (qh->type == USB_ENDPOINT_XFER_CONTROL) {
1787                 head = &musb->control;
1788                 hw_ep = musb->control_ep;
1789                 goto success;
1790         }
1791
1792         /* else, periodic transfers get muxed to other endpoints */
1793
1794         /*
1795          * We know this qh hasn't been scheduled, so all we need to do
1796          * is choose which hardware endpoint to put it on ...
1797          *
1798          * REVISIT what we really want here is a regular schedule tree
1799          * like e.g. OHCI uses.
1800          */
1801         best_diff = 4096;
1802         best_end = -1;
1803
1804         for (epnum = 1, hw_ep = musb->endpoints + 1;
1805                         epnum < musb->nr_endpoints;
1806                         epnum++, hw_ep++) {
1807                 int     diff;
1808
1809                 if (is_in || hw_ep->is_shared_fifo) {
1810                         if (hw_ep->in_qh  != NULL)
1811                                 continue;
1812                 } else  if (hw_ep->out_qh != NULL)
1813                         continue;
1814
1815                 if (hw_ep == musb->bulk_ep)
1816                         continue;
1817
1818                 if (is_in)
1819                         diff = hw_ep->max_packet_sz_rx - qh->maxpacket;
1820                 else
1821                         diff = hw_ep->max_packet_sz_tx - qh->maxpacket;
1822
1823                 if (diff >= 0 && best_diff > diff) {
1824                         best_diff = diff;
1825                         best_end = epnum;
1826                 }
1827         }
1828         /* use bulk reserved ep1 if no other ep is free */
1829         if (best_end < 0 && qh->type == USB_ENDPOINT_XFER_BULK) {
1830                 hw_ep = musb->bulk_ep;
1831                 if (is_in)
1832                         head = &musb->in_bulk;
1833                 else
1834                         head = &musb->out_bulk;
1835
1836                 /* Enable bulk RX NAK timeout scheme when bulk requests are
1837                  * multiplexed.  This scheme doen't work in high speed to full
1838                  * speed scenario as NAK interrupts are not coming from a
1839                  * full speed device connected to a high speed device.
1840                  * NAK timeout interval is 8 (128 uframe or 16ms) for HS and
1841                  * 4 (8 frame or 8ms) for FS device.
1842                  */
1843                 if (is_in && qh->dev)
1844                         qh->intv_reg =
1845                                 (USB_SPEED_HIGH == qh->dev->speed) ? 8 : 4;
1846                 goto success;
1847         } else if (best_end < 0) {
1848                 return -ENOSPC;
1849         }
1850
1851         idle = 1;
1852         qh->mux = 0;
1853         hw_ep = musb->endpoints + best_end;
1854         DBG(4, "qh %p periodic slot %d\n", qh, best_end);
1855 success:
1856         if (head) {
1857                 idle = list_empty(head);
1858                 list_add_tail(&qh->ring, head);
1859                 qh->mux = 1;
1860         }
1861         qh->hw_ep = hw_ep;
1862         qh->hep->hcpriv = qh;
1863         if (idle)
1864                 musb_start_urb(musb, is_in, qh);
1865         return 0;
1866 }
1867
1868 static int musb_urb_enqueue(
1869         struct usb_hcd                  *hcd,
1870         struct urb                      *urb,
1871         gfp_t                           mem_flags)
1872 {
1873         unsigned long                   flags;
1874         struct musb                     *musb = hcd_to_musb(hcd);
1875         struct usb_host_endpoint        *hep = urb->ep;
1876         struct musb_qh                  *qh;
1877         struct usb_endpoint_descriptor  *epd = &hep->desc;
1878         int                             ret;
1879         unsigned                        type_reg;
1880         unsigned                        interval;
1881
1882         /* host role must be active */
1883         if (!is_host_active(musb) || !musb->is_active)
1884                 return -ENODEV;
1885
1886         spin_lock_irqsave(&musb->lock, flags);
1887         ret = usb_hcd_link_urb_to_ep(hcd, urb);
1888         qh = ret ? NULL : hep->hcpriv;
1889         if (qh)
1890                 urb->hcpriv = qh;
1891         spin_unlock_irqrestore(&musb->lock, flags);
1892
1893         /* DMA mapping was already done, if needed, and this urb is on
1894          * hep->urb_list now ... so we're done, unless hep wasn't yet
1895          * scheduled onto a live qh.
1896          *
1897          * REVISIT best to keep hep->hcpriv valid until the endpoint gets
1898          * disabled, testing for empty qh->ring and avoiding qh setup costs
1899          * except for the first urb queued after a config change.
1900          */
1901         if (qh || ret)
1902                 return ret;
1903
1904         /* Allocate and initialize qh, minimizing the work done each time
1905          * hw_ep gets reprogrammed, or with irqs blocked.  Then schedule it.
1906          *
1907          * REVISIT consider a dedicated qh kmem_cache, so it's harder
1908          * for bugs in other kernel code to break this driver...
1909          */
1910         qh = kzalloc(sizeof *qh, mem_flags);
1911         if (!qh) {
1912                 spin_lock_irqsave(&musb->lock, flags);
1913                 usb_hcd_unlink_urb_from_ep(hcd, urb);
1914                 spin_unlock_irqrestore(&musb->lock, flags);
1915                 return -ENOMEM;
1916         }
1917
1918         qh->hep = hep;
1919         qh->dev = urb->dev;
1920         INIT_LIST_HEAD(&qh->ring);
1921         qh->is_ready = 1;
1922
1923         qh->maxpacket = le16_to_cpu(epd->wMaxPacketSize);
1924
1925         /* no high bandwidth support yet */
1926         if (qh->maxpacket & ~0x7ff) {
1927                 ret = -EMSGSIZE;
1928                 goto done;
1929         }
1930
1931         qh->epnum = usb_endpoint_num(epd);
1932         qh->type = usb_endpoint_type(epd);
1933
1934         /* NOTE: urb->dev->devnum is wrong during SET_ADDRESS */
1935         qh->addr_reg = (u8) usb_pipedevice(urb->pipe);
1936
1937         /* precompute rxtype/txtype/type0 register */
1938         type_reg = (qh->type << 4) | qh->epnum;
1939         switch (urb->dev->speed) {
1940         case USB_SPEED_LOW:
1941                 type_reg |= 0xc0;
1942                 break;
1943         case USB_SPEED_FULL:
1944                 type_reg |= 0x80;
1945                 break;
1946         default:
1947                 type_reg |= 0x40;
1948         }
1949         qh->type_reg = type_reg;
1950
1951         /* Precompute RXINTERVAL/TXINTERVAL register */
1952         switch (qh->type) {
1953         case USB_ENDPOINT_XFER_INT:
1954                 /*
1955                  * Full/low speeds use the  linear encoding,
1956                  * high speed uses the logarithmic encoding.
1957                  */
1958                 if (urb->dev->speed <= USB_SPEED_FULL) {
1959                         interval = max_t(u8, epd->bInterval, 1);
1960                         break;
1961                 }
1962                 /* FALLTHROUGH */
1963         case USB_ENDPOINT_XFER_ISOC:
1964                 /* ISO always uses logarithmic encoding */
1965                 interval = min_t(u8, epd->bInterval, 16);
1966                 break;
1967         default:
1968                 /* REVISIT we actually want to use NAK limits, hinting to the
1969                  * transfer scheduling logic to try some other qh, e.g. try
1970                  * for 2 msec first:
1971                  *
1972                  * interval = (USB_SPEED_HIGH == urb->dev->speed) ? 16 : 2;
1973                  *
1974                  * The downside of disabling this is that transfer scheduling
1975                  * gets VERY unfair for nonperiodic transfers; a misbehaving
1976                  * peripheral could make that hurt.  That's perfectly normal
1977                  * for reads from network or serial adapters ... so we have
1978                  * partial NAKlimit support for bulk RX.
1979                  *
1980                  * The upside of disabling it is simpler transfer scheduling.
1981                  */
1982                 interval = 0;
1983         }
1984         qh->intv_reg = interval;
1985
1986         /* precompute addressing for external hub/tt ports */
1987         if (musb->is_multipoint) {
1988                 struct usb_device       *parent = urb->dev->parent;
1989
1990                 if (parent != hcd->self.root_hub) {
1991                         qh->h_addr_reg = (u8) parent->devnum;
1992
1993                         /* set up tt info if needed */
1994                         if (urb->dev->tt) {
1995                                 qh->h_port_reg = (u8) urb->dev->ttport;
1996                                 if (urb->dev->tt->hub)
1997                                         qh->h_addr_reg =
1998                                                 (u8) urb->dev->tt->hub->devnum;
1999                                 if (urb->dev->tt->multi)
2000                                         qh->h_addr_reg |= 0x80;
2001                         }
2002                 }
2003         }
2004
2005         /* invariant: hep->hcpriv is null OR the qh that's already scheduled.
2006          * until we get real dma queues (with an entry for each urb/buffer),
2007          * we only have work to do in the former case.
2008          */
2009         spin_lock_irqsave(&musb->lock, flags);
2010         if (hep->hcpriv) {
2011                 /* some concurrent activity submitted another urb to hep...
2012                  * odd, rare, error prone, but legal.
2013                  */
2014                 kfree(qh);
2015                 ret = 0;
2016         } else
2017                 ret = musb_schedule(musb, qh,
2018                                 epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK);
2019
2020         if (ret == 0) {
2021                 urb->hcpriv = qh;
2022                 /* FIXME set urb->start_frame for iso/intr, it's tested in
2023                  * musb_start_urb(), but otherwise only konicawc cares ...
2024                  */
2025         }
2026         spin_unlock_irqrestore(&musb->lock, flags);
2027
2028 done:
2029         if (ret != 0) {
2030                 spin_lock_irqsave(&musb->lock, flags);
2031                 usb_hcd_unlink_urb_from_ep(hcd, urb);
2032                 spin_unlock_irqrestore(&musb->lock, flags);
2033                 kfree(qh);
2034         }
2035         return ret;
2036 }
2037
2038
2039 /*
2040  * abort a transfer that's at the head of a hardware queue.
2041  * called with controller locked, irqs blocked
2042  * that hardware queue advances to the next transfer, unless prevented
2043  */
2044 static int musb_cleanup_urb(struct urb *urb, struct musb_qh *qh, int is_in)
2045 {
2046         struct musb_hw_ep       *ep = qh->hw_ep;
2047         void __iomem            *epio = ep->regs;
2048         unsigned                hw_end = ep->epnum;
2049         void __iomem            *regs = ep->musb->mregs;
2050         u16                     csr;
2051         int                     status = 0;
2052
2053         musb_ep_select(regs, hw_end);
2054
2055         if (is_dma_capable()) {
2056                 struct dma_channel      *dma;
2057
2058                 dma = is_in ? ep->rx_channel : ep->tx_channel;
2059                 if (dma) {
2060                         status = ep->musb->dma_controller->channel_abort(dma);
2061                         DBG(status ? 1 : 3,
2062                                 "abort %cX%d DMA for urb %p --> %d\n",
2063                                 is_in ? 'R' : 'T', ep->epnum,
2064                                 urb, status);
2065                         urb->actual_length += dma->actual_len;
2066                 }
2067         }
2068
2069         /* turn off DMA requests, discard state, stop polling ... */
2070         if (is_in) {
2071                 /* giveback saves bulk toggle */
2072                 csr = musb_h_flush_rxfifo(ep, 0);
2073
2074                 /* REVISIT we still get an irq; should likely clear the
2075                  * endpoint's irq status here to avoid bogus irqs.
2076                  * clearing that status is platform-specific...
2077                  */
2078         } else if (ep->epnum) {
2079                 musb_h_tx_flush_fifo(ep);
2080                 csr = musb_readw(epio, MUSB_TXCSR);
2081                 csr &= ~(MUSB_TXCSR_AUTOSET
2082                         | MUSB_TXCSR_DMAENAB
2083                         | MUSB_TXCSR_H_RXSTALL
2084                         | MUSB_TXCSR_H_NAKTIMEOUT
2085                         | MUSB_TXCSR_H_ERROR
2086                         | MUSB_TXCSR_TXPKTRDY);
2087                 musb_writew(epio, MUSB_TXCSR, csr);
2088                 /* REVISIT may need to clear FLUSHFIFO ... */
2089                 musb_writew(epio, MUSB_TXCSR, csr);
2090                 /* flush cpu writebuffer */
2091                 csr = musb_readw(epio, MUSB_TXCSR);
2092         } else  {
2093                 musb_h_ep0_flush_fifo(ep);
2094         }
2095         if (status == 0)
2096                 musb_advance_schedule(ep->musb, urb, ep, is_in);
2097         return status;
2098 }
2099
2100 static int musb_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
2101 {
2102         struct musb             *musb = hcd_to_musb(hcd);
2103         struct musb_qh          *qh;
2104         struct list_head        *sched;
2105         unsigned long           flags;
2106         int                     ret;
2107
2108         DBG(4, "urb=%p, dev%d ep%d%s\n", urb,
2109                         usb_pipedevice(urb->pipe),
2110                         usb_pipeendpoint(urb->pipe),
2111                         usb_pipein(urb->pipe) ? "in" : "out");
2112
2113         spin_lock_irqsave(&musb->lock, flags);
2114         ret = usb_hcd_check_unlink_urb(hcd, urb, status);
2115         if (ret)
2116                 goto done;
2117
2118         qh = urb->hcpriv;
2119         if (!qh)
2120                 goto done;
2121
2122         /* Any URB not actively programmed into endpoint hardware can be
2123          * immediately given back; that's any URB not at the head of an
2124          * endpoint queue, unless someday we get real DMA queues.  And even
2125          * if it's at the head, it might not be known to the hardware...
2126          *
2127          * Otherwise abort current transfer, pending dma, etc.; urb->status
2128          * has already been updated.  This is a synchronous abort; it'd be
2129          * OK to hold off until after some IRQ, though.
2130          */
2131         if (!qh->is_ready || urb->urb_list.prev != &qh->hep->urb_list)
2132                 ret = -EINPROGRESS;
2133         else {
2134                 switch (qh->type) {
2135                 case USB_ENDPOINT_XFER_CONTROL:
2136                         sched = &musb->control;
2137                         break;
2138                 case USB_ENDPOINT_XFER_BULK:
2139                         if (qh->mux == 1) {
2140                                 if (usb_pipein(urb->pipe))
2141                                         sched = &musb->in_bulk;
2142                                 else
2143                                         sched = &musb->out_bulk;
2144                                 break;
2145                         }
2146                 default:
2147                         /* REVISIT when we get a schedule tree, periodic
2148                          * transfers won't always be at the head of a
2149                          * singleton queue...
2150                          */
2151                         sched = NULL;
2152                         break;
2153                 }
2154         }
2155
2156         /* NOTE:  qh is invalid unless !list_empty(&hep->urb_list) */
2157         if (ret < 0 || (sched && qh != first_qh(sched))) {
2158                 int     ready = qh->is_ready;
2159
2160                 ret = 0;
2161                 qh->is_ready = 0;
2162                 __musb_giveback(musb, urb, 0);
2163                 qh->is_ready = ready;
2164
2165                 /* If nothing else (usually musb_giveback) is using it
2166                  * and its URB list has emptied, recycle this qh.
2167                  */
2168                 if (ready && list_empty(&qh->hep->urb_list)) {
2169                         qh->hep->hcpriv = NULL;
2170                         list_del(&qh->ring);
2171                         kfree(qh);
2172                 }
2173         } else
2174                 ret = musb_cleanup_urb(urb, qh, urb->pipe & USB_DIR_IN);
2175 done:
2176         spin_unlock_irqrestore(&musb->lock, flags);
2177         return ret;
2178 }
2179
2180 /* disable an endpoint */
2181 static void
2182 musb_h_disable(struct usb_hcd *hcd, struct usb_host_endpoint *hep)
2183 {
2184         u8                      epnum = hep->desc.bEndpointAddress;
2185         unsigned long           flags;
2186         struct musb             *musb = hcd_to_musb(hcd);
2187         u8                      is_in = epnum & USB_DIR_IN;
2188         struct musb_qh          *qh;
2189         struct urb              *urb;
2190         struct list_head        *sched;
2191
2192         spin_lock_irqsave(&musb->lock, flags);
2193
2194         qh = hep->hcpriv;
2195         if (qh == NULL)
2196                 goto exit;
2197
2198         switch (qh->type) {
2199         case USB_ENDPOINT_XFER_CONTROL:
2200                 sched = &musb->control;
2201                 break;
2202         case USB_ENDPOINT_XFER_BULK:
2203                 if (qh->mux == 1) {
2204                         if (is_in)
2205                                 sched = &musb->in_bulk;
2206                         else
2207                                 sched = &musb->out_bulk;
2208                         break;
2209                 }
2210         default:
2211                 /* REVISIT when we get a schedule tree, periodic transfers
2212                  * won't always be at the head of a singleton queue...
2213                  */
2214                 sched = NULL;
2215                 break;
2216         }
2217
2218         /* NOTE:  qh is invalid unless !list_empty(&hep->urb_list) */
2219
2220         /* kick first urb off the hardware, if needed */
2221         qh->is_ready = 0;
2222         if (!sched || qh == first_qh(sched)) {
2223                 urb = next_urb(qh);
2224
2225                 /* make software (then hardware) stop ASAP */
2226                 if (!urb->unlinked)
2227                         urb->status = -ESHUTDOWN;
2228
2229                 /* cleanup */
2230                 musb_cleanup_urb(urb, qh, urb->pipe & USB_DIR_IN);
2231
2232                 /* Then nuke all the others ... and advance the
2233                  * queue on hw_ep (e.g. bulk ring) when we're done.
2234                  */
2235                 while (!list_empty(&hep->urb_list)) {
2236                         urb = next_urb(qh);
2237                         urb->status = -ESHUTDOWN;
2238                         musb_advance_schedule(musb, urb, qh->hw_ep, is_in);
2239                 }
2240         } else {
2241                 /* Just empty the queue; the hardware is busy with
2242                  * other transfers, and since !qh->is_ready nothing
2243                  * will activate any of these as it advances.
2244                  */
2245                 while (!list_empty(&hep->urb_list))
2246                         __musb_giveback(musb, next_urb(qh), -ESHUTDOWN);
2247
2248                 hep->hcpriv = NULL;
2249                 list_del(&qh->ring);
2250                 kfree(qh);
2251         }
2252 exit:
2253         spin_unlock_irqrestore(&musb->lock, flags);
2254 }
2255
2256 static int musb_h_get_frame_number(struct usb_hcd *hcd)
2257 {
2258         struct musb     *musb = hcd_to_musb(hcd);
2259
2260         return musb_readw(musb->mregs, MUSB_FRAME);
2261 }
2262
2263 static int musb_h_start(struct usb_hcd *hcd)
2264 {
2265         struct musb     *musb = hcd_to_musb(hcd);
2266
2267         /* NOTE: musb_start() is called when the hub driver turns
2268          * on port power, or when (OTG) peripheral starts.
2269          */
2270         hcd->state = HC_STATE_RUNNING;
2271         musb->port1_status = 0;
2272         return 0;
2273 }
2274
2275 static void musb_h_stop(struct usb_hcd *hcd)
2276 {
2277         musb_stop(hcd_to_musb(hcd));
2278         hcd->state = HC_STATE_HALT;
2279 }
2280
2281 static int musb_bus_suspend(struct usb_hcd *hcd)
2282 {
2283         struct musb     *musb = hcd_to_musb(hcd);
2284
2285         if (musb->xceiv.state == OTG_STATE_A_SUSPEND)
2286                 return 0;
2287
2288         if (is_host_active(musb) && musb->is_active) {
2289                 WARNING("trying to suspend as %s is_active=%i\n",
2290                         otg_state_string(musb), musb->is_active);
2291                 return -EBUSY;
2292         } else
2293                 return 0;
2294 }
2295
2296 static int musb_bus_resume(struct usb_hcd *hcd)
2297 {
2298         /* resuming child port does the work */
2299         return 0;
2300 }
2301
2302 const struct hc_driver musb_hc_driver = {
2303         .description            = "musb-hcd",
2304         .product_desc           = "MUSB HDRC host driver",
2305         .hcd_priv_size          = sizeof(struct musb),
2306         .flags                  = HCD_USB2 | HCD_MEMORY,
2307
2308         /* not using irq handler or reset hooks from usbcore, since
2309          * those must be shared with peripheral code for OTG configs
2310          */
2311
2312         .start                  = musb_h_start,
2313         .stop                   = musb_h_stop,
2314
2315         .get_frame_number       = musb_h_get_frame_number,
2316
2317         .urb_enqueue            = musb_urb_enqueue,
2318         .urb_dequeue            = musb_urb_dequeue,
2319         .endpoint_disable       = musb_h_disable,
2320
2321         .hub_status_data        = musb_hub_status_data,
2322         .hub_control            = musb_hub_control,
2323         .bus_suspend            = musb_bus_suspend,
2324         .bus_resume             = musb_bus_resume,
2325         /* .start_port_reset    = NULL, */
2326         /* .hub_irq_enable      = NULL, */
2327 };