xref: /openbmc/linux/drivers/usb/dwc2/gadget.c (revision 1491eaf9)
1 /**
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd.
3  *		http://www.samsung.com
4  *
5  * Copyright 2008 Openmoko, Inc.
6  * Copyright 2008 Simtec Electronics
7  *      Ben Dooks <ben@simtec.co.uk>
8  *      http://armlinux.simtec.co.uk/
9  *
10  * S3C USB2.0 High-speed / OtG driver
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License version 2 as
14  * published by the Free Software Foundation.
15  */
16 
17 #include <linux/kernel.h>
18 #include <linux/module.h>
19 #include <linux/spinlock.h>
20 #include <linux/interrupt.h>
21 #include <linux/platform_device.h>
22 #include <linux/dma-mapping.h>
23 #include <linux/mutex.h>
24 #include <linux/seq_file.h>
25 #include <linux/delay.h>
26 #include <linux/io.h>
27 #include <linux/slab.h>
28 #include <linux/of_platform.h>
29 
30 #include <linux/usb/ch9.h>
31 #include <linux/usb/gadget.h>
32 #include <linux/usb/phy.h>
33 
34 #include "core.h"
35 #include "hw.h"
36 
37 /* conversion functions */
38 static inline struct dwc2_hsotg_req *our_req(struct usb_request *req)
39 {
40 	return container_of(req, struct dwc2_hsotg_req, req);
41 }
42 
43 static inline struct dwc2_hsotg_ep *our_ep(struct usb_ep *ep)
44 {
45 	return container_of(ep, struct dwc2_hsotg_ep, ep);
46 }
47 
48 static inline struct dwc2_hsotg *to_hsotg(struct usb_gadget *gadget)
49 {
50 	return container_of(gadget, struct dwc2_hsotg, gadget);
51 }
52 
53 static inline void __orr32(void __iomem *ptr, u32 val)
54 {
55 	dwc2_writel(dwc2_readl(ptr) | val, ptr);
56 }
57 
58 static inline void __bic32(void __iomem *ptr, u32 val)
59 {
60 	dwc2_writel(dwc2_readl(ptr) & ~val, ptr);
61 }
62 
63 static inline struct dwc2_hsotg_ep *index_to_ep(struct dwc2_hsotg *hsotg,
64 						u32 ep_index, u32 dir_in)
65 {
66 	if (dir_in)
67 		return hsotg->eps_in[ep_index];
68 	else
69 		return hsotg->eps_out[ep_index];
70 }
71 
72 /* forward declaration of functions */
73 static void dwc2_hsotg_dump(struct dwc2_hsotg *hsotg);
74 
75 /**
76  * using_dma - return the DMA status of the driver.
77  * @hsotg: The driver state.
78  *
79  * Return true if we're using DMA.
80  *
81  * Currently, we have the DMA support code worked into everywhere
82  * that needs it, but the AMBA DMA implementation in the hardware can
83  * only DMA from 32bit aligned addresses. This means that gadgets such
84  * as the CDC Ethernet cannot work as they often pass packets which are
85  * not 32bit aligned.
86  *
87  * Unfortunately the choice to use DMA or not is global to the controller
88  * and seems to be only settable when the controller is being put through
89  * a core reset. This means we either need to fix the gadgets to take
90  * account of DMA alignment, or add bounce buffers (yuerk).
91  *
92  * g_using_dma is set depending on dts flag.
93  */
94 static inline bool using_dma(struct dwc2_hsotg *hsotg)
95 {
96 	return hsotg->g_using_dma;
97 }
98 
99 /**
100  * dwc2_gadget_incr_frame_num - Increments the targeted frame number.
101  * @hs_ep: The endpoint
102  * @increment: The value to increment by
103  *
104  * This function will also check if the frame number overruns DSTS_SOFFN_LIMIT.
105  * If an overrun occurs it will wrap the value and set the frame_overrun flag.
106  */
107 static inline void dwc2_gadget_incr_frame_num(struct dwc2_hsotg_ep *hs_ep)
108 {
109 	hs_ep->target_frame += hs_ep->interval;
110 	if (hs_ep->target_frame > DSTS_SOFFN_LIMIT) {
111 		hs_ep->frame_overrun = 1;
112 		hs_ep->target_frame &= DSTS_SOFFN_LIMIT;
113 	} else {
114 		hs_ep->frame_overrun = 0;
115 	}
116 }
117 
118 /**
119  * dwc2_hsotg_en_gsint - enable one or more of the general interrupt
120  * @hsotg: The device state
121  * @ints: A bitmask of the interrupts to enable
122  */
123 static void dwc2_hsotg_en_gsint(struct dwc2_hsotg *hsotg, u32 ints)
124 {
125 	u32 gsintmsk = dwc2_readl(hsotg->regs + GINTMSK);
126 	u32 new_gsintmsk;
127 
128 	new_gsintmsk = gsintmsk | ints;
129 
130 	if (new_gsintmsk != gsintmsk) {
131 		dev_dbg(hsotg->dev, "gsintmsk now 0x%08x\n", new_gsintmsk);
132 		dwc2_writel(new_gsintmsk, hsotg->regs + GINTMSK);
133 	}
134 }
135 
136 /**
137  * dwc2_hsotg_disable_gsint - disable one or more of the general interrupt
138  * @hsotg: The device state
139  * @ints: A bitmask of the interrupts to enable
140  */
141 static void dwc2_hsotg_disable_gsint(struct dwc2_hsotg *hsotg, u32 ints)
142 {
143 	u32 gsintmsk = dwc2_readl(hsotg->regs + GINTMSK);
144 	u32 new_gsintmsk;
145 
146 	new_gsintmsk = gsintmsk & ~ints;
147 
148 	if (new_gsintmsk != gsintmsk)
149 		dwc2_writel(new_gsintmsk, hsotg->regs + GINTMSK);
150 }
151 
152 /**
153  * dwc2_hsotg_ctrl_epint - enable/disable an endpoint irq
154  * @hsotg: The device state
155  * @ep: The endpoint index
156  * @dir_in: True if direction is in.
157  * @en: The enable value, true to enable
158  *
159  * Set or clear the mask for an individual endpoint's interrupt
160  * request.
161  */
162 static void dwc2_hsotg_ctrl_epint(struct dwc2_hsotg *hsotg,
163 				 unsigned int ep, unsigned int dir_in,
164 				 unsigned int en)
165 {
166 	unsigned long flags;
167 	u32 bit = 1 << ep;
168 	u32 daint;
169 
170 	if (!dir_in)
171 		bit <<= 16;
172 
173 	local_irq_save(flags);
174 	daint = dwc2_readl(hsotg->regs + DAINTMSK);
175 	if (en)
176 		daint |= bit;
177 	else
178 		daint &= ~bit;
179 	dwc2_writel(daint, hsotg->regs + DAINTMSK);
180 	local_irq_restore(flags);
181 }
182 
183 /**
184  * dwc2_hsotg_init_fifo - initialise non-periodic FIFOs
185  * @hsotg: The device instance.
186  */
187 static void dwc2_hsotg_init_fifo(struct dwc2_hsotg *hsotg)
188 {
189 	unsigned int ep;
190 	unsigned int addr;
191 	int timeout;
192 	u32 val;
193 
194 	/* Reset fifo map if not correctly cleared during previous session */
195 	WARN_ON(hsotg->fifo_map);
196 	hsotg->fifo_map = 0;
197 
198 	/* set RX/NPTX FIFO sizes */
199 	dwc2_writel(hsotg->g_rx_fifo_sz, hsotg->regs + GRXFSIZ);
200 	dwc2_writel((hsotg->g_rx_fifo_sz << FIFOSIZE_STARTADDR_SHIFT) |
201 		(hsotg->g_np_g_tx_fifo_sz << FIFOSIZE_DEPTH_SHIFT),
202 		hsotg->regs + GNPTXFSIZ);
203 
204 	/*
205 	 * arange all the rest of the TX FIFOs, as some versions of this
206 	 * block have overlapping default addresses. This also ensures
207 	 * that if the settings have been changed, then they are set to
208 	 * known values.
209 	 */
210 
211 	/* start at the end of the GNPTXFSIZ, rounded up */
212 	addr = hsotg->g_rx_fifo_sz + hsotg->g_np_g_tx_fifo_sz;
213 
214 	/*
215 	 * Configure fifos sizes from provided configuration and assign
216 	 * them to endpoints dynamically according to maxpacket size value of
217 	 * given endpoint.
218 	 */
219 	for (ep = 1; ep < MAX_EPS_CHANNELS; ep++) {
220 		if (!hsotg->g_tx_fifo_sz[ep])
221 			continue;
222 		val = addr;
223 		val |= hsotg->g_tx_fifo_sz[ep] << FIFOSIZE_DEPTH_SHIFT;
224 		WARN_ONCE(addr + hsotg->g_tx_fifo_sz[ep] > hsotg->fifo_mem,
225 			  "insufficient fifo memory");
226 		addr += hsotg->g_tx_fifo_sz[ep];
227 
228 		dwc2_writel(val, hsotg->regs + DPTXFSIZN(ep));
229 	}
230 
231 	/*
232 	 * according to p428 of the design guide, we need to ensure that
233 	 * all fifos are flushed before continuing
234 	 */
235 
236 	dwc2_writel(GRSTCTL_TXFNUM(0x10) | GRSTCTL_TXFFLSH |
237 	       GRSTCTL_RXFFLSH, hsotg->regs + GRSTCTL);
238 
239 	/* wait until the fifos are both flushed */
240 	timeout = 100;
241 	while (1) {
242 		val = dwc2_readl(hsotg->regs + GRSTCTL);
243 
244 		if ((val & (GRSTCTL_TXFFLSH | GRSTCTL_RXFFLSH)) == 0)
245 			break;
246 
247 		if (--timeout == 0) {
248 			dev_err(hsotg->dev,
249 				"%s: timeout flushing fifos (GRSTCTL=%08x)\n",
250 				__func__, val);
251 			break;
252 		}
253 
254 		udelay(1);
255 	}
256 
257 	dev_dbg(hsotg->dev, "FIFOs reset, timeout at %d\n", timeout);
258 }
259 
260 /**
261  * @ep: USB endpoint to allocate request for.
262  * @flags: Allocation flags
263  *
264  * Allocate a new USB request structure appropriate for the specified endpoint
265  */
266 static struct usb_request *dwc2_hsotg_ep_alloc_request(struct usb_ep *ep,
267 						      gfp_t flags)
268 {
269 	struct dwc2_hsotg_req *req;
270 
271 	req = kzalloc(sizeof(struct dwc2_hsotg_req), flags);
272 	if (!req)
273 		return NULL;
274 
275 	INIT_LIST_HEAD(&req->queue);
276 
277 	return &req->req;
278 }
279 
280 /**
281  * is_ep_periodic - return true if the endpoint is in periodic mode.
282  * @hs_ep: The endpoint to query.
283  *
284  * Returns true if the endpoint is in periodic mode, meaning it is being
285  * used for an Interrupt or ISO transfer.
286  */
287 static inline int is_ep_periodic(struct dwc2_hsotg_ep *hs_ep)
288 {
289 	return hs_ep->periodic;
290 }
291 
292 /**
293  * dwc2_hsotg_unmap_dma - unmap the DMA memory being used for the request
294  * @hsotg: The device state.
295  * @hs_ep: The endpoint for the request
296  * @hs_req: The request being processed.
297  *
298  * This is the reverse of dwc2_hsotg_map_dma(), called for the completion
299  * of a request to ensure the buffer is ready for access by the caller.
300  */
301 static void dwc2_hsotg_unmap_dma(struct dwc2_hsotg *hsotg,
302 				struct dwc2_hsotg_ep *hs_ep,
303 				struct dwc2_hsotg_req *hs_req)
304 {
305 	struct usb_request *req = &hs_req->req;
306 
307 	/* ignore this if we're not moving any data */
308 	if (hs_req->req.length == 0)
309 		return;
310 
311 	usb_gadget_unmap_request(&hsotg->gadget, req, hs_ep->dir_in);
312 }
313 
314 /**
315  * dwc2_hsotg_write_fifo - write packet Data to the TxFIFO
316  * @hsotg: The controller state.
317  * @hs_ep: The endpoint we're going to write for.
318  * @hs_req: The request to write data for.
319  *
320  * This is called when the TxFIFO has some space in it to hold a new
321  * transmission and we have something to give it. The actual setup of
322  * the data size is done elsewhere, so all we have to do is to actually
323  * write the data.
324  *
325  * The return value is zero if there is more space (or nothing was done)
326  * otherwise -ENOSPC is returned if the FIFO space was used up.
327  *
328  * This routine is only needed for PIO
329  */
330 static int dwc2_hsotg_write_fifo(struct dwc2_hsotg *hsotg,
331 				struct dwc2_hsotg_ep *hs_ep,
332 				struct dwc2_hsotg_req *hs_req)
333 {
334 	bool periodic = is_ep_periodic(hs_ep);
335 	u32 gnptxsts = dwc2_readl(hsotg->regs + GNPTXSTS);
336 	int buf_pos = hs_req->req.actual;
337 	int to_write = hs_ep->size_loaded;
338 	void *data;
339 	int can_write;
340 	int pkt_round;
341 	int max_transfer;
342 
343 	to_write -= (buf_pos - hs_ep->last_load);
344 
345 	/* if there's nothing to write, get out early */
346 	if (to_write == 0)
347 		return 0;
348 
349 	if (periodic && !hsotg->dedicated_fifos) {
350 		u32 epsize = dwc2_readl(hsotg->regs + DIEPTSIZ(hs_ep->index));
351 		int size_left;
352 		int size_done;
353 
354 		/*
355 		 * work out how much data was loaded so we can calculate
356 		 * how much data is left in the fifo.
357 		 */
358 
359 		size_left = DXEPTSIZ_XFERSIZE_GET(epsize);
360 
361 		/*
362 		 * if shared fifo, we cannot write anything until the
363 		 * previous data has been completely sent.
364 		 */
365 		if (hs_ep->fifo_load != 0) {
366 			dwc2_hsotg_en_gsint(hsotg, GINTSTS_PTXFEMP);
367 			return -ENOSPC;
368 		}
369 
370 		dev_dbg(hsotg->dev, "%s: left=%d, load=%d, fifo=%d, size %d\n",
371 			__func__, size_left,
372 			hs_ep->size_loaded, hs_ep->fifo_load, hs_ep->fifo_size);
373 
374 		/* how much of the data has moved */
375 		size_done = hs_ep->size_loaded - size_left;
376 
377 		/* how much data is left in the fifo */
378 		can_write = hs_ep->fifo_load - size_done;
379 		dev_dbg(hsotg->dev, "%s: => can_write1=%d\n",
380 			__func__, can_write);
381 
382 		can_write = hs_ep->fifo_size - can_write;
383 		dev_dbg(hsotg->dev, "%s: => can_write2=%d\n",
384 			__func__, can_write);
385 
386 		if (can_write <= 0) {
387 			dwc2_hsotg_en_gsint(hsotg, GINTSTS_PTXFEMP);
388 			return -ENOSPC;
389 		}
390 	} else if (hsotg->dedicated_fifos && hs_ep->index != 0) {
391 		can_write = dwc2_readl(hsotg->regs + DTXFSTS(hs_ep->index));
392 
393 		can_write &= 0xffff;
394 		can_write *= 4;
395 	} else {
396 		if (GNPTXSTS_NP_TXQ_SPC_AVAIL_GET(gnptxsts) == 0) {
397 			dev_dbg(hsotg->dev,
398 				"%s: no queue slots available (0x%08x)\n",
399 				__func__, gnptxsts);
400 
401 			dwc2_hsotg_en_gsint(hsotg, GINTSTS_NPTXFEMP);
402 			return -ENOSPC;
403 		}
404 
405 		can_write = GNPTXSTS_NP_TXF_SPC_AVAIL_GET(gnptxsts);
406 		can_write *= 4;	/* fifo size is in 32bit quantities. */
407 	}
408 
409 	max_transfer = hs_ep->ep.maxpacket * hs_ep->mc;
410 
411 	dev_dbg(hsotg->dev, "%s: GNPTXSTS=%08x, can=%d, to=%d, max_transfer %d\n",
412 		 __func__, gnptxsts, can_write, to_write, max_transfer);
413 
414 	/*
415 	 * limit to 512 bytes of data, it seems at least on the non-periodic
416 	 * FIFO, requests of >512 cause the endpoint to get stuck with a
417 	 * fragment of the end of the transfer in it.
418 	 */
419 	if (can_write > 512 && !periodic)
420 		can_write = 512;
421 
422 	/*
423 	 * limit the write to one max-packet size worth of data, but allow
424 	 * the transfer to return that it did not run out of fifo space
425 	 * doing it.
426 	 */
427 	if (to_write > max_transfer) {
428 		to_write = max_transfer;
429 
430 		/* it's needed only when we do not use dedicated fifos */
431 		if (!hsotg->dedicated_fifos)
432 			dwc2_hsotg_en_gsint(hsotg,
433 					   periodic ? GINTSTS_PTXFEMP :
434 					   GINTSTS_NPTXFEMP);
435 	}
436 
437 	/* see if we can write data */
438 
439 	if (to_write > can_write) {
440 		to_write = can_write;
441 		pkt_round = to_write % max_transfer;
442 
443 		/*
444 		 * Round the write down to an
445 		 * exact number of packets.
446 		 *
447 		 * Note, we do not currently check to see if we can ever
448 		 * write a full packet or not to the FIFO.
449 		 */
450 
451 		if (pkt_round)
452 			to_write -= pkt_round;
453 
454 		/*
455 		 * enable correct FIFO interrupt to alert us when there
456 		 * is more room left.
457 		 */
458 
459 		/* it's needed only when we do not use dedicated fifos */
460 		if (!hsotg->dedicated_fifos)
461 			dwc2_hsotg_en_gsint(hsotg,
462 					   periodic ? GINTSTS_PTXFEMP :
463 					   GINTSTS_NPTXFEMP);
464 	}
465 
466 	dev_dbg(hsotg->dev, "write %d/%d, can_write %d, done %d\n",
467 		 to_write, hs_req->req.length, can_write, buf_pos);
468 
469 	if (to_write <= 0)
470 		return -ENOSPC;
471 
472 	hs_req->req.actual = buf_pos + to_write;
473 	hs_ep->total_data += to_write;
474 
475 	if (periodic)
476 		hs_ep->fifo_load += to_write;
477 
478 	to_write = DIV_ROUND_UP(to_write, 4);
479 	data = hs_req->req.buf + buf_pos;
480 
481 	iowrite32_rep(hsotg->regs + EPFIFO(hs_ep->index), data, to_write);
482 
483 	return (to_write >= can_write) ? -ENOSPC : 0;
484 }
485 
486 /**
487  * get_ep_limit - get the maximum data legnth for this endpoint
488  * @hs_ep: The endpoint
489  *
490  * Return the maximum data that can be queued in one go on a given endpoint
491  * so that transfers that are too long can be split.
492  */
493 static unsigned get_ep_limit(struct dwc2_hsotg_ep *hs_ep)
494 {
495 	int index = hs_ep->index;
496 	unsigned maxsize;
497 	unsigned maxpkt;
498 
499 	if (index != 0) {
500 		maxsize = DXEPTSIZ_XFERSIZE_LIMIT + 1;
501 		maxpkt = DXEPTSIZ_PKTCNT_LIMIT + 1;
502 	} else {
503 		maxsize = 64+64;
504 		if (hs_ep->dir_in)
505 			maxpkt = DIEPTSIZ0_PKTCNT_LIMIT + 1;
506 		else
507 			maxpkt = 2;
508 	}
509 
510 	/* we made the constant loading easier above by using +1 */
511 	maxpkt--;
512 	maxsize--;
513 
514 	/*
515 	 * constrain by packet count if maxpkts*pktsize is greater
516 	 * than the length register size.
517 	 */
518 
519 	if ((maxpkt * hs_ep->ep.maxpacket) < maxsize)
520 		maxsize = maxpkt * hs_ep->ep.maxpacket;
521 
522 	return maxsize;
523 }
524 
525 /**
526 * dwc2_hsotg_read_frameno - read current frame number
527 * @hsotg: The device instance
528 *
529 * Return the current frame number
530 */
531 static u32 dwc2_hsotg_read_frameno(struct dwc2_hsotg *hsotg)
532 {
533 	u32 dsts;
534 
535 	dsts = dwc2_readl(hsotg->regs + DSTS);
536 	dsts &= DSTS_SOFFN_MASK;
537 	dsts >>= DSTS_SOFFN_SHIFT;
538 
539 	return dsts;
540 }
541 
542 /**
543  * dwc2_hsotg_start_req - start a USB request from an endpoint's queue
544  * @hsotg: The controller state.
545  * @hs_ep: The endpoint to process a request for
546  * @hs_req: The request to start.
547  * @continuing: True if we are doing more for the current request.
548  *
549  * Start the given request running by setting the endpoint registers
550  * appropriately, and writing any data to the FIFOs.
551  */
552 static void dwc2_hsotg_start_req(struct dwc2_hsotg *hsotg,
553 				struct dwc2_hsotg_ep *hs_ep,
554 				struct dwc2_hsotg_req *hs_req,
555 				bool continuing)
556 {
557 	struct usb_request *ureq = &hs_req->req;
558 	int index = hs_ep->index;
559 	int dir_in = hs_ep->dir_in;
560 	u32 epctrl_reg;
561 	u32 epsize_reg;
562 	u32 epsize;
563 	u32 ctrl;
564 	unsigned length;
565 	unsigned packets;
566 	unsigned maxreq;
567 
568 	if (index != 0) {
569 		if (hs_ep->req && !continuing) {
570 			dev_err(hsotg->dev, "%s: active request\n", __func__);
571 			WARN_ON(1);
572 			return;
573 		} else if (hs_ep->req != hs_req && continuing) {
574 			dev_err(hsotg->dev,
575 				"%s: continue different req\n", __func__);
576 			WARN_ON(1);
577 			return;
578 		}
579 	}
580 
581 	epctrl_reg = dir_in ? DIEPCTL(index) : DOEPCTL(index);
582 	epsize_reg = dir_in ? DIEPTSIZ(index) : DOEPTSIZ(index);
583 
584 	dev_dbg(hsotg->dev, "%s: DxEPCTL=0x%08x, ep %d, dir %s\n",
585 		__func__, dwc2_readl(hsotg->regs + epctrl_reg), index,
586 		hs_ep->dir_in ? "in" : "out");
587 
588 	/* If endpoint is stalled, we will restart request later */
589 	ctrl = dwc2_readl(hsotg->regs + epctrl_reg);
590 
591 	if (index && ctrl & DXEPCTL_STALL) {
592 		dev_warn(hsotg->dev, "%s: ep%d is stalled\n", __func__, index);
593 		return;
594 	}
595 
596 	length = ureq->length - ureq->actual;
597 	dev_dbg(hsotg->dev, "ureq->length:%d ureq->actual:%d\n",
598 		ureq->length, ureq->actual);
599 
600 	maxreq = get_ep_limit(hs_ep);
601 	if (length > maxreq) {
602 		int round = maxreq % hs_ep->ep.maxpacket;
603 
604 		dev_dbg(hsotg->dev, "%s: length %d, max-req %d, r %d\n",
605 			__func__, length, maxreq, round);
606 
607 		/* round down to multiple of packets */
608 		if (round)
609 			maxreq -= round;
610 
611 		length = maxreq;
612 	}
613 
614 	if (length)
615 		packets = DIV_ROUND_UP(length, hs_ep->ep.maxpacket);
616 	else
617 		packets = 1;	/* send one packet if length is zero. */
618 
619 	if (hs_ep->isochronous && length > (hs_ep->mc * hs_ep->ep.maxpacket)) {
620 		dev_err(hsotg->dev, "req length > maxpacket*mc\n");
621 		return;
622 	}
623 
624 	if (dir_in && index != 0)
625 		if (hs_ep->isochronous)
626 			epsize = DXEPTSIZ_MC(packets);
627 		else
628 			epsize = DXEPTSIZ_MC(1);
629 	else
630 		epsize = 0;
631 
632 	/*
633 	 * zero length packet should be programmed on its own and should not
634 	 * be counted in DIEPTSIZ.PktCnt with other packets.
635 	 */
636 	if (dir_in && ureq->zero && !continuing) {
637 		/* Test if zlp is actually required. */
638 		if ((ureq->length >= hs_ep->ep.maxpacket) &&
639 					!(ureq->length % hs_ep->ep.maxpacket))
640 			hs_ep->send_zlp = 1;
641 	}
642 
643 	epsize |= DXEPTSIZ_PKTCNT(packets);
644 	epsize |= DXEPTSIZ_XFERSIZE(length);
645 
646 	dev_dbg(hsotg->dev, "%s: %d@%d/%d, 0x%08x => 0x%08x\n",
647 		__func__, packets, length, ureq->length, epsize, epsize_reg);
648 
649 	/* store the request as the current one we're doing */
650 	hs_ep->req = hs_req;
651 
652 	/* write size / packets */
653 	dwc2_writel(epsize, hsotg->regs + epsize_reg);
654 
655 	if (using_dma(hsotg) && !continuing) {
656 		unsigned int dma_reg;
657 
658 		/*
659 		 * write DMA address to control register, buffer already
660 		 * synced by dwc2_hsotg_ep_queue().
661 		 */
662 
663 		dma_reg = dir_in ? DIEPDMA(index) : DOEPDMA(index);
664 		dwc2_writel(ureq->dma, hsotg->regs + dma_reg);
665 
666 		dev_dbg(hsotg->dev, "%s: %pad => 0x%08x\n",
667 			__func__, &ureq->dma, dma_reg);
668 	}
669 
670 	if (hs_ep->isochronous && hs_ep->interval == 1) {
671 		hs_ep->target_frame = dwc2_hsotg_read_frameno(hsotg);
672 		dwc2_gadget_incr_frame_num(hs_ep);
673 
674 		if (hs_ep->target_frame & 0x1)
675 			ctrl |= DXEPCTL_SETODDFR;
676 		else
677 			ctrl |= DXEPCTL_SETEVENFR;
678 	}
679 
680 	ctrl |= DXEPCTL_EPENA;	/* ensure ep enabled */
681 
682 	dev_dbg(hsotg->dev, "ep0 state:%d\n", hsotg->ep0_state);
683 
684 	/* For Setup request do not clear NAK */
685 	if (!(index == 0 && hsotg->ep0_state == DWC2_EP0_SETUP))
686 		ctrl |= DXEPCTL_CNAK;	/* clear NAK set by core */
687 
688 	dev_dbg(hsotg->dev, "%s: DxEPCTL=0x%08x\n", __func__, ctrl);
689 	dwc2_writel(ctrl, hsotg->regs + epctrl_reg);
690 
691 	/*
692 	 * set these, it seems that DMA support increments past the end
693 	 * of the packet buffer so we need to calculate the length from
694 	 * this information.
695 	 */
696 	hs_ep->size_loaded = length;
697 	hs_ep->last_load = ureq->actual;
698 
699 	if (dir_in && !using_dma(hsotg)) {
700 		/* set these anyway, we may need them for non-periodic in */
701 		hs_ep->fifo_load = 0;
702 
703 		dwc2_hsotg_write_fifo(hsotg, hs_ep, hs_req);
704 	}
705 
706 	/*
707 	 * Note, trying to clear the NAK here causes problems with transmit
708 	 * on the S3C6400 ending up with the TXFIFO becoming full.
709 	 */
710 
711 	/* check ep is enabled */
712 	if (!(dwc2_readl(hsotg->regs + epctrl_reg) & DXEPCTL_EPENA))
713 		dev_dbg(hsotg->dev,
714 			 "ep%d: failed to become enabled (DXEPCTL=0x%08x)?\n",
715 			 index, dwc2_readl(hsotg->regs + epctrl_reg));
716 
717 	dev_dbg(hsotg->dev, "%s: DXEPCTL=0x%08x\n",
718 		__func__, dwc2_readl(hsotg->regs + epctrl_reg));
719 
720 	/* enable ep interrupts */
721 	dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index, hs_ep->dir_in, 1);
722 }
723 
724 /**
725  * dwc2_hsotg_map_dma - map the DMA memory being used for the request
726  * @hsotg: The device state.
727  * @hs_ep: The endpoint the request is on.
728  * @req: The request being processed.
729  *
730  * We've been asked to queue a request, so ensure that the memory buffer
731  * is correctly setup for DMA. If we've been passed an extant DMA address
732  * then ensure the buffer has been synced to memory. If our buffer has no
733  * DMA memory, then we map the memory and mark our request to allow us to
734  * cleanup on completion.
735  */
736 static int dwc2_hsotg_map_dma(struct dwc2_hsotg *hsotg,
737 			     struct dwc2_hsotg_ep *hs_ep,
738 			     struct usb_request *req)
739 {
740 	struct dwc2_hsotg_req *hs_req = our_req(req);
741 	int ret;
742 
743 	/* if the length is zero, ignore the DMA data */
744 	if (hs_req->req.length == 0)
745 		return 0;
746 
747 	ret = usb_gadget_map_request(&hsotg->gadget, req, hs_ep->dir_in);
748 	if (ret)
749 		goto dma_error;
750 
751 	return 0;
752 
753 dma_error:
754 	dev_err(hsotg->dev, "%s: failed to map buffer %p, %d bytes\n",
755 		__func__, req->buf, req->length);
756 
757 	return -EIO;
758 }
759 
760 static int dwc2_hsotg_handle_unaligned_buf_start(struct dwc2_hsotg *hsotg,
761 	struct dwc2_hsotg_ep *hs_ep, struct dwc2_hsotg_req *hs_req)
762 {
763 	void *req_buf = hs_req->req.buf;
764 
765 	/* If dma is not being used or buffer is aligned */
766 	if (!using_dma(hsotg) || !((long)req_buf & 3))
767 		return 0;
768 
769 	WARN_ON(hs_req->saved_req_buf);
770 
771 	dev_dbg(hsotg->dev, "%s: %s: buf=%p length=%d\n", __func__,
772 			hs_ep->ep.name, req_buf, hs_req->req.length);
773 
774 	hs_req->req.buf = kmalloc(hs_req->req.length, GFP_ATOMIC);
775 	if (!hs_req->req.buf) {
776 		hs_req->req.buf = req_buf;
777 		dev_err(hsotg->dev,
778 			"%s: unable to allocate memory for bounce buffer\n",
779 			__func__);
780 		return -ENOMEM;
781 	}
782 
783 	/* Save actual buffer */
784 	hs_req->saved_req_buf = req_buf;
785 
786 	if (hs_ep->dir_in)
787 		memcpy(hs_req->req.buf, req_buf, hs_req->req.length);
788 	return 0;
789 }
790 
791 static void dwc2_hsotg_handle_unaligned_buf_complete(struct dwc2_hsotg *hsotg,
792 	struct dwc2_hsotg_ep *hs_ep, struct dwc2_hsotg_req *hs_req)
793 {
794 	/* If dma is not being used or buffer was aligned */
795 	if (!using_dma(hsotg) || !hs_req->saved_req_buf)
796 		return;
797 
798 	dev_dbg(hsotg->dev, "%s: %s: status=%d actual-length=%d\n", __func__,
799 		hs_ep->ep.name, hs_req->req.status, hs_req->req.actual);
800 
801 	/* Copy data from bounce buffer on successful out transfer */
802 	if (!hs_ep->dir_in && !hs_req->req.status)
803 		memcpy(hs_req->saved_req_buf, hs_req->req.buf,
804 							hs_req->req.actual);
805 
806 	/* Free bounce buffer */
807 	kfree(hs_req->req.buf);
808 
809 	hs_req->req.buf = hs_req->saved_req_buf;
810 	hs_req->saved_req_buf = NULL;
811 }
812 
813 /**
814  * dwc2_gadget_target_frame_elapsed - Checks target frame
815  * @hs_ep: The driver endpoint to check
816  *
817  * Returns 1 if targeted frame elapsed. If returned 1 then we need to drop
818  * corresponding transfer.
819  */
820 static bool dwc2_gadget_target_frame_elapsed(struct dwc2_hsotg_ep *hs_ep)
821 {
822 	struct dwc2_hsotg *hsotg = hs_ep->parent;
823 	u32 target_frame = hs_ep->target_frame;
824 	u32 current_frame = dwc2_hsotg_read_frameno(hsotg);
825 	bool frame_overrun = hs_ep->frame_overrun;
826 
827 	if (!frame_overrun && current_frame >= target_frame)
828 		return true;
829 
830 	if (frame_overrun && current_frame >= target_frame &&
831 	    ((current_frame - target_frame) < DSTS_SOFFN_LIMIT / 2))
832 		return true;
833 
834 	return false;
835 }
836 
837 static int dwc2_hsotg_ep_queue(struct usb_ep *ep, struct usb_request *req,
838 			      gfp_t gfp_flags)
839 {
840 	struct dwc2_hsotg_req *hs_req = our_req(req);
841 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
842 	struct dwc2_hsotg *hs = hs_ep->parent;
843 	bool first;
844 	int ret;
845 
846 	dev_dbg(hs->dev, "%s: req %p: %d@%p, noi=%d, zero=%d, snok=%d\n",
847 		ep->name, req, req->length, req->buf, req->no_interrupt,
848 		req->zero, req->short_not_ok);
849 
850 	/* Prevent new request submission when controller is suspended */
851 	if (hs->lx_state == DWC2_L2) {
852 		dev_dbg(hs->dev, "%s: don't submit request while suspended\n",
853 				__func__);
854 		return -EAGAIN;
855 	}
856 
857 	/* initialise status of the request */
858 	INIT_LIST_HEAD(&hs_req->queue);
859 	req->actual = 0;
860 	req->status = -EINPROGRESS;
861 
862 	ret = dwc2_hsotg_handle_unaligned_buf_start(hs, hs_ep, hs_req);
863 	if (ret)
864 		return ret;
865 
866 	/* if we're using DMA, sync the buffers as necessary */
867 	if (using_dma(hs)) {
868 		ret = dwc2_hsotg_map_dma(hs, hs_ep, req);
869 		if (ret)
870 			return ret;
871 	}
872 
873 	first = list_empty(&hs_ep->queue);
874 	list_add_tail(&hs_req->queue, &hs_ep->queue);
875 
876 	if (first) {
877 		if (!hs_ep->isochronous) {
878 			dwc2_hsotg_start_req(hs, hs_ep, hs_req, false);
879 			return 0;
880 		}
881 
882 		while (dwc2_gadget_target_frame_elapsed(hs_ep))
883 			dwc2_gadget_incr_frame_num(hs_ep);
884 
885 		if (hs_ep->target_frame != TARGET_FRAME_INITIAL)
886 			dwc2_hsotg_start_req(hs, hs_ep, hs_req, false);
887 	}
888 	return 0;
889 }
890 
891 static int dwc2_hsotg_ep_queue_lock(struct usb_ep *ep, struct usb_request *req,
892 			      gfp_t gfp_flags)
893 {
894 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
895 	struct dwc2_hsotg *hs = hs_ep->parent;
896 	unsigned long flags = 0;
897 	int ret = 0;
898 
899 	spin_lock_irqsave(&hs->lock, flags);
900 	ret = dwc2_hsotg_ep_queue(ep, req, gfp_flags);
901 	spin_unlock_irqrestore(&hs->lock, flags);
902 
903 	return ret;
904 }
905 
906 static void dwc2_hsotg_ep_free_request(struct usb_ep *ep,
907 				      struct usb_request *req)
908 {
909 	struct dwc2_hsotg_req *hs_req = our_req(req);
910 
911 	kfree(hs_req);
912 }
913 
914 /**
915  * dwc2_hsotg_complete_oursetup - setup completion callback
916  * @ep: The endpoint the request was on.
917  * @req: The request completed.
918  *
919  * Called on completion of any requests the driver itself
920  * submitted that need cleaning up.
921  */
922 static void dwc2_hsotg_complete_oursetup(struct usb_ep *ep,
923 					struct usb_request *req)
924 {
925 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
926 	struct dwc2_hsotg *hsotg = hs_ep->parent;
927 
928 	dev_dbg(hsotg->dev, "%s: ep %p, req %p\n", __func__, ep, req);
929 
930 	dwc2_hsotg_ep_free_request(ep, req);
931 }
932 
933 /**
934  * ep_from_windex - convert control wIndex value to endpoint
935  * @hsotg: The driver state.
936  * @windex: The control request wIndex field (in host order).
937  *
938  * Convert the given wIndex into a pointer to an driver endpoint
939  * structure, or return NULL if it is not a valid endpoint.
940  */
941 static struct dwc2_hsotg_ep *ep_from_windex(struct dwc2_hsotg *hsotg,
942 					   u32 windex)
943 {
944 	struct dwc2_hsotg_ep *ep;
945 	int dir = (windex & USB_DIR_IN) ? 1 : 0;
946 	int idx = windex & 0x7F;
947 
948 	if (windex >= 0x100)
949 		return NULL;
950 
951 	if (idx > hsotg->num_of_eps)
952 		return NULL;
953 
954 	ep = index_to_ep(hsotg, idx, dir);
955 
956 	if (idx && ep->dir_in != dir)
957 		return NULL;
958 
959 	return ep;
960 }
961 
962 /**
963  * dwc2_hsotg_set_test_mode - Enable usb Test Modes
964  * @hsotg: The driver state.
965  * @testmode: requested usb test mode
966  * Enable usb Test Mode requested by the Host.
967  */
968 int dwc2_hsotg_set_test_mode(struct dwc2_hsotg *hsotg, int testmode)
969 {
970 	int dctl = dwc2_readl(hsotg->regs + DCTL);
971 
972 	dctl &= ~DCTL_TSTCTL_MASK;
973 	switch (testmode) {
974 	case TEST_J:
975 	case TEST_K:
976 	case TEST_SE0_NAK:
977 	case TEST_PACKET:
978 	case TEST_FORCE_EN:
979 		dctl |= testmode << DCTL_TSTCTL_SHIFT;
980 		break;
981 	default:
982 		return -EINVAL;
983 	}
984 	dwc2_writel(dctl, hsotg->regs + DCTL);
985 	return 0;
986 }
987 
988 /**
989  * dwc2_hsotg_send_reply - send reply to control request
990  * @hsotg: The device state
991  * @ep: Endpoint 0
992  * @buff: Buffer for request
993  * @length: Length of reply.
994  *
995  * Create a request and queue it on the given endpoint. This is useful as
996  * an internal method of sending replies to certain control requests, etc.
997  */
998 static int dwc2_hsotg_send_reply(struct dwc2_hsotg *hsotg,
999 				struct dwc2_hsotg_ep *ep,
1000 				void *buff,
1001 				int length)
1002 {
1003 	struct usb_request *req;
1004 	int ret;
1005 
1006 	dev_dbg(hsotg->dev, "%s: buff %p, len %d\n", __func__, buff, length);
1007 
1008 	req = dwc2_hsotg_ep_alloc_request(&ep->ep, GFP_ATOMIC);
1009 	hsotg->ep0_reply = req;
1010 	if (!req) {
1011 		dev_warn(hsotg->dev, "%s: cannot alloc req\n", __func__);
1012 		return -ENOMEM;
1013 	}
1014 
1015 	req->buf = hsotg->ep0_buff;
1016 	req->length = length;
1017 	/*
1018 	 * zero flag is for sending zlp in DATA IN stage. It has no impact on
1019 	 * STATUS stage.
1020 	 */
1021 	req->zero = 0;
1022 	req->complete = dwc2_hsotg_complete_oursetup;
1023 
1024 	if (length)
1025 		memcpy(req->buf, buff, length);
1026 
1027 	ret = dwc2_hsotg_ep_queue(&ep->ep, req, GFP_ATOMIC);
1028 	if (ret) {
1029 		dev_warn(hsotg->dev, "%s: cannot queue req\n", __func__);
1030 		return ret;
1031 	}
1032 
1033 	return 0;
1034 }
1035 
1036 /**
1037  * dwc2_hsotg_process_req_status - process request GET_STATUS
1038  * @hsotg: The device state
1039  * @ctrl: USB control request
1040  */
1041 static int dwc2_hsotg_process_req_status(struct dwc2_hsotg *hsotg,
1042 					struct usb_ctrlrequest *ctrl)
1043 {
1044 	struct dwc2_hsotg_ep *ep0 = hsotg->eps_out[0];
1045 	struct dwc2_hsotg_ep *ep;
1046 	__le16 reply;
1047 	int ret;
1048 
1049 	dev_dbg(hsotg->dev, "%s: USB_REQ_GET_STATUS\n", __func__);
1050 
1051 	if (!ep0->dir_in) {
1052 		dev_warn(hsotg->dev, "%s: direction out?\n", __func__);
1053 		return -EINVAL;
1054 	}
1055 
1056 	switch (ctrl->bRequestType & USB_RECIP_MASK) {
1057 	case USB_RECIP_DEVICE:
1058 		reply = cpu_to_le16(0); /* bit 0 => self powered,
1059 					 * bit 1 => remote wakeup */
1060 		break;
1061 
1062 	case USB_RECIP_INTERFACE:
1063 		/* currently, the data result should be zero */
1064 		reply = cpu_to_le16(0);
1065 		break;
1066 
1067 	case USB_RECIP_ENDPOINT:
1068 		ep = ep_from_windex(hsotg, le16_to_cpu(ctrl->wIndex));
1069 		if (!ep)
1070 			return -ENOENT;
1071 
1072 		reply = cpu_to_le16(ep->halted ? 1 : 0);
1073 		break;
1074 
1075 	default:
1076 		return 0;
1077 	}
1078 
1079 	if (le16_to_cpu(ctrl->wLength) != 2)
1080 		return -EINVAL;
1081 
1082 	ret = dwc2_hsotg_send_reply(hsotg, ep0, &reply, 2);
1083 	if (ret) {
1084 		dev_err(hsotg->dev, "%s: failed to send reply\n", __func__);
1085 		return ret;
1086 	}
1087 
1088 	return 1;
1089 }
1090 
1091 static int dwc2_hsotg_ep_sethalt(struct usb_ep *ep, int value, bool now);
1092 
1093 /**
1094  * get_ep_head - return the first request on the endpoint
1095  * @hs_ep: The controller endpoint to get
1096  *
1097  * Get the first request on the endpoint.
1098  */
1099 static struct dwc2_hsotg_req *get_ep_head(struct dwc2_hsotg_ep *hs_ep)
1100 {
1101 	if (list_empty(&hs_ep->queue))
1102 		return NULL;
1103 
1104 	return list_first_entry(&hs_ep->queue, struct dwc2_hsotg_req, queue);
1105 }
1106 
1107 /**
1108  * dwc2_gadget_start_next_request - Starts next request from ep queue
1109  * @hs_ep: Endpoint structure
1110  *
1111  * If queue is empty and EP is ISOC-OUT - unmasks OUTTKNEPDIS which is masked
1112  * in its handler. Hence we need to unmask it here to be able to do
1113  * resynchronization.
1114  */
1115 static void dwc2_gadget_start_next_request(struct dwc2_hsotg_ep *hs_ep)
1116 {
1117 	u32 mask;
1118 	struct dwc2_hsotg *hsotg = hs_ep->parent;
1119 	int dir_in = hs_ep->dir_in;
1120 	struct dwc2_hsotg_req *hs_req;
1121 	u32 epmsk_reg = dir_in ? DIEPMSK : DOEPMSK;
1122 
1123 	if (!list_empty(&hs_ep->queue)) {
1124 		hs_req = get_ep_head(hs_ep);
1125 		dwc2_hsotg_start_req(hsotg, hs_ep, hs_req, false);
1126 		return;
1127 	}
1128 	if (!hs_ep->isochronous)
1129 		return;
1130 
1131 	if (dir_in) {
1132 		dev_dbg(hsotg->dev, "%s: No more ISOC-IN requests\n",
1133 			__func__);
1134 	} else {
1135 		dev_dbg(hsotg->dev, "%s: No more ISOC-OUT requests\n",
1136 			__func__);
1137 		mask = dwc2_readl(hsotg->regs + epmsk_reg);
1138 		mask |= DOEPMSK_OUTTKNEPDISMSK;
1139 		dwc2_writel(mask, hsotg->regs + epmsk_reg);
1140 	}
1141 }
1142 
1143 /**
1144  * dwc2_hsotg_process_req_feature - process request {SET,CLEAR}_FEATURE
1145  * @hsotg: The device state
1146  * @ctrl: USB control request
1147  */
1148 static int dwc2_hsotg_process_req_feature(struct dwc2_hsotg *hsotg,
1149 					 struct usb_ctrlrequest *ctrl)
1150 {
1151 	struct dwc2_hsotg_ep *ep0 = hsotg->eps_out[0];
1152 	struct dwc2_hsotg_req *hs_req;
1153 	bool set = (ctrl->bRequest == USB_REQ_SET_FEATURE);
1154 	struct dwc2_hsotg_ep *ep;
1155 	int ret;
1156 	bool halted;
1157 	u32 recip;
1158 	u32 wValue;
1159 	u32 wIndex;
1160 
1161 	dev_dbg(hsotg->dev, "%s: %s_FEATURE\n",
1162 		__func__, set ? "SET" : "CLEAR");
1163 
1164 	wValue = le16_to_cpu(ctrl->wValue);
1165 	wIndex = le16_to_cpu(ctrl->wIndex);
1166 	recip = ctrl->bRequestType & USB_RECIP_MASK;
1167 
1168 	switch (recip) {
1169 	case USB_RECIP_DEVICE:
1170 		switch (wValue) {
1171 		case USB_DEVICE_TEST_MODE:
1172 			if ((wIndex & 0xff) != 0)
1173 				return -EINVAL;
1174 			if (!set)
1175 				return -EINVAL;
1176 
1177 			hsotg->test_mode = wIndex >> 8;
1178 			ret = dwc2_hsotg_send_reply(hsotg, ep0, NULL, 0);
1179 			if (ret) {
1180 				dev_err(hsotg->dev,
1181 					"%s: failed to send reply\n", __func__);
1182 				return ret;
1183 			}
1184 			break;
1185 		default:
1186 			return -ENOENT;
1187 		}
1188 		break;
1189 
1190 	case USB_RECIP_ENDPOINT:
1191 		ep = ep_from_windex(hsotg, wIndex);
1192 		if (!ep) {
1193 			dev_dbg(hsotg->dev, "%s: no endpoint for 0x%04x\n",
1194 				__func__, wIndex);
1195 			return -ENOENT;
1196 		}
1197 
1198 		switch (wValue) {
1199 		case USB_ENDPOINT_HALT:
1200 			halted = ep->halted;
1201 
1202 			dwc2_hsotg_ep_sethalt(&ep->ep, set, true);
1203 
1204 			ret = dwc2_hsotg_send_reply(hsotg, ep0, NULL, 0);
1205 			if (ret) {
1206 				dev_err(hsotg->dev,
1207 					"%s: failed to send reply\n", __func__);
1208 				return ret;
1209 			}
1210 
1211 			/*
1212 			 * we have to complete all requests for ep if it was
1213 			 * halted, and the halt was cleared by CLEAR_FEATURE
1214 			 */
1215 
1216 			if (!set && halted) {
1217 				/*
1218 				 * If we have request in progress,
1219 				 * then complete it
1220 				 */
1221 				if (ep->req) {
1222 					hs_req = ep->req;
1223 					ep->req = NULL;
1224 					list_del_init(&hs_req->queue);
1225 					if (hs_req->req.complete) {
1226 						spin_unlock(&hsotg->lock);
1227 						usb_gadget_giveback_request(
1228 							&ep->ep, &hs_req->req);
1229 						spin_lock(&hsotg->lock);
1230 					}
1231 				}
1232 
1233 				/* If we have pending request, then start it */
1234 				if (!ep->req) {
1235 					dwc2_gadget_start_next_request(ep);
1236 				}
1237 			}
1238 
1239 			break;
1240 
1241 		default:
1242 			return -ENOENT;
1243 		}
1244 		break;
1245 	default:
1246 		return -ENOENT;
1247 	}
1248 	return 1;
1249 }
1250 
1251 static void dwc2_hsotg_enqueue_setup(struct dwc2_hsotg *hsotg);
1252 
1253 /**
1254  * dwc2_hsotg_stall_ep0 - stall ep0
1255  * @hsotg: The device state
1256  *
1257  * Set stall for ep0 as response for setup request.
1258  */
1259 static void dwc2_hsotg_stall_ep0(struct dwc2_hsotg *hsotg)
1260 {
1261 	struct dwc2_hsotg_ep *ep0 = hsotg->eps_out[0];
1262 	u32 reg;
1263 	u32 ctrl;
1264 
1265 	dev_dbg(hsotg->dev, "ep0 stall (dir=%d)\n", ep0->dir_in);
1266 	reg = (ep0->dir_in) ? DIEPCTL0 : DOEPCTL0;
1267 
1268 	/*
1269 	 * DxEPCTL_Stall will be cleared by EP once it has
1270 	 * taken effect, so no need to clear later.
1271 	 */
1272 
1273 	ctrl = dwc2_readl(hsotg->regs + reg);
1274 	ctrl |= DXEPCTL_STALL;
1275 	ctrl |= DXEPCTL_CNAK;
1276 	dwc2_writel(ctrl, hsotg->regs + reg);
1277 
1278 	dev_dbg(hsotg->dev,
1279 		"written DXEPCTL=0x%08x to %08x (DXEPCTL=0x%08x)\n",
1280 		ctrl, reg, dwc2_readl(hsotg->regs + reg));
1281 
1282 	 /*
1283 	  * complete won't be called, so we enqueue
1284 	  * setup request here
1285 	  */
1286 	 dwc2_hsotg_enqueue_setup(hsotg);
1287 }
1288 
1289 /**
1290  * dwc2_hsotg_process_control - process a control request
1291  * @hsotg: The device state
1292  * @ctrl: The control request received
1293  *
1294  * The controller has received the SETUP phase of a control request, and
1295  * needs to work out what to do next (and whether to pass it on to the
1296  * gadget driver).
1297  */
1298 static void dwc2_hsotg_process_control(struct dwc2_hsotg *hsotg,
1299 				      struct usb_ctrlrequest *ctrl)
1300 {
1301 	struct dwc2_hsotg_ep *ep0 = hsotg->eps_out[0];
1302 	int ret = 0;
1303 	u32 dcfg;
1304 
1305 	dev_dbg(hsotg->dev,
1306 		"ctrl Type=%02x, Req=%02x, V=%04x, I=%04x, L=%04x\n",
1307 		ctrl->bRequestType, ctrl->bRequest, ctrl->wValue,
1308 		ctrl->wIndex, ctrl->wLength);
1309 
1310 	if (ctrl->wLength == 0) {
1311 		ep0->dir_in = 1;
1312 		hsotg->ep0_state = DWC2_EP0_STATUS_IN;
1313 	} else if (ctrl->bRequestType & USB_DIR_IN) {
1314 		ep0->dir_in = 1;
1315 		hsotg->ep0_state = DWC2_EP0_DATA_IN;
1316 	} else {
1317 		ep0->dir_in = 0;
1318 		hsotg->ep0_state = DWC2_EP0_DATA_OUT;
1319 	}
1320 
1321 	if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) {
1322 		switch (ctrl->bRequest) {
1323 		case USB_REQ_SET_ADDRESS:
1324 			hsotg->connected = 1;
1325 			dcfg = dwc2_readl(hsotg->regs + DCFG);
1326 			dcfg &= ~DCFG_DEVADDR_MASK;
1327 			dcfg |= (le16_to_cpu(ctrl->wValue) <<
1328 				 DCFG_DEVADDR_SHIFT) & DCFG_DEVADDR_MASK;
1329 			dwc2_writel(dcfg, hsotg->regs + DCFG);
1330 
1331 			dev_info(hsotg->dev, "new address %d\n", ctrl->wValue);
1332 
1333 			ret = dwc2_hsotg_send_reply(hsotg, ep0, NULL, 0);
1334 			return;
1335 
1336 		case USB_REQ_GET_STATUS:
1337 			ret = dwc2_hsotg_process_req_status(hsotg, ctrl);
1338 			break;
1339 
1340 		case USB_REQ_CLEAR_FEATURE:
1341 		case USB_REQ_SET_FEATURE:
1342 			ret = dwc2_hsotg_process_req_feature(hsotg, ctrl);
1343 			break;
1344 		}
1345 	}
1346 
1347 	/* as a fallback, try delivering it to the driver to deal with */
1348 
1349 	if (ret == 0 && hsotg->driver) {
1350 		spin_unlock(&hsotg->lock);
1351 		ret = hsotg->driver->setup(&hsotg->gadget, ctrl);
1352 		spin_lock(&hsotg->lock);
1353 		if (ret < 0)
1354 			dev_dbg(hsotg->dev, "driver->setup() ret %d\n", ret);
1355 	}
1356 
1357 	/*
1358 	 * the request is either unhandlable, or is not formatted correctly
1359 	 * so respond with a STALL for the status stage to indicate failure.
1360 	 */
1361 
1362 	if (ret < 0)
1363 		dwc2_hsotg_stall_ep0(hsotg);
1364 }
1365 
1366 /**
1367  * dwc2_hsotg_complete_setup - completion of a setup transfer
1368  * @ep: The endpoint the request was on.
1369  * @req: The request completed.
1370  *
1371  * Called on completion of any requests the driver itself submitted for
1372  * EP0 setup packets
1373  */
1374 static void dwc2_hsotg_complete_setup(struct usb_ep *ep,
1375 				     struct usb_request *req)
1376 {
1377 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
1378 	struct dwc2_hsotg *hsotg = hs_ep->parent;
1379 
1380 	if (req->status < 0) {
1381 		dev_dbg(hsotg->dev, "%s: failed %d\n", __func__, req->status);
1382 		return;
1383 	}
1384 
1385 	spin_lock(&hsotg->lock);
1386 	if (req->actual == 0)
1387 		dwc2_hsotg_enqueue_setup(hsotg);
1388 	else
1389 		dwc2_hsotg_process_control(hsotg, req->buf);
1390 	spin_unlock(&hsotg->lock);
1391 }
1392 
1393 /**
1394  * dwc2_hsotg_enqueue_setup - start a request for EP0 packets
1395  * @hsotg: The device state.
1396  *
1397  * Enqueue a request on EP0 if necessary to received any SETUP packets
1398  * received from the host.
1399  */
1400 static void dwc2_hsotg_enqueue_setup(struct dwc2_hsotg *hsotg)
1401 {
1402 	struct usb_request *req = hsotg->ctrl_req;
1403 	struct dwc2_hsotg_req *hs_req = our_req(req);
1404 	int ret;
1405 
1406 	dev_dbg(hsotg->dev, "%s: queueing setup request\n", __func__);
1407 
1408 	req->zero = 0;
1409 	req->length = 8;
1410 	req->buf = hsotg->ctrl_buff;
1411 	req->complete = dwc2_hsotg_complete_setup;
1412 
1413 	if (!list_empty(&hs_req->queue)) {
1414 		dev_dbg(hsotg->dev, "%s already queued???\n", __func__);
1415 		return;
1416 	}
1417 
1418 	hsotg->eps_out[0]->dir_in = 0;
1419 	hsotg->eps_out[0]->send_zlp = 0;
1420 	hsotg->ep0_state = DWC2_EP0_SETUP;
1421 
1422 	ret = dwc2_hsotg_ep_queue(&hsotg->eps_out[0]->ep, req, GFP_ATOMIC);
1423 	if (ret < 0) {
1424 		dev_err(hsotg->dev, "%s: failed queue (%d)\n", __func__, ret);
1425 		/*
1426 		 * Don't think there's much we can do other than watch the
1427 		 * driver fail.
1428 		 */
1429 	}
1430 }
1431 
1432 static void dwc2_hsotg_program_zlp(struct dwc2_hsotg *hsotg,
1433 					struct dwc2_hsotg_ep *hs_ep)
1434 {
1435 	u32 ctrl;
1436 	u8 index = hs_ep->index;
1437 	u32 epctl_reg = hs_ep->dir_in ? DIEPCTL(index) : DOEPCTL(index);
1438 	u32 epsiz_reg = hs_ep->dir_in ? DIEPTSIZ(index) : DOEPTSIZ(index);
1439 
1440 	if (hs_ep->dir_in)
1441 		dev_dbg(hsotg->dev, "Sending zero-length packet on ep%d\n",
1442 									index);
1443 	else
1444 		dev_dbg(hsotg->dev, "Receiving zero-length packet on ep%d\n",
1445 									index);
1446 
1447 	dwc2_writel(DXEPTSIZ_MC(1) | DXEPTSIZ_PKTCNT(1) |
1448 		    DXEPTSIZ_XFERSIZE(0), hsotg->regs +
1449 		    epsiz_reg);
1450 
1451 	ctrl = dwc2_readl(hsotg->regs + epctl_reg);
1452 	ctrl |= DXEPCTL_CNAK;  /* clear NAK set by core */
1453 	ctrl |= DXEPCTL_EPENA; /* ensure ep enabled */
1454 	ctrl |= DXEPCTL_USBACTEP;
1455 	dwc2_writel(ctrl, hsotg->regs + epctl_reg);
1456 }
1457 
1458 /**
1459  * dwc2_hsotg_complete_request - complete a request given to us
1460  * @hsotg: The device state.
1461  * @hs_ep: The endpoint the request was on.
1462  * @hs_req: The request to complete.
1463  * @result: The result code (0 => Ok, otherwise errno)
1464  *
1465  * The given request has finished, so call the necessary completion
1466  * if it has one and then look to see if we can start a new request
1467  * on the endpoint.
1468  *
1469  * Note, expects the ep to already be locked as appropriate.
1470  */
1471 static void dwc2_hsotg_complete_request(struct dwc2_hsotg *hsotg,
1472 				       struct dwc2_hsotg_ep *hs_ep,
1473 				       struct dwc2_hsotg_req *hs_req,
1474 				       int result)
1475 {
1476 
1477 	if (!hs_req) {
1478 		dev_dbg(hsotg->dev, "%s: nothing to complete?\n", __func__);
1479 		return;
1480 	}
1481 
1482 	dev_dbg(hsotg->dev, "complete: ep %p %s, req %p, %d => %p\n",
1483 		hs_ep, hs_ep->ep.name, hs_req, result, hs_req->req.complete);
1484 
1485 	/*
1486 	 * only replace the status if we've not already set an error
1487 	 * from a previous transaction
1488 	 */
1489 
1490 	if (hs_req->req.status == -EINPROGRESS)
1491 		hs_req->req.status = result;
1492 
1493 	if (using_dma(hsotg))
1494 		dwc2_hsotg_unmap_dma(hsotg, hs_ep, hs_req);
1495 
1496 	dwc2_hsotg_handle_unaligned_buf_complete(hsotg, hs_ep, hs_req);
1497 
1498 	hs_ep->req = NULL;
1499 	list_del_init(&hs_req->queue);
1500 
1501 	/*
1502 	 * call the complete request with the locks off, just in case the
1503 	 * request tries to queue more work for this endpoint.
1504 	 */
1505 
1506 	if (hs_req->req.complete) {
1507 		spin_unlock(&hsotg->lock);
1508 		usb_gadget_giveback_request(&hs_ep->ep, &hs_req->req);
1509 		spin_lock(&hsotg->lock);
1510 	}
1511 
1512 	/*
1513 	 * Look to see if there is anything else to do. Note, the completion
1514 	 * of the previous request may have caused a new request to be started
1515 	 * so be careful when doing this.
1516 	 */
1517 
1518 	if (!hs_ep->req && result >= 0) {
1519 		dwc2_gadget_start_next_request(hs_ep);
1520 	}
1521 }
1522 
1523 /**
1524  * dwc2_hsotg_rx_data - receive data from the FIFO for an endpoint
1525  * @hsotg: The device state.
1526  * @ep_idx: The endpoint index for the data
1527  * @size: The size of data in the fifo, in bytes
1528  *
1529  * The FIFO status shows there is data to read from the FIFO for a given
1530  * endpoint, so sort out whether we need to read the data into a request
1531  * that has been made for that endpoint.
1532  */
1533 static void dwc2_hsotg_rx_data(struct dwc2_hsotg *hsotg, int ep_idx, int size)
1534 {
1535 	struct dwc2_hsotg_ep *hs_ep = hsotg->eps_out[ep_idx];
1536 	struct dwc2_hsotg_req *hs_req = hs_ep->req;
1537 	void __iomem *fifo = hsotg->regs + EPFIFO(ep_idx);
1538 	int to_read;
1539 	int max_req;
1540 	int read_ptr;
1541 
1542 
1543 	if (!hs_req) {
1544 		u32 epctl = dwc2_readl(hsotg->regs + DOEPCTL(ep_idx));
1545 		int ptr;
1546 
1547 		dev_dbg(hsotg->dev,
1548 			 "%s: FIFO %d bytes on ep%d but no req (DXEPCTl=0x%08x)\n",
1549 			 __func__, size, ep_idx, epctl);
1550 
1551 		/* dump the data from the FIFO, we've nothing we can do */
1552 		for (ptr = 0; ptr < size; ptr += 4)
1553 			(void)dwc2_readl(fifo);
1554 
1555 		return;
1556 	}
1557 
1558 	to_read = size;
1559 	read_ptr = hs_req->req.actual;
1560 	max_req = hs_req->req.length - read_ptr;
1561 
1562 	dev_dbg(hsotg->dev, "%s: read %d/%d, done %d/%d\n",
1563 		__func__, to_read, max_req, read_ptr, hs_req->req.length);
1564 
1565 	if (to_read > max_req) {
1566 		/*
1567 		 * more data appeared than we where willing
1568 		 * to deal with in this request.
1569 		 */
1570 
1571 		/* currently we don't deal this */
1572 		WARN_ON_ONCE(1);
1573 	}
1574 
1575 	hs_ep->total_data += to_read;
1576 	hs_req->req.actual += to_read;
1577 	to_read = DIV_ROUND_UP(to_read, 4);
1578 
1579 	/*
1580 	 * note, we might over-write the buffer end by 3 bytes depending on
1581 	 * alignment of the data.
1582 	 */
1583 	ioread32_rep(fifo, hs_req->req.buf + read_ptr, to_read);
1584 }
1585 
1586 /**
1587  * dwc2_hsotg_ep0_zlp - send/receive zero-length packet on control endpoint
1588  * @hsotg: The device instance
1589  * @dir_in: If IN zlp
1590  *
1591  * Generate a zero-length IN packet request for terminating a SETUP
1592  * transaction.
1593  *
1594  * Note, since we don't write any data to the TxFIFO, then it is
1595  * currently believed that we do not need to wait for any space in
1596  * the TxFIFO.
1597  */
1598 static void dwc2_hsotg_ep0_zlp(struct dwc2_hsotg *hsotg, bool dir_in)
1599 {
1600 	/* eps_out[0] is used in both directions */
1601 	hsotg->eps_out[0]->dir_in = dir_in;
1602 	hsotg->ep0_state = dir_in ? DWC2_EP0_STATUS_IN : DWC2_EP0_STATUS_OUT;
1603 
1604 	dwc2_hsotg_program_zlp(hsotg, hsotg->eps_out[0]);
1605 }
1606 
1607 static void dwc2_hsotg_change_ep_iso_parity(struct dwc2_hsotg *hsotg,
1608 			u32 epctl_reg)
1609 {
1610 	u32 ctrl;
1611 
1612 	ctrl = dwc2_readl(hsotg->regs + epctl_reg);
1613 	if (ctrl & DXEPCTL_EOFRNUM)
1614 		ctrl |= DXEPCTL_SETEVENFR;
1615 	else
1616 		ctrl |= DXEPCTL_SETODDFR;
1617 	dwc2_writel(ctrl, hsotg->regs + epctl_reg);
1618 }
1619 
1620 /**
1621  * dwc2_hsotg_handle_outdone - handle receiving OutDone/SetupDone from RXFIFO
1622  * @hsotg: The device instance
1623  * @epnum: The endpoint received from
1624  *
1625  * The RXFIFO has delivered an OutDone event, which means that the data
1626  * transfer for an OUT endpoint has been completed, either by a short
1627  * packet or by the finish of a transfer.
1628  */
1629 static void dwc2_hsotg_handle_outdone(struct dwc2_hsotg *hsotg, int epnum)
1630 {
1631 	u32 epsize = dwc2_readl(hsotg->regs + DOEPTSIZ(epnum));
1632 	struct dwc2_hsotg_ep *hs_ep = hsotg->eps_out[epnum];
1633 	struct dwc2_hsotg_req *hs_req = hs_ep->req;
1634 	struct usb_request *req = &hs_req->req;
1635 	unsigned size_left = DXEPTSIZ_XFERSIZE_GET(epsize);
1636 	int result = 0;
1637 
1638 	if (!hs_req) {
1639 		dev_dbg(hsotg->dev, "%s: no request active\n", __func__);
1640 		return;
1641 	}
1642 
1643 	if (epnum == 0 && hsotg->ep0_state == DWC2_EP0_STATUS_OUT) {
1644 		dev_dbg(hsotg->dev, "zlp packet received\n");
1645 		dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, 0);
1646 		dwc2_hsotg_enqueue_setup(hsotg);
1647 		return;
1648 	}
1649 
1650 	if (using_dma(hsotg)) {
1651 		unsigned size_done;
1652 
1653 		/*
1654 		 * Calculate the size of the transfer by checking how much
1655 		 * is left in the endpoint size register and then working it
1656 		 * out from the amount we loaded for the transfer.
1657 		 *
1658 		 * We need to do this as DMA pointers are always 32bit aligned
1659 		 * so may overshoot/undershoot the transfer.
1660 		 */
1661 
1662 		size_done = hs_ep->size_loaded - size_left;
1663 		size_done += hs_ep->last_load;
1664 
1665 		req->actual = size_done;
1666 	}
1667 
1668 	/* if there is more request to do, schedule new transfer */
1669 	if (req->actual < req->length && size_left == 0) {
1670 		dwc2_hsotg_start_req(hsotg, hs_ep, hs_req, true);
1671 		return;
1672 	}
1673 
1674 	if (req->actual < req->length && req->short_not_ok) {
1675 		dev_dbg(hsotg->dev, "%s: got %d/%d (short not ok) => error\n",
1676 			__func__, req->actual, req->length);
1677 
1678 		/*
1679 		 * todo - what should we return here? there's no one else
1680 		 * even bothering to check the status.
1681 		 */
1682 	}
1683 
1684 	if (epnum == 0 && hsotg->ep0_state == DWC2_EP0_DATA_OUT) {
1685 		/* Move to STATUS IN */
1686 		dwc2_hsotg_ep0_zlp(hsotg, true);
1687 		return;
1688 	}
1689 
1690 	/*
1691 	 * Slave mode OUT transfers do not go through XferComplete so
1692 	 * adjust the ISOC parity here.
1693 	 */
1694 	if (!using_dma(hsotg)) {
1695 		if (hs_ep->isochronous && hs_ep->interval == 1)
1696 			dwc2_hsotg_change_ep_iso_parity(hsotg, DOEPCTL(epnum));
1697 		else if (hs_ep->isochronous && hs_ep->interval > 1)
1698 			dwc2_gadget_incr_frame_num(hs_ep);
1699 	}
1700 
1701 	dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, result);
1702 }
1703 
1704 /**
1705  * dwc2_hsotg_handle_rx - RX FIFO has data
1706  * @hsotg: The device instance
1707  *
1708  * The IRQ handler has detected that the RX FIFO has some data in it
1709  * that requires processing, so find out what is in there and do the
1710  * appropriate read.
1711  *
1712  * The RXFIFO is a true FIFO, the packets coming out are still in packet
1713  * chunks, so if you have x packets received on an endpoint you'll get x
1714  * FIFO events delivered, each with a packet's worth of data in it.
1715  *
1716  * When using DMA, we should not be processing events from the RXFIFO
1717  * as the actual data should be sent to the memory directly and we turn
1718  * on the completion interrupts to get notifications of transfer completion.
1719  */
1720 static void dwc2_hsotg_handle_rx(struct dwc2_hsotg *hsotg)
1721 {
1722 	u32 grxstsr = dwc2_readl(hsotg->regs + GRXSTSP);
1723 	u32 epnum, status, size;
1724 
1725 	WARN_ON(using_dma(hsotg));
1726 
1727 	epnum = grxstsr & GRXSTS_EPNUM_MASK;
1728 	status = grxstsr & GRXSTS_PKTSTS_MASK;
1729 
1730 	size = grxstsr & GRXSTS_BYTECNT_MASK;
1731 	size >>= GRXSTS_BYTECNT_SHIFT;
1732 
1733 	dev_dbg(hsotg->dev, "%s: GRXSTSP=0x%08x (%d@%d)\n",
1734 			__func__, grxstsr, size, epnum);
1735 
1736 	switch ((status & GRXSTS_PKTSTS_MASK) >> GRXSTS_PKTSTS_SHIFT) {
1737 	case GRXSTS_PKTSTS_GLOBALOUTNAK:
1738 		dev_dbg(hsotg->dev, "GLOBALOUTNAK\n");
1739 		break;
1740 
1741 	case GRXSTS_PKTSTS_OUTDONE:
1742 		dev_dbg(hsotg->dev, "OutDone (Frame=0x%08x)\n",
1743 			dwc2_hsotg_read_frameno(hsotg));
1744 
1745 		if (!using_dma(hsotg))
1746 			dwc2_hsotg_handle_outdone(hsotg, epnum);
1747 		break;
1748 
1749 	case GRXSTS_PKTSTS_SETUPDONE:
1750 		dev_dbg(hsotg->dev,
1751 			"SetupDone (Frame=0x%08x, DOPEPCTL=0x%08x)\n",
1752 			dwc2_hsotg_read_frameno(hsotg),
1753 			dwc2_readl(hsotg->regs + DOEPCTL(0)));
1754 		/*
1755 		 * Call dwc2_hsotg_handle_outdone here if it was not called from
1756 		 * GRXSTS_PKTSTS_OUTDONE. That is, if the core didn't
1757 		 * generate GRXSTS_PKTSTS_OUTDONE for setup packet.
1758 		 */
1759 		if (hsotg->ep0_state == DWC2_EP0_SETUP)
1760 			dwc2_hsotg_handle_outdone(hsotg, epnum);
1761 		break;
1762 
1763 	case GRXSTS_PKTSTS_OUTRX:
1764 		dwc2_hsotg_rx_data(hsotg, epnum, size);
1765 		break;
1766 
1767 	case GRXSTS_PKTSTS_SETUPRX:
1768 		dev_dbg(hsotg->dev,
1769 			"SetupRX (Frame=0x%08x, DOPEPCTL=0x%08x)\n",
1770 			dwc2_hsotg_read_frameno(hsotg),
1771 			dwc2_readl(hsotg->regs + DOEPCTL(0)));
1772 
1773 		WARN_ON(hsotg->ep0_state != DWC2_EP0_SETUP);
1774 
1775 		dwc2_hsotg_rx_data(hsotg, epnum, size);
1776 		break;
1777 
1778 	default:
1779 		dev_warn(hsotg->dev, "%s: unknown status %08x\n",
1780 			 __func__, grxstsr);
1781 
1782 		dwc2_hsotg_dump(hsotg);
1783 		break;
1784 	}
1785 }
1786 
1787 /**
1788  * dwc2_hsotg_ep0_mps - turn max packet size into register setting
1789  * @mps: The maximum packet size in bytes.
1790  */
1791 static u32 dwc2_hsotg_ep0_mps(unsigned int mps)
1792 {
1793 	switch (mps) {
1794 	case 64:
1795 		return D0EPCTL_MPS_64;
1796 	case 32:
1797 		return D0EPCTL_MPS_32;
1798 	case 16:
1799 		return D0EPCTL_MPS_16;
1800 	case 8:
1801 		return D0EPCTL_MPS_8;
1802 	}
1803 
1804 	/* bad max packet size, warn and return invalid result */
1805 	WARN_ON(1);
1806 	return (u32)-1;
1807 }
1808 
1809 /**
1810  * dwc2_hsotg_set_ep_maxpacket - set endpoint's max-packet field
1811  * @hsotg: The driver state.
1812  * @ep: The index number of the endpoint
1813  * @mps: The maximum packet size in bytes
1814  *
1815  * Configure the maximum packet size for the given endpoint, updating
1816  * the hardware control registers to reflect this.
1817  */
1818 static void dwc2_hsotg_set_ep_maxpacket(struct dwc2_hsotg *hsotg,
1819 			unsigned int ep, unsigned int mps, unsigned int dir_in)
1820 {
1821 	struct dwc2_hsotg_ep *hs_ep;
1822 	void __iomem *regs = hsotg->regs;
1823 	u32 mpsval;
1824 	u32 mcval;
1825 	u32 reg;
1826 
1827 	hs_ep = index_to_ep(hsotg, ep, dir_in);
1828 	if (!hs_ep)
1829 		return;
1830 
1831 	if (ep == 0) {
1832 		/* EP0 is a special case */
1833 		mpsval = dwc2_hsotg_ep0_mps(mps);
1834 		if (mpsval > 3)
1835 			goto bad_mps;
1836 		hs_ep->ep.maxpacket = mps;
1837 		hs_ep->mc = 1;
1838 	} else {
1839 		mpsval = mps & DXEPCTL_MPS_MASK;
1840 		if (mpsval > 1024)
1841 			goto bad_mps;
1842 		mcval = ((mps >> 11) & 0x3) + 1;
1843 		hs_ep->mc = mcval;
1844 		if (mcval > 3)
1845 			goto bad_mps;
1846 		hs_ep->ep.maxpacket = mpsval;
1847 	}
1848 
1849 	if (dir_in) {
1850 		reg = dwc2_readl(regs + DIEPCTL(ep));
1851 		reg &= ~DXEPCTL_MPS_MASK;
1852 		reg |= mpsval;
1853 		dwc2_writel(reg, regs + DIEPCTL(ep));
1854 	} else {
1855 		reg = dwc2_readl(regs + DOEPCTL(ep));
1856 		reg &= ~DXEPCTL_MPS_MASK;
1857 		reg |= mpsval;
1858 		dwc2_writel(reg, regs + DOEPCTL(ep));
1859 	}
1860 
1861 	return;
1862 
1863 bad_mps:
1864 	dev_err(hsotg->dev, "ep%d: bad mps of %d\n", ep, mps);
1865 }
1866 
1867 /**
1868  * dwc2_hsotg_txfifo_flush - flush Tx FIFO
1869  * @hsotg: The driver state
1870  * @idx: The index for the endpoint (0..15)
1871  */
1872 static void dwc2_hsotg_txfifo_flush(struct dwc2_hsotg *hsotg, unsigned int idx)
1873 {
1874 	int timeout;
1875 	int val;
1876 
1877 	dwc2_writel(GRSTCTL_TXFNUM(idx) | GRSTCTL_TXFFLSH,
1878 		    hsotg->regs + GRSTCTL);
1879 
1880 	/* wait until the fifo is flushed */
1881 	timeout = 100;
1882 
1883 	while (1) {
1884 		val = dwc2_readl(hsotg->regs + GRSTCTL);
1885 
1886 		if ((val & (GRSTCTL_TXFFLSH)) == 0)
1887 			break;
1888 
1889 		if (--timeout == 0) {
1890 			dev_err(hsotg->dev,
1891 				"%s: timeout flushing fifo (GRSTCTL=%08x)\n",
1892 				__func__, val);
1893 			break;
1894 		}
1895 
1896 		udelay(1);
1897 	}
1898 }
1899 
1900 /**
1901  * dwc2_hsotg_trytx - check to see if anything needs transmitting
1902  * @hsotg: The driver state
1903  * @hs_ep: The driver endpoint to check.
1904  *
1905  * Check to see if there is a request that has data to send, and if so
1906  * make an attempt to write data into the FIFO.
1907  */
1908 static int dwc2_hsotg_trytx(struct dwc2_hsotg *hsotg,
1909 			   struct dwc2_hsotg_ep *hs_ep)
1910 {
1911 	struct dwc2_hsotg_req *hs_req = hs_ep->req;
1912 
1913 	if (!hs_ep->dir_in || !hs_req) {
1914 		/**
1915 		 * if request is not enqueued, we disable interrupts
1916 		 * for endpoints, excepting ep0
1917 		 */
1918 		if (hs_ep->index != 0)
1919 			dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index,
1920 					     hs_ep->dir_in, 0);
1921 		return 0;
1922 	}
1923 
1924 	if (hs_req->req.actual < hs_req->req.length) {
1925 		dev_dbg(hsotg->dev, "trying to write more for ep%d\n",
1926 			hs_ep->index);
1927 		return dwc2_hsotg_write_fifo(hsotg, hs_ep, hs_req);
1928 	}
1929 
1930 	return 0;
1931 }
1932 
1933 /**
1934  * dwc2_hsotg_complete_in - complete IN transfer
1935  * @hsotg: The device state.
1936  * @hs_ep: The endpoint that has just completed.
1937  *
1938  * An IN transfer has been completed, update the transfer's state and then
1939  * call the relevant completion routines.
1940  */
1941 static void dwc2_hsotg_complete_in(struct dwc2_hsotg *hsotg,
1942 				  struct dwc2_hsotg_ep *hs_ep)
1943 {
1944 	struct dwc2_hsotg_req *hs_req = hs_ep->req;
1945 	u32 epsize = dwc2_readl(hsotg->regs + DIEPTSIZ(hs_ep->index));
1946 	int size_left, size_done;
1947 
1948 	if (!hs_req) {
1949 		dev_dbg(hsotg->dev, "XferCompl but no req\n");
1950 		return;
1951 	}
1952 
1953 	/* Finish ZLP handling for IN EP0 transactions */
1954 	if (hs_ep->index == 0 && hsotg->ep0_state == DWC2_EP0_STATUS_IN) {
1955 		dev_dbg(hsotg->dev, "zlp packet sent\n");
1956 		dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, 0);
1957 		if (hsotg->test_mode) {
1958 			int ret;
1959 
1960 			ret = dwc2_hsotg_set_test_mode(hsotg, hsotg->test_mode);
1961 			if (ret < 0) {
1962 				dev_dbg(hsotg->dev, "Invalid Test #%d\n",
1963 						hsotg->test_mode);
1964 				dwc2_hsotg_stall_ep0(hsotg);
1965 				return;
1966 			}
1967 		}
1968 		dwc2_hsotg_enqueue_setup(hsotg);
1969 		return;
1970 	}
1971 
1972 	/*
1973 	 * Calculate the size of the transfer by checking how much is left
1974 	 * in the endpoint size register and then working it out from
1975 	 * the amount we loaded for the transfer.
1976 	 *
1977 	 * We do this even for DMA, as the transfer may have incremented
1978 	 * past the end of the buffer (DMA transfers are always 32bit
1979 	 * aligned).
1980 	 */
1981 
1982 	size_left = DXEPTSIZ_XFERSIZE_GET(epsize);
1983 
1984 	size_done = hs_ep->size_loaded - size_left;
1985 	size_done += hs_ep->last_load;
1986 
1987 	if (hs_req->req.actual != size_done)
1988 		dev_dbg(hsotg->dev, "%s: adjusting size done %d => %d\n",
1989 			__func__, hs_req->req.actual, size_done);
1990 
1991 	hs_req->req.actual = size_done;
1992 	dev_dbg(hsotg->dev, "req->length:%d req->actual:%d req->zero:%d\n",
1993 		hs_req->req.length, hs_req->req.actual, hs_req->req.zero);
1994 
1995 	if (!size_left && hs_req->req.actual < hs_req->req.length) {
1996 		dev_dbg(hsotg->dev, "%s trying more for req...\n", __func__);
1997 		dwc2_hsotg_start_req(hsotg, hs_ep, hs_req, true);
1998 		return;
1999 	}
2000 
2001 	/* Zlp for all endpoints, for ep0 only in DATA IN stage */
2002 	if (hs_ep->send_zlp) {
2003 		dwc2_hsotg_program_zlp(hsotg, hs_ep);
2004 		hs_ep->send_zlp = 0;
2005 		/* transfer will be completed on next complete interrupt */
2006 		return;
2007 	}
2008 
2009 	if (hs_ep->index == 0 && hsotg->ep0_state == DWC2_EP0_DATA_IN) {
2010 		/* Move to STATUS OUT */
2011 		dwc2_hsotg_ep0_zlp(hsotg, false);
2012 		return;
2013 	}
2014 
2015 	dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, 0);
2016 }
2017 
2018 /**
2019  * dwc2_gadget_read_ep_interrupts - reads interrupts for given ep
2020  * @hsotg: The device state.
2021  * @idx: Index of ep.
2022  * @dir_in: Endpoint direction 1-in 0-out.
2023  *
2024  * Reads for endpoint with given index and direction, by masking
2025  * epint_reg with coresponding mask.
2026  */
2027 static u32 dwc2_gadget_read_ep_interrupts(struct dwc2_hsotg *hsotg,
2028 					  unsigned int idx, int dir_in)
2029 {
2030 	u32 epmsk_reg = dir_in ? DIEPMSK : DOEPMSK;
2031 	u32 epint_reg = dir_in ? DIEPINT(idx) : DOEPINT(idx);
2032 	u32 ints;
2033 	u32 mask;
2034 	u32 diepempmsk;
2035 
2036 	mask = dwc2_readl(hsotg->regs + epmsk_reg);
2037 	diepempmsk = dwc2_readl(hsotg->regs + DIEPEMPMSK);
2038 	mask |= ((diepempmsk >> idx) & 0x1) ? DIEPMSK_TXFIFOEMPTY : 0;
2039 	mask |= DXEPINT_SETUP_RCVD;
2040 
2041 	ints = dwc2_readl(hsotg->regs + epint_reg);
2042 	ints &= mask;
2043 	return ints;
2044 }
2045 
2046 /**
2047  * dwc2_gadget_handle_ep_disabled - handle DXEPINT_EPDISBLD
2048  * @hs_ep: The endpoint on which interrupt is asserted.
2049  *
2050  * This interrupt indicates that the endpoint has been disabled per the
2051  * application's request.
2052  *
2053  * For IN endpoints flushes txfifo, in case of BULK clears DCTL_CGNPINNAK,
2054  * in case of ISOC completes current request.
2055  *
2056  * For ISOC-OUT endpoints completes expired requests. If there is remaining
2057  * request starts it.
2058  */
2059 static void dwc2_gadget_handle_ep_disabled(struct dwc2_hsotg_ep *hs_ep)
2060 {
2061 	struct dwc2_hsotg *hsotg = hs_ep->parent;
2062 	struct dwc2_hsotg_req *hs_req;
2063 	unsigned char idx = hs_ep->index;
2064 	int dir_in = hs_ep->dir_in;
2065 	u32 epctl_reg = dir_in ? DIEPCTL(idx) : DOEPCTL(idx);
2066 	int dctl = dwc2_readl(hsotg->regs + DCTL);
2067 
2068 	dev_dbg(hsotg->dev, "%s: EPDisbld\n", __func__);
2069 
2070 	if (dir_in) {
2071 		int epctl = dwc2_readl(hsotg->regs + epctl_reg);
2072 
2073 		dwc2_hsotg_txfifo_flush(hsotg, hs_ep->fifo_index);
2074 
2075 		if (hs_ep->isochronous) {
2076 			dwc2_hsotg_complete_in(hsotg, hs_ep);
2077 			return;
2078 		}
2079 
2080 		if ((epctl & DXEPCTL_STALL) && (epctl & DXEPCTL_EPTYPE_BULK)) {
2081 			int dctl = dwc2_readl(hsotg->regs + DCTL);
2082 
2083 			dctl |= DCTL_CGNPINNAK;
2084 			dwc2_writel(dctl, hsotg->regs + DCTL);
2085 		}
2086 		return;
2087 	}
2088 
2089 	if (dctl & DCTL_GOUTNAKSTS) {
2090 		dctl |= DCTL_CGOUTNAK;
2091 		dwc2_writel(dctl, hsotg->regs + DCTL);
2092 	}
2093 
2094 	if (!hs_ep->isochronous)
2095 		return;
2096 
2097 	if (list_empty(&hs_ep->queue)) {
2098 		dev_dbg(hsotg->dev, "%s: complete_ep 0x%p, ep->queue empty!\n",
2099 			__func__, hs_ep);
2100 		return;
2101 	}
2102 
2103 	do {
2104 		hs_req = get_ep_head(hs_ep);
2105 		if (hs_req)
2106 			dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req,
2107 						    -ENODATA);
2108 		dwc2_gadget_incr_frame_num(hs_ep);
2109 	} while (dwc2_gadget_target_frame_elapsed(hs_ep));
2110 
2111 	dwc2_gadget_start_next_request(hs_ep);
2112 }
2113 
2114 /**
2115  * dwc2_gadget_handle_out_token_ep_disabled - handle DXEPINT_OUTTKNEPDIS
2116  * @hs_ep: The endpoint on which interrupt is asserted.
2117  *
2118  * This is starting point for ISOC-OUT transfer, synchronization done with
2119  * first out token received from host while corresponding EP is disabled.
2120  *
2121  * Device does not know initial frame in which out token will come. For this
2122  * HW generates OUTTKNEPDIS - out token is received while EP is disabled. Upon
2123  * getting this interrupt SW starts calculation for next transfer frame.
2124  */
2125 static void dwc2_gadget_handle_out_token_ep_disabled(struct dwc2_hsotg_ep *ep)
2126 {
2127 	struct dwc2_hsotg *hsotg = ep->parent;
2128 	int dir_in = ep->dir_in;
2129 	u32 doepmsk;
2130 
2131 	if (dir_in || !ep->isochronous)
2132 		return;
2133 
2134 	dwc2_hsotg_complete_request(hsotg, ep, get_ep_head(ep), -ENODATA);
2135 
2136 	if (ep->interval > 1 &&
2137 	    ep->target_frame == TARGET_FRAME_INITIAL) {
2138 		u32 dsts;
2139 		u32 ctrl;
2140 
2141 		dsts = dwc2_readl(hsotg->regs + DSTS);
2142 		ep->target_frame = dwc2_hsotg_read_frameno(hsotg);
2143 		dwc2_gadget_incr_frame_num(ep);
2144 
2145 		ctrl = dwc2_readl(hsotg->regs + DOEPCTL(ep->index));
2146 		if (ep->target_frame & 0x1)
2147 			ctrl |= DXEPCTL_SETODDFR;
2148 		else
2149 			ctrl |= DXEPCTL_SETEVENFR;
2150 
2151 		dwc2_writel(ctrl, hsotg->regs + DOEPCTL(ep->index));
2152 	}
2153 
2154 	dwc2_gadget_start_next_request(ep);
2155 	doepmsk = dwc2_readl(hsotg->regs + DOEPMSK);
2156 	doepmsk &= ~DOEPMSK_OUTTKNEPDISMSK;
2157 	dwc2_writel(doepmsk, hsotg->regs + DOEPMSK);
2158 }
2159 
2160 /**
2161 * dwc2_gadget_handle_nak - handle NAK interrupt
2162 * @hs_ep: The endpoint on which interrupt is asserted.
2163 *
2164 * This is starting point for ISOC-IN transfer, synchronization done with
2165 * first IN token received from host while corresponding EP is disabled.
2166 *
2167 * Device does not know when first one token will arrive from host. On first
2168 * token arrival HW generates 2 interrupts: 'in token received while FIFO empty'
2169 * and 'NAK'. NAK interrupt for ISOC-IN means that token has arrived and ZLP was
2170 * sent in response to that as there was no data in FIFO. SW is basing on this
2171 * interrupt to obtain frame in which token has come and then based on the
2172 * interval calculates next frame for transfer.
2173 */
2174 static void dwc2_gadget_handle_nak(struct dwc2_hsotg_ep *hs_ep)
2175 {
2176 	struct dwc2_hsotg *hsotg = hs_ep->parent;
2177 	int dir_in = hs_ep->dir_in;
2178 
2179 	if (!dir_in || !hs_ep->isochronous)
2180 		return;
2181 
2182 	if (hs_ep->target_frame == TARGET_FRAME_INITIAL) {
2183 		hs_ep->target_frame = dwc2_hsotg_read_frameno(hsotg);
2184 		if (hs_ep->interval > 1) {
2185 			u32 ctrl = dwc2_readl(hsotg->regs +
2186 					      DIEPCTL(hs_ep->index));
2187 			if (hs_ep->target_frame & 0x1)
2188 				ctrl |= DXEPCTL_SETODDFR;
2189 			else
2190 				ctrl |= DXEPCTL_SETEVENFR;
2191 
2192 			dwc2_writel(ctrl, hsotg->regs + DIEPCTL(hs_ep->index));
2193 		}
2194 
2195 		dwc2_hsotg_complete_request(hsotg, hs_ep,
2196 					    get_ep_head(hs_ep), 0);
2197 	}
2198 
2199 	dwc2_gadget_incr_frame_num(hs_ep);
2200 }
2201 
2202 /**
2203  * dwc2_hsotg_epint - handle an in/out endpoint interrupt
2204  * @hsotg: The driver state
2205  * @idx: The index for the endpoint (0..15)
2206  * @dir_in: Set if this is an IN endpoint
2207  *
2208  * Process and clear any interrupt pending for an individual endpoint
2209  */
2210 static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx,
2211 			    int dir_in)
2212 {
2213 	struct dwc2_hsotg_ep *hs_ep = index_to_ep(hsotg, idx, dir_in);
2214 	u32 epint_reg = dir_in ? DIEPINT(idx) : DOEPINT(idx);
2215 	u32 epctl_reg = dir_in ? DIEPCTL(idx) : DOEPCTL(idx);
2216 	u32 epsiz_reg = dir_in ? DIEPTSIZ(idx) : DOEPTSIZ(idx);
2217 	u32 ints;
2218 	u32 ctrl;
2219 
2220 	ints = dwc2_gadget_read_ep_interrupts(hsotg, idx, dir_in);
2221 	ctrl = dwc2_readl(hsotg->regs + epctl_reg);
2222 
2223 	/* Clear endpoint interrupts */
2224 	dwc2_writel(ints, hsotg->regs + epint_reg);
2225 
2226 	if (!hs_ep) {
2227 		dev_err(hsotg->dev, "%s:Interrupt for unconfigured ep%d(%s)\n",
2228 					__func__, idx, dir_in ? "in" : "out");
2229 		return;
2230 	}
2231 
2232 	dev_dbg(hsotg->dev, "%s: ep%d(%s) DxEPINT=0x%08x\n",
2233 		__func__, idx, dir_in ? "in" : "out", ints);
2234 
2235 	/* Don't process XferCompl interrupt if it is a setup packet */
2236 	if (idx == 0 && (ints & (DXEPINT_SETUP | DXEPINT_SETUP_RCVD)))
2237 		ints &= ~DXEPINT_XFERCOMPL;
2238 
2239 	if (ints & DXEPINT_STSPHSERCVD)
2240 		dev_dbg(hsotg->dev, "%s: StsPhseRcvd asserted\n", __func__);
2241 
2242 	if (ints & DXEPINT_XFERCOMPL) {
2243 		dev_dbg(hsotg->dev,
2244 			"%s: XferCompl: DxEPCTL=0x%08x, DXEPTSIZ=%08x\n",
2245 			__func__, dwc2_readl(hsotg->regs + epctl_reg),
2246 			dwc2_readl(hsotg->regs + epsiz_reg));
2247 
2248 		/*
2249 		 * we get OutDone from the FIFO, so we only need to look
2250 		 * at completing IN requests here
2251 		 */
2252 		if (dir_in) {
2253 			if (hs_ep->isochronous && hs_ep->interval > 1)
2254 				dwc2_gadget_incr_frame_num(hs_ep);
2255 
2256 			dwc2_hsotg_complete_in(hsotg, hs_ep);
2257 			if (ints & DXEPINT_NAKINTRPT)
2258 				ints &= ~DXEPINT_NAKINTRPT;
2259 
2260 			if (idx == 0 && !hs_ep->req)
2261 				dwc2_hsotg_enqueue_setup(hsotg);
2262 		} else if (using_dma(hsotg)) {
2263 			/*
2264 			 * We're using DMA, we need to fire an OutDone here
2265 			 * as we ignore the RXFIFO.
2266 			 */
2267 			if (hs_ep->isochronous && hs_ep->interval > 1)
2268 				dwc2_gadget_incr_frame_num(hs_ep);
2269 
2270 			dwc2_hsotg_handle_outdone(hsotg, idx);
2271 		}
2272 	}
2273 
2274 	if (ints & DXEPINT_EPDISBLD)
2275 		dwc2_gadget_handle_ep_disabled(hs_ep);
2276 
2277 	if (ints & DXEPINT_OUTTKNEPDIS)
2278 		dwc2_gadget_handle_out_token_ep_disabled(hs_ep);
2279 
2280 	if (ints & DXEPINT_NAKINTRPT)
2281 		dwc2_gadget_handle_nak(hs_ep);
2282 
2283 	if (ints & DXEPINT_AHBERR)
2284 		dev_dbg(hsotg->dev, "%s: AHBErr\n", __func__);
2285 
2286 	if (ints & DXEPINT_SETUP) {  /* Setup or Timeout */
2287 		dev_dbg(hsotg->dev, "%s: Setup/Timeout\n",  __func__);
2288 
2289 		if (using_dma(hsotg) && idx == 0) {
2290 			/*
2291 			 * this is the notification we've received a
2292 			 * setup packet. In non-DMA mode we'd get this
2293 			 * from the RXFIFO, instead we need to process
2294 			 * the setup here.
2295 			 */
2296 
2297 			if (dir_in)
2298 				WARN_ON_ONCE(1);
2299 			else
2300 				dwc2_hsotg_handle_outdone(hsotg, 0);
2301 		}
2302 	}
2303 
2304 	if (ints & DXEPINT_BACK2BACKSETUP)
2305 		dev_dbg(hsotg->dev, "%s: B2BSetup/INEPNakEff\n", __func__);
2306 
2307 	if (dir_in && !hs_ep->isochronous) {
2308 		/* not sure if this is important, but we'll clear it anyway */
2309 		if (ints & DXEPINT_INTKNTXFEMP) {
2310 			dev_dbg(hsotg->dev, "%s: ep%d: INTknTXFEmpMsk\n",
2311 				__func__, idx);
2312 		}
2313 
2314 		/* this probably means something bad is happening */
2315 		if (ints & DXEPINT_INTKNEPMIS) {
2316 			dev_warn(hsotg->dev, "%s: ep%d: INTknEP\n",
2317 				 __func__, idx);
2318 		}
2319 
2320 		/* FIFO has space or is empty (see GAHBCFG) */
2321 		if (hsotg->dedicated_fifos &&
2322 		    ints & DXEPINT_TXFEMP) {
2323 			dev_dbg(hsotg->dev, "%s: ep%d: TxFIFOEmpty\n",
2324 				__func__, idx);
2325 			if (!using_dma(hsotg))
2326 				dwc2_hsotg_trytx(hsotg, hs_ep);
2327 		}
2328 	}
2329 }
2330 
2331 /**
2332  * dwc2_hsotg_irq_enumdone - Handle EnumDone interrupt (enumeration done)
2333  * @hsotg: The device state.
2334  *
2335  * Handle updating the device settings after the enumeration phase has
2336  * been completed.
2337  */
2338 static void dwc2_hsotg_irq_enumdone(struct dwc2_hsotg *hsotg)
2339 {
2340 	u32 dsts = dwc2_readl(hsotg->regs + DSTS);
2341 	int ep0_mps = 0, ep_mps = 8;
2342 
2343 	/*
2344 	 * This should signal the finish of the enumeration phase
2345 	 * of the USB handshaking, so we should now know what rate
2346 	 * we connected at.
2347 	 */
2348 
2349 	dev_dbg(hsotg->dev, "EnumDone (DSTS=0x%08x)\n", dsts);
2350 
2351 	/*
2352 	 * note, since we're limited by the size of transfer on EP0, and
2353 	 * it seems IN transfers must be a even number of packets we do
2354 	 * not advertise a 64byte MPS on EP0.
2355 	 */
2356 
2357 	/* catch both EnumSpd_FS and EnumSpd_FS48 */
2358 	switch ((dsts & DSTS_ENUMSPD_MASK) >> DSTS_ENUMSPD_SHIFT) {
2359 	case DSTS_ENUMSPD_FS:
2360 	case DSTS_ENUMSPD_FS48:
2361 		hsotg->gadget.speed = USB_SPEED_FULL;
2362 		ep0_mps = EP0_MPS_LIMIT;
2363 		ep_mps = 1023;
2364 		break;
2365 
2366 	case DSTS_ENUMSPD_HS:
2367 		hsotg->gadget.speed = USB_SPEED_HIGH;
2368 		ep0_mps = EP0_MPS_LIMIT;
2369 		ep_mps = 1024;
2370 		break;
2371 
2372 	case DSTS_ENUMSPD_LS:
2373 		hsotg->gadget.speed = USB_SPEED_LOW;
2374 		/*
2375 		 * note, we don't actually support LS in this driver at the
2376 		 * moment, and the documentation seems to imply that it isn't
2377 		 * supported by the PHYs on some of the devices.
2378 		 */
2379 		break;
2380 	}
2381 	dev_info(hsotg->dev, "new device is %s\n",
2382 		 usb_speed_string(hsotg->gadget.speed));
2383 
2384 	/*
2385 	 * we should now know the maximum packet size for an
2386 	 * endpoint, so set the endpoints to a default value.
2387 	 */
2388 
2389 	if (ep0_mps) {
2390 		int i;
2391 		/* Initialize ep0 for both in and out directions */
2392 		dwc2_hsotg_set_ep_maxpacket(hsotg, 0, ep0_mps, 1);
2393 		dwc2_hsotg_set_ep_maxpacket(hsotg, 0, ep0_mps, 0);
2394 		for (i = 1; i < hsotg->num_of_eps; i++) {
2395 			if (hsotg->eps_in[i])
2396 				dwc2_hsotg_set_ep_maxpacket(hsotg, i, ep_mps, 1);
2397 			if (hsotg->eps_out[i])
2398 				dwc2_hsotg_set_ep_maxpacket(hsotg, i, ep_mps, 0);
2399 		}
2400 	}
2401 
2402 	/* ensure after enumeration our EP0 is active */
2403 
2404 	dwc2_hsotg_enqueue_setup(hsotg);
2405 
2406 	dev_dbg(hsotg->dev, "EP0: DIEPCTL0=0x%08x, DOEPCTL0=0x%08x\n",
2407 		dwc2_readl(hsotg->regs + DIEPCTL0),
2408 		dwc2_readl(hsotg->regs + DOEPCTL0));
2409 }
2410 
2411 /**
2412  * kill_all_requests - remove all requests from the endpoint's queue
2413  * @hsotg: The device state.
2414  * @ep: The endpoint the requests may be on.
2415  * @result: The result code to use.
2416  *
2417  * Go through the requests on the given endpoint and mark them
2418  * completed with the given result code.
2419  */
2420 static void kill_all_requests(struct dwc2_hsotg *hsotg,
2421 			      struct dwc2_hsotg_ep *ep,
2422 			      int result)
2423 {
2424 	struct dwc2_hsotg_req *req, *treq;
2425 	unsigned size;
2426 
2427 	ep->req = NULL;
2428 
2429 	list_for_each_entry_safe(req, treq, &ep->queue, queue)
2430 		dwc2_hsotg_complete_request(hsotg, ep, req,
2431 					   result);
2432 
2433 	if (!hsotg->dedicated_fifos)
2434 		return;
2435 	size = (dwc2_readl(hsotg->regs + DTXFSTS(ep->index)) & 0xffff) * 4;
2436 	if (size < ep->fifo_size)
2437 		dwc2_hsotg_txfifo_flush(hsotg, ep->fifo_index);
2438 }
2439 
2440 /**
2441  * dwc2_hsotg_disconnect - disconnect service
2442  * @hsotg: The device state.
2443  *
2444  * The device has been disconnected. Remove all current
2445  * transactions and signal the gadget driver that this
2446  * has happened.
2447  */
2448 void dwc2_hsotg_disconnect(struct dwc2_hsotg *hsotg)
2449 {
2450 	unsigned ep;
2451 
2452 	if (!hsotg->connected)
2453 		return;
2454 
2455 	hsotg->connected = 0;
2456 	hsotg->test_mode = 0;
2457 
2458 	for (ep = 0; ep < hsotg->num_of_eps; ep++) {
2459 		if (hsotg->eps_in[ep])
2460 			kill_all_requests(hsotg, hsotg->eps_in[ep],
2461 								-ESHUTDOWN);
2462 		if (hsotg->eps_out[ep])
2463 			kill_all_requests(hsotg, hsotg->eps_out[ep],
2464 								-ESHUTDOWN);
2465 	}
2466 
2467 	call_gadget(hsotg, disconnect);
2468 	hsotg->lx_state = DWC2_L3;
2469 }
2470 
2471 /**
2472  * dwc2_hsotg_irq_fifoempty - TX FIFO empty interrupt handler
2473  * @hsotg: The device state:
2474  * @periodic: True if this is a periodic FIFO interrupt
2475  */
2476 static void dwc2_hsotg_irq_fifoempty(struct dwc2_hsotg *hsotg, bool periodic)
2477 {
2478 	struct dwc2_hsotg_ep *ep;
2479 	int epno, ret;
2480 
2481 	/* look through for any more data to transmit */
2482 	for (epno = 0; epno < hsotg->num_of_eps; epno++) {
2483 		ep = index_to_ep(hsotg, epno, 1);
2484 
2485 		if (!ep)
2486 			continue;
2487 
2488 		if (!ep->dir_in)
2489 			continue;
2490 
2491 		if ((periodic && !ep->periodic) ||
2492 		    (!periodic && ep->periodic))
2493 			continue;
2494 
2495 		ret = dwc2_hsotg_trytx(hsotg, ep);
2496 		if (ret < 0)
2497 			break;
2498 	}
2499 }
2500 
2501 /* IRQ flags which will trigger a retry around the IRQ loop */
2502 #define IRQ_RETRY_MASK (GINTSTS_NPTXFEMP | \
2503 			GINTSTS_PTXFEMP |  \
2504 			GINTSTS_RXFLVL)
2505 
2506 /**
2507  * dwc2_hsotg_core_init - issue softreset to the core
2508  * @hsotg: The device state
2509  *
2510  * Issue a soft reset to the core, and await the core finishing it.
2511  */
2512 void dwc2_hsotg_core_init_disconnected(struct dwc2_hsotg *hsotg,
2513 						bool is_usb_reset)
2514 {
2515 	u32 intmsk;
2516 	u32 val;
2517 	u32 usbcfg;
2518 
2519 	/* Kill any ep0 requests as controller will be reinitialized */
2520 	kill_all_requests(hsotg, hsotg->eps_out[0], -ECONNRESET);
2521 
2522 	if (!is_usb_reset)
2523 		if (dwc2_core_reset(hsotg))
2524 			return;
2525 
2526 	/*
2527 	 * we must now enable ep0 ready for host detection and then
2528 	 * set configuration.
2529 	 */
2530 
2531 	/* keep other bits untouched (so e.g. forced modes are not lost) */
2532 	usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
2533 	usbcfg &= ~(GUSBCFG_TOUTCAL_MASK | GUSBCFG_PHYIF16 | GUSBCFG_SRPCAP |
2534 		GUSBCFG_HNPCAP);
2535 
2536 	/* set the PLL on, remove the HNP/SRP and set the PHY */
2537 	val = (hsotg->phyif == GUSBCFG_PHYIF8) ? 9 : 5;
2538 	usbcfg |= hsotg->phyif | GUSBCFG_TOUTCAL(7) |
2539 		(val << GUSBCFG_USBTRDTIM_SHIFT);
2540 	dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
2541 
2542 	dwc2_hsotg_init_fifo(hsotg);
2543 
2544 	if (!is_usb_reset)
2545 		__orr32(hsotg->regs + DCTL, DCTL_SFTDISCON);
2546 
2547 	dwc2_writel(DCFG_EPMISCNT(1) | DCFG_DEVSPD_HS,  hsotg->regs + DCFG);
2548 
2549 	/* Clear any pending OTG interrupts */
2550 	dwc2_writel(0xffffffff, hsotg->regs + GOTGINT);
2551 
2552 	/* Clear any pending interrupts */
2553 	dwc2_writel(0xffffffff, hsotg->regs + GINTSTS);
2554 	intmsk = GINTSTS_ERLYSUSP | GINTSTS_SESSREQINT |
2555 		GINTSTS_GOUTNAKEFF | GINTSTS_GINNAKEFF |
2556 		GINTSTS_USBRST | GINTSTS_RESETDET |
2557 		GINTSTS_ENUMDONE | GINTSTS_OTGINT |
2558 		GINTSTS_USBSUSP | GINTSTS_WKUPINT |
2559 		GINTSTS_INCOMPL_SOIN | GINTSTS_INCOMPL_SOOUT;
2560 
2561 	if (hsotg->core_params->external_id_pin_ctl <= 0)
2562 		intmsk |= GINTSTS_CONIDSTSCHNG;
2563 
2564 	dwc2_writel(intmsk, hsotg->regs + GINTMSK);
2565 
2566 	if (using_dma(hsotg))
2567 		dwc2_writel(GAHBCFG_GLBL_INTR_EN | GAHBCFG_DMA_EN |
2568 			    (GAHBCFG_HBSTLEN_INCR4 << GAHBCFG_HBSTLEN_SHIFT),
2569 			    hsotg->regs + GAHBCFG);
2570 	else
2571 		dwc2_writel(((hsotg->dedicated_fifos) ?
2572 						(GAHBCFG_NP_TXF_EMP_LVL |
2573 						 GAHBCFG_P_TXF_EMP_LVL) : 0) |
2574 			    GAHBCFG_GLBL_INTR_EN, hsotg->regs + GAHBCFG);
2575 
2576 	/*
2577 	 * If INTknTXFEmpMsk is enabled, it's important to disable ep interrupts
2578 	 * when we have no data to transfer. Otherwise we get being flooded by
2579 	 * interrupts.
2580 	 */
2581 
2582 	dwc2_writel(((hsotg->dedicated_fifos && !using_dma(hsotg)) ?
2583 		DIEPMSK_TXFIFOEMPTY | DIEPMSK_INTKNTXFEMPMSK : 0) |
2584 		DIEPMSK_EPDISBLDMSK | DIEPMSK_XFERCOMPLMSK |
2585 		DIEPMSK_TIMEOUTMSK | DIEPMSK_AHBERRMSK,
2586 		hsotg->regs + DIEPMSK);
2587 
2588 	/*
2589 	 * don't need XferCompl, we get that from RXFIFO in slave mode. In
2590 	 * DMA mode we may need this.
2591 	 */
2592 	dwc2_writel((using_dma(hsotg) ? (DIEPMSK_XFERCOMPLMSK) : 0) |
2593 		DOEPMSK_EPDISBLDMSK | DOEPMSK_AHBERRMSK |
2594 		DOEPMSK_SETUPMSK | DOEPMSK_STSPHSERCVDMSK,
2595 		hsotg->regs + DOEPMSK);
2596 
2597 	dwc2_writel(0, hsotg->regs + DAINTMSK);
2598 
2599 	dev_dbg(hsotg->dev, "EP0: DIEPCTL0=0x%08x, DOEPCTL0=0x%08x\n",
2600 		dwc2_readl(hsotg->regs + DIEPCTL0),
2601 		dwc2_readl(hsotg->regs + DOEPCTL0));
2602 
2603 	/* enable in and out endpoint interrupts */
2604 	dwc2_hsotg_en_gsint(hsotg, GINTSTS_OEPINT | GINTSTS_IEPINT);
2605 
2606 	/*
2607 	 * Enable the RXFIFO when in slave mode, as this is how we collect
2608 	 * the data. In DMA mode, we get events from the FIFO but also
2609 	 * things we cannot process, so do not use it.
2610 	 */
2611 	if (!using_dma(hsotg))
2612 		dwc2_hsotg_en_gsint(hsotg, GINTSTS_RXFLVL);
2613 
2614 	/* Enable interrupts for EP0 in and out */
2615 	dwc2_hsotg_ctrl_epint(hsotg, 0, 0, 1);
2616 	dwc2_hsotg_ctrl_epint(hsotg, 0, 1, 1);
2617 
2618 	if (!is_usb_reset) {
2619 		__orr32(hsotg->regs + DCTL, DCTL_PWRONPRGDONE);
2620 		udelay(10);  /* see openiboot */
2621 		__bic32(hsotg->regs + DCTL, DCTL_PWRONPRGDONE);
2622 	}
2623 
2624 	dev_dbg(hsotg->dev, "DCTL=0x%08x\n", dwc2_readl(hsotg->regs + DCTL));
2625 
2626 	/*
2627 	 * DxEPCTL_USBActEp says RO in manual, but seems to be set by
2628 	 * writing to the EPCTL register..
2629 	 */
2630 
2631 	/* set to read 1 8byte packet */
2632 	dwc2_writel(DXEPTSIZ_MC(1) | DXEPTSIZ_PKTCNT(1) |
2633 	       DXEPTSIZ_XFERSIZE(8), hsotg->regs + DOEPTSIZ0);
2634 
2635 	dwc2_writel(dwc2_hsotg_ep0_mps(hsotg->eps_out[0]->ep.maxpacket) |
2636 	       DXEPCTL_CNAK | DXEPCTL_EPENA |
2637 	       DXEPCTL_USBACTEP,
2638 	       hsotg->regs + DOEPCTL0);
2639 
2640 	/* enable, but don't activate EP0in */
2641 	dwc2_writel(dwc2_hsotg_ep0_mps(hsotg->eps_out[0]->ep.maxpacket) |
2642 	       DXEPCTL_USBACTEP, hsotg->regs + DIEPCTL0);
2643 
2644 	dwc2_hsotg_enqueue_setup(hsotg);
2645 
2646 	dev_dbg(hsotg->dev, "EP0: DIEPCTL0=0x%08x, DOEPCTL0=0x%08x\n",
2647 		dwc2_readl(hsotg->regs + DIEPCTL0),
2648 		dwc2_readl(hsotg->regs + DOEPCTL0));
2649 
2650 	/* clear global NAKs */
2651 	val = DCTL_CGOUTNAK | DCTL_CGNPINNAK;
2652 	if (!is_usb_reset)
2653 		val |= DCTL_SFTDISCON;
2654 	__orr32(hsotg->regs + DCTL, val);
2655 
2656 	/* must be at-least 3ms to allow bus to see disconnect */
2657 	mdelay(3);
2658 
2659 	hsotg->lx_state = DWC2_L0;
2660 }
2661 
2662 static void dwc2_hsotg_core_disconnect(struct dwc2_hsotg *hsotg)
2663 {
2664 	/* set the soft-disconnect bit */
2665 	__orr32(hsotg->regs + DCTL, DCTL_SFTDISCON);
2666 }
2667 
2668 void dwc2_hsotg_core_connect(struct dwc2_hsotg *hsotg)
2669 {
2670 	/* remove the soft-disconnect and let's go */
2671 	__bic32(hsotg->regs + DCTL, DCTL_SFTDISCON);
2672 }
2673 
2674 /**
2675  * dwc2_gadget_handle_incomplete_isoc_in - handle incomplete ISO IN Interrupt.
2676  * @hsotg: The device state:
2677  *
2678  * This interrupt indicates one of the following conditions occurred while
2679  * transmitting an ISOC transaction.
2680  * - Corrupted IN Token for ISOC EP.
2681  * - Packet not complete in FIFO.
2682  *
2683  * The following actions will be taken:
2684  * - Determine the EP
2685  * - Disable EP; when 'Endpoint Disabled' interrupt is received Flush FIFO
2686  */
2687 static void dwc2_gadget_handle_incomplete_isoc_in(struct dwc2_hsotg *hsotg)
2688 {
2689 	struct dwc2_hsotg_ep *hs_ep;
2690 	u32 epctrl;
2691 	u32 idx;
2692 
2693 	dev_dbg(hsotg->dev, "Incomplete isoc in interrupt received:\n");
2694 
2695 	for (idx = 1; idx <= hsotg->num_of_eps; idx++) {
2696 		hs_ep = hsotg->eps_in[idx];
2697 		epctrl = dwc2_readl(hsotg->regs + DIEPCTL(idx));
2698 		if ((epctrl & DXEPCTL_EPENA) && hs_ep->isochronous &&
2699 		    dwc2_gadget_target_frame_elapsed(hs_ep)) {
2700 			epctrl |= DXEPCTL_SNAK;
2701 			epctrl |= DXEPCTL_EPDIS;
2702 			dwc2_writel(epctrl, hsotg->regs + DIEPCTL(idx));
2703 		}
2704 	}
2705 
2706 	/* Clear interrupt */
2707 	dwc2_writel(GINTSTS_INCOMPL_SOIN, hsotg->regs + GINTSTS);
2708 }
2709 
2710 /**
2711  * dwc2_gadget_handle_incomplete_isoc_out - handle incomplete ISO OUT Interrupt
2712  * @hsotg: The device state:
2713  *
2714  * This interrupt indicates one of the following conditions occurred while
2715  * transmitting an ISOC transaction.
2716  * - Corrupted OUT Token for ISOC EP.
2717  * - Packet not complete in FIFO.
2718  *
2719  * The following actions will be taken:
2720  * - Determine the EP
2721  * - Set DCTL_SGOUTNAK and unmask GOUTNAKEFF if target frame elapsed.
2722  */
2723 static void dwc2_gadget_handle_incomplete_isoc_out(struct dwc2_hsotg *hsotg)
2724 {
2725 	u32 gintsts;
2726 	u32 gintmsk;
2727 	u32 epctrl;
2728 	struct dwc2_hsotg_ep *hs_ep;
2729 	int idx;
2730 
2731 	dev_dbg(hsotg->dev, "%s: GINTSTS_INCOMPL_SOOUT\n", __func__);
2732 
2733 	for (idx = 1; idx <= hsotg->num_of_eps; idx++) {
2734 		hs_ep = hsotg->eps_out[idx];
2735 		epctrl = dwc2_readl(hsotg->regs + DOEPCTL(idx));
2736 		if ((epctrl & DXEPCTL_EPENA) && hs_ep->isochronous &&
2737 		    dwc2_gadget_target_frame_elapsed(hs_ep)) {
2738 			/* Unmask GOUTNAKEFF interrupt */
2739 			gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
2740 			gintmsk |= GINTSTS_GOUTNAKEFF;
2741 			dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
2742 
2743 			gintsts = dwc2_readl(hsotg->regs + GINTSTS);
2744 			if (!(gintsts & GINTSTS_GOUTNAKEFF))
2745 				__orr32(hsotg->regs + DCTL, DCTL_SGOUTNAK);
2746 		}
2747 	}
2748 
2749 	/* Clear interrupt */
2750 	dwc2_writel(GINTSTS_INCOMPL_SOOUT, hsotg->regs + GINTSTS);
2751 }
2752 
2753 /**
2754  * dwc2_hsotg_irq - handle device interrupt
2755  * @irq: The IRQ number triggered
2756  * @pw: The pw value when registered the handler.
2757  */
2758 static irqreturn_t dwc2_hsotg_irq(int irq, void *pw)
2759 {
2760 	struct dwc2_hsotg *hsotg = pw;
2761 	int retry_count = 8;
2762 	u32 gintsts;
2763 	u32 gintmsk;
2764 
2765 	if (!dwc2_is_device_mode(hsotg))
2766 		return IRQ_NONE;
2767 
2768 	spin_lock(&hsotg->lock);
2769 irq_retry:
2770 	gintsts = dwc2_readl(hsotg->regs + GINTSTS);
2771 	gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
2772 
2773 	dev_dbg(hsotg->dev, "%s: %08x %08x (%08x) retry %d\n",
2774 		__func__, gintsts, gintsts & gintmsk, gintmsk, retry_count);
2775 
2776 	gintsts &= gintmsk;
2777 
2778 	if (gintsts & GINTSTS_RESETDET) {
2779 		dev_dbg(hsotg->dev, "%s: USBRstDet\n", __func__);
2780 
2781 		dwc2_writel(GINTSTS_RESETDET, hsotg->regs + GINTSTS);
2782 
2783 		/* This event must be used only if controller is suspended */
2784 		if (hsotg->lx_state == DWC2_L2) {
2785 			dwc2_exit_hibernation(hsotg, true);
2786 			hsotg->lx_state = DWC2_L0;
2787 		}
2788 	}
2789 
2790 	if (gintsts & (GINTSTS_USBRST | GINTSTS_RESETDET)) {
2791 
2792 		u32 usb_status = dwc2_readl(hsotg->regs + GOTGCTL);
2793 		u32 connected = hsotg->connected;
2794 
2795 		dev_dbg(hsotg->dev, "%s: USBRst\n", __func__);
2796 		dev_dbg(hsotg->dev, "GNPTXSTS=%08x\n",
2797 			dwc2_readl(hsotg->regs + GNPTXSTS));
2798 
2799 		dwc2_writel(GINTSTS_USBRST, hsotg->regs + GINTSTS);
2800 
2801 		/* Report disconnection if it is not already done. */
2802 		dwc2_hsotg_disconnect(hsotg);
2803 
2804 		if (usb_status & GOTGCTL_BSESVLD && connected)
2805 			dwc2_hsotg_core_init_disconnected(hsotg, true);
2806 	}
2807 
2808 	if (gintsts & GINTSTS_ENUMDONE) {
2809 		dwc2_writel(GINTSTS_ENUMDONE, hsotg->regs + GINTSTS);
2810 
2811 		dwc2_hsotg_irq_enumdone(hsotg);
2812 	}
2813 
2814 	if (gintsts & (GINTSTS_OEPINT | GINTSTS_IEPINT)) {
2815 		u32 daint = dwc2_readl(hsotg->regs + DAINT);
2816 		u32 daintmsk = dwc2_readl(hsotg->regs + DAINTMSK);
2817 		u32 daint_out, daint_in;
2818 		int ep;
2819 
2820 		daint &= daintmsk;
2821 		daint_out = daint >> DAINT_OUTEP_SHIFT;
2822 		daint_in = daint & ~(daint_out << DAINT_OUTEP_SHIFT);
2823 
2824 		dev_dbg(hsotg->dev, "%s: daint=%08x\n", __func__, daint);
2825 
2826 		for (ep = 0; ep < hsotg->num_of_eps && daint_out;
2827 						ep++, daint_out >>= 1) {
2828 			if (daint_out & 1)
2829 				dwc2_hsotg_epint(hsotg, ep, 0);
2830 		}
2831 
2832 		for (ep = 0; ep < hsotg->num_of_eps  && daint_in;
2833 						ep++, daint_in >>= 1) {
2834 			if (daint_in & 1)
2835 				dwc2_hsotg_epint(hsotg, ep, 1);
2836 		}
2837 	}
2838 
2839 	/* check both FIFOs */
2840 
2841 	if (gintsts & GINTSTS_NPTXFEMP) {
2842 		dev_dbg(hsotg->dev, "NPTxFEmp\n");
2843 
2844 		/*
2845 		 * Disable the interrupt to stop it happening again
2846 		 * unless one of these endpoint routines decides that
2847 		 * it needs re-enabling
2848 		 */
2849 
2850 		dwc2_hsotg_disable_gsint(hsotg, GINTSTS_NPTXFEMP);
2851 		dwc2_hsotg_irq_fifoempty(hsotg, false);
2852 	}
2853 
2854 	if (gintsts & GINTSTS_PTXFEMP) {
2855 		dev_dbg(hsotg->dev, "PTxFEmp\n");
2856 
2857 		/* See note in GINTSTS_NPTxFEmp */
2858 
2859 		dwc2_hsotg_disable_gsint(hsotg, GINTSTS_PTXFEMP);
2860 		dwc2_hsotg_irq_fifoempty(hsotg, true);
2861 	}
2862 
2863 	if (gintsts & GINTSTS_RXFLVL) {
2864 		/*
2865 		 * note, since GINTSTS_RxFLvl doubles as FIFO-not-empty,
2866 		 * we need to retry dwc2_hsotg_handle_rx if this is still
2867 		 * set.
2868 		 */
2869 
2870 		dwc2_hsotg_handle_rx(hsotg);
2871 	}
2872 
2873 	if (gintsts & GINTSTS_ERLYSUSP) {
2874 		dev_dbg(hsotg->dev, "GINTSTS_ErlySusp\n");
2875 		dwc2_writel(GINTSTS_ERLYSUSP, hsotg->regs + GINTSTS);
2876 	}
2877 
2878 	/*
2879 	 * these next two seem to crop-up occasionally causing the core
2880 	 * to shutdown the USB transfer, so try clearing them and logging
2881 	 * the occurrence.
2882 	 */
2883 
2884 	if (gintsts & GINTSTS_GOUTNAKEFF) {
2885 		u8 idx;
2886 		u32 epctrl;
2887 		u32 gintmsk;
2888 		struct dwc2_hsotg_ep *hs_ep;
2889 
2890 		/* Mask this interrupt */
2891 		gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
2892 		gintmsk &= ~GINTSTS_GOUTNAKEFF;
2893 		dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
2894 
2895 		dev_dbg(hsotg->dev, "GOUTNakEff triggered\n");
2896 		for (idx = 1; idx <= hsotg->num_of_eps; idx++) {
2897 			hs_ep = hsotg->eps_out[idx];
2898 			epctrl = dwc2_readl(hsotg->regs + DOEPCTL(idx));
2899 
2900 			if ((epctrl & DXEPCTL_EPENA) && hs_ep->isochronous) {
2901 				epctrl |= DXEPCTL_SNAK;
2902 				epctrl |= DXEPCTL_EPDIS;
2903 				dwc2_writel(epctrl, hsotg->regs + DOEPCTL(idx));
2904 			}
2905 		}
2906 
2907 		/* This interrupt bit is cleared in DXEPINT_EPDISBLD handler */
2908 	}
2909 
2910 	if (gintsts & GINTSTS_GINNAKEFF) {
2911 		dev_info(hsotg->dev, "GINNakEff triggered\n");
2912 
2913 		__orr32(hsotg->regs + DCTL, DCTL_CGNPINNAK);
2914 
2915 		dwc2_hsotg_dump(hsotg);
2916 	}
2917 
2918 	if (gintsts & GINTSTS_INCOMPL_SOIN)
2919 		dwc2_gadget_handle_incomplete_isoc_in(hsotg);
2920 
2921 	if (gintsts & GINTSTS_INCOMPL_SOOUT)
2922 		dwc2_gadget_handle_incomplete_isoc_out(hsotg);
2923 
2924 	/*
2925 	 * if we've had fifo events, we should try and go around the
2926 	 * loop again to see if there's any point in returning yet.
2927 	 */
2928 
2929 	if (gintsts & IRQ_RETRY_MASK && --retry_count > 0)
2930 			goto irq_retry;
2931 
2932 	spin_unlock(&hsotg->lock);
2933 
2934 	return IRQ_HANDLED;
2935 }
2936 
2937 /**
2938  * dwc2_hsotg_ep_enable - enable the given endpoint
2939  * @ep: The USB endpint to configure
2940  * @desc: The USB endpoint descriptor to configure with.
2941  *
2942  * This is called from the USB gadget code's usb_ep_enable().
2943  */
2944 static int dwc2_hsotg_ep_enable(struct usb_ep *ep,
2945 			       const struct usb_endpoint_descriptor *desc)
2946 {
2947 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
2948 	struct dwc2_hsotg *hsotg = hs_ep->parent;
2949 	unsigned long flags;
2950 	unsigned int index = hs_ep->index;
2951 	u32 epctrl_reg;
2952 	u32 epctrl;
2953 	u32 mps;
2954 	u32 mask;
2955 	unsigned int dir_in;
2956 	unsigned int i, val, size;
2957 	int ret = 0;
2958 
2959 	dev_dbg(hsotg->dev,
2960 		"%s: ep %s: a 0x%02x, attr 0x%02x, mps 0x%04x, intr %d\n",
2961 		__func__, ep->name, desc->bEndpointAddress, desc->bmAttributes,
2962 		desc->wMaxPacketSize, desc->bInterval);
2963 
2964 	/* not to be called for EP0 */
2965 	if (index == 0) {
2966 		dev_err(hsotg->dev, "%s: called for EP 0\n", __func__);
2967 		return -EINVAL;
2968 	}
2969 
2970 	dir_in = (desc->bEndpointAddress & USB_ENDPOINT_DIR_MASK) ? 1 : 0;
2971 	if (dir_in != hs_ep->dir_in) {
2972 		dev_err(hsotg->dev, "%s: direction mismatch!\n", __func__);
2973 		return -EINVAL;
2974 	}
2975 
2976 	mps = usb_endpoint_maxp(desc);
2977 
2978 	/* note, we handle this here instead of dwc2_hsotg_set_ep_maxpacket */
2979 
2980 	epctrl_reg = dir_in ? DIEPCTL(index) : DOEPCTL(index);
2981 	epctrl = dwc2_readl(hsotg->regs + epctrl_reg);
2982 
2983 	dev_dbg(hsotg->dev, "%s: read DxEPCTL=0x%08x from 0x%08x\n",
2984 		__func__, epctrl, epctrl_reg);
2985 
2986 	spin_lock_irqsave(&hsotg->lock, flags);
2987 
2988 	epctrl &= ~(DXEPCTL_EPTYPE_MASK | DXEPCTL_MPS_MASK);
2989 	epctrl |= DXEPCTL_MPS(mps);
2990 
2991 	/*
2992 	 * mark the endpoint as active, otherwise the core may ignore
2993 	 * transactions entirely for this endpoint
2994 	 */
2995 	epctrl |= DXEPCTL_USBACTEP;
2996 
2997 	/* update the endpoint state */
2998 	dwc2_hsotg_set_ep_maxpacket(hsotg, hs_ep->index, mps, dir_in);
2999 
3000 	/* default, set to non-periodic */
3001 	hs_ep->isochronous = 0;
3002 	hs_ep->periodic = 0;
3003 	hs_ep->halted = 0;
3004 	hs_ep->interval = desc->bInterval;
3005 
3006 	switch (desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) {
3007 	case USB_ENDPOINT_XFER_ISOC:
3008 		epctrl |= DXEPCTL_EPTYPE_ISO;
3009 		epctrl |= DXEPCTL_SETEVENFR;
3010 		hs_ep->isochronous = 1;
3011 		hs_ep->interval = 1 << (desc->bInterval - 1);
3012 		hs_ep->target_frame = TARGET_FRAME_INITIAL;
3013 		if (dir_in) {
3014 			hs_ep->periodic = 1;
3015 			mask = dwc2_readl(hsotg->regs + DIEPMSK);
3016 			mask |= DIEPMSK_NAKMSK;
3017 			dwc2_writel(mask, hsotg->regs + DIEPMSK);
3018 		} else {
3019 			mask = dwc2_readl(hsotg->regs + DOEPMSK);
3020 			mask |= DOEPMSK_OUTTKNEPDISMSK;
3021 			dwc2_writel(mask, hsotg->regs + DOEPMSK);
3022 		}
3023 		break;
3024 
3025 	case USB_ENDPOINT_XFER_BULK:
3026 		epctrl |= DXEPCTL_EPTYPE_BULK;
3027 		break;
3028 
3029 	case USB_ENDPOINT_XFER_INT:
3030 		if (dir_in)
3031 			hs_ep->periodic = 1;
3032 
3033 		if (hsotg->gadget.speed == USB_SPEED_HIGH)
3034 			hs_ep->interval = 1 << (desc->bInterval - 1);
3035 
3036 		epctrl |= DXEPCTL_EPTYPE_INTERRUPT;
3037 		break;
3038 
3039 	case USB_ENDPOINT_XFER_CONTROL:
3040 		epctrl |= DXEPCTL_EPTYPE_CONTROL;
3041 		break;
3042 	}
3043 
3044 	/* If fifo is already allocated for this ep */
3045 	if (hs_ep->fifo_index) {
3046 		size =  hs_ep->ep.maxpacket * hs_ep->mc;
3047 		/* If bigger fifo is required deallocate current one */
3048 		if (size > hs_ep->fifo_size) {
3049 			hsotg->fifo_map &= ~(1 << hs_ep->fifo_index);
3050 			hs_ep->fifo_index = 0;
3051 			hs_ep->fifo_size = 0;
3052 		}
3053 	}
3054 
3055 	/*
3056 	 * if the hardware has dedicated fifos, we must give each IN EP
3057 	 * a unique tx-fifo even if it is non-periodic.
3058 	 */
3059 	if (dir_in && hsotg->dedicated_fifos && !hs_ep->fifo_index) {
3060 		u32 fifo_index = 0;
3061 		u32 fifo_size = UINT_MAX;
3062 		size = hs_ep->ep.maxpacket*hs_ep->mc;
3063 		for (i = 1; i < hsotg->num_of_eps; ++i) {
3064 			if (hsotg->fifo_map & (1<<i))
3065 				continue;
3066 			val = dwc2_readl(hsotg->regs + DPTXFSIZN(i));
3067 			val = (val >> FIFOSIZE_DEPTH_SHIFT)*4;
3068 			if (val < size)
3069 				continue;
3070 			/* Search for smallest acceptable fifo */
3071 			if (val < fifo_size) {
3072 				fifo_size = val;
3073 				fifo_index = i;
3074 			}
3075 		}
3076 		if (!fifo_index) {
3077 			dev_err(hsotg->dev,
3078 				"%s: No suitable fifo found\n", __func__);
3079 			ret = -ENOMEM;
3080 			goto error;
3081 		}
3082 		hsotg->fifo_map |= 1 << fifo_index;
3083 		epctrl |= DXEPCTL_TXFNUM(fifo_index);
3084 		hs_ep->fifo_index = fifo_index;
3085 		hs_ep->fifo_size = fifo_size;
3086 	}
3087 
3088 	/* for non control endpoints, set PID to D0 */
3089 	if (index && !hs_ep->isochronous)
3090 		epctrl |= DXEPCTL_SETD0PID;
3091 
3092 	dev_dbg(hsotg->dev, "%s: write DxEPCTL=0x%08x\n",
3093 		__func__, epctrl);
3094 
3095 	dwc2_writel(epctrl, hsotg->regs + epctrl_reg);
3096 	dev_dbg(hsotg->dev, "%s: read DxEPCTL=0x%08x\n",
3097 		__func__, dwc2_readl(hsotg->regs + epctrl_reg));
3098 
3099 	/* enable the endpoint interrupt */
3100 	dwc2_hsotg_ctrl_epint(hsotg, index, dir_in, 1);
3101 
3102 error:
3103 	spin_unlock_irqrestore(&hsotg->lock, flags);
3104 	return ret;
3105 }
3106 
3107 /**
3108  * dwc2_hsotg_ep_disable - disable given endpoint
3109  * @ep: The endpoint to disable.
3110  */
3111 static int dwc2_hsotg_ep_disable(struct usb_ep *ep)
3112 {
3113 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
3114 	struct dwc2_hsotg *hsotg = hs_ep->parent;
3115 	int dir_in = hs_ep->dir_in;
3116 	int index = hs_ep->index;
3117 	unsigned long flags;
3118 	u32 epctrl_reg;
3119 	u32 ctrl;
3120 
3121 	dev_dbg(hsotg->dev, "%s(ep %p)\n", __func__, ep);
3122 
3123 	if (ep == &hsotg->eps_out[0]->ep) {
3124 		dev_err(hsotg->dev, "%s: called for ep0\n", __func__);
3125 		return -EINVAL;
3126 	}
3127 
3128 	epctrl_reg = dir_in ? DIEPCTL(index) : DOEPCTL(index);
3129 
3130 	spin_lock_irqsave(&hsotg->lock, flags);
3131 
3132 	hsotg->fifo_map &= ~(1<<hs_ep->fifo_index);
3133 	hs_ep->fifo_index = 0;
3134 	hs_ep->fifo_size = 0;
3135 
3136 	ctrl = dwc2_readl(hsotg->regs + epctrl_reg);
3137 	ctrl &= ~DXEPCTL_EPENA;
3138 	ctrl &= ~DXEPCTL_USBACTEP;
3139 	ctrl |= DXEPCTL_SNAK;
3140 
3141 	dev_dbg(hsotg->dev, "%s: DxEPCTL=0x%08x\n", __func__, ctrl);
3142 	dwc2_writel(ctrl, hsotg->regs + epctrl_reg);
3143 
3144 	/* disable endpoint interrupts */
3145 	dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index, hs_ep->dir_in, 0);
3146 
3147 	/* terminate all requests with shutdown */
3148 	kill_all_requests(hsotg, hs_ep, -ESHUTDOWN);
3149 
3150 	spin_unlock_irqrestore(&hsotg->lock, flags);
3151 	return 0;
3152 }
3153 
3154 /**
3155  * on_list - check request is on the given endpoint
3156  * @ep: The endpoint to check.
3157  * @test: The request to test if it is on the endpoint.
3158  */
3159 static bool on_list(struct dwc2_hsotg_ep *ep, struct dwc2_hsotg_req *test)
3160 {
3161 	struct dwc2_hsotg_req *req, *treq;
3162 
3163 	list_for_each_entry_safe(req, treq, &ep->queue, queue) {
3164 		if (req == test)
3165 			return true;
3166 	}
3167 
3168 	return false;
3169 }
3170 
3171 static int dwc2_hsotg_wait_bit_set(struct dwc2_hsotg *hs_otg, u32 reg,
3172 							u32 bit, u32 timeout)
3173 {
3174 	u32 i;
3175 
3176 	for (i = 0; i < timeout; i++) {
3177 		if (dwc2_readl(hs_otg->regs + reg) & bit)
3178 			return 0;
3179 		udelay(1);
3180 	}
3181 
3182 	return -ETIMEDOUT;
3183 }
3184 
3185 static void dwc2_hsotg_ep_stop_xfr(struct dwc2_hsotg *hsotg,
3186 						struct dwc2_hsotg_ep *hs_ep)
3187 {
3188 	u32 epctrl_reg;
3189 	u32 epint_reg;
3190 
3191 	epctrl_reg = hs_ep->dir_in ? DIEPCTL(hs_ep->index) :
3192 		DOEPCTL(hs_ep->index);
3193 	epint_reg = hs_ep->dir_in ? DIEPINT(hs_ep->index) :
3194 		DOEPINT(hs_ep->index);
3195 
3196 	dev_dbg(hsotg->dev, "%s: stopping transfer on %s\n", __func__,
3197 			hs_ep->name);
3198 	if (hs_ep->dir_in) {
3199 		__orr32(hsotg->regs + epctrl_reg, DXEPCTL_SNAK);
3200 		/* Wait for Nak effect */
3201 		if (dwc2_hsotg_wait_bit_set(hsotg, epint_reg,
3202 						DXEPINT_INEPNAKEFF, 100))
3203 			dev_warn(hsotg->dev,
3204 				"%s: timeout DIEPINT.NAKEFF\n", __func__);
3205 	} else {
3206 		if (!(dwc2_readl(hsotg->regs + GINTSTS) & GINTSTS_GOUTNAKEFF))
3207 			__orr32(hsotg->regs + DCTL, DCTL_SGOUTNAK);
3208 
3209 		/* Wait for global nak to take effect */
3210 		if (dwc2_hsotg_wait_bit_set(hsotg, GINTSTS,
3211 						GINTSTS_GOUTNAKEFF, 100))
3212 			dev_warn(hsotg->dev,
3213 				"%s: timeout GINTSTS.GOUTNAKEFF\n", __func__);
3214 	}
3215 
3216 	/* Disable ep */
3217 	__orr32(hsotg->regs + epctrl_reg, DXEPCTL_EPDIS | DXEPCTL_SNAK);
3218 
3219 	/* Wait for ep to be disabled */
3220 	if (dwc2_hsotg_wait_bit_set(hsotg, epint_reg, DXEPINT_EPDISBLD, 100))
3221 		dev_warn(hsotg->dev,
3222 			"%s: timeout DOEPCTL.EPDisable\n", __func__);
3223 
3224 	if (hs_ep->dir_in) {
3225 		if (hsotg->dedicated_fifos) {
3226 			dwc2_writel(GRSTCTL_TXFNUM(hs_ep->fifo_index) |
3227 				GRSTCTL_TXFFLSH, hsotg->regs + GRSTCTL);
3228 			/* Wait for fifo flush */
3229 			if (dwc2_hsotg_wait_bit_set(hsotg, GRSTCTL,
3230 							GRSTCTL_TXFFLSH, 100))
3231 				dev_warn(hsotg->dev,
3232 					"%s: timeout flushing fifos\n",
3233 					__func__);
3234 		}
3235 		/* TODO: Flush shared tx fifo */
3236 	} else {
3237 		/* Remove global NAKs */
3238 		__bic32(hsotg->regs + DCTL, DCTL_SGOUTNAK);
3239 	}
3240 }
3241 
3242 /**
3243  * dwc2_hsotg_ep_dequeue - dequeue given endpoint
3244  * @ep: The endpoint to dequeue.
3245  * @req: The request to be removed from a queue.
3246  */
3247 static int dwc2_hsotg_ep_dequeue(struct usb_ep *ep, struct usb_request *req)
3248 {
3249 	struct dwc2_hsotg_req *hs_req = our_req(req);
3250 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
3251 	struct dwc2_hsotg *hs = hs_ep->parent;
3252 	unsigned long flags;
3253 
3254 	dev_dbg(hs->dev, "ep_dequeue(%p,%p)\n", ep, req);
3255 
3256 	spin_lock_irqsave(&hs->lock, flags);
3257 
3258 	if (!on_list(hs_ep, hs_req)) {
3259 		spin_unlock_irqrestore(&hs->lock, flags);
3260 		return -EINVAL;
3261 	}
3262 
3263 	/* Dequeue already started request */
3264 	if (req == &hs_ep->req->req)
3265 		dwc2_hsotg_ep_stop_xfr(hs, hs_ep);
3266 
3267 	dwc2_hsotg_complete_request(hs, hs_ep, hs_req, -ECONNRESET);
3268 	spin_unlock_irqrestore(&hs->lock, flags);
3269 
3270 	return 0;
3271 }
3272 
3273 /**
3274  * dwc2_hsotg_ep_sethalt - set halt on a given endpoint
3275  * @ep: The endpoint to set halt.
3276  * @value: Set or unset the halt.
3277  * @now: If true, stall the endpoint now. Otherwise return -EAGAIN if
3278  *       the endpoint is busy processing requests.
3279  *
3280  * We need to stall the endpoint immediately if request comes from set_feature
3281  * protocol command handler.
3282  */
3283 static int dwc2_hsotg_ep_sethalt(struct usb_ep *ep, int value, bool now)
3284 {
3285 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
3286 	struct dwc2_hsotg *hs = hs_ep->parent;
3287 	int index = hs_ep->index;
3288 	u32 epreg;
3289 	u32 epctl;
3290 	u32 xfertype;
3291 
3292 	dev_info(hs->dev, "%s(ep %p %s, %d)\n", __func__, ep, ep->name, value);
3293 
3294 	if (index == 0) {
3295 		if (value)
3296 			dwc2_hsotg_stall_ep0(hs);
3297 		else
3298 			dev_warn(hs->dev,
3299 				 "%s: can't clear halt on ep0\n", __func__);
3300 		return 0;
3301 	}
3302 
3303 	if (hs_ep->isochronous) {
3304 		dev_err(hs->dev, "%s is Isochronous Endpoint\n", ep->name);
3305 		return -EINVAL;
3306 	}
3307 
3308 	if (!now && value && !list_empty(&hs_ep->queue)) {
3309 		dev_dbg(hs->dev, "%s request is pending, cannot halt\n",
3310 			ep->name);
3311 		return -EAGAIN;
3312 	}
3313 
3314 	if (hs_ep->dir_in) {
3315 		epreg = DIEPCTL(index);
3316 		epctl = dwc2_readl(hs->regs + epreg);
3317 
3318 		if (value) {
3319 			epctl |= DXEPCTL_STALL | DXEPCTL_SNAK;
3320 			if (epctl & DXEPCTL_EPENA)
3321 				epctl |= DXEPCTL_EPDIS;
3322 		} else {
3323 			epctl &= ~DXEPCTL_STALL;
3324 			xfertype = epctl & DXEPCTL_EPTYPE_MASK;
3325 			if (xfertype == DXEPCTL_EPTYPE_BULK ||
3326 				xfertype == DXEPCTL_EPTYPE_INTERRUPT)
3327 					epctl |= DXEPCTL_SETD0PID;
3328 		}
3329 		dwc2_writel(epctl, hs->regs + epreg);
3330 	} else {
3331 
3332 		epreg = DOEPCTL(index);
3333 		epctl = dwc2_readl(hs->regs + epreg);
3334 
3335 		if (value)
3336 			epctl |= DXEPCTL_STALL;
3337 		else {
3338 			epctl &= ~DXEPCTL_STALL;
3339 			xfertype = epctl & DXEPCTL_EPTYPE_MASK;
3340 			if (xfertype == DXEPCTL_EPTYPE_BULK ||
3341 				xfertype == DXEPCTL_EPTYPE_INTERRUPT)
3342 					epctl |= DXEPCTL_SETD0PID;
3343 		}
3344 		dwc2_writel(epctl, hs->regs + epreg);
3345 	}
3346 
3347 	hs_ep->halted = value;
3348 
3349 	return 0;
3350 }
3351 
3352 /**
3353  * dwc2_hsotg_ep_sethalt_lock - set halt on a given endpoint with lock held
3354  * @ep: The endpoint to set halt.
3355  * @value: Set or unset the halt.
3356  */
3357 static int dwc2_hsotg_ep_sethalt_lock(struct usb_ep *ep, int value)
3358 {
3359 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
3360 	struct dwc2_hsotg *hs = hs_ep->parent;
3361 	unsigned long flags = 0;
3362 	int ret = 0;
3363 
3364 	spin_lock_irqsave(&hs->lock, flags);
3365 	ret = dwc2_hsotg_ep_sethalt(ep, value, false);
3366 	spin_unlock_irqrestore(&hs->lock, flags);
3367 
3368 	return ret;
3369 }
3370 
3371 static struct usb_ep_ops dwc2_hsotg_ep_ops = {
3372 	.enable		= dwc2_hsotg_ep_enable,
3373 	.disable	= dwc2_hsotg_ep_disable,
3374 	.alloc_request	= dwc2_hsotg_ep_alloc_request,
3375 	.free_request	= dwc2_hsotg_ep_free_request,
3376 	.queue		= dwc2_hsotg_ep_queue_lock,
3377 	.dequeue	= dwc2_hsotg_ep_dequeue,
3378 	.set_halt	= dwc2_hsotg_ep_sethalt_lock,
3379 	/* note, don't believe we have any call for the fifo routines */
3380 };
3381 
3382 /**
3383  * dwc2_hsotg_init - initalize the usb core
3384  * @hsotg: The driver state
3385  */
3386 static void dwc2_hsotg_init(struct dwc2_hsotg *hsotg)
3387 {
3388 	u32 trdtim;
3389 	u32 usbcfg;
3390 	/* unmask subset of endpoint interrupts */
3391 
3392 	dwc2_writel(DIEPMSK_TIMEOUTMSK | DIEPMSK_AHBERRMSK |
3393 		    DIEPMSK_EPDISBLDMSK | DIEPMSK_XFERCOMPLMSK,
3394 		    hsotg->regs + DIEPMSK);
3395 
3396 	dwc2_writel(DOEPMSK_SETUPMSK | DOEPMSK_AHBERRMSK |
3397 		    DOEPMSK_EPDISBLDMSK | DOEPMSK_XFERCOMPLMSK,
3398 		    hsotg->regs + DOEPMSK);
3399 
3400 	dwc2_writel(0, hsotg->regs + DAINTMSK);
3401 
3402 	/* Be in disconnected state until gadget is registered */
3403 	__orr32(hsotg->regs + DCTL, DCTL_SFTDISCON);
3404 
3405 	/* setup fifos */
3406 
3407 	dev_dbg(hsotg->dev, "GRXFSIZ=0x%08x, GNPTXFSIZ=0x%08x\n",
3408 		dwc2_readl(hsotg->regs + GRXFSIZ),
3409 		dwc2_readl(hsotg->regs + GNPTXFSIZ));
3410 
3411 	dwc2_hsotg_init_fifo(hsotg);
3412 
3413 	/* keep other bits untouched (so e.g. forced modes are not lost) */
3414 	usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
3415 	usbcfg &= ~(GUSBCFG_TOUTCAL_MASK | GUSBCFG_PHYIF16 | GUSBCFG_SRPCAP |
3416 		GUSBCFG_HNPCAP);
3417 
3418 	/* set the PLL on, remove the HNP/SRP and set the PHY */
3419 	trdtim = (hsotg->phyif == GUSBCFG_PHYIF8) ? 9 : 5;
3420 	usbcfg |= hsotg->phyif | GUSBCFG_TOUTCAL(7) |
3421 		(trdtim << GUSBCFG_USBTRDTIM_SHIFT);
3422 	dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
3423 
3424 	if (using_dma(hsotg))
3425 		__orr32(hsotg->regs + GAHBCFG, GAHBCFG_DMA_EN);
3426 }
3427 
3428 /**
3429  * dwc2_hsotg_udc_start - prepare the udc for work
3430  * @gadget: The usb gadget state
3431  * @driver: The usb gadget driver
3432  *
3433  * Perform initialization to prepare udc device and driver
3434  * to work.
3435  */
3436 static int dwc2_hsotg_udc_start(struct usb_gadget *gadget,
3437 			   struct usb_gadget_driver *driver)
3438 {
3439 	struct dwc2_hsotg *hsotg = to_hsotg(gadget);
3440 	unsigned long flags;
3441 	int ret;
3442 
3443 	if (!hsotg) {
3444 		pr_err("%s: called with no device\n", __func__);
3445 		return -ENODEV;
3446 	}
3447 
3448 	if (!driver) {
3449 		dev_err(hsotg->dev, "%s: no driver\n", __func__);
3450 		return -EINVAL;
3451 	}
3452 
3453 	if (driver->max_speed < USB_SPEED_FULL)
3454 		dev_err(hsotg->dev, "%s: bad speed\n", __func__);
3455 
3456 	if (!driver->setup) {
3457 		dev_err(hsotg->dev, "%s: missing entry points\n", __func__);
3458 		return -EINVAL;
3459 	}
3460 
3461 	WARN_ON(hsotg->driver);
3462 
3463 	driver->driver.bus = NULL;
3464 	hsotg->driver = driver;
3465 	hsotg->gadget.dev.of_node = hsotg->dev->of_node;
3466 	hsotg->gadget.speed = USB_SPEED_UNKNOWN;
3467 
3468 	if (hsotg->dr_mode == USB_DR_MODE_PERIPHERAL) {
3469 		ret = dwc2_lowlevel_hw_enable(hsotg);
3470 		if (ret)
3471 			goto err;
3472 	}
3473 
3474 	if (!IS_ERR_OR_NULL(hsotg->uphy))
3475 		otg_set_peripheral(hsotg->uphy->otg, &hsotg->gadget);
3476 
3477 	spin_lock_irqsave(&hsotg->lock, flags);
3478 	dwc2_hsotg_init(hsotg);
3479 	dwc2_hsotg_core_init_disconnected(hsotg, false);
3480 	hsotg->enabled = 0;
3481 	spin_unlock_irqrestore(&hsotg->lock, flags);
3482 
3483 	dev_info(hsotg->dev, "bound driver %s\n", driver->driver.name);
3484 
3485 	return 0;
3486 
3487 err:
3488 	hsotg->driver = NULL;
3489 	return ret;
3490 }
3491 
3492 /**
3493  * dwc2_hsotg_udc_stop - stop the udc
3494  * @gadget: The usb gadget state
3495  * @driver: The usb gadget driver
3496  *
3497  * Stop udc hw block and stay tunned for future transmissions
3498  */
3499 static int dwc2_hsotg_udc_stop(struct usb_gadget *gadget)
3500 {
3501 	struct dwc2_hsotg *hsotg = to_hsotg(gadget);
3502 	unsigned long flags = 0;
3503 	int ep;
3504 
3505 	if (!hsotg)
3506 		return -ENODEV;
3507 
3508 	/* all endpoints should be shutdown */
3509 	for (ep = 1; ep < hsotg->num_of_eps; ep++) {
3510 		if (hsotg->eps_in[ep])
3511 			dwc2_hsotg_ep_disable(&hsotg->eps_in[ep]->ep);
3512 		if (hsotg->eps_out[ep])
3513 			dwc2_hsotg_ep_disable(&hsotg->eps_out[ep]->ep);
3514 	}
3515 
3516 	spin_lock_irqsave(&hsotg->lock, flags);
3517 
3518 	hsotg->driver = NULL;
3519 	hsotg->gadget.speed = USB_SPEED_UNKNOWN;
3520 	hsotg->enabled = 0;
3521 
3522 	spin_unlock_irqrestore(&hsotg->lock, flags);
3523 
3524 	if (!IS_ERR_OR_NULL(hsotg->uphy))
3525 		otg_set_peripheral(hsotg->uphy->otg, NULL);
3526 
3527 	if (hsotg->dr_mode == USB_DR_MODE_PERIPHERAL)
3528 		dwc2_lowlevel_hw_disable(hsotg);
3529 
3530 	return 0;
3531 }
3532 
3533 /**
3534  * dwc2_hsotg_gadget_getframe - read the frame number
3535  * @gadget: The usb gadget state
3536  *
3537  * Read the {micro} frame number
3538  */
3539 static int dwc2_hsotg_gadget_getframe(struct usb_gadget *gadget)
3540 {
3541 	return dwc2_hsotg_read_frameno(to_hsotg(gadget));
3542 }
3543 
3544 /**
3545  * dwc2_hsotg_pullup - connect/disconnect the USB PHY
3546  * @gadget: The usb gadget state
3547  * @is_on: Current state of the USB PHY
3548  *
3549  * Connect/Disconnect the USB PHY pullup
3550  */
3551 static int dwc2_hsotg_pullup(struct usb_gadget *gadget, int is_on)
3552 {
3553 	struct dwc2_hsotg *hsotg = to_hsotg(gadget);
3554 	unsigned long flags = 0;
3555 
3556 	dev_dbg(hsotg->dev, "%s: is_on: %d op_state: %d\n", __func__, is_on,
3557 			hsotg->op_state);
3558 
3559 	/* Don't modify pullup state while in host mode */
3560 	if (hsotg->op_state != OTG_STATE_B_PERIPHERAL) {
3561 		hsotg->enabled = is_on;
3562 		return 0;
3563 	}
3564 
3565 	spin_lock_irqsave(&hsotg->lock, flags);
3566 	if (is_on) {
3567 		hsotg->enabled = 1;
3568 		dwc2_hsotg_core_init_disconnected(hsotg, false);
3569 		dwc2_hsotg_core_connect(hsotg);
3570 	} else {
3571 		dwc2_hsotg_core_disconnect(hsotg);
3572 		dwc2_hsotg_disconnect(hsotg);
3573 		hsotg->enabled = 0;
3574 	}
3575 
3576 	hsotg->gadget.speed = USB_SPEED_UNKNOWN;
3577 	spin_unlock_irqrestore(&hsotg->lock, flags);
3578 
3579 	return 0;
3580 }
3581 
3582 static int dwc2_hsotg_vbus_session(struct usb_gadget *gadget, int is_active)
3583 {
3584 	struct dwc2_hsotg *hsotg = to_hsotg(gadget);
3585 	unsigned long flags;
3586 
3587 	dev_dbg(hsotg->dev, "%s: is_active: %d\n", __func__, is_active);
3588 	spin_lock_irqsave(&hsotg->lock, flags);
3589 
3590 	/*
3591 	 * If controller is hibernated, it must exit from hibernation
3592 	 * before being initialized / de-initialized
3593 	 */
3594 	if (hsotg->lx_state == DWC2_L2)
3595 		dwc2_exit_hibernation(hsotg, false);
3596 
3597 	if (is_active) {
3598 		hsotg->op_state = OTG_STATE_B_PERIPHERAL;
3599 
3600 		dwc2_hsotg_core_init_disconnected(hsotg, false);
3601 		if (hsotg->enabled)
3602 			dwc2_hsotg_core_connect(hsotg);
3603 	} else {
3604 		dwc2_hsotg_core_disconnect(hsotg);
3605 		dwc2_hsotg_disconnect(hsotg);
3606 	}
3607 
3608 	spin_unlock_irqrestore(&hsotg->lock, flags);
3609 	return 0;
3610 }
3611 
3612 /**
3613  * dwc2_hsotg_vbus_draw - report bMaxPower field
3614  * @gadget: The usb gadget state
3615  * @mA: Amount of current
3616  *
3617  * Report how much power the device may consume to the phy.
3618  */
3619 static int dwc2_hsotg_vbus_draw(struct usb_gadget *gadget, unsigned mA)
3620 {
3621 	struct dwc2_hsotg *hsotg = to_hsotg(gadget);
3622 
3623 	if (IS_ERR_OR_NULL(hsotg->uphy))
3624 		return -ENOTSUPP;
3625 	return usb_phy_set_power(hsotg->uphy, mA);
3626 }
3627 
3628 static const struct usb_gadget_ops dwc2_hsotg_gadget_ops = {
3629 	.get_frame	= dwc2_hsotg_gadget_getframe,
3630 	.udc_start		= dwc2_hsotg_udc_start,
3631 	.udc_stop		= dwc2_hsotg_udc_stop,
3632 	.pullup                 = dwc2_hsotg_pullup,
3633 	.vbus_session		= dwc2_hsotg_vbus_session,
3634 	.vbus_draw		= dwc2_hsotg_vbus_draw,
3635 };
3636 
3637 /**
3638  * dwc2_hsotg_initep - initialise a single endpoint
3639  * @hsotg: The device state.
3640  * @hs_ep: The endpoint to be initialised.
3641  * @epnum: The endpoint number
3642  *
3643  * Initialise the given endpoint (as part of the probe and device state
3644  * creation) to give to the gadget driver. Setup the endpoint name, any
3645  * direction information and other state that may be required.
3646  */
3647 static void dwc2_hsotg_initep(struct dwc2_hsotg *hsotg,
3648 				       struct dwc2_hsotg_ep *hs_ep,
3649 				       int epnum,
3650 				       bool dir_in)
3651 {
3652 	char *dir;
3653 
3654 	if (epnum == 0)
3655 		dir = "";
3656 	else if (dir_in)
3657 		dir = "in";
3658 	else
3659 		dir = "out";
3660 
3661 	hs_ep->dir_in = dir_in;
3662 	hs_ep->index = epnum;
3663 
3664 	snprintf(hs_ep->name, sizeof(hs_ep->name), "ep%d%s", epnum, dir);
3665 
3666 	INIT_LIST_HEAD(&hs_ep->queue);
3667 	INIT_LIST_HEAD(&hs_ep->ep.ep_list);
3668 
3669 	/* add to the list of endpoints known by the gadget driver */
3670 	if (epnum)
3671 		list_add_tail(&hs_ep->ep.ep_list, &hsotg->gadget.ep_list);
3672 
3673 	hs_ep->parent = hsotg;
3674 	hs_ep->ep.name = hs_ep->name;
3675 	usb_ep_set_maxpacket_limit(&hs_ep->ep, epnum ? 1024 : EP0_MPS_LIMIT);
3676 	hs_ep->ep.ops = &dwc2_hsotg_ep_ops;
3677 
3678 	if (epnum == 0) {
3679 		hs_ep->ep.caps.type_control = true;
3680 	} else {
3681 		hs_ep->ep.caps.type_iso = true;
3682 		hs_ep->ep.caps.type_bulk = true;
3683 		hs_ep->ep.caps.type_int = true;
3684 	}
3685 
3686 	if (dir_in)
3687 		hs_ep->ep.caps.dir_in = true;
3688 	else
3689 		hs_ep->ep.caps.dir_out = true;
3690 
3691 	/*
3692 	 * if we're using dma, we need to set the next-endpoint pointer
3693 	 * to be something valid.
3694 	 */
3695 
3696 	if (using_dma(hsotg)) {
3697 		u32 next = DXEPCTL_NEXTEP((epnum + 1) % 15);
3698 		if (dir_in)
3699 			dwc2_writel(next, hsotg->regs + DIEPCTL(epnum));
3700 		else
3701 			dwc2_writel(next, hsotg->regs + DOEPCTL(epnum));
3702 	}
3703 }
3704 
3705 /**
3706  * dwc2_hsotg_hw_cfg - read HW configuration registers
3707  * @param: The device state
3708  *
3709  * Read the USB core HW configuration registers
3710  */
3711 static int dwc2_hsotg_hw_cfg(struct dwc2_hsotg *hsotg)
3712 {
3713 	u32 cfg;
3714 	u32 ep_type;
3715 	u32 i;
3716 
3717 	/* check hardware configuration */
3718 
3719 	hsotg->num_of_eps = hsotg->hw_params.num_dev_ep;
3720 
3721 	/* Add ep0 */
3722 	hsotg->num_of_eps++;
3723 
3724 	hsotg->eps_in[0] = devm_kzalloc(hsotg->dev, sizeof(struct dwc2_hsotg_ep),
3725 								GFP_KERNEL);
3726 	if (!hsotg->eps_in[0])
3727 		return -ENOMEM;
3728 	/* Same dwc2_hsotg_ep is used in both directions for ep0 */
3729 	hsotg->eps_out[0] = hsotg->eps_in[0];
3730 
3731 	cfg = hsotg->hw_params.dev_ep_dirs;
3732 	for (i = 1, cfg >>= 2; i < hsotg->num_of_eps; i++, cfg >>= 2) {
3733 		ep_type = cfg & 3;
3734 		/* Direction in or both */
3735 		if (!(ep_type & 2)) {
3736 			hsotg->eps_in[i] = devm_kzalloc(hsotg->dev,
3737 				sizeof(struct dwc2_hsotg_ep), GFP_KERNEL);
3738 			if (!hsotg->eps_in[i])
3739 				return -ENOMEM;
3740 		}
3741 		/* Direction out or both */
3742 		if (!(ep_type & 1)) {
3743 			hsotg->eps_out[i] = devm_kzalloc(hsotg->dev,
3744 				sizeof(struct dwc2_hsotg_ep), GFP_KERNEL);
3745 			if (!hsotg->eps_out[i])
3746 				return -ENOMEM;
3747 		}
3748 	}
3749 
3750 	hsotg->fifo_mem = hsotg->hw_params.total_fifo_size;
3751 	hsotg->dedicated_fifos = hsotg->hw_params.en_multiple_tx_fifo;
3752 
3753 	dev_info(hsotg->dev, "EPs: %d, %s fifos, %d entries in SPRAM\n",
3754 		 hsotg->num_of_eps,
3755 		 hsotg->dedicated_fifos ? "dedicated" : "shared",
3756 		 hsotg->fifo_mem);
3757 	return 0;
3758 }
3759 
3760 /**
3761  * dwc2_hsotg_dump - dump state of the udc
3762  * @param: The device state
3763  */
3764 static void dwc2_hsotg_dump(struct dwc2_hsotg *hsotg)
3765 {
3766 #ifdef DEBUG
3767 	struct device *dev = hsotg->dev;
3768 	void __iomem *regs = hsotg->regs;
3769 	u32 val;
3770 	int idx;
3771 
3772 	dev_info(dev, "DCFG=0x%08x, DCTL=0x%08x, DIEPMSK=%08x\n",
3773 		 dwc2_readl(regs + DCFG), dwc2_readl(regs + DCTL),
3774 		 dwc2_readl(regs + DIEPMSK));
3775 
3776 	dev_info(dev, "GAHBCFG=0x%08x, GHWCFG1=0x%08x\n",
3777 		 dwc2_readl(regs + GAHBCFG), dwc2_readl(regs + GHWCFG1));
3778 
3779 	dev_info(dev, "GRXFSIZ=0x%08x, GNPTXFSIZ=0x%08x\n",
3780 		 dwc2_readl(regs + GRXFSIZ), dwc2_readl(regs + GNPTXFSIZ));
3781 
3782 	/* show periodic fifo settings */
3783 
3784 	for (idx = 1; idx < hsotg->num_of_eps; idx++) {
3785 		val = dwc2_readl(regs + DPTXFSIZN(idx));
3786 		dev_info(dev, "DPTx[%d] FSize=%d, StAddr=0x%08x\n", idx,
3787 			 val >> FIFOSIZE_DEPTH_SHIFT,
3788 			 val & FIFOSIZE_STARTADDR_MASK);
3789 	}
3790 
3791 	for (idx = 0; idx < hsotg->num_of_eps; idx++) {
3792 		dev_info(dev,
3793 			 "ep%d-in: EPCTL=0x%08x, SIZ=0x%08x, DMA=0x%08x\n", idx,
3794 			 dwc2_readl(regs + DIEPCTL(idx)),
3795 			 dwc2_readl(regs + DIEPTSIZ(idx)),
3796 			 dwc2_readl(regs + DIEPDMA(idx)));
3797 
3798 		val = dwc2_readl(regs + DOEPCTL(idx));
3799 		dev_info(dev,
3800 			 "ep%d-out: EPCTL=0x%08x, SIZ=0x%08x, DMA=0x%08x\n",
3801 			 idx, dwc2_readl(regs + DOEPCTL(idx)),
3802 			 dwc2_readl(regs + DOEPTSIZ(idx)),
3803 			 dwc2_readl(regs + DOEPDMA(idx)));
3804 
3805 	}
3806 
3807 	dev_info(dev, "DVBUSDIS=0x%08x, DVBUSPULSE=%08x\n",
3808 		 dwc2_readl(regs + DVBUSDIS), dwc2_readl(regs + DVBUSPULSE));
3809 #endif
3810 }
3811 
3812 #ifdef CONFIG_OF
3813 static void dwc2_hsotg_of_probe(struct dwc2_hsotg *hsotg)
3814 {
3815 	struct device_node *np = hsotg->dev->of_node;
3816 	u32 len = 0;
3817 	u32 i = 0;
3818 
3819 	/* Enable dma if requested in device tree */
3820 	hsotg->g_using_dma = of_property_read_bool(np, "g-use-dma");
3821 
3822 	/*
3823 	* Register TX periodic fifo size per endpoint.
3824 	* EP0 is excluded since it has no fifo configuration.
3825 	*/
3826 	if (!of_find_property(np, "g-tx-fifo-size", &len))
3827 		goto rx_fifo;
3828 
3829 	len /= sizeof(u32);
3830 
3831 	/* Read tx fifo sizes other than ep0 */
3832 	if (of_property_read_u32_array(np, "g-tx-fifo-size",
3833 						&hsotg->g_tx_fifo_sz[1], len))
3834 		goto rx_fifo;
3835 
3836 	/* Add ep0 */
3837 	len++;
3838 
3839 	/* Make remaining TX fifos unavailable */
3840 	if (len < MAX_EPS_CHANNELS) {
3841 		for (i = len; i < MAX_EPS_CHANNELS; i++)
3842 			hsotg->g_tx_fifo_sz[i] = 0;
3843 	}
3844 
3845 rx_fifo:
3846 	/* Register RX fifo size */
3847 	of_property_read_u32(np, "g-rx-fifo-size", &hsotg->g_rx_fifo_sz);
3848 
3849 	/* Register NPTX fifo size */
3850 	of_property_read_u32(np, "g-np-tx-fifo-size",
3851 						&hsotg->g_np_g_tx_fifo_sz);
3852 }
3853 #else
3854 static inline void dwc2_hsotg_of_probe(struct dwc2_hsotg *hsotg) { }
3855 #endif
3856 
3857 /**
3858  * dwc2_gadget_init - init function for gadget
3859  * @dwc2: The data structure for the DWC2 driver.
3860  * @irq: The IRQ number for the controller.
3861  */
3862 int dwc2_gadget_init(struct dwc2_hsotg *hsotg, int irq)
3863 {
3864 	struct device *dev = hsotg->dev;
3865 	int epnum;
3866 	int ret;
3867 	int i;
3868 	u32 p_tx_fifo[] = DWC2_G_P_LEGACY_TX_FIFO_SIZE;
3869 
3870 	/* Initialize to legacy fifo configuration values */
3871 	hsotg->g_rx_fifo_sz = 2048;
3872 	hsotg->g_np_g_tx_fifo_sz = 1024;
3873 	memcpy(&hsotg->g_tx_fifo_sz[1], p_tx_fifo, sizeof(p_tx_fifo));
3874 	/* Device tree specific probe */
3875 	dwc2_hsotg_of_probe(hsotg);
3876 
3877 	/* Check against largest possible value. */
3878 	if (hsotg->g_np_g_tx_fifo_sz >
3879 	    hsotg->hw_params.dev_nperio_tx_fifo_size) {
3880 		dev_warn(dev, "Specified GNPTXFDEP=%d > %d\n",
3881 			 hsotg->g_np_g_tx_fifo_sz,
3882 			 hsotg->hw_params.dev_nperio_tx_fifo_size);
3883 		hsotg->g_np_g_tx_fifo_sz =
3884 			hsotg->hw_params.dev_nperio_tx_fifo_size;
3885 	}
3886 
3887 	/* Dump fifo information */
3888 	dev_dbg(dev, "NonPeriodic TXFIFO size: %d\n",
3889 						hsotg->g_np_g_tx_fifo_sz);
3890 	dev_dbg(dev, "RXFIFO size: %d\n", hsotg->g_rx_fifo_sz);
3891 	for (i = 0; i < MAX_EPS_CHANNELS; i++)
3892 		dev_dbg(dev, "Periodic TXFIFO%2d size: %d\n", i,
3893 						hsotg->g_tx_fifo_sz[i]);
3894 
3895 	hsotg->gadget.max_speed = USB_SPEED_HIGH;
3896 	hsotg->gadget.ops = &dwc2_hsotg_gadget_ops;
3897 	hsotg->gadget.name = dev_name(dev);
3898 	if (hsotg->dr_mode == USB_DR_MODE_OTG)
3899 		hsotg->gadget.is_otg = 1;
3900 	else if (hsotg->dr_mode == USB_DR_MODE_PERIPHERAL)
3901 		hsotg->op_state = OTG_STATE_B_PERIPHERAL;
3902 
3903 	ret = dwc2_hsotg_hw_cfg(hsotg);
3904 	if (ret) {
3905 		dev_err(hsotg->dev, "Hardware configuration failed: %d\n", ret);
3906 		return ret;
3907 	}
3908 
3909 	hsotg->ctrl_buff = devm_kzalloc(hsotg->dev,
3910 			DWC2_CTRL_BUFF_SIZE, GFP_KERNEL);
3911 	if (!hsotg->ctrl_buff) {
3912 		dev_err(dev, "failed to allocate ctrl request buff\n");
3913 		return -ENOMEM;
3914 	}
3915 
3916 	hsotg->ep0_buff = devm_kzalloc(hsotg->dev,
3917 			DWC2_CTRL_BUFF_SIZE, GFP_KERNEL);
3918 	if (!hsotg->ep0_buff) {
3919 		dev_err(dev, "failed to allocate ctrl reply buff\n");
3920 		return -ENOMEM;
3921 	}
3922 
3923 	ret = devm_request_irq(hsotg->dev, irq, dwc2_hsotg_irq, IRQF_SHARED,
3924 				dev_name(hsotg->dev), hsotg);
3925 	if (ret < 0) {
3926 		dev_err(dev, "cannot claim IRQ for gadget\n");
3927 		return ret;
3928 	}
3929 
3930 	/* hsotg->num_of_eps holds number of EPs other than ep0 */
3931 
3932 	if (hsotg->num_of_eps == 0) {
3933 		dev_err(dev, "wrong number of EPs (zero)\n");
3934 		return -EINVAL;
3935 	}
3936 
3937 	/* setup endpoint information */
3938 
3939 	INIT_LIST_HEAD(&hsotg->gadget.ep_list);
3940 	hsotg->gadget.ep0 = &hsotg->eps_out[0]->ep;
3941 
3942 	/* allocate EP0 request */
3943 
3944 	hsotg->ctrl_req = dwc2_hsotg_ep_alloc_request(&hsotg->eps_out[0]->ep,
3945 						     GFP_KERNEL);
3946 	if (!hsotg->ctrl_req) {
3947 		dev_err(dev, "failed to allocate ctrl req\n");
3948 		return -ENOMEM;
3949 	}
3950 
3951 	/* initialise the endpoints now the core has been initialised */
3952 	for (epnum = 0; epnum < hsotg->num_of_eps; epnum++) {
3953 		if (hsotg->eps_in[epnum])
3954 			dwc2_hsotg_initep(hsotg, hsotg->eps_in[epnum],
3955 								epnum, 1);
3956 		if (hsotg->eps_out[epnum])
3957 			dwc2_hsotg_initep(hsotg, hsotg->eps_out[epnum],
3958 								epnum, 0);
3959 	}
3960 
3961 	ret = usb_add_gadget_udc(dev, &hsotg->gadget);
3962 	if (ret)
3963 		return ret;
3964 
3965 	dwc2_hsotg_dump(hsotg);
3966 
3967 	return 0;
3968 }
3969 
3970 /**
3971  * dwc2_hsotg_remove - remove function for hsotg driver
3972  * @pdev: The platform information for the driver
3973  */
3974 int dwc2_hsotg_remove(struct dwc2_hsotg *hsotg)
3975 {
3976 	usb_del_gadget_udc(&hsotg->gadget);
3977 
3978 	return 0;
3979 }
3980 
3981 int dwc2_hsotg_suspend(struct dwc2_hsotg *hsotg)
3982 {
3983 	unsigned long flags;
3984 
3985 	if (hsotg->lx_state != DWC2_L0)
3986 		return 0;
3987 
3988 	if (hsotg->driver) {
3989 		int ep;
3990 
3991 		dev_info(hsotg->dev, "suspending usb gadget %s\n",
3992 			 hsotg->driver->driver.name);
3993 
3994 		spin_lock_irqsave(&hsotg->lock, flags);
3995 		if (hsotg->enabled)
3996 			dwc2_hsotg_core_disconnect(hsotg);
3997 		dwc2_hsotg_disconnect(hsotg);
3998 		hsotg->gadget.speed = USB_SPEED_UNKNOWN;
3999 		spin_unlock_irqrestore(&hsotg->lock, flags);
4000 
4001 		for (ep = 0; ep < hsotg->num_of_eps; ep++) {
4002 			if (hsotg->eps_in[ep])
4003 				dwc2_hsotg_ep_disable(&hsotg->eps_in[ep]->ep);
4004 			if (hsotg->eps_out[ep])
4005 				dwc2_hsotg_ep_disable(&hsotg->eps_out[ep]->ep);
4006 		}
4007 	}
4008 
4009 	return 0;
4010 }
4011 
4012 int dwc2_hsotg_resume(struct dwc2_hsotg *hsotg)
4013 {
4014 	unsigned long flags;
4015 
4016 	if (hsotg->lx_state == DWC2_L2)
4017 		return 0;
4018 
4019 	if (hsotg->driver) {
4020 		dev_info(hsotg->dev, "resuming usb gadget %s\n",
4021 			 hsotg->driver->driver.name);
4022 
4023 		spin_lock_irqsave(&hsotg->lock, flags);
4024 		dwc2_hsotg_core_init_disconnected(hsotg, false);
4025 		if (hsotg->enabled)
4026 			dwc2_hsotg_core_connect(hsotg);
4027 		spin_unlock_irqrestore(&hsotg->lock, flags);
4028 	}
4029 
4030 	return 0;
4031 }
4032 
4033 /**
4034  * dwc2_backup_device_registers() - Backup controller device registers.
4035  * When suspending usb bus, registers needs to be backuped
4036  * if controller power is disabled once suspended.
4037  *
4038  * @hsotg: Programming view of the DWC_otg controller
4039  */
4040 int dwc2_backup_device_registers(struct dwc2_hsotg *hsotg)
4041 {
4042 	struct dwc2_dregs_backup *dr;
4043 	int i;
4044 
4045 	dev_dbg(hsotg->dev, "%s\n", __func__);
4046 
4047 	/* Backup dev regs */
4048 	dr = &hsotg->dr_backup;
4049 
4050 	dr->dcfg = dwc2_readl(hsotg->regs + DCFG);
4051 	dr->dctl = dwc2_readl(hsotg->regs + DCTL);
4052 	dr->daintmsk = dwc2_readl(hsotg->regs + DAINTMSK);
4053 	dr->diepmsk = dwc2_readl(hsotg->regs + DIEPMSK);
4054 	dr->doepmsk = dwc2_readl(hsotg->regs + DOEPMSK);
4055 
4056 	for (i = 0; i < hsotg->num_of_eps; i++) {
4057 		/* Backup IN EPs */
4058 		dr->diepctl[i] = dwc2_readl(hsotg->regs + DIEPCTL(i));
4059 
4060 		/* Ensure DATA PID is correctly configured */
4061 		if (dr->diepctl[i] & DXEPCTL_DPID)
4062 			dr->diepctl[i] |= DXEPCTL_SETD1PID;
4063 		else
4064 			dr->diepctl[i] |= DXEPCTL_SETD0PID;
4065 
4066 		dr->dieptsiz[i] = dwc2_readl(hsotg->regs + DIEPTSIZ(i));
4067 		dr->diepdma[i] = dwc2_readl(hsotg->regs + DIEPDMA(i));
4068 
4069 		/* Backup OUT EPs */
4070 		dr->doepctl[i] = dwc2_readl(hsotg->regs + DOEPCTL(i));
4071 
4072 		/* Ensure DATA PID is correctly configured */
4073 		if (dr->doepctl[i] & DXEPCTL_DPID)
4074 			dr->doepctl[i] |= DXEPCTL_SETD1PID;
4075 		else
4076 			dr->doepctl[i] |= DXEPCTL_SETD0PID;
4077 
4078 		dr->doeptsiz[i] = dwc2_readl(hsotg->regs + DOEPTSIZ(i));
4079 		dr->doepdma[i] = dwc2_readl(hsotg->regs + DOEPDMA(i));
4080 	}
4081 	dr->valid = true;
4082 	return 0;
4083 }
4084 
4085 /**
4086  * dwc2_restore_device_registers() - Restore controller device registers.
4087  * When resuming usb bus, device registers needs to be restored
4088  * if controller power were disabled.
4089  *
4090  * @hsotg: Programming view of the DWC_otg controller
4091  */
4092 int dwc2_restore_device_registers(struct dwc2_hsotg *hsotg)
4093 {
4094 	struct dwc2_dregs_backup *dr;
4095 	u32 dctl;
4096 	int i;
4097 
4098 	dev_dbg(hsotg->dev, "%s\n", __func__);
4099 
4100 	/* Restore dev regs */
4101 	dr = &hsotg->dr_backup;
4102 	if (!dr->valid) {
4103 		dev_err(hsotg->dev, "%s: no device registers to restore\n",
4104 			__func__);
4105 		return -EINVAL;
4106 	}
4107 	dr->valid = false;
4108 
4109 	dwc2_writel(dr->dcfg, hsotg->regs + DCFG);
4110 	dwc2_writel(dr->dctl, hsotg->regs + DCTL);
4111 	dwc2_writel(dr->daintmsk, hsotg->regs + DAINTMSK);
4112 	dwc2_writel(dr->diepmsk, hsotg->regs + DIEPMSK);
4113 	dwc2_writel(dr->doepmsk, hsotg->regs + DOEPMSK);
4114 
4115 	for (i = 0; i < hsotg->num_of_eps; i++) {
4116 		/* Restore IN EPs */
4117 		dwc2_writel(dr->diepctl[i], hsotg->regs + DIEPCTL(i));
4118 		dwc2_writel(dr->dieptsiz[i], hsotg->regs + DIEPTSIZ(i));
4119 		dwc2_writel(dr->diepdma[i], hsotg->regs + DIEPDMA(i));
4120 
4121 		/* Restore OUT EPs */
4122 		dwc2_writel(dr->doepctl[i], hsotg->regs + DOEPCTL(i));
4123 		dwc2_writel(dr->doeptsiz[i], hsotg->regs + DOEPTSIZ(i));
4124 		dwc2_writel(dr->doepdma[i], hsotg->regs + DOEPDMA(i));
4125 	}
4126 
4127 	/* Set the Power-On Programming done bit */
4128 	dctl = dwc2_readl(hsotg->regs + DCTL);
4129 	dctl |= DCTL_PWRONPRGDONE;
4130 	dwc2_writel(dctl, hsotg->regs + DCTL);
4131 
4132 	return 0;
4133 }
4134