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