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