xref: /openbmc/linux/drivers/usb/dwc2/gadget.c (revision ccb01374)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2011 Samsung Electronics Co., Ltd.
4  *		http://www.samsung.com
5  *
6  * Copyright 2008 Openmoko, Inc.
7  * Copyright 2008 Simtec Electronics
8  *      Ben Dooks <ben@simtec.co.uk>
9  *      http://armlinux.simtec.co.uk/
10  *
11  * S3C USB2.0 High-speed / OtG driver
12  */
13 
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/spinlock.h>
17 #include <linux/interrupt.h>
18 #include <linux/platform_device.h>
19 #include <linux/dma-mapping.h>
20 #include <linux/mutex.h>
21 #include <linux/seq_file.h>
22 #include <linux/delay.h>
23 #include <linux/io.h>
24 #include <linux/slab.h>
25 #include <linux/of_platform.h>
26 
27 #include <linux/usb/ch9.h>
28 #include <linux/usb/gadget.h>
29 #include <linux/usb/phy.h>
30 
31 #include "core.h"
32 #include "hw.h"
33 
34 /* conversion functions */
35 static inline struct dwc2_hsotg_req *our_req(struct usb_request *req)
36 {
37 	return container_of(req, struct dwc2_hsotg_req, req);
38 }
39 
40 static inline struct dwc2_hsotg_ep *our_ep(struct usb_ep *ep)
41 {
42 	return container_of(ep, struct dwc2_hsotg_ep, ep);
43 }
44 
45 static inline struct dwc2_hsotg *to_hsotg(struct usb_gadget *gadget)
46 {
47 	return container_of(gadget, struct dwc2_hsotg, gadget);
48 }
49 
50 static inline void dwc2_set_bit(struct dwc2_hsotg *hsotg, u32 offset, u32 val)
51 {
52 	dwc2_writel(hsotg, dwc2_readl(hsotg, offset) | val, offset);
53 }
54 
55 static inline void dwc2_clear_bit(struct dwc2_hsotg *hsotg, u32 offset, u32 val)
56 {
57 	dwc2_writel(hsotg, dwc2_readl(hsotg, offset) & ~val, offset);
58 }
59 
60 static inline struct dwc2_hsotg_ep *index_to_ep(struct dwc2_hsotg *hsotg,
61 						u32 ep_index, u32 dir_in)
62 {
63 	if (dir_in)
64 		return hsotg->eps_in[ep_index];
65 	else
66 		return hsotg->eps_out[ep_index];
67 }
68 
69 /* forward declaration of functions */
70 static void dwc2_hsotg_dump(struct dwc2_hsotg *hsotg);
71 
72 /**
73  * using_dma - return the DMA status of the driver.
74  * @hsotg: The driver state.
75  *
76  * Return true if we're using DMA.
77  *
78  * Currently, we have the DMA support code worked into everywhere
79  * that needs it, but the AMBA DMA implementation in the hardware can
80  * only DMA from 32bit aligned addresses. This means that gadgets such
81  * as the CDC Ethernet cannot work as they often pass packets which are
82  * not 32bit aligned.
83  *
84  * Unfortunately the choice to use DMA or not is global to the controller
85  * and seems to be only settable when the controller is being put through
86  * a core reset. This means we either need to fix the gadgets to take
87  * account of DMA alignment, or add bounce buffers (yuerk).
88  *
89  * g_using_dma is set depending on dts flag.
90  */
91 static inline bool using_dma(struct dwc2_hsotg *hsotg)
92 {
93 	return hsotg->params.g_dma;
94 }
95 
96 /*
97  * using_desc_dma - return the descriptor DMA status of the driver.
98  * @hsotg: The driver state.
99  *
100  * Return true if we're using descriptor DMA.
101  */
102 static inline bool using_desc_dma(struct dwc2_hsotg *hsotg)
103 {
104 	return hsotg->params.g_dma_desc;
105 }
106 
107 /**
108  * dwc2_gadget_incr_frame_num - Increments the targeted frame number.
109  * @hs_ep: The endpoint
110  *
111  * This function will also check if the frame number overruns DSTS_SOFFN_LIMIT.
112  * If an overrun occurs it will wrap the value and set the frame_overrun flag.
113  */
114 static inline void dwc2_gadget_incr_frame_num(struct dwc2_hsotg_ep *hs_ep)
115 {
116 	hs_ep->target_frame += hs_ep->interval;
117 	if (hs_ep->target_frame > DSTS_SOFFN_LIMIT) {
118 		hs_ep->frame_overrun = true;
119 		hs_ep->target_frame &= DSTS_SOFFN_LIMIT;
120 	} else {
121 		hs_ep->frame_overrun = false;
122 	}
123 }
124 
125 /**
126  * dwc2_gadget_dec_frame_num_by_one - Decrements the targeted frame number
127  *                                    by one.
128  * @hs_ep: The endpoint.
129  *
130  * This function used in service interval based scheduling flow to calculate
131  * descriptor frame number filed value. For service interval mode frame
132  * number in descriptor should point to last (u)frame in the interval.
133  *
134  */
135 static inline void dwc2_gadget_dec_frame_num_by_one(struct dwc2_hsotg_ep *hs_ep)
136 {
137 	if (hs_ep->target_frame)
138 		hs_ep->target_frame -= 1;
139 	else
140 		hs_ep->target_frame = DSTS_SOFFN_LIMIT;
141 }
142 
143 /**
144  * dwc2_hsotg_en_gsint - enable one or more of the general interrupt
145  * @hsotg: The device state
146  * @ints: A bitmask of the interrupts to enable
147  */
148 static void dwc2_hsotg_en_gsint(struct dwc2_hsotg *hsotg, u32 ints)
149 {
150 	u32 gsintmsk = dwc2_readl(hsotg, GINTMSK);
151 	u32 new_gsintmsk;
152 
153 	new_gsintmsk = gsintmsk | ints;
154 
155 	if (new_gsintmsk != gsintmsk) {
156 		dev_dbg(hsotg->dev, "gsintmsk now 0x%08x\n", new_gsintmsk);
157 		dwc2_writel(hsotg, new_gsintmsk, GINTMSK);
158 	}
159 }
160 
161 /**
162  * dwc2_hsotg_disable_gsint - disable one or more of the general interrupt
163  * @hsotg: The device state
164  * @ints: A bitmask of the interrupts to enable
165  */
166 static void dwc2_hsotg_disable_gsint(struct dwc2_hsotg *hsotg, u32 ints)
167 {
168 	u32 gsintmsk = dwc2_readl(hsotg, GINTMSK);
169 	u32 new_gsintmsk;
170 
171 	new_gsintmsk = gsintmsk & ~ints;
172 
173 	if (new_gsintmsk != gsintmsk)
174 		dwc2_writel(hsotg, new_gsintmsk, GINTMSK);
175 }
176 
177 /**
178  * dwc2_hsotg_ctrl_epint - enable/disable an endpoint irq
179  * @hsotg: The device state
180  * @ep: The endpoint index
181  * @dir_in: True if direction is in.
182  * @en: The enable value, true to enable
183  *
184  * Set or clear the mask for an individual endpoint's interrupt
185  * request.
186  */
187 static void dwc2_hsotg_ctrl_epint(struct dwc2_hsotg *hsotg,
188 				  unsigned int ep, unsigned int dir_in,
189 				 unsigned int en)
190 {
191 	unsigned long flags;
192 	u32 bit = 1 << ep;
193 	u32 daint;
194 
195 	if (!dir_in)
196 		bit <<= 16;
197 
198 	local_irq_save(flags);
199 	daint = dwc2_readl(hsotg, DAINTMSK);
200 	if (en)
201 		daint |= bit;
202 	else
203 		daint &= ~bit;
204 	dwc2_writel(hsotg, daint, DAINTMSK);
205 	local_irq_restore(flags);
206 }
207 
208 /**
209  * dwc2_hsotg_tx_fifo_count - return count of TX FIFOs in device mode
210  *
211  * @hsotg: Programming view of the DWC_otg controller
212  */
213 int dwc2_hsotg_tx_fifo_count(struct dwc2_hsotg *hsotg)
214 {
215 	if (hsotg->hw_params.en_multiple_tx_fifo)
216 		/* In dedicated FIFO mode we need count of IN EPs */
217 		return hsotg->hw_params.num_dev_in_eps;
218 	else
219 		/* In shared FIFO mode we need count of Periodic IN EPs */
220 		return hsotg->hw_params.num_dev_perio_in_ep;
221 }
222 
223 /**
224  * dwc2_hsotg_tx_fifo_total_depth - return total FIFO depth available for
225  * device mode TX FIFOs
226  *
227  * @hsotg: Programming view of the DWC_otg controller
228  */
229 int dwc2_hsotg_tx_fifo_total_depth(struct dwc2_hsotg *hsotg)
230 {
231 	int addr;
232 	int tx_addr_max;
233 	u32 np_tx_fifo_size;
234 
235 	np_tx_fifo_size = min_t(u32, hsotg->hw_params.dev_nperio_tx_fifo_size,
236 				hsotg->params.g_np_tx_fifo_size);
237 
238 	/* Get Endpoint Info Control block size in DWORDs. */
239 	tx_addr_max = hsotg->hw_params.total_fifo_size;
240 
241 	addr = hsotg->params.g_rx_fifo_size + np_tx_fifo_size;
242 	if (tx_addr_max <= addr)
243 		return 0;
244 
245 	return tx_addr_max - addr;
246 }
247 
248 /**
249  * dwc2_gadget_wkup_alert_handler - Handler for WKUP_ALERT interrupt
250  *
251  * @hsotg: Programming view of the DWC_otg controller
252  *
253  */
254 static void dwc2_gadget_wkup_alert_handler(struct dwc2_hsotg *hsotg)
255 {
256 	u32 gintsts2;
257 	u32 gintmsk2;
258 
259 	gintsts2 = dwc2_readl(hsotg, GINTSTS2);
260 	gintmsk2 = dwc2_readl(hsotg, GINTMSK2);
261 
262 	if (gintsts2 & GINTSTS2_WKUP_ALERT_INT) {
263 		dev_dbg(hsotg->dev, "%s: Wkup_Alert_Int\n", __func__);
264 		dwc2_clear_bit(hsotg, GINTSTS2, GINTSTS2_WKUP_ALERT_INT);
265 		dwc2_set_bit(hsotg, DCTL, DCTL_RMTWKUPSIG);
266 	}
267 }
268 
269 /**
270  * dwc2_hsotg_tx_fifo_average_depth - returns average depth of device mode
271  * TX FIFOs
272  *
273  * @hsotg: Programming view of the DWC_otg controller
274  */
275 int dwc2_hsotg_tx_fifo_average_depth(struct dwc2_hsotg *hsotg)
276 {
277 	int tx_fifo_count;
278 	int tx_fifo_depth;
279 
280 	tx_fifo_depth = dwc2_hsotg_tx_fifo_total_depth(hsotg);
281 
282 	tx_fifo_count = dwc2_hsotg_tx_fifo_count(hsotg);
283 
284 	if (!tx_fifo_count)
285 		return tx_fifo_depth;
286 	else
287 		return tx_fifo_depth / tx_fifo_count;
288 }
289 
290 /**
291  * dwc2_hsotg_init_fifo - initialise non-periodic FIFOs
292  * @hsotg: The device instance.
293  */
294 static void dwc2_hsotg_init_fifo(struct dwc2_hsotg *hsotg)
295 {
296 	unsigned int ep;
297 	unsigned int addr;
298 	int timeout;
299 
300 	u32 val;
301 	u32 *txfsz = hsotg->params.g_tx_fifo_size;
302 
303 	/* Reset fifo map if not correctly cleared during previous session */
304 	WARN_ON(hsotg->fifo_map);
305 	hsotg->fifo_map = 0;
306 
307 	/* set RX/NPTX FIFO sizes */
308 	dwc2_writel(hsotg, hsotg->params.g_rx_fifo_size, GRXFSIZ);
309 	dwc2_writel(hsotg, (hsotg->params.g_rx_fifo_size <<
310 		    FIFOSIZE_STARTADDR_SHIFT) |
311 		    (hsotg->params.g_np_tx_fifo_size << FIFOSIZE_DEPTH_SHIFT),
312 		    GNPTXFSIZ);
313 
314 	/*
315 	 * arange all the rest of the TX FIFOs, as some versions of this
316 	 * block have overlapping default addresses. This also ensures
317 	 * that if the settings have been changed, then they are set to
318 	 * known values.
319 	 */
320 
321 	/* start at the end of the GNPTXFSIZ, rounded up */
322 	addr = hsotg->params.g_rx_fifo_size + hsotg->params.g_np_tx_fifo_size;
323 
324 	/*
325 	 * Configure fifos sizes from provided configuration and assign
326 	 * them to endpoints dynamically according to maxpacket size value of
327 	 * given endpoint.
328 	 */
329 	for (ep = 1; ep < MAX_EPS_CHANNELS; ep++) {
330 		if (!txfsz[ep])
331 			continue;
332 		val = addr;
333 		val |= txfsz[ep] << FIFOSIZE_DEPTH_SHIFT;
334 		WARN_ONCE(addr + txfsz[ep] > hsotg->fifo_mem,
335 			  "insufficient fifo memory");
336 		addr += txfsz[ep];
337 
338 		dwc2_writel(hsotg, val, DPTXFSIZN(ep));
339 		val = dwc2_readl(hsotg, DPTXFSIZN(ep));
340 	}
341 
342 	dwc2_writel(hsotg, hsotg->hw_params.total_fifo_size |
343 		    addr << GDFIFOCFG_EPINFOBASE_SHIFT,
344 		    GDFIFOCFG);
345 	/*
346 	 * according to p428 of the design guide, we need to ensure that
347 	 * all fifos are flushed before continuing
348 	 */
349 
350 	dwc2_writel(hsotg, GRSTCTL_TXFNUM(0x10) | GRSTCTL_TXFFLSH |
351 	       GRSTCTL_RXFFLSH, GRSTCTL);
352 
353 	/* wait until the fifos are both flushed */
354 	timeout = 100;
355 	while (1) {
356 		val = dwc2_readl(hsotg, GRSTCTL);
357 
358 		if ((val & (GRSTCTL_TXFFLSH | GRSTCTL_RXFFLSH)) == 0)
359 			break;
360 
361 		if (--timeout == 0) {
362 			dev_err(hsotg->dev,
363 				"%s: timeout flushing fifos (GRSTCTL=%08x)\n",
364 				__func__, val);
365 			break;
366 		}
367 
368 		udelay(1);
369 	}
370 
371 	dev_dbg(hsotg->dev, "FIFOs reset, timeout at %d\n", timeout);
372 }
373 
374 /**
375  * dwc2_hsotg_ep_alloc_request - allocate USB rerequest structure
376  * @ep: USB endpoint to allocate request for.
377  * @flags: Allocation flags
378  *
379  * Allocate a new USB request structure appropriate for the specified endpoint
380  */
381 static struct usb_request *dwc2_hsotg_ep_alloc_request(struct usb_ep *ep,
382 						       gfp_t flags)
383 {
384 	struct dwc2_hsotg_req *req;
385 
386 	req = kzalloc(sizeof(*req), flags);
387 	if (!req)
388 		return NULL;
389 
390 	INIT_LIST_HEAD(&req->queue);
391 
392 	return &req->req;
393 }
394 
395 /**
396  * is_ep_periodic - return true if the endpoint is in periodic mode.
397  * @hs_ep: The endpoint to query.
398  *
399  * Returns true if the endpoint is in periodic mode, meaning it is being
400  * used for an Interrupt or ISO transfer.
401  */
402 static inline int is_ep_periodic(struct dwc2_hsotg_ep *hs_ep)
403 {
404 	return hs_ep->periodic;
405 }
406 
407 /**
408  * dwc2_hsotg_unmap_dma - unmap the DMA memory being used for the request
409  * @hsotg: The device state.
410  * @hs_ep: The endpoint for the request
411  * @hs_req: The request being processed.
412  *
413  * This is the reverse of dwc2_hsotg_map_dma(), called for the completion
414  * of a request to ensure the buffer is ready for access by the caller.
415  */
416 static void dwc2_hsotg_unmap_dma(struct dwc2_hsotg *hsotg,
417 				 struct dwc2_hsotg_ep *hs_ep,
418 				struct dwc2_hsotg_req *hs_req)
419 {
420 	struct usb_request *req = &hs_req->req;
421 
422 	usb_gadget_unmap_request(&hsotg->gadget, req, hs_ep->dir_in);
423 }
424 
425 /*
426  * dwc2_gadget_alloc_ctrl_desc_chains - allocate DMA descriptor chains
427  * for Control endpoint
428  * @hsotg: The device state.
429  *
430  * This function will allocate 4 descriptor chains for EP 0: 2 for
431  * Setup stage, per one for IN and OUT data/status transactions.
432  */
433 static int dwc2_gadget_alloc_ctrl_desc_chains(struct dwc2_hsotg *hsotg)
434 {
435 	hsotg->setup_desc[0] =
436 		dmam_alloc_coherent(hsotg->dev,
437 				    sizeof(struct dwc2_dma_desc),
438 				    &hsotg->setup_desc_dma[0],
439 				    GFP_KERNEL);
440 	if (!hsotg->setup_desc[0])
441 		goto fail;
442 
443 	hsotg->setup_desc[1] =
444 		dmam_alloc_coherent(hsotg->dev,
445 				    sizeof(struct dwc2_dma_desc),
446 				    &hsotg->setup_desc_dma[1],
447 				    GFP_KERNEL);
448 	if (!hsotg->setup_desc[1])
449 		goto fail;
450 
451 	hsotg->ctrl_in_desc =
452 		dmam_alloc_coherent(hsotg->dev,
453 				    sizeof(struct dwc2_dma_desc),
454 				    &hsotg->ctrl_in_desc_dma,
455 				    GFP_KERNEL);
456 	if (!hsotg->ctrl_in_desc)
457 		goto fail;
458 
459 	hsotg->ctrl_out_desc =
460 		dmam_alloc_coherent(hsotg->dev,
461 				    sizeof(struct dwc2_dma_desc),
462 				    &hsotg->ctrl_out_desc_dma,
463 				    GFP_KERNEL);
464 	if (!hsotg->ctrl_out_desc)
465 		goto fail;
466 
467 	return 0;
468 
469 fail:
470 	return -ENOMEM;
471 }
472 
473 /**
474  * dwc2_hsotg_write_fifo - write packet Data to the TxFIFO
475  * @hsotg: The controller state.
476  * @hs_ep: The endpoint we're going to write for.
477  * @hs_req: The request to write data for.
478  *
479  * This is called when the TxFIFO has some space in it to hold a new
480  * transmission and we have something to give it. The actual setup of
481  * the data size is done elsewhere, so all we have to do is to actually
482  * write the data.
483  *
484  * The return value is zero if there is more space (or nothing was done)
485  * otherwise -ENOSPC is returned if the FIFO space was used up.
486  *
487  * This routine is only needed for PIO
488  */
489 static int dwc2_hsotg_write_fifo(struct dwc2_hsotg *hsotg,
490 				 struct dwc2_hsotg_ep *hs_ep,
491 				struct dwc2_hsotg_req *hs_req)
492 {
493 	bool periodic = is_ep_periodic(hs_ep);
494 	u32 gnptxsts = dwc2_readl(hsotg, GNPTXSTS);
495 	int buf_pos = hs_req->req.actual;
496 	int to_write = hs_ep->size_loaded;
497 	void *data;
498 	int can_write;
499 	int pkt_round;
500 	int max_transfer;
501 
502 	to_write -= (buf_pos - hs_ep->last_load);
503 
504 	/* if there's nothing to write, get out early */
505 	if (to_write == 0)
506 		return 0;
507 
508 	if (periodic && !hsotg->dedicated_fifos) {
509 		u32 epsize = dwc2_readl(hsotg, DIEPTSIZ(hs_ep->index));
510 		int size_left;
511 		int size_done;
512 
513 		/*
514 		 * work out how much data was loaded so we can calculate
515 		 * how much data is left in the fifo.
516 		 */
517 
518 		size_left = DXEPTSIZ_XFERSIZE_GET(epsize);
519 
520 		/*
521 		 * if shared fifo, we cannot write anything until the
522 		 * previous data has been completely sent.
523 		 */
524 		if (hs_ep->fifo_load != 0) {
525 			dwc2_hsotg_en_gsint(hsotg, GINTSTS_PTXFEMP);
526 			return -ENOSPC;
527 		}
528 
529 		dev_dbg(hsotg->dev, "%s: left=%d, load=%d, fifo=%d, size %d\n",
530 			__func__, size_left,
531 			hs_ep->size_loaded, hs_ep->fifo_load, hs_ep->fifo_size);
532 
533 		/* how much of the data has moved */
534 		size_done = hs_ep->size_loaded - size_left;
535 
536 		/* how much data is left in the fifo */
537 		can_write = hs_ep->fifo_load - size_done;
538 		dev_dbg(hsotg->dev, "%s: => can_write1=%d\n",
539 			__func__, can_write);
540 
541 		can_write = hs_ep->fifo_size - can_write;
542 		dev_dbg(hsotg->dev, "%s: => can_write2=%d\n",
543 			__func__, can_write);
544 
545 		if (can_write <= 0) {
546 			dwc2_hsotg_en_gsint(hsotg, GINTSTS_PTXFEMP);
547 			return -ENOSPC;
548 		}
549 	} else if (hsotg->dedicated_fifos && hs_ep->index != 0) {
550 		can_write = dwc2_readl(hsotg,
551 				       DTXFSTS(hs_ep->fifo_index));
552 
553 		can_write &= 0xffff;
554 		can_write *= 4;
555 	} else {
556 		if (GNPTXSTS_NP_TXQ_SPC_AVAIL_GET(gnptxsts) == 0) {
557 			dev_dbg(hsotg->dev,
558 				"%s: no queue slots available (0x%08x)\n",
559 				__func__, gnptxsts);
560 
561 			dwc2_hsotg_en_gsint(hsotg, GINTSTS_NPTXFEMP);
562 			return -ENOSPC;
563 		}
564 
565 		can_write = GNPTXSTS_NP_TXF_SPC_AVAIL_GET(gnptxsts);
566 		can_write *= 4;	/* fifo size is in 32bit quantities. */
567 	}
568 
569 	max_transfer = hs_ep->ep.maxpacket * hs_ep->mc;
570 
571 	dev_dbg(hsotg->dev, "%s: GNPTXSTS=%08x, can=%d, to=%d, max_transfer %d\n",
572 		__func__, gnptxsts, can_write, to_write, max_transfer);
573 
574 	/*
575 	 * limit to 512 bytes of data, it seems at least on the non-periodic
576 	 * FIFO, requests of >512 cause the endpoint to get stuck with a
577 	 * fragment of the end of the transfer in it.
578 	 */
579 	if (can_write > 512 && !periodic)
580 		can_write = 512;
581 
582 	/*
583 	 * limit the write to one max-packet size worth of data, but allow
584 	 * the transfer to return that it did not run out of fifo space
585 	 * doing it.
586 	 */
587 	if (to_write > max_transfer) {
588 		to_write = max_transfer;
589 
590 		/* it's needed only when we do not use dedicated fifos */
591 		if (!hsotg->dedicated_fifos)
592 			dwc2_hsotg_en_gsint(hsotg,
593 					    periodic ? GINTSTS_PTXFEMP :
594 					   GINTSTS_NPTXFEMP);
595 	}
596 
597 	/* see if we can write data */
598 
599 	if (to_write > can_write) {
600 		to_write = can_write;
601 		pkt_round = to_write % max_transfer;
602 
603 		/*
604 		 * Round the write down to an
605 		 * exact number of packets.
606 		 *
607 		 * Note, we do not currently check to see if we can ever
608 		 * write a full packet or not to the FIFO.
609 		 */
610 
611 		if (pkt_round)
612 			to_write -= pkt_round;
613 
614 		/*
615 		 * enable correct FIFO interrupt to alert us when there
616 		 * is more room left.
617 		 */
618 
619 		/* it's needed only when we do not use dedicated fifos */
620 		if (!hsotg->dedicated_fifos)
621 			dwc2_hsotg_en_gsint(hsotg,
622 					    periodic ? GINTSTS_PTXFEMP :
623 					   GINTSTS_NPTXFEMP);
624 	}
625 
626 	dev_dbg(hsotg->dev, "write %d/%d, can_write %d, done %d\n",
627 		to_write, hs_req->req.length, can_write, buf_pos);
628 
629 	if (to_write <= 0)
630 		return -ENOSPC;
631 
632 	hs_req->req.actual = buf_pos + to_write;
633 	hs_ep->total_data += to_write;
634 
635 	if (periodic)
636 		hs_ep->fifo_load += to_write;
637 
638 	to_write = DIV_ROUND_UP(to_write, 4);
639 	data = hs_req->req.buf + buf_pos;
640 
641 	dwc2_writel_rep(hsotg, EPFIFO(hs_ep->index), data, to_write);
642 
643 	return (to_write >= can_write) ? -ENOSPC : 0;
644 }
645 
646 /**
647  * get_ep_limit - get the maximum data legnth for this endpoint
648  * @hs_ep: The endpoint
649  *
650  * Return the maximum data that can be queued in one go on a given endpoint
651  * so that transfers that are too long can be split.
652  */
653 static unsigned int get_ep_limit(struct dwc2_hsotg_ep *hs_ep)
654 {
655 	int index = hs_ep->index;
656 	unsigned int maxsize;
657 	unsigned int maxpkt;
658 
659 	if (index != 0) {
660 		maxsize = DXEPTSIZ_XFERSIZE_LIMIT + 1;
661 		maxpkt = DXEPTSIZ_PKTCNT_LIMIT + 1;
662 	} else {
663 		maxsize = 64 + 64;
664 		if (hs_ep->dir_in)
665 			maxpkt = DIEPTSIZ0_PKTCNT_LIMIT + 1;
666 		else
667 			maxpkt = 2;
668 	}
669 
670 	/* we made the constant loading easier above by using +1 */
671 	maxpkt--;
672 	maxsize--;
673 
674 	/*
675 	 * constrain by packet count if maxpkts*pktsize is greater
676 	 * than the length register size.
677 	 */
678 
679 	if ((maxpkt * hs_ep->ep.maxpacket) < maxsize)
680 		maxsize = maxpkt * hs_ep->ep.maxpacket;
681 
682 	return maxsize;
683 }
684 
685 /**
686  * dwc2_hsotg_read_frameno - read current frame number
687  * @hsotg: The device instance
688  *
689  * Return the current frame number
690  */
691 static u32 dwc2_hsotg_read_frameno(struct dwc2_hsotg *hsotg)
692 {
693 	u32 dsts;
694 
695 	dsts = dwc2_readl(hsotg, DSTS);
696 	dsts &= DSTS_SOFFN_MASK;
697 	dsts >>= DSTS_SOFFN_SHIFT;
698 
699 	return dsts;
700 }
701 
702 /**
703  * dwc2_gadget_get_chain_limit - get the maximum data payload value of the
704  * DMA descriptor chain prepared for specific endpoint
705  * @hs_ep: The endpoint
706  *
707  * Return the maximum data that can be queued in one go on a given endpoint
708  * depending on its descriptor chain capacity so that transfers that
709  * are too long can be split.
710  */
711 static unsigned int dwc2_gadget_get_chain_limit(struct dwc2_hsotg_ep *hs_ep)
712 {
713 	int is_isoc = hs_ep->isochronous;
714 	unsigned int maxsize;
715 
716 	if (is_isoc)
717 		maxsize = hs_ep->dir_in ? DEV_DMA_ISOC_TX_NBYTES_LIMIT :
718 					   DEV_DMA_ISOC_RX_NBYTES_LIMIT;
719 	else
720 		maxsize = DEV_DMA_NBYTES_LIMIT;
721 
722 	/* Above size of one descriptor was chosen, multiple it */
723 	maxsize *= MAX_DMA_DESC_NUM_GENERIC;
724 
725 	return maxsize;
726 }
727 
728 /*
729  * dwc2_gadget_get_desc_params - get DMA descriptor parameters.
730  * @hs_ep: The endpoint
731  * @mask: RX/TX bytes mask to be defined
732  *
733  * Returns maximum data payload for one descriptor after analyzing endpoint
734  * characteristics.
735  * DMA descriptor transfer bytes limit depends on EP type:
736  * Control out - MPS,
737  * Isochronous - descriptor rx/tx bytes bitfield limit,
738  * Control In/Bulk/Interrupt - multiple of mps. This will allow to not
739  * have concatenations from various descriptors within one packet.
740  *
741  * Selects corresponding mask for RX/TX bytes as well.
742  */
743 static u32 dwc2_gadget_get_desc_params(struct dwc2_hsotg_ep *hs_ep, u32 *mask)
744 {
745 	u32 mps = hs_ep->ep.maxpacket;
746 	int dir_in = hs_ep->dir_in;
747 	u32 desc_size = 0;
748 
749 	if (!hs_ep->index && !dir_in) {
750 		desc_size = mps;
751 		*mask = DEV_DMA_NBYTES_MASK;
752 	} else if (hs_ep->isochronous) {
753 		if (dir_in) {
754 			desc_size = DEV_DMA_ISOC_TX_NBYTES_LIMIT;
755 			*mask = DEV_DMA_ISOC_TX_NBYTES_MASK;
756 		} else {
757 			desc_size = DEV_DMA_ISOC_RX_NBYTES_LIMIT;
758 			*mask = DEV_DMA_ISOC_RX_NBYTES_MASK;
759 		}
760 	} else {
761 		desc_size = DEV_DMA_NBYTES_LIMIT;
762 		*mask = DEV_DMA_NBYTES_MASK;
763 
764 		/* Round down desc_size to be mps multiple */
765 		desc_size -= desc_size % mps;
766 	}
767 
768 	return desc_size;
769 }
770 
771 /*
772  * dwc2_gadget_config_nonisoc_xfer_ddma - prepare non ISOC DMA desc chain.
773  * @hs_ep: The endpoint
774  * @dma_buff: DMA address to use
775  * @len: Length of the transfer
776  *
777  * This function will iterate over descriptor chain and fill its entries
778  * with corresponding information based on transfer data.
779  */
780 static void dwc2_gadget_config_nonisoc_xfer_ddma(struct dwc2_hsotg_ep *hs_ep,
781 						 dma_addr_t dma_buff,
782 						 unsigned int len)
783 {
784 	struct dwc2_hsotg *hsotg = hs_ep->parent;
785 	int dir_in = hs_ep->dir_in;
786 	struct dwc2_dma_desc *desc = hs_ep->desc_list;
787 	u32 mps = hs_ep->ep.maxpacket;
788 	u32 maxsize = 0;
789 	u32 offset = 0;
790 	u32 mask = 0;
791 	int i;
792 
793 	maxsize = dwc2_gadget_get_desc_params(hs_ep, &mask);
794 
795 	hs_ep->desc_count = (len / maxsize) +
796 				((len % maxsize) ? 1 : 0);
797 	if (len == 0)
798 		hs_ep->desc_count = 1;
799 
800 	for (i = 0; i < hs_ep->desc_count; ++i) {
801 		desc->status = 0;
802 		desc->status |= (DEV_DMA_BUFF_STS_HBUSY
803 				 << DEV_DMA_BUFF_STS_SHIFT);
804 
805 		if (len > maxsize) {
806 			if (!hs_ep->index && !dir_in)
807 				desc->status |= (DEV_DMA_L | DEV_DMA_IOC);
808 
809 			desc->status |= (maxsize <<
810 						DEV_DMA_NBYTES_SHIFT & mask);
811 			desc->buf = dma_buff + offset;
812 
813 			len -= maxsize;
814 			offset += maxsize;
815 		} else {
816 			desc->status |= (DEV_DMA_L | DEV_DMA_IOC);
817 
818 			if (dir_in)
819 				desc->status |= (len % mps) ? DEV_DMA_SHORT :
820 					((hs_ep->send_zlp) ? DEV_DMA_SHORT : 0);
821 			if (len > maxsize)
822 				dev_err(hsotg->dev, "wrong len %d\n", len);
823 
824 			desc->status |=
825 				len << DEV_DMA_NBYTES_SHIFT & mask;
826 			desc->buf = dma_buff + offset;
827 		}
828 
829 		desc->status &= ~DEV_DMA_BUFF_STS_MASK;
830 		desc->status |= (DEV_DMA_BUFF_STS_HREADY
831 				 << DEV_DMA_BUFF_STS_SHIFT);
832 		desc++;
833 	}
834 }
835 
836 /*
837  * dwc2_gadget_fill_isoc_desc - fills next isochronous descriptor in chain.
838  * @hs_ep: The isochronous endpoint.
839  * @dma_buff: usb requests dma buffer.
840  * @len: usb request transfer length.
841  *
842  * Fills next free descriptor with the data of the arrived usb request,
843  * frame info, sets Last and IOC bits increments next_desc. If filled
844  * descriptor is not the first one, removes L bit from the previous descriptor
845  * status.
846  */
847 static int dwc2_gadget_fill_isoc_desc(struct dwc2_hsotg_ep *hs_ep,
848 				      dma_addr_t dma_buff, unsigned int len)
849 {
850 	struct dwc2_dma_desc *desc;
851 	struct dwc2_hsotg *hsotg = hs_ep->parent;
852 	u32 index;
853 	u32 maxsize = 0;
854 	u32 mask = 0;
855 	u8 pid = 0;
856 
857 	maxsize = dwc2_gadget_get_desc_params(hs_ep, &mask);
858 
859 	index = hs_ep->next_desc;
860 	desc = &hs_ep->desc_list[index];
861 
862 	/* Check if descriptor chain full */
863 	if ((desc->status >> DEV_DMA_BUFF_STS_SHIFT) ==
864 	    DEV_DMA_BUFF_STS_HREADY) {
865 		dev_dbg(hsotg->dev, "%s: desc chain full\n", __func__);
866 		return 1;
867 	}
868 
869 	/* Clear L bit of previous desc if more than one entries in the chain */
870 	if (hs_ep->next_desc)
871 		hs_ep->desc_list[index - 1].status &= ~DEV_DMA_L;
872 
873 	dev_dbg(hsotg->dev, "%s: Filling ep %d, dir %s isoc desc # %d\n",
874 		__func__, hs_ep->index, hs_ep->dir_in ? "in" : "out", index);
875 
876 	desc->status = 0;
877 	desc->status |= (DEV_DMA_BUFF_STS_HBUSY	<< DEV_DMA_BUFF_STS_SHIFT);
878 
879 	desc->buf = dma_buff;
880 	desc->status |= (DEV_DMA_L | DEV_DMA_IOC |
881 			 ((len << DEV_DMA_NBYTES_SHIFT) & mask));
882 
883 	if (hs_ep->dir_in) {
884 		if (len)
885 			pid = DIV_ROUND_UP(len, hs_ep->ep.maxpacket);
886 		else
887 			pid = 1;
888 		desc->status |= ((pid << DEV_DMA_ISOC_PID_SHIFT) &
889 				 DEV_DMA_ISOC_PID_MASK) |
890 				((len % hs_ep->ep.maxpacket) ?
891 				 DEV_DMA_SHORT : 0) |
892 				((hs_ep->target_frame <<
893 				  DEV_DMA_ISOC_FRNUM_SHIFT) &
894 				 DEV_DMA_ISOC_FRNUM_MASK);
895 	}
896 
897 	desc->status &= ~DEV_DMA_BUFF_STS_MASK;
898 	desc->status |= (DEV_DMA_BUFF_STS_HREADY << DEV_DMA_BUFF_STS_SHIFT);
899 
900 	/* Increment frame number by interval for IN */
901 	if (hs_ep->dir_in)
902 		dwc2_gadget_incr_frame_num(hs_ep);
903 
904 	/* Update index of last configured entry in the chain */
905 	hs_ep->next_desc++;
906 	if (hs_ep->next_desc >= MAX_DMA_DESC_NUM_GENERIC)
907 		hs_ep->next_desc = 0;
908 
909 	return 0;
910 }
911 
912 /*
913  * dwc2_gadget_start_isoc_ddma - start isochronous transfer in DDMA
914  * @hs_ep: The isochronous endpoint.
915  *
916  * Prepare descriptor chain for isochronous endpoints. Afterwards
917  * write DMA address to HW and enable the endpoint.
918  */
919 static void dwc2_gadget_start_isoc_ddma(struct dwc2_hsotg_ep *hs_ep)
920 {
921 	struct dwc2_hsotg *hsotg = hs_ep->parent;
922 	struct dwc2_hsotg_req *hs_req, *treq;
923 	int index = hs_ep->index;
924 	int ret;
925 	int i;
926 	u32 dma_reg;
927 	u32 depctl;
928 	u32 ctrl;
929 	struct dwc2_dma_desc *desc;
930 
931 	if (list_empty(&hs_ep->queue)) {
932 		hs_ep->target_frame = TARGET_FRAME_INITIAL;
933 		dev_dbg(hsotg->dev, "%s: No requests in queue\n", __func__);
934 		return;
935 	}
936 
937 	/* Initialize descriptor chain by Host Busy status */
938 	for (i = 0; i < MAX_DMA_DESC_NUM_GENERIC; i++) {
939 		desc = &hs_ep->desc_list[i];
940 		desc->status = 0;
941 		desc->status |= (DEV_DMA_BUFF_STS_HBUSY
942 				    << DEV_DMA_BUFF_STS_SHIFT);
943 	}
944 
945 	hs_ep->next_desc = 0;
946 	list_for_each_entry_safe(hs_req, treq, &hs_ep->queue, queue) {
947 		ret = dwc2_gadget_fill_isoc_desc(hs_ep, hs_req->req.dma,
948 						 hs_req->req.length);
949 		if (ret)
950 			break;
951 	}
952 
953 	hs_ep->compl_desc = 0;
954 	depctl = hs_ep->dir_in ? DIEPCTL(index) : DOEPCTL(index);
955 	dma_reg = hs_ep->dir_in ? DIEPDMA(index) : DOEPDMA(index);
956 
957 	/* write descriptor chain address to control register */
958 	dwc2_writel(hsotg, hs_ep->desc_list_dma, dma_reg);
959 
960 	ctrl = dwc2_readl(hsotg, depctl);
961 	ctrl |= DXEPCTL_EPENA | DXEPCTL_CNAK;
962 	dwc2_writel(hsotg, ctrl, depctl);
963 }
964 
965 /**
966  * dwc2_hsotg_start_req - start a USB request from an endpoint's queue
967  * @hsotg: The controller state.
968  * @hs_ep: The endpoint to process a request for
969  * @hs_req: The request to start.
970  * @continuing: True if we are doing more for the current request.
971  *
972  * Start the given request running by setting the endpoint registers
973  * appropriately, and writing any data to the FIFOs.
974  */
975 static void dwc2_hsotg_start_req(struct dwc2_hsotg *hsotg,
976 				 struct dwc2_hsotg_ep *hs_ep,
977 				struct dwc2_hsotg_req *hs_req,
978 				bool continuing)
979 {
980 	struct usb_request *ureq = &hs_req->req;
981 	int index = hs_ep->index;
982 	int dir_in = hs_ep->dir_in;
983 	u32 epctrl_reg;
984 	u32 epsize_reg;
985 	u32 epsize;
986 	u32 ctrl;
987 	unsigned int length;
988 	unsigned int packets;
989 	unsigned int maxreq;
990 	unsigned int dma_reg;
991 
992 	if (index != 0) {
993 		if (hs_ep->req && !continuing) {
994 			dev_err(hsotg->dev, "%s: active request\n", __func__);
995 			WARN_ON(1);
996 			return;
997 		} else if (hs_ep->req != hs_req && continuing) {
998 			dev_err(hsotg->dev,
999 				"%s: continue different req\n", __func__);
1000 			WARN_ON(1);
1001 			return;
1002 		}
1003 	}
1004 
1005 	dma_reg = dir_in ? DIEPDMA(index) : DOEPDMA(index);
1006 	epctrl_reg = dir_in ? DIEPCTL(index) : DOEPCTL(index);
1007 	epsize_reg = dir_in ? DIEPTSIZ(index) : DOEPTSIZ(index);
1008 
1009 	dev_dbg(hsotg->dev, "%s: DxEPCTL=0x%08x, ep %d, dir %s\n",
1010 		__func__, dwc2_readl(hsotg, epctrl_reg), index,
1011 		hs_ep->dir_in ? "in" : "out");
1012 
1013 	/* If endpoint is stalled, we will restart request later */
1014 	ctrl = dwc2_readl(hsotg, epctrl_reg);
1015 
1016 	if (index && ctrl & DXEPCTL_STALL) {
1017 		dev_warn(hsotg->dev, "%s: ep%d is stalled\n", __func__, index);
1018 		return;
1019 	}
1020 
1021 	length = ureq->length - ureq->actual;
1022 	dev_dbg(hsotg->dev, "ureq->length:%d ureq->actual:%d\n",
1023 		ureq->length, ureq->actual);
1024 
1025 	if (!using_desc_dma(hsotg))
1026 		maxreq = get_ep_limit(hs_ep);
1027 	else
1028 		maxreq = dwc2_gadget_get_chain_limit(hs_ep);
1029 
1030 	if (length > maxreq) {
1031 		int round = maxreq % hs_ep->ep.maxpacket;
1032 
1033 		dev_dbg(hsotg->dev, "%s: length %d, max-req %d, r %d\n",
1034 			__func__, length, maxreq, round);
1035 
1036 		/* round down to multiple of packets */
1037 		if (round)
1038 			maxreq -= round;
1039 
1040 		length = maxreq;
1041 	}
1042 
1043 	if (length)
1044 		packets = DIV_ROUND_UP(length, hs_ep->ep.maxpacket);
1045 	else
1046 		packets = 1;	/* send one packet if length is zero. */
1047 
1048 	if (hs_ep->isochronous && length > (hs_ep->mc * hs_ep->ep.maxpacket)) {
1049 		dev_err(hsotg->dev, "req length > maxpacket*mc\n");
1050 		return;
1051 	}
1052 
1053 	if (dir_in && index != 0)
1054 		if (hs_ep->isochronous)
1055 			epsize = DXEPTSIZ_MC(packets);
1056 		else
1057 			epsize = DXEPTSIZ_MC(1);
1058 	else
1059 		epsize = 0;
1060 
1061 	/*
1062 	 * zero length packet should be programmed on its own and should not
1063 	 * be counted in DIEPTSIZ.PktCnt with other packets.
1064 	 */
1065 	if (dir_in && ureq->zero && !continuing) {
1066 		/* Test if zlp is actually required. */
1067 		if ((ureq->length >= hs_ep->ep.maxpacket) &&
1068 		    !(ureq->length % hs_ep->ep.maxpacket))
1069 			hs_ep->send_zlp = 1;
1070 	}
1071 
1072 	epsize |= DXEPTSIZ_PKTCNT(packets);
1073 	epsize |= DXEPTSIZ_XFERSIZE(length);
1074 
1075 	dev_dbg(hsotg->dev, "%s: %d@%d/%d, 0x%08x => 0x%08x\n",
1076 		__func__, packets, length, ureq->length, epsize, epsize_reg);
1077 
1078 	/* store the request as the current one we're doing */
1079 	hs_ep->req = hs_req;
1080 
1081 	if (using_desc_dma(hsotg)) {
1082 		u32 offset = 0;
1083 		u32 mps = hs_ep->ep.maxpacket;
1084 
1085 		/* Adjust length: EP0 - MPS, other OUT EPs - multiple of MPS */
1086 		if (!dir_in) {
1087 			if (!index)
1088 				length = mps;
1089 			else if (length % mps)
1090 				length += (mps - (length % mps));
1091 		}
1092 
1093 		/*
1094 		 * If more data to send, adjust DMA for EP0 out data stage.
1095 		 * ureq->dma stays unchanged, hence increment it by already
1096 		 * passed passed data count before starting new transaction.
1097 		 */
1098 		if (!index && hsotg->ep0_state == DWC2_EP0_DATA_OUT &&
1099 		    continuing)
1100 			offset = ureq->actual;
1101 
1102 		/* Fill DDMA chain entries */
1103 		dwc2_gadget_config_nonisoc_xfer_ddma(hs_ep, ureq->dma + offset,
1104 						     length);
1105 
1106 		/* write descriptor chain address to control register */
1107 		dwc2_writel(hsotg, hs_ep->desc_list_dma, dma_reg);
1108 
1109 		dev_dbg(hsotg->dev, "%s: %08x pad => 0x%08x\n",
1110 			__func__, (u32)hs_ep->desc_list_dma, dma_reg);
1111 	} else {
1112 		/* write size / packets */
1113 		dwc2_writel(hsotg, epsize, epsize_reg);
1114 
1115 		if (using_dma(hsotg) && !continuing && (length != 0)) {
1116 			/*
1117 			 * write DMA address to control register, buffer
1118 			 * already synced by dwc2_hsotg_ep_queue().
1119 			 */
1120 
1121 			dwc2_writel(hsotg, ureq->dma, dma_reg);
1122 
1123 			dev_dbg(hsotg->dev, "%s: %pad => 0x%08x\n",
1124 				__func__, &ureq->dma, dma_reg);
1125 		}
1126 	}
1127 
1128 	if (hs_ep->isochronous && hs_ep->interval == 1) {
1129 		hs_ep->target_frame = dwc2_hsotg_read_frameno(hsotg);
1130 		dwc2_gadget_incr_frame_num(hs_ep);
1131 
1132 		if (hs_ep->target_frame & 0x1)
1133 			ctrl |= DXEPCTL_SETODDFR;
1134 		else
1135 			ctrl |= DXEPCTL_SETEVENFR;
1136 	}
1137 
1138 	ctrl |= DXEPCTL_EPENA;	/* ensure ep enabled */
1139 
1140 	dev_dbg(hsotg->dev, "ep0 state:%d\n", hsotg->ep0_state);
1141 
1142 	/* For Setup request do not clear NAK */
1143 	if (!(index == 0 && hsotg->ep0_state == DWC2_EP0_SETUP))
1144 		ctrl |= DXEPCTL_CNAK;	/* clear NAK set by core */
1145 
1146 	dev_dbg(hsotg->dev, "%s: DxEPCTL=0x%08x\n", __func__, ctrl);
1147 	dwc2_writel(hsotg, ctrl, epctrl_reg);
1148 
1149 	/*
1150 	 * set these, it seems that DMA support increments past the end
1151 	 * of the packet buffer so we need to calculate the length from
1152 	 * this information.
1153 	 */
1154 	hs_ep->size_loaded = length;
1155 	hs_ep->last_load = ureq->actual;
1156 
1157 	if (dir_in && !using_dma(hsotg)) {
1158 		/* set these anyway, we may need them for non-periodic in */
1159 		hs_ep->fifo_load = 0;
1160 
1161 		dwc2_hsotg_write_fifo(hsotg, hs_ep, hs_req);
1162 	}
1163 
1164 	/*
1165 	 * Note, trying to clear the NAK here causes problems with transmit
1166 	 * on the S3C6400 ending up with the TXFIFO becoming full.
1167 	 */
1168 
1169 	/* check ep is enabled */
1170 	if (!(dwc2_readl(hsotg, epctrl_reg) & DXEPCTL_EPENA))
1171 		dev_dbg(hsotg->dev,
1172 			"ep%d: failed to become enabled (DXEPCTL=0x%08x)?\n",
1173 			 index, dwc2_readl(hsotg, epctrl_reg));
1174 
1175 	dev_dbg(hsotg->dev, "%s: DXEPCTL=0x%08x\n",
1176 		__func__, dwc2_readl(hsotg, epctrl_reg));
1177 
1178 	/* enable ep interrupts */
1179 	dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index, hs_ep->dir_in, 1);
1180 }
1181 
1182 /**
1183  * dwc2_hsotg_map_dma - map the DMA memory being used for the request
1184  * @hsotg: The device state.
1185  * @hs_ep: The endpoint the request is on.
1186  * @req: The request being processed.
1187  *
1188  * We've been asked to queue a request, so ensure that the memory buffer
1189  * is correctly setup for DMA. If we've been passed an extant DMA address
1190  * then ensure the buffer has been synced to memory. If our buffer has no
1191  * DMA memory, then we map the memory and mark our request to allow us to
1192  * cleanup on completion.
1193  */
1194 static int dwc2_hsotg_map_dma(struct dwc2_hsotg *hsotg,
1195 			      struct dwc2_hsotg_ep *hs_ep,
1196 			     struct usb_request *req)
1197 {
1198 	int ret;
1199 
1200 	ret = usb_gadget_map_request(&hsotg->gadget, req, hs_ep->dir_in);
1201 	if (ret)
1202 		goto dma_error;
1203 
1204 	return 0;
1205 
1206 dma_error:
1207 	dev_err(hsotg->dev, "%s: failed to map buffer %p, %d bytes\n",
1208 		__func__, req->buf, req->length);
1209 
1210 	return -EIO;
1211 }
1212 
1213 static int dwc2_hsotg_handle_unaligned_buf_start(struct dwc2_hsotg *hsotg,
1214 						 struct dwc2_hsotg_ep *hs_ep,
1215 						 struct dwc2_hsotg_req *hs_req)
1216 {
1217 	void *req_buf = hs_req->req.buf;
1218 
1219 	/* If dma is not being used or buffer is aligned */
1220 	if (!using_dma(hsotg) || !((long)req_buf & 3))
1221 		return 0;
1222 
1223 	WARN_ON(hs_req->saved_req_buf);
1224 
1225 	dev_dbg(hsotg->dev, "%s: %s: buf=%p length=%d\n", __func__,
1226 		hs_ep->ep.name, req_buf, hs_req->req.length);
1227 
1228 	hs_req->req.buf = kmalloc(hs_req->req.length, GFP_ATOMIC);
1229 	if (!hs_req->req.buf) {
1230 		hs_req->req.buf = req_buf;
1231 		dev_err(hsotg->dev,
1232 			"%s: unable to allocate memory for bounce buffer\n",
1233 			__func__);
1234 		return -ENOMEM;
1235 	}
1236 
1237 	/* Save actual buffer */
1238 	hs_req->saved_req_buf = req_buf;
1239 
1240 	if (hs_ep->dir_in)
1241 		memcpy(hs_req->req.buf, req_buf, hs_req->req.length);
1242 	return 0;
1243 }
1244 
1245 static void
1246 dwc2_hsotg_handle_unaligned_buf_complete(struct dwc2_hsotg *hsotg,
1247 					 struct dwc2_hsotg_ep *hs_ep,
1248 					 struct dwc2_hsotg_req *hs_req)
1249 {
1250 	/* If dma is not being used or buffer was aligned */
1251 	if (!using_dma(hsotg) || !hs_req->saved_req_buf)
1252 		return;
1253 
1254 	dev_dbg(hsotg->dev, "%s: %s: status=%d actual-length=%d\n", __func__,
1255 		hs_ep->ep.name, hs_req->req.status, hs_req->req.actual);
1256 
1257 	/* Copy data from bounce buffer on successful out transfer */
1258 	if (!hs_ep->dir_in && !hs_req->req.status)
1259 		memcpy(hs_req->saved_req_buf, hs_req->req.buf,
1260 		       hs_req->req.actual);
1261 
1262 	/* Free bounce buffer */
1263 	kfree(hs_req->req.buf);
1264 
1265 	hs_req->req.buf = hs_req->saved_req_buf;
1266 	hs_req->saved_req_buf = NULL;
1267 }
1268 
1269 /**
1270  * dwc2_gadget_target_frame_elapsed - Checks target frame
1271  * @hs_ep: The driver endpoint to check
1272  *
1273  * Returns 1 if targeted frame elapsed. If returned 1 then we need to drop
1274  * corresponding transfer.
1275  */
1276 static bool dwc2_gadget_target_frame_elapsed(struct dwc2_hsotg_ep *hs_ep)
1277 {
1278 	struct dwc2_hsotg *hsotg = hs_ep->parent;
1279 	u32 target_frame = hs_ep->target_frame;
1280 	u32 current_frame = hsotg->frame_number;
1281 	bool frame_overrun = hs_ep->frame_overrun;
1282 
1283 	if (!frame_overrun && current_frame >= target_frame)
1284 		return true;
1285 
1286 	if (frame_overrun && current_frame >= target_frame &&
1287 	    ((current_frame - target_frame) < DSTS_SOFFN_LIMIT / 2))
1288 		return true;
1289 
1290 	return false;
1291 }
1292 
1293 /*
1294  * dwc2_gadget_set_ep0_desc_chain - Set EP's desc chain pointers
1295  * @hsotg: The driver state
1296  * @hs_ep: the ep descriptor chain is for
1297  *
1298  * Called to update EP0 structure's pointers depend on stage of
1299  * control transfer.
1300  */
1301 static int dwc2_gadget_set_ep0_desc_chain(struct dwc2_hsotg *hsotg,
1302 					  struct dwc2_hsotg_ep *hs_ep)
1303 {
1304 	switch (hsotg->ep0_state) {
1305 	case DWC2_EP0_SETUP:
1306 	case DWC2_EP0_STATUS_OUT:
1307 		hs_ep->desc_list = hsotg->setup_desc[0];
1308 		hs_ep->desc_list_dma = hsotg->setup_desc_dma[0];
1309 		break;
1310 	case DWC2_EP0_DATA_IN:
1311 	case DWC2_EP0_STATUS_IN:
1312 		hs_ep->desc_list = hsotg->ctrl_in_desc;
1313 		hs_ep->desc_list_dma = hsotg->ctrl_in_desc_dma;
1314 		break;
1315 	case DWC2_EP0_DATA_OUT:
1316 		hs_ep->desc_list = hsotg->ctrl_out_desc;
1317 		hs_ep->desc_list_dma = hsotg->ctrl_out_desc_dma;
1318 		break;
1319 	default:
1320 		dev_err(hsotg->dev, "invalid EP 0 state in queue %d\n",
1321 			hsotg->ep0_state);
1322 		return -EINVAL;
1323 	}
1324 
1325 	return 0;
1326 }
1327 
1328 static int dwc2_hsotg_ep_queue(struct usb_ep *ep, struct usb_request *req,
1329 			       gfp_t gfp_flags)
1330 {
1331 	struct dwc2_hsotg_req *hs_req = our_req(req);
1332 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
1333 	struct dwc2_hsotg *hs = hs_ep->parent;
1334 	bool first;
1335 	int ret;
1336 	u32 maxsize = 0;
1337 	u32 mask = 0;
1338 
1339 
1340 	dev_dbg(hs->dev, "%s: req %p: %d@%p, noi=%d, zero=%d, snok=%d\n",
1341 		ep->name, req, req->length, req->buf, req->no_interrupt,
1342 		req->zero, req->short_not_ok);
1343 
1344 	/* Prevent new request submission when controller is suspended */
1345 	if (hs->lx_state != DWC2_L0) {
1346 		dev_dbg(hs->dev, "%s: submit request only in active state\n",
1347 			__func__);
1348 		return -EAGAIN;
1349 	}
1350 
1351 	/* initialise status of the request */
1352 	INIT_LIST_HEAD(&hs_req->queue);
1353 	req->actual = 0;
1354 	req->status = -EINPROGRESS;
1355 
1356 	/* In DDMA mode for ISOC's don't queue request if length greater
1357 	 * than descriptor limits.
1358 	 */
1359 	if (using_desc_dma(hs) && hs_ep->isochronous) {
1360 		maxsize = dwc2_gadget_get_desc_params(hs_ep, &mask);
1361 		if (hs_ep->dir_in && req->length > maxsize) {
1362 			dev_err(hs->dev, "wrong length %d (maxsize=%d)\n",
1363 				req->length, maxsize);
1364 			return -EINVAL;
1365 		}
1366 
1367 		if (!hs_ep->dir_in && req->length > hs_ep->ep.maxpacket) {
1368 			dev_err(hs->dev, "ISOC OUT: wrong length %d (mps=%d)\n",
1369 				req->length, hs_ep->ep.maxpacket);
1370 			return -EINVAL;
1371 		}
1372 	}
1373 
1374 	ret = dwc2_hsotg_handle_unaligned_buf_start(hs, hs_ep, hs_req);
1375 	if (ret)
1376 		return ret;
1377 
1378 	/* if we're using DMA, sync the buffers as necessary */
1379 	if (using_dma(hs)) {
1380 		ret = dwc2_hsotg_map_dma(hs, hs_ep, req);
1381 		if (ret)
1382 			return ret;
1383 	}
1384 	/* If using descriptor DMA configure EP0 descriptor chain pointers */
1385 	if (using_desc_dma(hs) && !hs_ep->index) {
1386 		ret = dwc2_gadget_set_ep0_desc_chain(hs, hs_ep);
1387 		if (ret)
1388 			return ret;
1389 	}
1390 
1391 	first = list_empty(&hs_ep->queue);
1392 	list_add_tail(&hs_req->queue, &hs_ep->queue);
1393 
1394 	/*
1395 	 * Handle DDMA isochronous transfers separately - just add new entry
1396 	 * to the descriptor chain.
1397 	 * Transfer will be started once SW gets either one of NAK or
1398 	 * OutTknEpDis interrupts.
1399 	 */
1400 	if (using_desc_dma(hs) && hs_ep->isochronous) {
1401 		if (hs_ep->target_frame != TARGET_FRAME_INITIAL) {
1402 			dwc2_gadget_fill_isoc_desc(hs_ep, hs_req->req.dma,
1403 						   hs_req->req.length);
1404 		}
1405 		return 0;
1406 	}
1407 
1408 	if (first) {
1409 		if (!hs_ep->isochronous) {
1410 			dwc2_hsotg_start_req(hs, hs_ep, hs_req, false);
1411 			return 0;
1412 		}
1413 
1414 		/* Update current frame number value. */
1415 		hs->frame_number = dwc2_hsotg_read_frameno(hs);
1416 		while (dwc2_gadget_target_frame_elapsed(hs_ep)) {
1417 			dwc2_gadget_incr_frame_num(hs_ep);
1418 			/* Update current frame number value once more as it
1419 			 * changes here.
1420 			 */
1421 			hs->frame_number = dwc2_hsotg_read_frameno(hs);
1422 		}
1423 
1424 		if (hs_ep->target_frame != TARGET_FRAME_INITIAL)
1425 			dwc2_hsotg_start_req(hs, hs_ep, hs_req, false);
1426 	}
1427 	return 0;
1428 }
1429 
1430 static int dwc2_hsotg_ep_queue_lock(struct usb_ep *ep, struct usb_request *req,
1431 				    gfp_t gfp_flags)
1432 {
1433 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
1434 	struct dwc2_hsotg *hs = hs_ep->parent;
1435 	unsigned long flags = 0;
1436 	int ret = 0;
1437 
1438 	spin_lock_irqsave(&hs->lock, flags);
1439 	ret = dwc2_hsotg_ep_queue(ep, req, gfp_flags);
1440 	spin_unlock_irqrestore(&hs->lock, flags);
1441 
1442 	return ret;
1443 }
1444 
1445 static void dwc2_hsotg_ep_free_request(struct usb_ep *ep,
1446 				       struct usb_request *req)
1447 {
1448 	struct dwc2_hsotg_req *hs_req = our_req(req);
1449 
1450 	kfree(hs_req);
1451 }
1452 
1453 /**
1454  * dwc2_hsotg_complete_oursetup - setup completion callback
1455  * @ep: The endpoint the request was on.
1456  * @req: The request completed.
1457  *
1458  * Called on completion of any requests the driver itself
1459  * submitted that need cleaning up.
1460  */
1461 static void dwc2_hsotg_complete_oursetup(struct usb_ep *ep,
1462 					 struct usb_request *req)
1463 {
1464 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
1465 	struct dwc2_hsotg *hsotg = hs_ep->parent;
1466 
1467 	dev_dbg(hsotg->dev, "%s: ep %p, req %p\n", __func__, ep, req);
1468 
1469 	dwc2_hsotg_ep_free_request(ep, req);
1470 }
1471 
1472 /**
1473  * ep_from_windex - convert control wIndex value to endpoint
1474  * @hsotg: The driver state.
1475  * @windex: The control request wIndex field (in host order).
1476  *
1477  * Convert the given wIndex into a pointer to an driver endpoint
1478  * structure, or return NULL if it is not a valid endpoint.
1479  */
1480 static struct dwc2_hsotg_ep *ep_from_windex(struct dwc2_hsotg *hsotg,
1481 					    u32 windex)
1482 {
1483 	struct dwc2_hsotg_ep *ep;
1484 	int dir = (windex & USB_DIR_IN) ? 1 : 0;
1485 	int idx = windex & 0x7F;
1486 
1487 	if (windex >= 0x100)
1488 		return NULL;
1489 
1490 	if (idx > hsotg->num_of_eps)
1491 		return NULL;
1492 
1493 	ep = index_to_ep(hsotg, idx, dir);
1494 
1495 	if (idx && ep->dir_in != dir)
1496 		return NULL;
1497 
1498 	return ep;
1499 }
1500 
1501 /**
1502  * dwc2_hsotg_set_test_mode - Enable usb Test Modes
1503  * @hsotg: The driver state.
1504  * @testmode: requested usb test mode
1505  * Enable usb Test Mode requested by the Host.
1506  */
1507 int dwc2_hsotg_set_test_mode(struct dwc2_hsotg *hsotg, int testmode)
1508 {
1509 	int dctl = dwc2_readl(hsotg, DCTL);
1510 
1511 	dctl &= ~DCTL_TSTCTL_MASK;
1512 	switch (testmode) {
1513 	case TEST_J:
1514 	case TEST_K:
1515 	case TEST_SE0_NAK:
1516 	case TEST_PACKET:
1517 	case TEST_FORCE_EN:
1518 		dctl |= testmode << DCTL_TSTCTL_SHIFT;
1519 		break;
1520 	default:
1521 		return -EINVAL;
1522 	}
1523 	dwc2_writel(hsotg, dctl, DCTL);
1524 	return 0;
1525 }
1526 
1527 /**
1528  * dwc2_hsotg_send_reply - send reply to control request
1529  * @hsotg: The device state
1530  * @ep: Endpoint 0
1531  * @buff: Buffer for request
1532  * @length: Length of reply.
1533  *
1534  * Create a request and queue it on the given endpoint. This is useful as
1535  * an internal method of sending replies to certain control requests, etc.
1536  */
1537 static int dwc2_hsotg_send_reply(struct dwc2_hsotg *hsotg,
1538 				 struct dwc2_hsotg_ep *ep,
1539 				void *buff,
1540 				int length)
1541 {
1542 	struct usb_request *req;
1543 	int ret;
1544 
1545 	dev_dbg(hsotg->dev, "%s: buff %p, len %d\n", __func__, buff, length);
1546 
1547 	req = dwc2_hsotg_ep_alloc_request(&ep->ep, GFP_ATOMIC);
1548 	hsotg->ep0_reply = req;
1549 	if (!req) {
1550 		dev_warn(hsotg->dev, "%s: cannot alloc req\n", __func__);
1551 		return -ENOMEM;
1552 	}
1553 
1554 	req->buf = hsotg->ep0_buff;
1555 	req->length = length;
1556 	/*
1557 	 * zero flag is for sending zlp in DATA IN stage. It has no impact on
1558 	 * STATUS stage.
1559 	 */
1560 	req->zero = 0;
1561 	req->complete = dwc2_hsotg_complete_oursetup;
1562 
1563 	if (length)
1564 		memcpy(req->buf, buff, length);
1565 
1566 	ret = dwc2_hsotg_ep_queue(&ep->ep, req, GFP_ATOMIC);
1567 	if (ret) {
1568 		dev_warn(hsotg->dev, "%s: cannot queue req\n", __func__);
1569 		return ret;
1570 	}
1571 
1572 	return 0;
1573 }
1574 
1575 /**
1576  * dwc2_hsotg_process_req_status - process request GET_STATUS
1577  * @hsotg: The device state
1578  * @ctrl: USB control request
1579  */
1580 static int dwc2_hsotg_process_req_status(struct dwc2_hsotg *hsotg,
1581 					 struct usb_ctrlrequest *ctrl)
1582 {
1583 	struct dwc2_hsotg_ep *ep0 = hsotg->eps_out[0];
1584 	struct dwc2_hsotg_ep *ep;
1585 	__le16 reply;
1586 	int ret;
1587 
1588 	dev_dbg(hsotg->dev, "%s: USB_REQ_GET_STATUS\n", __func__);
1589 
1590 	if (!ep0->dir_in) {
1591 		dev_warn(hsotg->dev, "%s: direction out?\n", __func__);
1592 		return -EINVAL;
1593 	}
1594 
1595 	switch (ctrl->bRequestType & USB_RECIP_MASK) {
1596 	case USB_RECIP_DEVICE:
1597 		/*
1598 		 * bit 0 => self powered
1599 		 * bit 1 => remote wakeup
1600 		 */
1601 		reply = cpu_to_le16(0);
1602 		break;
1603 
1604 	case USB_RECIP_INTERFACE:
1605 		/* currently, the data result should be zero */
1606 		reply = cpu_to_le16(0);
1607 		break;
1608 
1609 	case USB_RECIP_ENDPOINT:
1610 		ep = ep_from_windex(hsotg, le16_to_cpu(ctrl->wIndex));
1611 		if (!ep)
1612 			return -ENOENT;
1613 
1614 		reply = cpu_to_le16(ep->halted ? 1 : 0);
1615 		break;
1616 
1617 	default:
1618 		return 0;
1619 	}
1620 
1621 	if (le16_to_cpu(ctrl->wLength) != 2)
1622 		return -EINVAL;
1623 
1624 	ret = dwc2_hsotg_send_reply(hsotg, ep0, &reply, 2);
1625 	if (ret) {
1626 		dev_err(hsotg->dev, "%s: failed to send reply\n", __func__);
1627 		return ret;
1628 	}
1629 
1630 	return 1;
1631 }
1632 
1633 static int dwc2_hsotg_ep_sethalt(struct usb_ep *ep, int value, bool now);
1634 
1635 /**
1636  * get_ep_head - return the first request on the endpoint
1637  * @hs_ep: The controller endpoint to get
1638  *
1639  * Get the first request on the endpoint.
1640  */
1641 static struct dwc2_hsotg_req *get_ep_head(struct dwc2_hsotg_ep *hs_ep)
1642 {
1643 	return list_first_entry_or_null(&hs_ep->queue, struct dwc2_hsotg_req,
1644 					queue);
1645 }
1646 
1647 /**
1648  * dwc2_gadget_start_next_request - Starts next request from ep queue
1649  * @hs_ep: Endpoint structure
1650  *
1651  * If queue is empty and EP is ISOC-OUT - unmasks OUTTKNEPDIS which is masked
1652  * in its handler. Hence we need to unmask it here to be able to do
1653  * resynchronization.
1654  */
1655 static void dwc2_gadget_start_next_request(struct dwc2_hsotg_ep *hs_ep)
1656 {
1657 	u32 mask;
1658 	struct dwc2_hsotg *hsotg = hs_ep->parent;
1659 	int dir_in = hs_ep->dir_in;
1660 	struct dwc2_hsotg_req *hs_req;
1661 	u32 epmsk_reg = dir_in ? DIEPMSK : DOEPMSK;
1662 
1663 	if (!list_empty(&hs_ep->queue)) {
1664 		hs_req = get_ep_head(hs_ep);
1665 		dwc2_hsotg_start_req(hsotg, hs_ep, hs_req, false);
1666 		return;
1667 	}
1668 	if (!hs_ep->isochronous)
1669 		return;
1670 
1671 	if (dir_in) {
1672 		dev_dbg(hsotg->dev, "%s: No more ISOC-IN requests\n",
1673 			__func__);
1674 	} else {
1675 		dev_dbg(hsotg->dev, "%s: No more ISOC-OUT requests\n",
1676 			__func__);
1677 		mask = dwc2_readl(hsotg, epmsk_reg);
1678 		mask |= DOEPMSK_OUTTKNEPDISMSK;
1679 		dwc2_writel(hsotg, mask, epmsk_reg);
1680 	}
1681 }
1682 
1683 /**
1684  * dwc2_hsotg_process_req_feature - process request {SET,CLEAR}_FEATURE
1685  * @hsotg: The device state
1686  * @ctrl: USB control request
1687  */
1688 static int dwc2_hsotg_process_req_feature(struct dwc2_hsotg *hsotg,
1689 					  struct usb_ctrlrequest *ctrl)
1690 {
1691 	struct dwc2_hsotg_ep *ep0 = hsotg->eps_out[0];
1692 	struct dwc2_hsotg_req *hs_req;
1693 	bool set = (ctrl->bRequest == USB_REQ_SET_FEATURE);
1694 	struct dwc2_hsotg_ep *ep;
1695 	int ret;
1696 	bool halted;
1697 	u32 recip;
1698 	u32 wValue;
1699 	u32 wIndex;
1700 
1701 	dev_dbg(hsotg->dev, "%s: %s_FEATURE\n",
1702 		__func__, set ? "SET" : "CLEAR");
1703 
1704 	wValue = le16_to_cpu(ctrl->wValue);
1705 	wIndex = le16_to_cpu(ctrl->wIndex);
1706 	recip = ctrl->bRequestType & USB_RECIP_MASK;
1707 
1708 	switch (recip) {
1709 	case USB_RECIP_DEVICE:
1710 		switch (wValue) {
1711 		case USB_DEVICE_REMOTE_WAKEUP:
1712 			hsotg->remote_wakeup_allowed = 1;
1713 			break;
1714 
1715 		case USB_DEVICE_TEST_MODE:
1716 			if ((wIndex & 0xff) != 0)
1717 				return -EINVAL;
1718 			if (!set)
1719 				return -EINVAL;
1720 
1721 			hsotg->test_mode = wIndex >> 8;
1722 			ret = dwc2_hsotg_send_reply(hsotg, ep0, NULL, 0);
1723 			if (ret) {
1724 				dev_err(hsotg->dev,
1725 					"%s: failed to send reply\n", __func__);
1726 				return ret;
1727 			}
1728 			break;
1729 		default:
1730 			return -ENOENT;
1731 		}
1732 		break;
1733 
1734 	case USB_RECIP_ENDPOINT:
1735 		ep = ep_from_windex(hsotg, wIndex);
1736 		if (!ep) {
1737 			dev_dbg(hsotg->dev, "%s: no endpoint for 0x%04x\n",
1738 				__func__, wIndex);
1739 			return -ENOENT;
1740 		}
1741 
1742 		switch (wValue) {
1743 		case USB_ENDPOINT_HALT:
1744 			halted = ep->halted;
1745 
1746 			dwc2_hsotg_ep_sethalt(&ep->ep, set, true);
1747 
1748 			ret = dwc2_hsotg_send_reply(hsotg, ep0, NULL, 0);
1749 			if (ret) {
1750 				dev_err(hsotg->dev,
1751 					"%s: failed to send reply\n", __func__);
1752 				return ret;
1753 			}
1754 
1755 			/*
1756 			 * we have to complete all requests for ep if it was
1757 			 * halted, and the halt was cleared by CLEAR_FEATURE
1758 			 */
1759 
1760 			if (!set && halted) {
1761 				/*
1762 				 * If we have request in progress,
1763 				 * then complete it
1764 				 */
1765 				if (ep->req) {
1766 					hs_req = ep->req;
1767 					ep->req = NULL;
1768 					list_del_init(&hs_req->queue);
1769 					if (hs_req->req.complete) {
1770 						spin_unlock(&hsotg->lock);
1771 						usb_gadget_giveback_request(
1772 							&ep->ep, &hs_req->req);
1773 						spin_lock(&hsotg->lock);
1774 					}
1775 				}
1776 
1777 				/* If we have pending request, then start it */
1778 				if (!ep->req)
1779 					dwc2_gadget_start_next_request(ep);
1780 			}
1781 
1782 			break;
1783 
1784 		default:
1785 			return -ENOENT;
1786 		}
1787 		break;
1788 	default:
1789 		return -ENOENT;
1790 	}
1791 	return 1;
1792 }
1793 
1794 static void dwc2_hsotg_enqueue_setup(struct dwc2_hsotg *hsotg);
1795 
1796 /**
1797  * dwc2_hsotg_stall_ep0 - stall ep0
1798  * @hsotg: The device state
1799  *
1800  * Set stall for ep0 as response for setup request.
1801  */
1802 static void dwc2_hsotg_stall_ep0(struct dwc2_hsotg *hsotg)
1803 {
1804 	struct dwc2_hsotg_ep *ep0 = hsotg->eps_out[0];
1805 	u32 reg;
1806 	u32 ctrl;
1807 
1808 	dev_dbg(hsotg->dev, "ep0 stall (dir=%d)\n", ep0->dir_in);
1809 	reg = (ep0->dir_in) ? DIEPCTL0 : DOEPCTL0;
1810 
1811 	/*
1812 	 * DxEPCTL_Stall will be cleared by EP once it has
1813 	 * taken effect, so no need to clear later.
1814 	 */
1815 
1816 	ctrl = dwc2_readl(hsotg, reg);
1817 	ctrl |= DXEPCTL_STALL;
1818 	ctrl |= DXEPCTL_CNAK;
1819 	dwc2_writel(hsotg, ctrl, reg);
1820 
1821 	dev_dbg(hsotg->dev,
1822 		"written DXEPCTL=0x%08x to %08x (DXEPCTL=0x%08x)\n",
1823 		ctrl, reg, dwc2_readl(hsotg, reg));
1824 
1825 	 /*
1826 	  * complete won't be called, so we enqueue
1827 	  * setup request here
1828 	  */
1829 	 dwc2_hsotg_enqueue_setup(hsotg);
1830 }
1831 
1832 /**
1833  * dwc2_hsotg_process_control - process a control request
1834  * @hsotg: The device state
1835  * @ctrl: The control request received
1836  *
1837  * The controller has received the SETUP phase of a control request, and
1838  * needs to work out what to do next (and whether to pass it on to the
1839  * gadget driver).
1840  */
1841 static void dwc2_hsotg_process_control(struct dwc2_hsotg *hsotg,
1842 				       struct usb_ctrlrequest *ctrl)
1843 {
1844 	struct dwc2_hsotg_ep *ep0 = hsotg->eps_out[0];
1845 	int ret = 0;
1846 	u32 dcfg;
1847 
1848 	dev_dbg(hsotg->dev,
1849 		"ctrl Type=%02x, Req=%02x, V=%04x, I=%04x, L=%04x\n",
1850 		ctrl->bRequestType, ctrl->bRequest, ctrl->wValue,
1851 		ctrl->wIndex, ctrl->wLength);
1852 
1853 	if (ctrl->wLength == 0) {
1854 		ep0->dir_in = 1;
1855 		hsotg->ep0_state = DWC2_EP0_STATUS_IN;
1856 	} else if (ctrl->bRequestType & USB_DIR_IN) {
1857 		ep0->dir_in = 1;
1858 		hsotg->ep0_state = DWC2_EP0_DATA_IN;
1859 	} else {
1860 		ep0->dir_in = 0;
1861 		hsotg->ep0_state = DWC2_EP0_DATA_OUT;
1862 	}
1863 
1864 	if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) {
1865 		switch (ctrl->bRequest) {
1866 		case USB_REQ_SET_ADDRESS:
1867 			hsotg->connected = 1;
1868 			dcfg = dwc2_readl(hsotg, DCFG);
1869 			dcfg &= ~DCFG_DEVADDR_MASK;
1870 			dcfg |= (le16_to_cpu(ctrl->wValue) <<
1871 				 DCFG_DEVADDR_SHIFT) & DCFG_DEVADDR_MASK;
1872 			dwc2_writel(hsotg, dcfg, DCFG);
1873 
1874 			dev_info(hsotg->dev, "new address %d\n", ctrl->wValue);
1875 
1876 			ret = dwc2_hsotg_send_reply(hsotg, ep0, NULL, 0);
1877 			return;
1878 
1879 		case USB_REQ_GET_STATUS:
1880 			ret = dwc2_hsotg_process_req_status(hsotg, ctrl);
1881 			break;
1882 
1883 		case USB_REQ_CLEAR_FEATURE:
1884 		case USB_REQ_SET_FEATURE:
1885 			ret = dwc2_hsotg_process_req_feature(hsotg, ctrl);
1886 			break;
1887 		}
1888 	}
1889 
1890 	/* as a fallback, try delivering it to the driver to deal with */
1891 
1892 	if (ret == 0 && hsotg->driver) {
1893 		spin_unlock(&hsotg->lock);
1894 		ret = hsotg->driver->setup(&hsotg->gadget, ctrl);
1895 		spin_lock(&hsotg->lock);
1896 		if (ret < 0)
1897 			dev_dbg(hsotg->dev, "driver->setup() ret %d\n", ret);
1898 	}
1899 
1900 	/*
1901 	 * the request is either unhandlable, or is not formatted correctly
1902 	 * so respond with a STALL for the status stage to indicate failure.
1903 	 */
1904 
1905 	if (ret < 0)
1906 		dwc2_hsotg_stall_ep0(hsotg);
1907 }
1908 
1909 /**
1910  * dwc2_hsotg_complete_setup - completion of a setup transfer
1911  * @ep: The endpoint the request was on.
1912  * @req: The request completed.
1913  *
1914  * Called on completion of any requests the driver itself submitted for
1915  * EP0 setup packets
1916  */
1917 static void dwc2_hsotg_complete_setup(struct usb_ep *ep,
1918 				      struct usb_request *req)
1919 {
1920 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
1921 	struct dwc2_hsotg *hsotg = hs_ep->parent;
1922 
1923 	if (req->status < 0) {
1924 		dev_dbg(hsotg->dev, "%s: failed %d\n", __func__, req->status);
1925 		return;
1926 	}
1927 
1928 	spin_lock(&hsotg->lock);
1929 	if (req->actual == 0)
1930 		dwc2_hsotg_enqueue_setup(hsotg);
1931 	else
1932 		dwc2_hsotg_process_control(hsotg, req->buf);
1933 	spin_unlock(&hsotg->lock);
1934 }
1935 
1936 /**
1937  * dwc2_hsotg_enqueue_setup - start a request for EP0 packets
1938  * @hsotg: The device state.
1939  *
1940  * Enqueue a request on EP0 if necessary to received any SETUP packets
1941  * received from the host.
1942  */
1943 static void dwc2_hsotg_enqueue_setup(struct dwc2_hsotg *hsotg)
1944 {
1945 	struct usb_request *req = hsotg->ctrl_req;
1946 	struct dwc2_hsotg_req *hs_req = our_req(req);
1947 	int ret;
1948 
1949 	dev_dbg(hsotg->dev, "%s: queueing setup request\n", __func__);
1950 
1951 	req->zero = 0;
1952 	req->length = 8;
1953 	req->buf = hsotg->ctrl_buff;
1954 	req->complete = dwc2_hsotg_complete_setup;
1955 
1956 	if (!list_empty(&hs_req->queue)) {
1957 		dev_dbg(hsotg->dev, "%s already queued???\n", __func__);
1958 		return;
1959 	}
1960 
1961 	hsotg->eps_out[0]->dir_in = 0;
1962 	hsotg->eps_out[0]->send_zlp = 0;
1963 	hsotg->ep0_state = DWC2_EP0_SETUP;
1964 
1965 	ret = dwc2_hsotg_ep_queue(&hsotg->eps_out[0]->ep, req, GFP_ATOMIC);
1966 	if (ret < 0) {
1967 		dev_err(hsotg->dev, "%s: failed queue (%d)\n", __func__, ret);
1968 		/*
1969 		 * Don't think there's much we can do other than watch the
1970 		 * driver fail.
1971 		 */
1972 	}
1973 }
1974 
1975 static void dwc2_hsotg_program_zlp(struct dwc2_hsotg *hsotg,
1976 				   struct dwc2_hsotg_ep *hs_ep)
1977 {
1978 	u32 ctrl;
1979 	u8 index = hs_ep->index;
1980 	u32 epctl_reg = hs_ep->dir_in ? DIEPCTL(index) : DOEPCTL(index);
1981 	u32 epsiz_reg = hs_ep->dir_in ? DIEPTSIZ(index) : DOEPTSIZ(index);
1982 
1983 	if (hs_ep->dir_in)
1984 		dev_dbg(hsotg->dev, "Sending zero-length packet on ep%d\n",
1985 			index);
1986 	else
1987 		dev_dbg(hsotg->dev, "Receiving zero-length packet on ep%d\n",
1988 			index);
1989 	if (using_desc_dma(hsotg)) {
1990 		/* Not specific buffer needed for ep0 ZLP */
1991 		dma_addr_t dma = hs_ep->desc_list_dma;
1992 
1993 		if (!index)
1994 			dwc2_gadget_set_ep0_desc_chain(hsotg, hs_ep);
1995 
1996 		dwc2_gadget_config_nonisoc_xfer_ddma(hs_ep, dma, 0);
1997 	} else {
1998 		dwc2_writel(hsotg, DXEPTSIZ_MC(1) | DXEPTSIZ_PKTCNT(1) |
1999 			    DXEPTSIZ_XFERSIZE(0),
2000 			    epsiz_reg);
2001 	}
2002 
2003 	ctrl = dwc2_readl(hsotg, epctl_reg);
2004 	ctrl |= DXEPCTL_CNAK;  /* clear NAK set by core */
2005 	ctrl |= DXEPCTL_EPENA; /* ensure ep enabled */
2006 	ctrl |= DXEPCTL_USBACTEP;
2007 	dwc2_writel(hsotg, ctrl, epctl_reg);
2008 }
2009 
2010 /**
2011  * dwc2_hsotg_complete_request - complete a request given to us
2012  * @hsotg: The device state.
2013  * @hs_ep: The endpoint the request was on.
2014  * @hs_req: The request to complete.
2015  * @result: The result code (0 => Ok, otherwise errno)
2016  *
2017  * The given request has finished, so call the necessary completion
2018  * if it has one and then look to see if we can start a new request
2019  * on the endpoint.
2020  *
2021  * Note, expects the ep to already be locked as appropriate.
2022  */
2023 static void dwc2_hsotg_complete_request(struct dwc2_hsotg *hsotg,
2024 					struct dwc2_hsotg_ep *hs_ep,
2025 				       struct dwc2_hsotg_req *hs_req,
2026 				       int result)
2027 {
2028 	if (!hs_req) {
2029 		dev_dbg(hsotg->dev, "%s: nothing to complete?\n", __func__);
2030 		return;
2031 	}
2032 
2033 	dev_dbg(hsotg->dev, "complete: ep %p %s, req %p, %d => %p\n",
2034 		hs_ep, hs_ep->ep.name, hs_req, result, hs_req->req.complete);
2035 
2036 	/*
2037 	 * only replace the status if we've not already set an error
2038 	 * from a previous transaction
2039 	 */
2040 
2041 	if (hs_req->req.status == -EINPROGRESS)
2042 		hs_req->req.status = result;
2043 
2044 	if (using_dma(hsotg))
2045 		dwc2_hsotg_unmap_dma(hsotg, hs_ep, hs_req);
2046 
2047 	dwc2_hsotg_handle_unaligned_buf_complete(hsotg, hs_ep, hs_req);
2048 
2049 	hs_ep->req = NULL;
2050 	list_del_init(&hs_req->queue);
2051 
2052 	/*
2053 	 * call the complete request with the locks off, just in case the
2054 	 * request tries to queue more work for this endpoint.
2055 	 */
2056 
2057 	if (hs_req->req.complete) {
2058 		spin_unlock(&hsotg->lock);
2059 		usb_gadget_giveback_request(&hs_ep->ep, &hs_req->req);
2060 		spin_lock(&hsotg->lock);
2061 	}
2062 
2063 	/* In DDMA don't need to proceed to starting of next ISOC request */
2064 	if (using_desc_dma(hsotg) && hs_ep->isochronous)
2065 		return;
2066 
2067 	/*
2068 	 * Look to see if there is anything else to do. Note, the completion
2069 	 * of the previous request may have caused a new request to be started
2070 	 * so be careful when doing this.
2071 	 */
2072 
2073 	if (!hs_ep->req && result >= 0)
2074 		dwc2_gadget_start_next_request(hs_ep);
2075 }
2076 
2077 /*
2078  * dwc2_gadget_complete_isoc_request_ddma - complete an isoc request in DDMA
2079  * @hs_ep: The endpoint the request was on.
2080  *
2081  * Get first request from the ep queue, determine descriptor on which complete
2082  * happened. SW discovers which descriptor currently in use by HW, adjusts
2083  * dma_address and calculates index of completed descriptor based on the value
2084  * of DEPDMA register. Update actual length of request, giveback to gadget.
2085  */
2086 static void dwc2_gadget_complete_isoc_request_ddma(struct dwc2_hsotg_ep *hs_ep)
2087 {
2088 	struct dwc2_hsotg *hsotg = hs_ep->parent;
2089 	struct dwc2_hsotg_req *hs_req;
2090 	struct usb_request *ureq;
2091 	u32 desc_sts;
2092 	u32 mask;
2093 
2094 	desc_sts = hs_ep->desc_list[hs_ep->compl_desc].status;
2095 
2096 	/* Process only descriptors with buffer status set to DMA done */
2097 	while ((desc_sts & DEV_DMA_BUFF_STS_MASK) >>
2098 		DEV_DMA_BUFF_STS_SHIFT == DEV_DMA_BUFF_STS_DMADONE) {
2099 
2100 		hs_req = get_ep_head(hs_ep);
2101 		if (!hs_req) {
2102 			dev_warn(hsotg->dev, "%s: ISOC EP queue empty\n", __func__);
2103 			return;
2104 		}
2105 		ureq = &hs_req->req;
2106 
2107 		/* Check completion status */
2108 		if ((desc_sts & DEV_DMA_STS_MASK) >> DEV_DMA_STS_SHIFT ==
2109 			DEV_DMA_STS_SUCC) {
2110 			mask = hs_ep->dir_in ? DEV_DMA_ISOC_TX_NBYTES_MASK :
2111 				DEV_DMA_ISOC_RX_NBYTES_MASK;
2112 			ureq->actual = ureq->length - ((desc_sts & mask) >>
2113 				DEV_DMA_ISOC_NBYTES_SHIFT);
2114 
2115 			/* Adjust actual len for ISOC Out if len is
2116 			 * not align of 4
2117 			 */
2118 			if (!hs_ep->dir_in && ureq->length & 0x3)
2119 				ureq->actual += 4 - (ureq->length & 0x3);
2120 		}
2121 
2122 		dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, 0);
2123 
2124 		hs_ep->compl_desc++;
2125 		if (hs_ep->compl_desc > (MAX_DMA_DESC_NUM_GENERIC - 1))
2126 			hs_ep->compl_desc = 0;
2127 		desc_sts = hs_ep->desc_list[hs_ep->compl_desc].status;
2128 	}
2129 }
2130 
2131 /*
2132  * dwc2_gadget_handle_isoc_bna - handle BNA interrupt for ISOC.
2133  * @hs_ep: The isochronous endpoint.
2134  *
2135  * If EP ISOC OUT then need to flush RX FIFO to remove source of BNA
2136  * interrupt. Reset target frame and next_desc to allow to start
2137  * ISOC's on NAK interrupt for IN direction or on OUTTKNEPDIS
2138  * interrupt for OUT direction.
2139  */
2140 static void dwc2_gadget_handle_isoc_bna(struct dwc2_hsotg_ep *hs_ep)
2141 {
2142 	struct dwc2_hsotg *hsotg = hs_ep->parent;
2143 
2144 	if (!hs_ep->dir_in)
2145 		dwc2_flush_rx_fifo(hsotg);
2146 	dwc2_hsotg_complete_request(hsotg, hs_ep, get_ep_head(hs_ep), 0);
2147 
2148 	hs_ep->target_frame = TARGET_FRAME_INITIAL;
2149 	hs_ep->next_desc = 0;
2150 	hs_ep->compl_desc = 0;
2151 }
2152 
2153 /**
2154  * dwc2_hsotg_rx_data - receive data from the FIFO for an endpoint
2155  * @hsotg: The device state.
2156  * @ep_idx: The endpoint index for the data
2157  * @size: The size of data in the fifo, in bytes
2158  *
2159  * The FIFO status shows there is data to read from the FIFO for a given
2160  * endpoint, so sort out whether we need to read the data into a request
2161  * that has been made for that endpoint.
2162  */
2163 static void dwc2_hsotg_rx_data(struct dwc2_hsotg *hsotg, int ep_idx, int size)
2164 {
2165 	struct dwc2_hsotg_ep *hs_ep = hsotg->eps_out[ep_idx];
2166 	struct dwc2_hsotg_req *hs_req = hs_ep->req;
2167 	int to_read;
2168 	int max_req;
2169 	int read_ptr;
2170 
2171 	if (!hs_req) {
2172 		u32 epctl = dwc2_readl(hsotg, DOEPCTL(ep_idx));
2173 		int ptr;
2174 
2175 		dev_dbg(hsotg->dev,
2176 			"%s: FIFO %d bytes on ep%d but no req (DXEPCTl=0x%08x)\n",
2177 			 __func__, size, ep_idx, epctl);
2178 
2179 		/* dump the data from the FIFO, we've nothing we can do */
2180 		for (ptr = 0; ptr < size; ptr += 4)
2181 			(void)dwc2_readl(hsotg, EPFIFO(ep_idx));
2182 
2183 		return;
2184 	}
2185 
2186 	to_read = size;
2187 	read_ptr = hs_req->req.actual;
2188 	max_req = hs_req->req.length - read_ptr;
2189 
2190 	dev_dbg(hsotg->dev, "%s: read %d/%d, done %d/%d\n",
2191 		__func__, to_read, max_req, read_ptr, hs_req->req.length);
2192 
2193 	if (to_read > max_req) {
2194 		/*
2195 		 * more data appeared than we where willing
2196 		 * to deal with in this request.
2197 		 */
2198 
2199 		/* currently we don't deal this */
2200 		WARN_ON_ONCE(1);
2201 	}
2202 
2203 	hs_ep->total_data += to_read;
2204 	hs_req->req.actual += to_read;
2205 	to_read = DIV_ROUND_UP(to_read, 4);
2206 
2207 	/*
2208 	 * note, we might over-write the buffer end by 3 bytes depending on
2209 	 * alignment of the data.
2210 	 */
2211 	dwc2_readl_rep(hsotg, EPFIFO(ep_idx),
2212 		       hs_req->req.buf + read_ptr, to_read);
2213 }
2214 
2215 /**
2216  * dwc2_hsotg_ep0_zlp - send/receive zero-length packet on control endpoint
2217  * @hsotg: The device instance
2218  * @dir_in: If IN zlp
2219  *
2220  * Generate a zero-length IN packet request for terminating a SETUP
2221  * transaction.
2222  *
2223  * Note, since we don't write any data to the TxFIFO, then it is
2224  * currently believed that we do not need to wait for any space in
2225  * the TxFIFO.
2226  */
2227 static void dwc2_hsotg_ep0_zlp(struct dwc2_hsotg *hsotg, bool dir_in)
2228 {
2229 	/* eps_out[0] is used in both directions */
2230 	hsotg->eps_out[0]->dir_in = dir_in;
2231 	hsotg->ep0_state = dir_in ? DWC2_EP0_STATUS_IN : DWC2_EP0_STATUS_OUT;
2232 
2233 	dwc2_hsotg_program_zlp(hsotg, hsotg->eps_out[0]);
2234 }
2235 
2236 static void dwc2_hsotg_change_ep_iso_parity(struct dwc2_hsotg *hsotg,
2237 					    u32 epctl_reg)
2238 {
2239 	u32 ctrl;
2240 
2241 	ctrl = dwc2_readl(hsotg, epctl_reg);
2242 	if (ctrl & DXEPCTL_EOFRNUM)
2243 		ctrl |= DXEPCTL_SETEVENFR;
2244 	else
2245 		ctrl |= DXEPCTL_SETODDFR;
2246 	dwc2_writel(hsotg, ctrl, epctl_reg);
2247 }
2248 
2249 /*
2250  * dwc2_gadget_get_xfersize_ddma - get transferred bytes amount from desc
2251  * @hs_ep - The endpoint on which transfer went
2252  *
2253  * Iterate over endpoints descriptor chain and get info on bytes remained
2254  * in DMA descriptors after transfer has completed. Used for non isoc EPs.
2255  */
2256 static unsigned int dwc2_gadget_get_xfersize_ddma(struct dwc2_hsotg_ep *hs_ep)
2257 {
2258 	struct dwc2_hsotg *hsotg = hs_ep->parent;
2259 	unsigned int bytes_rem = 0;
2260 	struct dwc2_dma_desc *desc = hs_ep->desc_list;
2261 	int i;
2262 	u32 status;
2263 
2264 	if (!desc)
2265 		return -EINVAL;
2266 
2267 	for (i = 0; i < hs_ep->desc_count; ++i) {
2268 		status = desc->status;
2269 		bytes_rem += status & DEV_DMA_NBYTES_MASK;
2270 
2271 		if (status & DEV_DMA_STS_MASK)
2272 			dev_err(hsotg->dev, "descriptor %d closed with %x\n",
2273 				i, status & DEV_DMA_STS_MASK);
2274 	}
2275 
2276 	return bytes_rem;
2277 }
2278 
2279 /**
2280  * dwc2_hsotg_handle_outdone - handle receiving OutDone/SetupDone from RXFIFO
2281  * @hsotg: The device instance
2282  * @epnum: The endpoint received from
2283  *
2284  * The RXFIFO has delivered an OutDone event, which means that the data
2285  * transfer for an OUT endpoint has been completed, either by a short
2286  * packet or by the finish of a transfer.
2287  */
2288 static void dwc2_hsotg_handle_outdone(struct dwc2_hsotg *hsotg, int epnum)
2289 {
2290 	u32 epsize = dwc2_readl(hsotg, DOEPTSIZ(epnum));
2291 	struct dwc2_hsotg_ep *hs_ep = hsotg->eps_out[epnum];
2292 	struct dwc2_hsotg_req *hs_req = hs_ep->req;
2293 	struct usb_request *req = &hs_req->req;
2294 	unsigned int size_left = DXEPTSIZ_XFERSIZE_GET(epsize);
2295 	int result = 0;
2296 
2297 	if (!hs_req) {
2298 		dev_dbg(hsotg->dev, "%s: no request active\n", __func__);
2299 		return;
2300 	}
2301 
2302 	if (epnum == 0 && hsotg->ep0_state == DWC2_EP0_STATUS_OUT) {
2303 		dev_dbg(hsotg->dev, "zlp packet received\n");
2304 		dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, 0);
2305 		dwc2_hsotg_enqueue_setup(hsotg);
2306 		return;
2307 	}
2308 
2309 	if (using_desc_dma(hsotg))
2310 		size_left = dwc2_gadget_get_xfersize_ddma(hs_ep);
2311 
2312 	if (using_dma(hsotg)) {
2313 		unsigned int size_done;
2314 
2315 		/*
2316 		 * Calculate the size of the transfer by checking how much
2317 		 * is left in the endpoint size register and then working it
2318 		 * out from the amount we loaded for the transfer.
2319 		 *
2320 		 * We need to do this as DMA pointers are always 32bit aligned
2321 		 * so may overshoot/undershoot the transfer.
2322 		 */
2323 
2324 		size_done = hs_ep->size_loaded - size_left;
2325 		size_done += hs_ep->last_load;
2326 
2327 		req->actual = size_done;
2328 	}
2329 
2330 	/* if there is more request to do, schedule new transfer */
2331 	if (req->actual < req->length && size_left == 0) {
2332 		dwc2_hsotg_start_req(hsotg, hs_ep, hs_req, true);
2333 		return;
2334 	}
2335 
2336 	if (req->actual < req->length && req->short_not_ok) {
2337 		dev_dbg(hsotg->dev, "%s: got %d/%d (short not ok) => error\n",
2338 			__func__, req->actual, req->length);
2339 
2340 		/*
2341 		 * todo - what should we return here? there's no one else
2342 		 * even bothering to check the status.
2343 		 */
2344 	}
2345 
2346 	/* DDMA IN status phase will start from StsPhseRcvd interrupt */
2347 	if (!using_desc_dma(hsotg) && epnum == 0 &&
2348 	    hsotg->ep0_state == DWC2_EP0_DATA_OUT) {
2349 		/* Move to STATUS IN */
2350 		dwc2_hsotg_ep0_zlp(hsotg, true);
2351 		return;
2352 	}
2353 
2354 	/*
2355 	 * Slave mode OUT transfers do not go through XferComplete so
2356 	 * adjust the ISOC parity here.
2357 	 */
2358 	if (!using_dma(hsotg)) {
2359 		if (hs_ep->isochronous && hs_ep->interval == 1)
2360 			dwc2_hsotg_change_ep_iso_parity(hsotg, DOEPCTL(epnum));
2361 		else if (hs_ep->isochronous && hs_ep->interval > 1)
2362 			dwc2_gadget_incr_frame_num(hs_ep);
2363 	}
2364 
2365 	dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, result);
2366 }
2367 
2368 /**
2369  * dwc2_hsotg_handle_rx - RX FIFO has data
2370  * @hsotg: The device instance
2371  *
2372  * The IRQ handler has detected that the RX FIFO has some data in it
2373  * that requires processing, so find out what is in there and do the
2374  * appropriate read.
2375  *
2376  * The RXFIFO is a true FIFO, the packets coming out are still in packet
2377  * chunks, so if you have x packets received on an endpoint you'll get x
2378  * FIFO events delivered, each with a packet's worth of data in it.
2379  *
2380  * When using DMA, we should not be processing events from the RXFIFO
2381  * as the actual data should be sent to the memory directly and we turn
2382  * on the completion interrupts to get notifications of transfer completion.
2383  */
2384 static void dwc2_hsotg_handle_rx(struct dwc2_hsotg *hsotg)
2385 {
2386 	u32 grxstsr = dwc2_readl(hsotg, GRXSTSP);
2387 	u32 epnum, status, size;
2388 
2389 	WARN_ON(using_dma(hsotg));
2390 
2391 	epnum = grxstsr & GRXSTS_EPNUM_MASK;
2392 	status = grxstsr & GRXSTS_PKTSTS_MASK;
2393 
2394 	size = grxstsr & GRXSTS_BYTECNT_MASK;
2395 	size >>= GRXSTS_BYTECNT_SHIFT;
2396 
2397 	dev_dbg(hsotg->dev, "%s: GRXSTSP=0x%08x (%d@%d)\n",
2398 		__func__, grxstsr, size, epnum);
2399 
2400 	switch ((status & GRXSTS_PKTSTS_MASK) >> GRXSTS_PKTSTS_SHIFT) {
2401 	case GRXSTS_PKTSTS_GLOBALOUTNAK:
2402 		dev_dbg(hsotg->dev, "GLOBALOUTNAK\n");
2403 		break;
2404 
2405 	case GRXSTS_PKTSTS_OUTDONE:
2406 		dev_dbg(hsotg->dev, "OutDone (Frame=0x%08x)\n",
2407 			dwc2_hsotg_read_frameno(hsotg));
2408 
2409 		if (!using_dma(hsotg))
2410 			dwc2_hsotg_handle_outdone(hsotg, epnum);
2411 		break;
2412 
2413 	case GRXSTS_PKTSTS_SETUPDONE:
2414 		dev_dbg(hsotg->dev,
2415 			"SetupDone (Frame=0x%08x, DOPEPCTL=0x%08x)\n",
2416 			dwc2_hsotg_read_frameno(hsotg),
2417 			dwc2_readl(hsotg, DOEPCTL(0)));
2418 		/*
2419 		 * Call dwc2_hsotg_handle_outdone here if it was not called from
2420 		 * GRXSTS_PKTSTS_OUTDONE. That is, if the core didn't
2421 		 * generate GRXSTS_PKTSTS_OUTDONE for setup packet.
2422 		 */
2423 		if (hsotg->ep0_state == DWC2_EP0_SETUP)
2424 			dwc2_hsotg_handle_outdone(hsotg, epnum);
2425 		break;
2426 
2427 	case GRXSTS_PKTSTS_OUTRX:
2428 		dwc2_hsotg_rx_data(hsotg, epnum, size);
2429 		break;
2430 
2431 	case GRXSTS_PKTSTS_SETUPRX:
2432 		dev_dbg(hsotg->dev,
2433 			"SetupRX (Frame=0x%08x, DOPEPCTL=0x%08x)\n",
2434 			dwc2_hsotg_read_frameno(hsotg),
2435 			dwc2_readl(hsotg, DOEPCTL(0)));
2436 
2437 		WARN_ON(hsotg->ep0_state != DWC2_EP0_SETUP);
2438 
2439 		dwc2_hsotg_rx_data(hsotg, epnum, size);
2440 		break;
2441 
2442 	default:
2443 		dev_warn(hsotg->dev, "%s: unknown status %08x\n",
2444 			 __func__, grxstsr);
2445 
2446 		dwc2_hsotg_dump(hsotg);
2447 		break;
2448 	}
2449 }
2450 
2451 /**
2452  * dwc2_hsotg_ep0_mps - turn max packet size into register setting
2453  * @mps: The maximum packet size in bytes.
2454  */
2455 static u32 dwc2_hsotg_ep0_mps(unsigned int mps)
2456 {
2457 	switch (mps) {
2458 	case 64:
2459 		return D0EPCTL_MPS_64;
2460 	case 32:
2461 		return D0EPCTL_MPS_32;
2462 	case 16:
2463 		return D0EPCTL_MPS_16;
2464 	case 8:
2465 		return D0EPCTL_MPS_8;
2466 	}
2467 
2468 	/* bad max packet size, warn and return invalid result */
2469 	WARN_ON(1);
2470 	return (u32)-1;
2471 }
2472 
2473 /**
2474  * dwc2_hsotg_set_ep_maxpacket - set endpoint's max-packet field
2475  * @hsotg: The driver state.
2476  * @ep: The index number of the endpoint
2477  * @mps: The maximum packet size in bytes
2478  * @mc: The multicount value
2479  * @dir_in: True if direction is in.
2480  *
2481  * Configure the maximum packet size for the given endpoint, updating
2482  * the hardware control registers to reflect this.
2483  */
2484 static void dwc2_hsotg_set_ep_maxpacket(struct dwc2_hsotg *hsotg,
2485 					unsigned int ep, unsigned int mps,
2486 					unsigned int mc, unsigned int dir_in)
2487 {
2488 	struct dwc2_hsotg_ep *hs_ep;
2489 	u32 reg;
2490 
2491 	hs_ep = index_to_ep(hsotg, ep, dir_in);
2492 	if (!hs_ep)
2493 		return;
2494 
2495 	if (ep == 0) {
2496 		u32 mps_bytes = mps;
2497 
2498 		/* EP0 is a special case */
2499 		mps = dwc2_hsotg_ep0_mps(mps_bytes);
2500 		if (mps > 3)
2501 			goto bad_mps;
2502 		hs_ep->ep.maxpacket = mps_bytes;
2503 		hs_ep->mc = 1;
2504 	} else {
2505 		if (mps > 1024)
2506 			goto bad_mps;
2507 		hs_ep->mc = mc;
2508 		if (mc > 3)
2509 			goto bad_mps;
2510 		hs_ep->ep.maxpacket = mps;
2511 	}
2512 
2513 	if (dir_in) {
2514 		reg = dwc2_readl(hsotg, DIEPCTL(ep));
2515 		reg &= ~DXEPCTL_MPS_MASK;
2516 		reg |= mps;
2517 		dwc2_writel(hsotg, reg, DIEPCTL(ep));
2518 	} else {
2519 		reg = dwc2_readl(hsotg, DOEPCTL(ep));
2520 		reg &= ~DXEPCTL_MPS_MASK;
2521 		reg |= mps;
2522 		dwc2_writel(hsotg, reg, DOEPCTL(ep));
2523 	}
2524 
2525 	return;
2526 
2527 bad_mps:
2528 	dev_err(hsotg->dev, "ep%d: bad mps of %d\n", ep, mps);
2529 }
2530 
2531 /**
2532  * dwc2_hsotg_txfifo_flush - flush Tx FIFO
2533  * @hsotg: The driver state
2534  * @idx: The index for the endpoint (0..15)
2535  */
2536 static void dwc2_hsotg_txfifo_flush(struct dwc2_hsotg *hsotg, unsigned int idx)
2537 {
2538 	dwc2_writel(hsotg, GRSTCTL_TXFNUM(idx) | GRSTCTL_TXFFLSH,
2539 		    GRSTCTL);
2540 
2541 	/* wait until the fifo is flushed */
2542 	if (dwc2_hsotg_wait_bit_clear(hsotg, GRSTCTL, GRSTCTL_TXFFLSH, 100))
2543 		dev_warn(hsotg->dev, "%s: timeout flushing fifo GRSTCTL_TXFFLSH\n",
2544 			 __func__);
2545 }
2546 
2547 /**
2548  * dwc2_hsotg_trytx - check to see if anything needs transmitting
2549  * @hsotg: The driver state
2550  * @hs_ep: The driver endpoint to check.
2551  *
2552  * Check to see if there is a request that has data to send, and if so
2553  * make an attempt to write data into the FIFO.
2554  */
2555 static int dwc2_hsotg_trytx(struct dwc2_hsotg *hsotg,
2556 			    struct dwc2_hsotg_ep *hs_ep)
2557 {
2558 	struct dwc2_hsotg_req *hs_req = hs_ep->req;
2559 
2560 	if (!hs_ep->dir_in || !hs_req) {
2561 		/**
2562 		 * if request is not enqueued, we disable interrupts
2563 		 * for endpoints, excepting ep0
2564 		 */
2565 		if (hs_ep->index != 0)
2566 			dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index,
2567 					      hs_ep->dir_in, 0);
2568 		return 0;
2569 	}
2570 
2571 	if (hs_req->req.actual < hs_req->req.length) {
2572 		dev_dbg(hsotg->dev, "trying to write more for ep%d\n",
2573 			hs_ep->index);
2574 		return dwc2_hsotg_write_fifo(hsotg, hs_ep, hs_req);
2575 	}
2576 
2577 	return 0;
2578 }
2579 
2580 /**
2581  * dwc2_hsotg_complete_in - complete IN transfer
2582  * @hsotg: The device state.
2583  * @hs_ep: The endpoint that has just completed.
2584  *
2585  * An IN transfer has been completed, update the transfer's state and then
2586  * call the relevant completion routines.
2587  */
2588 static void dwc2_hsotg_complete_in(struct dwc2_hsotg *hsotg,
2589 				   struct dwc2_hsotg_ep *hs_ep)
2590 {
2591 	struct dwc2_hsotg_req *hs_req = hs_ep->req;
2592 	u32 epsize = dwc2_readl(hsotg, DIEPTSIZ(hs_ep->index));
2593 	int size_left, size_done;
2594 
2595 	if (!hs_req) {
2596 		dev_dbg(hsotg->dev, "XferCompl but no req\n");
2597 		return;
2598 	}
2599 
2600 	/* Finish ZLP handling for IN EP0 transactions */
2601 	if (hs_ep->index == 0 && hsotg->ep0_state == DWC2_EP0_STATUS_IN) {
2602 		dev_dbg(hsotg->dev, "zlp packet sent\n");
2603 
2604 		/*
2605 		 * While send zlp for DWC2_EP0_STATUS_IN EP direction was
2606 		 * changed to IN. Change back to complete OUT transfer request
2607 		 */
2608 		hs_ep->dir_in = 0;
2609 
2610 		dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, 0);
2611 		if (hsotg->test_mode) {
2612 			int ret;
2613 
2614 			ret = dwc2_hsotg_set_test_mode(hsotg, hsotg->test_mode);
2615 			if (ret < 0) {
2616 				dev_dbg(hsotg->dev, "Invalid Test #%d\n",
2617 					hsotg->test_mode);
2618 				dwc2_hsotg_stall_ep0(hsotg);
2619 				return;
2620 			}
2621 		}
2622 		dwc2_hsotg_enqueue_setup(hsotg);
2623 		return;
2624 	}
2625 
2626 	/*
2627 	 * Calculate the size of the transfer by checking how much is left
2628 	 * in the endpoint size register and then working it out from
2629 	 * the amount we loaded for the transfer.
2630 	 *
2631 	 * We do this even for DMA, as the transfer may have incremented
2632 	 * past the end of the buffer (DMA transfers are always 32bit
2633 	 * aligned).
2634 	 */
2635 	if (using_desc_dma(hsotg)) {
2636 		size_left = dwc2_gadget_get_xfersize_ddma(hs_ep);
2637 		if (size_left < 0)
2638 			dev_err(hsotg->dev, "error parsing DDMA results %d\n",
2639 				size_left);
2640 	} else {
2641 		size_left = DXEPTSIZ_XFERSIZE_GET(epsize);
2642 	}
2643 
2644 	size_done = hs_ep->size_loaded - size_left;
2645 	size_done += hs_ep->last_load;
2646 
2647 	if (hs_req->req.actual != size_done)
2648 		dev_dbg(hsotg->dev, "%s: adjusting size done %d => %d\n",
2649 			__func__, hs_req->req.actual, size_done);
2650 
2651 	hs_req->req.actual = size_done;
2652 	dev_dbg(hsotg->dev, "req->length:%d req->actual:%d req->zero:%d\n",
2653 		hs_req->req.length, hs_req->req.actual, hs_req->req.zero);
2654 
2655 	if (!size_left && hs_req->req.actual < hs_req->req.length) {
2656 		dev_dbg(hsotg->dev, "%s trying more for req...\n", __func__);
2657 		dwc2_hsotg_start_req(hsotg, hs_ep, hs_req, true);
2658 		return;
2659 	}
2660 
2661 	/* Zlp for all endpoints, for ep0 only in DATA IN stage */
2662 	if (hs_ep->send_zlp) {
2663 		dwc2_hsotg_program_zlp(hsotg, hs_ep);
2664 		hs_ep->send_zlp = 0;
2665 		/* transfer will be completed on next complete interrupt */
2666 		return;
2667 	}
2668 
2669 	if (hs_ep->index == 0 && hsotg->ep0_state == DWC2_EP0_DATA_IN) {
2670 		/* Move to STATUS OUT */
2671 		dwc2_hsotg_ep0_zlp(hsotg, false);
2672 		return;
2673 	}
2674 
2675 	dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, 0);
2676 }
2677 
2678 /**
2679  * dwc2_gadget_read_ep_interrupts - reads interrupts for given ep
2680  * @hsotg: The device state.
2681  * @idx: Index of ep.
2682  * @dir_in: Endpoint direction 1-in 0-out.
2683  *
2684  * Reads for endpoint with given index and direction, by masking
2685  * epint_reg with coresponding mask.
2686  */
2687 static u32 dwc2_gadget_read_ep_interrupts(struct dwc2_hsotg *hsotg,
2688 					  unsigned int idx, int dir_in)
2689 {
2690 	u32 epmsk_reg = dir_in ? DIEPMSK : DOEPMSK;
2691 	u32 epint_reg = dir_in ? DIEPINT(idx) : DOEPINT(idx);
2692 	u32 ints;
2693 	u32 mask;
2694 	u32 diepempmsk;
2695 
2696 	mask = dwc2_readl(hsotg, epmsk_reg);
2697 	diepempmsk = dwc2_readl(hsotg, DIEPEMPMSK);
2698 	mask |= ((diepempmsk >> idx) & 0x1) ? DIEPMSK_TXFIFOEMPTY : 0;
2699 	mask |= DXEPINT_SETUP_RCVD;
2700 
2701 	ints = dwc2_readl(hsotg, epint_reg);
2702 	ints &= mask;
2703 	return ints;
2704 }
2705 
2706 /**
2707  * dwc2_gadget_handle_ep_disabled - handle DXEPINT_EPDISBLD
2708  * @hs_ep: The endpoint on which interrupt is asserted.
2709  *
2710  * This interrupt indicates that the endpoint has been disabled per the
2711  * application's request.
2712  *
2713  * For IN endpoints flushes txfifo, in case of BULK clears DCTL_CGNPINNAK,
2714  * in case of ISOC completes current request.
2715  *
2716  * For ISOC-OUT endpoints completes expired requests. If there is remaining
2717  * request starts it.
2718  */
2719 static void dwc2_gadget_handle_ep_disabled(struct dwc2_hsotg_ep *hs_ep)
2720 {
2721 	struct dwc2_hsotg *hsotg = hs_ep->parent;
2722 	struct dwc2_hsotg_req *hs_req;
2723 	unsigned char idx = hs_ep->index;
2724 	int dir_in = hs_ep->dir_in;
2725 	u32 epctl_reg = dir_in ? DIEPCTL(idx) : DOEPCTL(idx);
2726 	int dctl = dwc2_readl(hsotg, DCTL);
2727 
2728 	dev_dbg(hsotg->dev, "%s: EPDisbld\n", __func__);
2729 
2730 	if (dir_in) {
2731 		int epctl = dwc2_readl(hsotg, epctl_reg);
2732 
2733 		dwc2_hsotg_txfifo_flush(hsotg, hs_ep->fifo_index);
2734 
2735 		if (hs_ep->isochronous) {
2736 			dwc2_hsotg_complete_in(hsotg, hs_ep);
2737 			return;
2738 		}
2739 
2740 		if ((epctl & DXEPCTL_STALL) && (epctl & DXEPCTL_EPTYPE_BULK)) {
2741 			int dctl = dwc2_readl(hsotg, DCTL);
2742 
2743 			dctl |= DCTL_CGNPINNAK;
2744 			dwc2_writel(hsotg, dctl, DCTL);
2745 		}
2746 		return;
2747 	}
2748 
2749 	if (dctl & DCTL_GOUTNAKSTS) {
2750 		dctl |= DCTL_CGOUTNAK;
2751 		dwc2_writel(hsotg, dctl, DCTL);
2752 	}
2753 
2754 	if (!hs_ep->isochronous)
2755 		return;
2756 
2757 	if (list_empty(&hs_ep->queue)) {
2758 		dev_dbg(hsotg->dev, "%s: complete_ep 0x%p, ep->queue empty!\n",
2759 			__func__, hs_ep);
2760 		return;
2761 	}
2762 
2763 	do {
2764 		hs_req = get_ep_head(hs_ep);
2765 		if (hs_req)
2766 			dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req,
2767 						    -ENODATA);
2768 		dwc2_gadget_incr_frame_num(hs_ep);
2769 		/* Update current frame number value. */
2770 		hsotg->frame_number = dwc2_hsotg_read_frameno(hsotg);
2771 	} while (dwc2_gadget_target_frame_elapsed(hs_ep));
2772 
2773 	dwc2_gadget_start_next_request(hs_ep);
2774 }
2775 
2776 /**
2777  * dwc2_gadget_handle_out_token_ep_disabled - handle DXEPINT_OUTTKNEPDIS
2778  * @ep: The endpoint on which interrupt is asserted.
2779  *
2780  * This is starting point for ISOC-OUT transfer, synchronization done with
2781  * first out token received from host while corresponding EP is disabled.
2782  *
2783  * Device does not know initial frame in which out token will come. For this
2784  * HW generates OUTTKNEPDIS - out token is received while EP is disabled. Upon
2785  * getting this interrupt SW starts calculation for next transfer frame.
2786  */
2787 static void dwc2_gadget_handle_out_token_ep_disabled(struct dwc2_hsotg_ep *ep)
2788 {
2789 	struct dwc2_hsotg *hsotg = ep->parent;
2790 	int dir_in = ep->dir_in;
2791 	u32 doepmsk;
2792 
2793 	if (dir_in || !ep->isochronous)
2794 		return;
2795 
2796 	if (using_desc_dma(hsotg)) {
2797 		if (ep->target_frame == TARGET_FRAME_INITIAL) {
2798 			/* Start first ISO Out */
2799 			ep->target_frame = hsotg->frame_number;
2800 			dwc2_gadget_start_isoc_ddma(ep);
2801 		}
2802 		return;
2803 	}
2804 
2805 	if (ep->interval > 1 &&
2806 	    ep->target_frame == TARGET_FRAME_INITIAL) {
2807 		u32 ctrl;
2808 
2809 		ep->target_frame = hsotg->frame_number;
2810 		dwc2_gadget_incr_frame_num(ep);
2811 
2812 		ctrl = dwc2_readl(hsotg, DOEPCTL(ep->index));
2813 		if (ep->target_frame & 0x1)
2814 			ctrl |= DXEPCTL_SETODDFR;
2815 		else
2816 			ctrl |= DXEPCTL_SETEVENFR;
2817 
2818 		dwc2_writel(hsotg, ctrl, DOEPCTL(ep->index));
2819 	}
2820 
2821 	dwc2_gadget_start_next_request(ep);
2822 	doepmsk = dwc2_readl(hsotg, DOEPMSK);
2823 	doepmsk &= ~DOEPMSK_OUTTKNEPDISMSK;
2824 	dwc2_writel(hsotg, doepmsk, DOEPMSK);
2825 }
2826 
2827 /**
2828  * dwc2_gadget_handle_nak - handle NAK interrupt
2829  * @hs_ep: The endpoint on which interrupt is asserted.
2830  *
2831  * This is starting point for ISOC-IN transfer, synchronization done with
2832  * first IN token received from host while corresponding EP is disabled.
2833  *
2834  * Device does not know when first one token will arrive from host. On first
2835  * token arrival HW generates 2 interrupts: 'in token received while FIFO empty'
2836  * and 'NAK'. NAK interrupt for ISOC-IN means that token has arrived and ZLP was
2837  * sent in response to that as there was no data in FIFO. SW is basing on this
2838  * interrupt to obtain frame in which token has come and then based on the
2839  * interval calculates next frame for transfer.
2840  */
2841 static void dwc2_gadget_handle_nak(struct dwc2_hsotg_ep *hs_ep)
2842 {
2843 	struct dwc2_hsotg *hsotg = hs_ep->parent;
2844 	int dir_in = hs_ep->dir_in;
2845 
2846 	if (!dir_in || !hs_ep->isochronous)
2847 		return;
2848 
2849 	if (hs_ep->target_frame == TARGET_FRAME_INITIAL) {
2850 
2851 		if (using_desc_dma(hsotg)) {
2852 			hs_ep->target_frame = hsotg->frame_number;
2853 			dwc2_gadget_incr_frame_num(hs_ep);
2854 
2855 			/* In service interval mode target_frame must
2856 			 * be set to last (u)frame of the service interval.
2857 			 */
2858 			if (hsotg->params.service_interval) {
2859 				/* Set target_frame to the first (u)frame of
2860 				 * the service interval
2861 				 */
2862 				hs_ep->target_frame &= ~hs_ep->interval + 1;
2863 
2864 				/* Set target_frame to the last (u)frame of
2865 				 * the service interval
2866 				 */
2867 				dwc2_gadget_incr_frame_num(hs_ep);
2868 				dwc2_gadget_dec_frame_num_by_one(hs_ep);
2869 			}
2870 
2871 			dwc2_gadget_start_isoc_ddma(hs_ep);
2872 			return;
2873 		}
2874 
2875 		hs_ep->target_frame = hsotg->frame_number;
2876 		if (hs_ep->interval > 1) {
2877 			u32 ctrl = dwc2_readl(hsotg,
2878 					      DIEPCTL(hs_ep->index));
2879 			if (hs_ep->target_frame & 0x1)
2880 				ctrl |= DXEPCTL_SETODDFR;
2881 			else
2882 				ctrl |= DXEPCTL_SETEVENFR;
2883 
2884 			dwc2_writel(hsotg, ctrl, DIEPCTL(hs_ep->index));
2885 		}
2886 
2887 		dwc2_hsotg_complete_request(hsotg, hs_ep,
2888 					    get_ep_head(hs_ep), 0);
2889 	}
2890 
2891 	if (!using_desc_dma(hsotg))
2892 		dwc2_gadget_incr_frame_num(hs_ep);
2893 }
2894 
2895 /**
2896  * dwc2_hsotg_epint - handle an in/out endpoint interrupt
2897  * @hsotg: The driver state
2898  * @idx: The index for the endpoint (0..15)
2899  * @dir_in: Set if this is an IN endpoint
2900  *
2901  * Process and clear any interrupt pending for an individual endpoint
2902  */
2903 static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx,
2904 			     int dir_in)
2905 {
2906 	struct dwc2_hsotg_ep *hs_ep = index_to_ep(hsotg, idx, dir_in);
2907 	u32 epint_reg = dir_in ? DIEPINT(idx) : DOEPINT(idx);
2908 	u32 epctl_reg = dir_in ? DIEPCTL(idx) : DOEPCTL(idx);
2909 	u32 epsiz_reg = dir_in ? DIEPTSIZ(idx) : DOEPTSIZ(idx);
2910 	u32 ints;
2911 	u32 ctrl;
2912 
2913 	ints = dwc2_gadget_read_ep_interrupts(hsotg, idx, dir_in);
2914 	ctrl = dwc2_readl(hsotg, epctl_reg);
2915 
2916 	/* Clear endpoint interrupts */
2917 	dwc2_writel(hsotg, ints, epint_reg);
2918 
2919 	if (!hs_ep) {
2920 		dev_err(hsotg->dev, "%s:Interrupt for unconfigured ep%d(%s)\n",
2921 			__func__, idx, dir_in ? "in" : "out");
2922 		return;
2923 	}
2924 
2925 	dev_dbg(hsotg->dev, "%s: ep%d(%s) DxEPINT=0x%08x\n",
2926 		__func__, idx, dir_in ? "in" : "out", ints);
2927 
2928 	/* Don't process XferCompl interrupt if it is a setup packet */
2929 	if (idx == 0 && (ints & (DXEPINT_SETUP | DXEPINT_SETUP_RCVD)))
2930 		ints &= ~DXEPINT_XFERCOMPL;
2931 
2932 	/*
2933 	 * Don't process XferCompl interrupt in DDMA if EP0 is still in SETUP
2934 	 * stage and xfercomplete was generated without SETUP phase done
2935 	 * interrupt. SW should parse received setup packet only after host's
2936 	 * exit from setup phase of control transfer.
2937 	 */
2938 	if (using_desc_dma(hsotg) && idx == 0 && !hs_ep->dir_in &&
2939 	    hsotg->ep0_state == DWC2_EP0_SETUP && !(ints & DXEPINT_SETUP))
2940 		ints &= ~DXEPINT_XFERCOMPL;
2941 
2942 	if (ints & DXEPINT_XFERCOMPL) {
2943 		dev_dbg(hsotg->dev,
2944 			"%s: XferCompl: DxEPCTL=0x%08x, DXEPTSIZ=%08x\n",
2945 			__func__, dwc2_readl(hsotg, epctl_reg),
2946 			dwc2_readl(hsotg, epsiz_reg));
2947 
2948 		/* In DDMA handle isochronous requests separately */
2949 		if (using_desc_dma(hsotg) && hs_ep->isochronous) {
2950 			/* XferCompl set along with BNA */
2951 			if (!(ints & DXEPINT_BNAINTR))
2952 				dwc2_gadget_complete_isoc_request_ddma(hs_ep);
2953 		} else if (dir_in) {
2954 			/*
2955 			 * We get OutDone from the FIFO, so we only
2956 			 * need to look at completing IN requests here
2957 			 * if operating slave mode
2958 			 */
2959 			if (hs_ep->isochronous && hs_ep->interval > 1)
2960 				dwc2_gadget_incr_frame_num(hs_ep);
2961 
2962 			dwc2_hsotg_complete_in(hsotg, hs_ep);
2963 			if (ints & DXEPINT_NAKINTRPT)
2964 				ints &= ~DXEPINT_NAKINTRPT;
2965 
2966 			if (idx == 0 && !hs_ep->req)
2967 				dwc2_hsotg_enqueue_setup(hsotg);
2968 		} else if (using_dma(hsotg)) {
2969 			/*
2970 			 * We're using DMA, we need to fire an OutDone here
2971 			 * as we ignore the RXFIFO.
2972 			 */
2973 			if (hs_ep->isochronous && hs_ep->interval > 1)
2974 				dwc2_gadget_incr_frame_num(hs_ep);
2975 
2976 			dwc2_hsotg_handle_outdone(hsotg, idx);
2977 		}
2978 	}
2979 
2980 	if (ints & DXEPINT_EPDISBLD)
2981 		dwc2_gadget_handle_ep_disabled(hs_ep);
2982 
2983 	if (ints & DXEPINT_OUTTKNEPDIS)
2984 		dwc2_gadget_handle_out_token_ep_disabled(hs_ep);
2985 
2986 	if (ints & DXEPINT_NAKINTRPT)
2987 		dwc2_gadget_handle_nak(hs_ep);
2988 
2989 	if (ints & DXEPINT_AHBERR)
2990 		dev_dbg(hsotg->dev, "%s: AHBErr\n", __func__);
2991 
2992 	if (ints & DXEPINT_SETUP) {  /* Setup or Timeout */
2993 		dev_dbg(hsotg->dev, "%s: Setup/Timeout\n",  __func__);
2994 
2995 		if (using_dma(hsotg) && idx == 0) {
2996 			/*
2997 			 * this is the notification we've received a
2998 			 * setup packet. In non-DMA mode we'd get this
2999 			 * from the RXFIFO, instead we need to process
3000 			 * the setup here.
3001 			 */
3002 
3003 			if (dir_in)
3004 				WARN_ON_ONCE(1);
3005 			else
3006 				dwc2_hsotg_handle_outdone(hsotg, 0);
3007 		}
3008 	}
3009 
3010 	if (ints & DXEPINT_STSPHSERCVD) {
3011 		dev_dbg(hsotg->dev, "%s: StsPhseRcvd\n", __func__);
3012 
3013 		/* Safety check EP0 state when STSPHSERCVD asserted */
3014 		if (hsotg->ep0_state == DWC2_EP0_DATA_OUT) {
3015 			/* Move to STATUS IN for DDMA */
3016 			if (using_desc_dma(hsotg))
3017 				dwc2_hsotg_ep0_zlp(hsotg, true);
3018 		}
3019 
3020 	}
3021 
3022 	if (ints & DXEPINT_BACK2BACKSETUP)
3023 		dev_dbg(hsotg->dev, "%s: B2BSetup/INEPNakEff\n", __func__);
3024 
3025 	if (ints & DXEPINT_BNAINTR) {
3026 		dev_dbg(hsotg->dev, "%s: BNA interrupt\n", __func__);
3027 		if (hs_ep->isochronous)
3028 			dwc2_gadget_handle_isoc_bna(hs_ep);
3029 	}
3030 
3031 	if (dir_in && !hs_ep->isochronous) {
3032 		/* not sure if this is important, but we'll clear it anyway */
3033 		if (ints & DXEPINT_INTKNTXFEMP) {
3034 			dev_dbg(hsotg->dev, "%s: ep%d: INTknTXFEmpMsk\n",
3035 				__func__, idx);
3036 		}
3037 
3038 		/* this probably means something bad is happening */
3039 		if (ints & DXEPINT_INTKNEPMIS) {
3040 			dev_warn(hsotg->dev, "%s: ep%d: INTknEP\n",
3041 				 __func__, idx);
3042 		}
3043 
3044 		/* FIFO has space or is empty (see GAHBCFG) */
3045 		if (hsotg->dedicated_fifos &&
3046 		    ints & DXEPINT_TXFEMP) {
3047 			dev_dbg(hsotg->dev, "%s: ep%d: TxFIFOEmpty\n",
3048 				__func__, idx);
3049 			if (!using_dma(hsotg))
3050 				dwc2_hsotg_trytx(hsotg, hs_ep);
3051 		}
3052 	}
3053 }
3054 
3055 /**
3056  * dwc2_hsotg_irq_enumdone - Handle EnumDone interrupt (enumeration done)
3057  * @hsotg: The device state.
3058  *
3059  * Handle updating the device settings after the enumeration phase has
3060  * been completed.
3061  */
3062 static void dwc2_hsotg_irq_enumdone(struct dwc2_hsotg *hsotg)
3063 {
3064 	u32 dsts = dwc2_readl(hsotg, DSTS);
3065 	int ep0_mps = 0, ep_mps = 8;
3066 
3067 	/*
3068 	 * This should signal the finish of the enumeration phase
3069 	 * of the USB handshaking, so we should now know what rate
3070 	 * we connected at.
3071 	 */
3072 
3073 	dev_dbg(hsotg->dev, "EnumDone (DSTS=0x%08x)\n", dsts);
3074 
3075 	/*
3076 	 * note, since we're limited by the size of transfer on EP0, and
3077 	 * it seems IN transfers must be a even number of packets we do
3078 	 * not advertise a 64byte MPS on EP0.
3079 	 */
3080 
3081 	/* catch both EnumSpd_FS and EnumSpd_FS48 */
3082 	switch ((dsts & DSTS_ENUMSPD_MASK) >> DSTS_ENUMSPD_SHIFT) {
3083 	case DSTS_ENUMSPD_FS:
3084 	case DSTS_ENUMSPD_FS48:
3085 		hsotg->gadget.speed = USB_SPEED_FULL;
3086 		ep0_mps = EP0_MPS_LIMIT;
3087 		ep_mps = 1023;
3088 		break;
3089 
3090 	case DSTS_ENUMSPD_HS:
3091 		hsotg->gadget.speed = USB_SPEED_HIGH;
3092 		ep0_mps = EP0_MPS_LIMIT;
3093 		ep_mps = 1024;
3094 		break;
3095 
3096 	case DSTS_ENUMSPD_LS:
3097 		hsotg->gadget.speed = USB_SPEED_LOW;
3098 		ep0_mps = 8;
3099 		ep_mps = 8;
3100 		/*
3101 		 * note, we don't actually support LS in this driver at the
3102 		 * moment, and the documentation seems to imply that it isn't
3103 		 * supported by the PHYs on some of the devices.
3104 		 */
3105 		break;
3106 	}
3107 	dev_info(hsotg->dev, "new device is %s\n",
3108 		 usb_speed_string(hsotg->gadget.speed));
3109 
3110 	/*
3111 	 * we should now know the maximum packet size for an
3112 	 * endpoint, so set the endpoints to a default value.
3113 	 */
3114 
3115 	if (ep0_mps) {
3116 		int i;
3117 		/* Initialize ep0 for both in and out directions */
3118 		dwc2_hsotg_set_ep_maxpacket(hsotg, 0, ep0_mps, 0, 1);
3119 		dwc2_hsotg_set_ep_maxpacket(hsotg, 0, ep0_mps, 0, 0);
3120 		for (i = 1; i < hsotg->num_of_eps; i++) {
3121 			if (hsotg->eps_in[i])
3122 				dwc2_hsotg_set_ep_maxpacket(hsotg, i, ep_mps,
3123 							    0, 1);
3124 			if (hsotg->eps_out[i])
3125 				dwc2_hsotg_set_ep_maxpacket(hsotg, i, ep_mps,
3126 							    0, 0);
3127 		}
3128 	}
3129 
3130 	/* ensure after enumeration our EP0 is active */
3131 
3132 	dwc2_hsotg_enqueue_setup(hsotg);
3133 
3134 	dev_dbg(hsotg->dev, "EP0: DIEPCTL0=0x%08x, DOEPCTL0=0x%08x\n",
3135 		dwc2_readl(hsotg, DIEPCTL0),
3136 		dwc2_readl(hsotg, DOEPCTL0));
3137 }
3138 
3139 /**
3140  * kill_all_requests - remove all requests from the endpoint's queue
3141  * @hsotg: The device state.
3142  * @ep: The endpoint the requests may be on.
3143  * @result: The result code to use.
3144  *
3145  * Go through the requests on the given endpoint and mark them
3146  * completed with the given result code.
3147  */
3148 static void kill_all_requests(struct dwc2_hsotg *hsotg,
3149 			      struct dwc2_hsotg_ep *ep,
3150 			      int result)
3151 {
3152 	struct dwc2_hsotg_req *req, *treq;
3153 	unsigned int size;
3154 
3155 	ep->req = NULL;
3156 
3157 	list_for_each_entry_safe(req, treq, &ep->queue, queue)
3158 		dwc2_hsotg_complete_request(hsotg, ep, req,
3159 					    result);
3160 
3161 	if (!hsotg->dedicated_fifos)
3162 		return;
3163 	size = (dwc2_readl(hsotg, DTXFSTS(ep->fifo_index)) & 0xffff) * 4;
3164 	if (size < ep->fifo_size)
3165 		dwc2_hsotg_txfifo_flush(hsotg, ep->fifo_index);
3166 }
3167 
3168 /**
3169  * dwc2_hsotg_disconnect - disconnect service
3170  * @hsotg: The device state.
3171  *
3172  * The device has been disconnected. Remove all current
3173  * transactions and signal the gadget driver that this
3174  * has happened.
3175  */
3176 void dwc2_hsotg_disconnect(struct dwc2_hsotg *hsotg)
3177 {
3178 	unsigned int ep;
3179 
3180 	if (!hsotg->connected)
3181 		return;
3182 
3183 	hsotg->connected = 0;
3184 	hsotg->test_mode = 0;
3185 
3186 	/* all endpoints should be shutdown */
3187 	for (ep = 0; ep < hsotg->num_of_eps; ep++) {
3188 		if (hsotg->eps_in[ep])
3189 			kill_all_requests(hsotg, hsotg->eps_in[ep],
3190 					  -ESHUTDOWN);
3191 		if (hsotg->eps_out[ep])
3192 			kill_all_requests(hsotg, hsotg->eps_out[ep],
3193 					  -ESHUTDOWN);
3194 	}
3195 
3196 	call_gadget(hsotg, disconnect);
3197 	hsotg->lx_state = DWC2_L3;
3198 
3199 	usb_gadget_set_state(&hsotg->gadget, USB_STATE_NOTATTACHED);
3200 }
3201 
3202 /**
3203  * dwc2_hsotg_irq_fifoempty - TX FIFO empty interrupt handler
3204  * @hsotg: The device state:
3205  * @periodic: True if this is a periodic FIFO interrupt
3206  */
3207 static void dwc2_hsotg_irq_fifoempty(struct dwc2_hsotg *hsotg, bool periodic)
3208 {
3209 	struct dwc2_hsotg_ep *ep;
3210 	int epno, ret;
3211 
3212 	/* look through for any more data to transmit */
3213 	for (epno = 0; epno < hsotg->num_of_eps; epno++) {
3214 		ep = index_to_ep(hsotg, epno, 1);
3215 
3216 		if (!ep)
3217 			continue;
3218 
3219 		if (!ep->dir_in)
3220 			continue;
3221 
3222 		if ((periodic && !ep->periodic) ||
3223 		    (!periodic && ep->periodic))
3224 			continue;
3225 
3226 		ret = dwc2_hsotg_trytx(hsotg, ep);
3227 		if (ret < 0)
3228 			break;
3229 	}
3230 }
3231 
3232 /* IRQ flags which will trigger a retry around the IRQ loop */
3233 #define IRQ_RETRY_MASK (GINTSTS_NPTXFEMP | \
3234 			GINTSTS_PTXFEMP |  \
3235 			GINTSTS_RXFLVL)
3236 
3237 static int dwc2_hsotg_ep_disable(struct usb_ep *ep);
3238 /**
3239  * dwc2_hsotg_core_init - issue softreset to the core
3240  * @hsotg: The device state
3241  * @is_usb_reset: Usb resetting flag
3242  *
3243  * Issue a soft reset to the core, and await the core finishing it.
3244  */
3245 void dwc2_hsotg_core_init_disconnected(struct dwc2_hsotg *hsotg,
3246 				       bool is_usb_reset)
3247 {
3248 	u32 intmsk;
3249 	u32 val;
3250 	u32 usbcfg;
3251 	u32 dcfg = 0;
3252 	int ep;
3253 
3254 	/* Kill any ep0 requests as controller will be reinitialized */
3255 	kill_all_requests(hsotg, hsotg->eps_out[0], -ECONNRESET);
3256 
3257 	if (!is_usb_reset) {
3258 		if (dwc2_core_reset(hsotg, true))
3259 			return;
3260 	} else {
3261 		/* all endpoints should be shutdown */
3262 		for (ep = 1; ep < hsotg->num_of_eps; ep++) {
3263 			if (hsotg->eps_in[ep])
3264 				dwc2_hsotg_ep_disable(&hsotg->eps_in[ep]->ep);
3265 			if (hsotg->eps_out[ep])
3266 				dwc2_hsotg_ep_disable(&hsotg->eps_out[ep]->ep);
3267 		}
3268 	}
3269 
3270 	/*
3271 	 * we must now enable ep0 ready for host detection and then
3272 	 * set configuration.
3273 	 */
3274 
3275 	/* keep other bits untouched (so e.g. forced modes are not lost) */
3276 	usbcfg = dwc2_readl(hsotg, GUSBCFG);
3277 	usbcfg &= ~(GUSBCFG_TOUTCAL_MASK | GUSBCFG_PHYIF16 | GUSBCFG_SRPCAP |
3278 		GUSBCFG_HNPCAP | GUSBCFG_USBTRDTIM_MASK);
3279 
3280 	if (hsotg->params.phy_type == DWC2_PHY_TYPE_PARAM_FS &&
3281 	    (hsotg->params.speed == DWC2_SPEED_PARAM_FULL ||
3282 	     hsotg->params.speed == DWC2_SPEED_PARAM_LOW)) {
3283 		/* FS/LS Dedicated Transceiver Interface */
3284 		usbcfg |= GUSBCFG_PHYSEL;
3285 	} else {
3286 		/* set the PLL on, remove the HNP/SRP and set the PHY */
3287 		val = (hsotg->phyif == GUSBCFG_PHYIF8) ? 9 : 5;
3288 		usbcfg |= hsotg->phyif | GUSBCFG_TOUTCAL(7) |
3289 			(val << GUSBCFG_USBTRDTIM_SHIFT);
3290 	}
3291 	dwc2_writel(hsotg, usbcfg, GUSBCFG);
3292 
3293 	dwc2_hsotg_init_fifo(hsotg);
3294 
3295 	if (!is_usb_reset)
3296 		dwc2_set_bit(hsotg, DCTL, DCTL_SFTDISCON);
3297 
3298 	dcfg |= DCFG_EPMISCNT(1);
3299 
3300 	switch (hsotg->params.speed) {
3301 	case DWC2_SPEED_PARAM_LOW:
3302 		dcfg |= DCFG_DEVSPD_LS;
3303 		break;
3304 	case DWC2_SPEED_PARAM_FULL:
3305 		if (hsotg->params.phy_type == DWC2_PHY_TYPE_PARAM_FS)
3306 			dcfg |= DCFG_DEVSPD_FS48;
3307 		else
3308 			dcfg |= DCFG_DEVSPD_FS;
3309 		break;
3310 	default:
3311 		dcfg |= DCFG_DEVSPD_HS;
3312 	}
3313 
3314 	if (hsotg->params.ipg_isoc_en)
3315 		dcfg |= DCFG_IPG_ISOC_SUPPORDED;
3316 
3317 	dwc2_writel(hsotg, dcfg,  DCFG);
3318 
3319 	/* Clear any pending OTG interrupts */
3320 	dwc2_writel(hsotg, 0xffffffff, GOTGINT);
3321 
3322 	/* Clear any pending interrupts */
3323 	dwc2_writel(hsotg, 0xffffffff, GINTSTS);
3324 	intmsk = GINTSTS_ERLYSUSP | GINTSTS_SESSREQINT |
3325 		GINTSTS_GOUTNAKEFF | GINTSTS_GINNAKEFF |
3326 		GINTSTS_USBRST | GINTSTS_RESETDET |
3327 		GINTSTS_ENUMDONE | GINTSTS_OTGINT |
3328 		GINTSTS_USBSUSP | GINTSTS_WKUPINT |
3329 		GINTSTS_LPMTRANRCVD;
3330 
3331 	if (!using_desc_dma(hsotg))
3332 		intmsk |= GINTSTS_INCOMPL_SOIN | GINTSTS_INCOMPL_SOOUT;
3333 
3334 	if (!hsotg->params.external_id_pin_ctl)
3335 		intmsk |= GINTSTS_CONIDSTSCHNG;
3336 
3337 	dwc2_writel(hsotg, intmsk, GINTMSK);
3338 
3339 	if (using_dma(hsotg)) {
3340 		dwc2_writel(hsotg, GAHBCFG_GLBL_INTR_EN | GAHBCFG_DMA_EN |
3341 			    hsotg->params.ahbcfg,
3342 			    GAHBCFG);
3343 
3344 		/* Set DDMA mode support in the core if needed */
3345 		if (using_desc_dma(hsotg))
3346 			dwc2_set_bit(hsotg, DCFG, DCFG_DESCDMA_EN);
3347 
3348 	} else {
3349 		dwc2_writel(hsotg, ((hsotg->dedicated_fifos) ?
3350 						(GAHBCFG_NP_TXF_EMP_LVL |
3351 						 GAHBCFG_P_TXF_EMP_LVL) : 0) |
3352 			    GAHBCFG_GLBL_INTR_EN, GAHBCFG);
3353 	}
3354 
3355 	/*
3356 	 * If INTknTXFEmpMsk is enabled, it's important to disable ep interrupts
3357 	 * when we have no data to transfer. Otherwise we get being flooded by
3358 	 * interrupts.
3359 	 */
3360 
3361 	dwc2_writel(hsotg, ((hsotg->dedicated_fifos && !using_dma(hsotg)) ?
3362 		DIEPMSK_TXFIFOEMPTY | DIEPMSK_INTKNTXFEMPMSK : 0) |
3363 		DIEPMSK_EPDISBLDMSK | DIEPMSK_XFERCOMPLMSK |
3364 		DIEPMSK_TIMEOUTMSK | DIEPMSK_AHBERRMSK,
3365 		DIEPMSK);
3366 
3367 	/*
3368 	 * don't need XferCompl, we get that from RXFIFO in slave mode. In
3369 	 * DMA mode we may need this and StsPhseRcvd.
3370 	 */
3371 	dwc2_writel(hsotg, (using_dma(hsotg) ? (DIEPMSK_XFERCOMPLMSK |
3372 		DOEPMSK_STSPHSERCVDMSK) : 0) |
3373 		DOEPMSK_EPDISBLDMSK | DOEPMSK_AHBERRMSK |
3374 		DOEPMSK_SETUPMSK,
3375 		DOEPMSK);
3376 
3377 	/* Enable BNA interrupt for DDMA */
3378 	if (using_desc_dma(hsotg)) {
3379 		dwc2_set_bit(hsotg, DOEPMSK, DOEPMSK_BNAMSK);
3380 		dwc2_set_bit(hsotg, DIEPMSK, DIEPMSK_BNAININTRMSK);
3381 	}
3382 
3383 	/* Enable Service Interval mode if supported */
3384 	if (using_desc_dma(hsotg) && hsotg->params.service_interval)
3385 		dwc2_set_bit(hsotg, DCTL, DCTL_SERVICE_INTERVAL_SUPPORTED);
3386 
3387 	dwc2_writel(hsotg, 0, DAINTMSK);
3388 
3389 	dev_dbg(hsotg->dev, "EP0: DIEPCTL0=0x%08x, DOEPCTL0=0x%08x\n",
3390 		dwc2_readl(hsotg, DIEPCTL0),
3391 		dwc2_readl(hsotg, DOEPCTL0));
3392 
3393 	/* enable in and out endpoint interrupts */
3394 	dwc2_hsotg_en_gsint(hsotg, GINTSTS_OEPINT | GINTSTS_IEPINT);
3395 
3396 	/*
3397 	 * Enable the RXFIFO when in slave mode, as this is how we collect
3398 	 * the data. In DMA mode, we get events from the FIFO but also
3399 	 * things we cannot process, so do not use it.
3400 	 */
3401 	if (!using_dma(hsotg))
3402 		dwc2_hsotg_en_gsint(hsotg, GINTSTS_RXFLVL);
3403 
3404 	/* Enable interrupts for EP0 in and out */
3405 	dwc2_hsotg_ctrl_epint(hsotg, 0, 0, 1);
3406 	dwc2_hsotg_ctrl_epint(hsotg, 0, 1, 1);
3407 
3408 	if (!is_usb_reset) {
3409 		dwc2_set_bit(hsotg, DCTL, DCTL_PWRONPRGDONE);
3410 		udelay(10);  /* see openiboot */
3411 		dwc2_clear_bit(hsotg, DCTL, DCTL_PWRONPRGDONE);
3412 	}
3413 
3414 	dev_dbg(hsotg->dev, "DCTL=0x%08x\n", dwc2_readl(hsotg, DCTL));
3415 
3416 	/*
3417 	 * DxEPCTL_USBActEp says RO in manual, but seems to be set by
3418 	 * writing to the EPCTL register..
3419 	 */
3420 
3421 	/* set to read 1 8byte packet */
3422 	dwc2_writel(hsotg, DXEPTSIZ_MC(1) | DXEPTSIZ_PKTCNT(1) |
3423 	       DXEPTSIZ_XFERSIZE(8), DOEPTSIZ0);
3424 
3425 	dwc2_writel(hsotg, dwc2_hsotg_ep0_mps(hsotg->eps_out[0]->ep.maxpacket) |
3426 	       DXEPCTL_CNAK | DXEPCTL_EPENA |
3427 	       DXEPCTL_USBACTEP,
3428 	       DOEPCTL0);
3429 
3430 	/* enable, but don't activate EP0in */
3431 	dwc2_writel(hsotg, dwc2_hsotg_ep0_mps(hsotg->eps_out[0]->ep.maxpacket) |
3432 	       DXEPCTL_USBACTEP, DIEPCTL0);
3433 
3434 	/* clear global NAKs */
3435 	val = DCTL_CGOUTNAK | DCTL_CGNPINNAK;
3436 	if (!is_usb_reset)
3437 		val |= DCTL_SFTDISCON;
3438 	dwc2_set_bit(hsotg, DCTL, val);
3439 
3440 	/* configure the core to support LPM */
3441 	dwc2_gadget_init_lpm(hsotg);
3442 
3443 	/* program GREFCLK register if needed */
3444 	if (using_desc_dma(hsotg) && hsotg->params.service_interval)
3445 		dwc2_gadget_program_ref_clk(hsotg);
3446 
3447 	/* must be at-least 3ms to allow bus to see disconnect */
3448 	mdelay(3);
3449 
3450 	hsotg->lx_state = DWC2_L0;
3451 
3452 	dwc2_hsotg_enqueue_setup(hsotg);
3453 
3454 	dev_dbg(hsotg->dev, "EP0: DIEPCTL0=0x%08x, DOEPCTL0=0x%08x\n",
3455 		dwc2_readl(hsotg, DIEPCTL0),
3456 		dwc2_readl(hsotg, DOEPCTL0));
3457 }
3458 
3459 static void dwc2_hsotg_core_disconnect(struct dwc2_hsotg *hsotg)
3460 {
3461 	/* set the soft-disconnect bit */
3462 	dwc2_set_bit(hsotg, DCTL, DCTL_SFTDISCON);
3463 }
3464 
3465 void dwc2_hsotg_core_connect(struct dwc2_hsotg *hsotg)
3466 {
3467 	/* remove the soft-disconnect and let's go */
3468 	dwc2_clear_bit(hsotg, DCTL, DCTL_SFTDISCON);
3469 }
3470 
3471 /**
3472  * dwc2_gadget_handle_incomplete_isoc_in - handle incomplete ISO IN Interrupt.
3473  * @hsotg: The device state:
3474  *
3475  * This interrupt indicates one of the following conditions occurred while
3476  * transmitting an ISOC transaction.
3477  * - Corrupted IN Token for ISOC EP.
3478  * - Packet not complete in FIFO.
3479  *
3480  * The following actions will be taken:
3481  * - Determine the EP
3482  * - Disable EP; when 'Endpoint Disabled' interrupt is received Flush FIFO
3483  */
3484 static void dwc2_gadget_handle_incomplete_isoc_in(struct dwc2_hsotg *hsotg)
3485 {
3486 	struct dwc2_hsotg_ep *hs_ep;
3487 	u32 epctrl;
3488 	u32 daintmsk;
3489 	u32 idx;
3490 
3491 	dev_dbg(hsotg->dev, "Incomplete isoc in interrupt received:\n");
3492 
3493 	daintmsk = dwc2_readl(hsotg, DAINTMSK);
3494 
3495 	for (idx = 1; idx < hsotg->num_of_eps; idx++) {
3496 		hs_ep = hsotg->eps_in[idx];
3497 		/* Proceed only unmasked ISOC EPs */
3498 		if ((BIT(idx) & ~daintmsk) || !hs_ep->isochronous)
3499 			continue;
3500 
3501 		epctrl = dwc2_readl(hsotg, DIEPCTL(idx));
3502 		if ((epctrl & DXEPCTL_EPENA) &&
3503 		    dwc2_gadget_target_frame_elapsed(hs_ep)) {
3504 			epctrl |= DXEPCTL_SNAK;
3505 			epctrl |= DXEPCTL_EPDIS;
3506 			dwc2_writel(hsotg, epctrl, DIEPCTL(idx));
3507 		}
3508 	}
3509 
3510 	/* Clear interrupt */
3511 	dwc2_writel(hsotg, GINTSTS_INCOMPL_SOIN, GINTSTS);
3512 }
3513 
3514 /**
3515  * dwc2_gadget_handle_incomplete_isoc_out - handle incomplete ISO OUT Interrupt
3516  * @hsotg: The device state:
3517  *
3518  * This interrupt indicates one of the following conditions occurred while
3519  * transmitting an ISOC transaction.
3520  * - Corrupted OUT Token for ISOC EP.
3521  * - Packet not complete in FIFO.
3522  *
3523  * The following actions will be taken:
3524  * - Determine the EP
3525  * - Set DCTL_SGOUTNAK and unmask GOUTNAKEFF if target frame elapsed.
3526  */
3527 static void dwc2_gadget_handle_incomplete_isoc_out(struct dwc2_hsotg *hsotg)
3528 {
3529 	u32 gintsts;
3530 	u32 gintmsk;
3531 	u32 daintmsk;
3532 	u32 epctrl;
3533 	struct dwc2_hsotg_ep *hs_ep;
3534 	int idx;
3535 
3536 	dev_dbg(hsotg->dev, "%s: GINTSTS_INCOMPL_SOOUT\n", __func__);
3537 
3538 	daintmsk = dwc2_readl(hsotg, DAINTMSK);
3539 	daintmsk >>= DAINT_OUTEP_SHIFT;
3540 
3541 	for (idx = 1; idx < hsotg->num_of_eps; idx++) {
3542 		hs_ep = hsotg->eps_out[idx];
3543 		/* Proceed only unmasked ISOC EPs */
3544 		if ((BIT(idx) & ~daintmsk) || !hs_ep->isochronous)
3545 			continue;
3546 
3547 		epctrl = dwc2_readl(hsotg, DOEPCTL(idx));
3548 		if ((epctrl & DXEPCTL_EPENA) &&
3549 		    dwc2_gadget_target_frame_elapsed(hs_ep)) {
3550 			/* Unmask GOUTNAKEFF interrupt */
3551 			gintmsk = dwc2_readl(hsotg, GINTMSK);
3552 			gintmsk |= GINTSTS_GOUTNAKEFF;
3553 			dwc2_writel(hsotg, gintmsk, GINTMSK);
3554 
3555 			gintsts = dwc2_readl(hsotg, GINTSTS);
3556 			if (!(gintsts & GINTSTS_GOUTNAKEFF)) {
3557 				dwc2_set_bit(hsotg, DCTL, DCTL_SGOUTNAK);
3558 				break;
3559 			}
3560 		}
3561 	}
3562 
3563 	/* Clear interrupt */
3564 	dwc2_writel(hsotg, GINTSTS_INCOMPL_SOOUT, GINTSTS);
3565 }
3566 
3567 /**
3568  * dwc2_hsotg_irq - handle device interrupt
3569  * @irq: The IRQ number triggered
3570  * @pw: The pw value when registered the handler.
3571  */
3572 static irqreturn_t dwc2_hsotg_irq(int irq, void *pw)
3573 {
3574 	struct dwc2_hsotg *hsotg = pw;
3575 	int retry_count = 8;
3576 	u32 gintsts;
3577 	u32 gintmsk;
3578 
3579 	if (!dwc2_is_device_mode(hsotg))
3580 		return IRQ_NONE;
3581 
3582 	spin_lock(&hsotg->lock);
3583 irq_retry:
3584 	gintsts = dwc2_readl(hsotg, GINTSTS);
3585 	gintmsk = dwc2_readl(hsotg, GINTMSK);
3586 
3587 	dev_dbg(hsotg->dev, "%s: %08x %08x (%08x) retry %d\n",
3588 		__func__, gintsts, gintsts & gintmsk, gintmsk, retry_count);
3589 
3590 	gintsts &= gintmsk;
3591 
3592 	if (gintsts & GINTSTS_RESETDET) {
3593 		dev_dbg(hsotg->dev, "%s: USBRstDet\n", __func__);
3594 
3595 		dwc2_writel(hsotg, GINTSTS_RESETDET, GINTSTS);
3596 
3597 		/* This event must be used only if controller is suspended */
3598 		if (hsotg->lx_state == DWC2_L2) {
3599 			dwc2_exit_partial_power_down(hsotg, true);
3600 			hsotg->lx_state = DWC2_L0;
3601 		}
3602 	}
3603 
3604 	if (gintsts & (GINTSTS_USBRST | GINTSTS_RESETDET)) {
3605 		u32 usb_status = dwc2_readl(hsotg, GOTGCTL);
3606 		u32 connected = hsotg->connected;
3607 
3608 		dev_dbg(hsotg->dev, "%s: USBRst\n", __func__);
3609 		dev_dbg(hsotg->dev, "GNPTXSTS=%08x\n",
3610 			dwc2_readl(hsotg, GNPTXSTS));
3611 
3612 		dwc2_writel(hsotg, GINTSTS_USBRST, GINTSTS);
3613 
3614 		/* Report disconnection if it is not already done. */
3615 		dwc2_hsotg_disconnect(hsotg);
3616 
3617 		/* Reset device address to zero */
3618 		dwc2_clear_bit(hsotg, DCFG, DCFG_DEVADDR_MASK);
3619 
3620 		if (usb_status & GOTGCTL_BSESVLD && connected)
3621 			dwc2_hsotg_core_init_disconnected(hsotg, true);
3622 	}
3623 
3624 	if (gintsts & GINTSTS_ENUMDONE) {
3625 		dwc2_writel(hsotg, GINTSTS_ENUMDONE, GINTSTS);
3626 
3627 		dwc2_hsotg_irq_enumdone(hsotg);
3628 	}
3629 
3630 	if (gintsts & (GINTSTS_OEPINT | GINTSTS_IEPINT)) {
3631 		u32 daint = dwc2_readl(hsotg, DAINT);
3632 		u32 daintmsk = dwc2_readl(hsotg, DAINTMSK);
3633 		u32 daint_out, daint_in;
3634 		int ep;
3635 
3636 		daint &= daintmsk;
3637 		daint_out = daint >> DAINT_OUTEP_SHIFT;
3638 		daint_in = daint & ~(daint_out << DAINT_OUTEP_SHIFT);
3639 
3640 		dev_dbg(hsotg->dev, "%s: daint=%08x\n", __func__, daint);
3641 
3642 		for (ep = 0; ep < hsotg->num_of_eps && daint_out;
3643 						ep++, daint_out >>= 1) {
3644 			if (daint_out & 1)
3645 				dwc2_hsotg_epint(hsotg, ep, 0);
3646 		}
3647 
3648 		for (ep = 0; ep < hsotg->num_of_eps  && daint_in;
3649 						ep++, daint_in >>= 1) {
3650 			if (daint_in & 1)
3651 				dwc2_hsotg_epint(hsotg, ep, 1);
3652 		}
3653 	}
3654 
3655 	/* check both FIFOs */
3656 
3657 	if (gintsts & GINTSTS_NPTXFEMP) {
3658 		dev_dbg(hsotg->dev, "NPTxFEmp\n");
3659 
3660 		/*
3661 		 * Disable the interrupt to stop it happening again
3662 		 * unless one of these endpoint routines decides that
3663 		 * it needs re-enabling
3664 		 */
3665 
3666 		dwc2_hsotg_disable_gsint(hsotg, GINTSTS_NPTXFEMP);
3667 		dwc2_hsotg_irq_fifoempty(hsotg, false);
3668 	}
3669 
3670 	if (gintsts & GINTSTS_PTXFEMP) {
3671 		dev_dbg(hsotg->dev, "PTxFEmp\n");
3672 
3673 		/* See note in GINTSTS_NPTxFEmp */
3674 
3675 		dwc2_hsotg_disable_gsint(hsotg, GINTSTS_PTXFEMP);
3676 		dwc2_hsotg_irq_fifoempty(hsotg, true);
3677 	}
3678 
3679 	if (gintsts & GINTSTS_RXFLVL) {
3680 		/*
3681 		 * note, since GINTSTS_RxFLvl doubles as FIFO-not-empty,
3682 		 * we need to retry dwc2_hsotg_handle_rx if this is still
3683 		 * set.
3684 		 */
3685 
3686 		dwc2_hsotg_handle_rx(hsotg);
3687 	}
3688 
3689 	if (gintsts & GINTSTS_ERLYSUSP) {
3690 		dev_dbg(hsotg->dev, "GINTSTS_ErlySusp\n");
3691 		dwc2_writel(hsotg, GINTSTS_ERLYSUSP, GINTSTS);
3692 	}
3693 
3694 	/*
3695 	 * these next two seem to crop-up occasionally causing the core
3696 	 * to shutdown the USB transfer, so try clearing them and logging
3697 	 * the occurrence.
3698 	 */
3699 
3700 	if (gintsts & GINTSTS_GOUTNAKEFF) {
3701 		u8 idx;
3702 		u32 epctrl;
3703 		u32 gintmsk;
3704 		u32 daintmsk;
3705 		struct dwc2_hsotg_ep *hs_ep;
3706 
3707 		daintmsk = dwc2_readl(hsotg, DAINTMSK);
3708 		daintmsk >>= DAINT_OUTEP_SHIFT;
3709 		/* Mask this interrupt */
3710 		gintmsk = dwc2_readl(hsotg, GINTMSK);
3711 		gintmsk &= ~GINTSTS_GOUTNAKEFF;
3712 		dwc2_writel(hsotg, gintmsk, GINTMSK);
3713 
3714 		dev_dbg(hsotg->dev, "GOUTNakEff triggered\n");
3715 		for (idx = 1; idx < hsotg->num_of_eps; idx++) {
3716 			hs_ep = hsotg->eps_out[idx];
3717 			/* Proceed only unmasked ISOC EPs */
3718 			if ((BIT(idx) & ~daintmsk) || !hs_ep->isochronous)
3719 				continue;
3720 
3721 			epctrl = dwc2_readl(hsotg, DOEPCTL(idx));
3722 
3723 			if (epctrl & DXEPCTL_EPENA) {
3724 				epctrl |= DXEPCTL_SNAK;
3725 				epctrl |= DXEPCTL_EPDIS;
3726 				dwc2_writel(hsotg, epctrl, DOEPCTL(idx));
3727 			}
3728 		}
3729 
3730 		/* This interrupt bit is cleared in DXEPINT_EPDISBLD handler */
3731 	}
3732 
3733 	if (gintsts & GINTSTS_GINNAKEFF) {
3734 		dev_info(hsotg->dev, "GINNakEff triggered\n");
3735 
3736 		dwc2_set_bit(hsotg, DCTL, DCTL_CGNPINNAK);
3737 
3738 		dwc2_hsotg_dump(hsotg);
3739 	}
3740 
3741 	if (gintsts & GINTSTS_INCOMPL_SOIN)
3742 		dwc2_gadget_handle_incomplete_isoc_in(hsotg);
3743 
3744 	if (gintsts & GINTSTS_INCOMPL_SOOUT)
3745 		dwc2_gadget_handle_incomplete_isoc_out(hsotg);
3746 
3747 	/*
3748 	 * if we've had fifo events, we should try and go around the
3749 	 * loop again to see if there's any point in returning yet.
3750 	 */
3751 
3752 	if (gintsts & IRQ_RETRY_MASK && --retry_count > 0)
3753 		goto irq_retry;
3754 
3755 	/* Check WKUP_ALERT interrupt*/
3756 	if (hsotg->params.service_interval)
3757 		dwc2_gadget_wkup_alert_handler(hsotg);
3758 
3759 	spin_unlock(&hsotg->lock);
3760 
3761 	return IRQ_HANDLED;
3762 }
3763 
3764 static void dwc2_hsotg_ep_stop_xfr(struct dwc2_hsotg *hsotg,
3765 				   struct dwc2_hsotg_ep *hs_ep)
3766 {
3767 	u32 epctrl_reg;
3768 	u32 epint_reg;
3769 
3770 	epctrl_reg = hs_ep->dir_in ? DIEPCTL(hs_ep->index) :
3771 		DOEPCTL(hs_ep->index);
3772 	epint_reg = hs_ep->dir_in ? DIEPINT(hs_ep->index) :
3773 		DOEPINT(hs_ep->index);
3774 
3775 	dev_dbg(hsotg->dev, "%s: stopping transfer on %s\n", __func__,
3776 		hs_ep->name);
3777 
3778 	if (hs_ep->dir_in) {
3779 		if (hsotg->dedicated_fifos || hs_ep->periodic) {
3780 			dwc2_set_bit(hsotg, epctrl_reg, DXEPCTL_SNAK);
3781 			/* Wait for Nak effect */
3782 			if (dwc2_hsotg_wait_bit_set(hsotg, epint_reg,
3783 						    DXEPINT_INEPNAKEFF, 100))
3784 				dev_warn(hsotg->dev,
3785 					 "%s: timeout DIEPINT.NAKEFF\n",
3786 					 __func__);
3787 		} else {
3788 			dwc2_set_bit(hsotg, DCTL, DCTL_SGNPINNAK);
3789 			/* Wait for Nak effect */
3790 			if (dwc2_hsotg_wait_bit_set(hsotg, GINTSTS,
3791 						    GINTSTS_GINNAKEFF, 100))
3792 				dev_warn(hsotg->dev,
3793 					 "%s: timeout GINTSTS.GINNAKEFF\n",
3794 					 __func__);
3795 		}
3796 	} else {
3797 		if (!(dwc2_readl(hsotg, GINTSTS) & GINTSTS_GOUTNAKEFF))
3798 			dwc2_set_bit(hsotg, DCTL, DCTL_SGOUTNAK);
3799 
3800 		/* Wait for global nak to take effect */
3801 		if (dwc2_hsotg_wait_bit_set(hsotg, GINTSTS,
3802 					    GINTSTS_GOUTNAKEFF, 100))
3803 			dev_warn(hsotg->dev, "%s: timeout GINTSTS.GOUTNAKEFF\n",
3804 				 __func__);
3805 	}
3806 
3807 	/* Disable ep */
3808 	dwc2_set_bit(hsotg, epctrl_reg, DXEPCTL_EPDIS | DXEPCTL_SNAK);
3809 
3810 	/* Wait for ep to be disabled */
3811 	if (dwc2_hsotg_wait_bit_set(hsotg, epint_reg, DXEPINT_EPDISBLD, 100))
3812 		dev_warn(hsotg->dev,
3813 			 "%s: timeout DOEPCTL.EPDisable\n", __func__);
3814 
3815 	/* Clear EPDISBLD interrupt */
3816 	dwc2_set_bit(hsotg, epint_reg, DXEPINT_EPDISBLD);
3817 
3818 	if (hs_ep->dir_in) {
3819 		unsigned short fifo_index;
3820 
3821 		if (hsotg->dedicated_fifos || hs_ep->periodic)
3822 			fifo_index = hs_ep->fifo_index;
3823 		else
3824 			fifo_index = 0;
3825 
3826 		/* Flush TX FIFO */
3827 		dwc2_flush_tx_fifo(hsotg, fifo_index);
3828 
3829 		/* Clear Global In NP NAK in Shared FIFO for non periodic ep */
3830 		if (!hsotg->dedicated_fifos && !hs_ep->periodic)
3831 			dwc2_set_bit(hsotg, DCTL, DCTL_CGNPINNAK);
3832 
3833 	} else {
3834 		/* Remove global NAKs */
3835 		dwc2_set_bit(hsotg, DCTL, DCTL_CGOUTNAK);
3836 	}
3837 }
3838 
3839 /**
3840  * dwc2_hsotg_ep_enable - enable the given endpoint
3841  * @ep: The USB endpint to configure
3842  * @desc: The USB endpoint descriptor to configure with.
3843  *
3844  * This is called from the USB gadget code's usb_ep_enable().
3845  */
3846 static int dwc2_hsotg_ep_enable(struct usb_ep *ep,
3847 				const struct usb_endpoint_descriptor *desc)
3848 {
3849 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
3850 	struct dwc2_hsotg *hsotg = hs_ep->parent;
3851 	unsigned long flags;
3852 	unsigned int index = hs_ep->index;
3853 	u32 epctrl_reg;
3854 	u32 epctrl;
3855 	u32 mps;
3856 	u32 mc;
3857 	u32 mask;
3858 	unsigned int dir_in;
3859 	unsigned int i, val, size;
3860 	int ret = 0;
3861 	unsigned char ep_type;
3862 
3863 	dev_dbg(hsotg->dev,
3864 		"%s: ep %s: a 0x%02x, attr 0x%02x, mps 0x%04x, intr %d\n",
3865 		__func__, ep->name, desc->bEndpointAddress, desc->bmAttributes,
3866 		desc->wMaxPacketSize, desc->bInterval);
3867 
3868 	/* not to be called for EP0 */
3869 	if (index == 0) {
3870 		dev_err(hsotg->dev, "%s: called for EP 0\n", __func__);
3871 		return -EINVAL;
3872 	}
3873 
3874 	dir_in = (desc->bEndpointAddress & USB_ENDPOINT_DIR_MASK) ? 1 : 0;
3875 	if (dir_in != hs_ep->dir_in) {
3876 		dev_err(hsotg->dev, "%s: direction mismatch!\n", __func__);
3877 		return -EINVAL;
3878 	}
3879 
3880 	ep_type = desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
3881 	mps = usb_endpoint_maxp(desc);
3882 	mc = usb_endpoint_maxp_mult(desc);
3883 
3884 	/* ISOC IN in DDMA supported bInterval up to 10 */
3885 	if (using_desc_dma(hsotg) && ep_type == USB_ENDPOINT_XFER_ISOC &&
3886 	    dir_in && desc->bInterval > 10) {
3887 		dev_err(hsotg->dev,
3888 			"%s: ISOC IN, DDMA: bInterval>10 not supported!\n", __func__);
3889 		return -EINVAL;
3890 	}
3891 
3892 	/* High bandwidth ISOC OUT in DDMA not supported */
3893 	if (using_desc_dma(hsotg) && ep_type == USB_ENDPOINT_XFER_ISOC &&
3894 	    !dir_in && mc > 1) {
3895 		dev_err(hsotg->dev,
3896 			"%s: ISOC OUT, DDMA: HB not supported!\n", __func__);
3897 		return -EINVAL;
3898 	}
3899 
3900 	/* note, we handle this here instead of dwc2_hsotg_set_ep_maxpacket */
3901 
3902 	epctrl_reg = dir_in ? DIEPCTL(index) : DOEPCTL(index);
3903 	epctrl = dwc2_readl(hsotg, epctrl_reg);
3904 
3905 	dev_dbg(hsotg->dev, "%s: read DxEPCTL=0x%08x from 0x%08x\n",
3906 		__func__, epctrl, epctrl_reg);
3907 
3908 	/* Allocate DMA descriptor chain for non-ctrl endpoints */
3909 	if (using_desc_dma(hsotg) && !hs_ep->desc_list) {
3910 		hs_ep->desc_list = dmam_alloc_coherent(hsotg->dev,
3911 			MAX_DMA_DESC_NUM_GENERIC *
3912 			sizeof(struct dwc2_dma_desc),
3913 			&hs_ep->desc_list_dma, GFP_ATOMIC);
3914 		if (!hs_ep->desc_list) {
3915 			ret = -ENOMEM;
3916 			goto error2;
3917 		}
3918 	}
3919 
3920 	spin_lock_irqsave(&hsotg->lock, flags);
3921 
3922 	epctrl &= ~(DXEPCTL_EPTYPE_MASK | DXEPCTL_MPS_MASK);
3923 	epctrl |= DXEPCTL_MPS(mps);
3924 
3925 	/*
3926 	 * mark the endpoint as active, otherwise the core may ignore
3927 	 * transactions entirely for this endpoint
3928 	 */
3929 	epctrl |= DXEPCTL_USBACTEP;
3930 
3931 	/* update the endpoint state */
3932 	dwc2_hsotg_set_ep_maxpacket(hsotg, hs_ep->index, mps, mc, dir_in);
3933 
3934 	/* default, set to non-periodic */
3935 	hs_ep->isochronous = 0;
3936 	hs_ep->periodic = 0;
3937 	hs_ep->halted = 0;
3938 	hs_ep->interval = desc->bInterval;
3939 
3940 	switch (ep_type) {
3941 	case USB_ENDPOINT_XFER_ISOC:
3942 		epctrl |= DXEPCTL_EPTYPE_ISO;
3943 		epctrl |= DXEPCTL_SETEVENFR;
3944 		hs_ep->isochronous = 1;
3945 		hs_ep->interval = 1 << (desc->bInterval - 1);
3946 		hs_ep->target_frame = TARGET_FRAME_INITIAL;
3947 		hs_ep->next_desc = 0;
3948 		hs_ep->compl_desc = 0;
3949 		if (dir_in) {
3950 			hs_ep->periodic = 1;
3951 			mask = dwc2_readl(hsotg, DIEPMSK);
3952 			mask |= DIEPMSK_NAKMSK;
3953 			dwc2_writel(hsotg, mask, DIEPMSK);
3954 		} else {
3955 			mask = dwc2_readl(hsotg, DOEPMSK);
3956 			mask |= DOEPMSK_OUTTKNEPDISMSK;
3957 			dwc2_writel(hsotg, mask, DOEPMSK);
3958 		}
3959 		break;
3960 
3961 	case USB_ENDPOINT_XFER_BULK:
3962 		epctrl |= DXEPCTL_EPTYPE_BULK;
3963 		break;
3964 
3965 	case USB_ENDPOINT_XFER_INT:
3966 		if (dir_in)
3967 			hs_ep->periodic = 1;
3968 
3969 		if (hsotg->gadget.speed == USB_SPEED_HIGH)
3970 			hs_ep->interval = 1 << (desc->bInterval - 1);
3971 
3972 		epctrl |= DXEPCTL_EPTYPE_INTERRUPT;
3973 		break;
3974 
3975 	case USB_ENDPOINT_XFER_CONTROL:
3976 		epctrl |= DXEPCTL_EPTYPE_CONTROL;
3977 		break;
3978 	}
3979 
3980 	/*
3981 	 * if the hardware has dedicated fifos, we must give each IN EP
3982 	 * a unique tx-fifo even if it is non-periodic.
3983 	 */
3984 	if (dir_in && hsotg->dedicated_fifos) {
3985 		u32 fifo_index = 0;
3986 		u32 fifo_size = UINT_MAX;
3987 
3988 		size = hs_ep->ep.maxpacket * hs_ep->mc;
3989 		for (i = 1; i < hsotg->num_of_eps; ++i) {
3990 			if (hsotg->fifo_map & (1 << i))
3991 				continue;
3992 			val = dwc2_readl(hsotg, DPTXFSIZN(i));
3993 			val = (val >> FIFOSIZE_DEPTH_SHIFT) * 4;
3994 			if (val < size)
3995 				continue;
3996 			/* Search for smallest acceptable fifo */
3997 			if (val < fifo_size) {
3998 				fifo_size = val;
3999 				fifo_index = i;
4000 			}
4001 		}
4002 		if (!fifo_index) {
4003 			dev_err(hsotg->dev,
4004 				"%s: No suitable fifo found\n", __func__);
4005 			ret = -ENOMEM;
4006 			goto error1;
4007 		}
4008 		hsotg->fifo_map |= 1 << fifo_index;
4009 		epctrl |= DXEPCTL_TXFNUM(fifo_index);
4010 		hs_ep->fifo_index = fifo_index;
4011 		hs_ep->fifo_size = fifo_size;
4012 	}
4013 
4014 	/* for non control endpoints, set PID to D0 */
4015 	if (index && !hs_ep->isochronous)
4016 		epctrl |= DXEPCTL_SETD0PID;
4017 
4018 	/* WA for Full speed ISOC IN in DDMA mode.
4019 	 * By Clear NAK status of EP, core will send ZLP
4020 	 * to IN token and assert NAK interrupt relying
4021 	 * on TxFIFO status only
4022 	 */
4023 
4024 	if (hsotg->gadget.speed == USB_SPEED_FULL &&
4025 	    hs_ep->isochronous && dir_in) {
4026 		/* The WA applies only to core versions from 2.72a
4027 		 * to 4.00a (including both). Also for FS_IOT_1.00a
4028 		 * and HS_IOT_1.00a.
4029 		 */
4030 		u32 gsnpsid = dwc2_readl(hsotg, GSNPSID);
4031 
4032 		if ((gsnpsid >= DWC2_CORE_REV_2_72a &&
4033 		     gsnpsid <= DWC2_CORE_REV_4_00a) ||
4034 		     gsnpsid == DWC2_FS_IOT_REV_1_00a ||
4035 		     gsnpsid == DWC2_HS_IOT_REV_1_00a)
4036 			epctrl |= DXEPCTL_CNAK;
4037 	}
4038 
4039 	dev_dbg(hsotg->dev, "%s: write DxEPCTL=0x%08x\n",
4040 		__func__, epctrl);
4041 
4042 	dwc2_writel(hsotg, epctrl, epctrl_reg);
4043 	dev_dbg(hsotg->dev, "%s: read DxEPCTL=0x%08x\n",
4044 		__func__, dwc2_readl(hsotg, epctrl_reg));
4045 
4046 	/* enable the endpoint interrupt */
4047 	dwc2_hsotg_ctrl_epint(hsotg, index, dir_in, 1);
4048 
4049 error1:
4050 	spin_unlock_irqrestore(&hsotg->lock, flags);
4051 
4052 error2:
4053 	if (ret && using_desc_dma(hsotg) && hs_ep->desc_list) {
4054 		dmam_free_coherent(hsotg->dev, MAX_DMA_DESC_NUM_GENERIC *
4055 			sizeof(struct dwc2_dma_desc),
4056 			hs_ep->desc_list, hs_ep->desc_list_dma);
4057 		hs_ep->desc_list = NULL;
4058 	}
4059 
4060 	return ret;
4061 }
4062 
4063 /**
4064  * dwc2_hsotg_ep_disable - disable given endpoint
4065  * @ep: The endpoint to disable.
4066  */
4067 static int dwc2_hsotg_ep_disable(struct usb_ep *ep)
4068 {
4069 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
4070 	struct dwc2_hsotg *hsotg = hs_ep->parent;
4071 	int dir_in = hs_ep->dir_in;
4072 	int index = hs_ep->index;
4073 	u32 epctrl_reg;
4074 	u32 ctrl;
4075 
4076 	dev_dbg(hsotg->dev, "%s(ep %p)\n", __func__, ep);
4077 
4078 	if (ep == &hsotg->eps_out[0]->ep) {
4079 		dev_err(hsotg->dev, "%s: called for ep0\n", __func__);
4080 		return -EINVAL;
4081 	}
4082 
4083 	if (hsotg->op_state != OTG_STATE_B_PERIPHERAL) {
4084 		dev_err(hsotg->dev, "%s: called in host mode?\n", __func__);
4085 		return -EINVAL;
4086 	}
4087 
4088 	epctrl_reg = dir_in ? DIEPCTL(index) : DOEPCTL(index);
4089 
4090 	ctrl = dwc2_readl(hsotg, epctrl_reg);
4091 
4092 	if (ctrl & DXEPCTL_EPENA)
4093 		dwc2_hsotg_ep_stop_xfr(hsotg, hs_ep);
4094 
4095 	ctrl &= ~DXEPCTL_EPENA;
4096 	ctrl &= ~DXEPCTL_USBACTEP;
4097 	ctrl |= DXEPCTL_SNAK;
4098 
4099 	dev_dbg(hsotg->dev, "%s: DxEPCTL=0x%08x\n", __func__, ctrl);
4100 	dwc2_writel(hsotg, ctrl, epctrl_reg);
4101 
4102 	/* disable endpoint interrupts */
4103 	dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index, hs_ep->dir_in, 0);
4104 
4105 	/* terminate all requests with shutdown */
4106 	kill_all_requests(hsotg, hs_ep, -ESHUTDOWN);
4107 
4108 	hsotg->fifo_map &= ~(1 << hs_ep->fifo_index);
4109 	hs_ep->fifo_index = 0;
4110 	hs_ep->fifo_size = 0;
4111 
4112 	return 0;
4113 }
4114 
4115 static int dwc2_hsotg_ep_disable_lock(struct usb_ep *ep)
4116 {
4117 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
4118 	struct dwc2_hsotg *hsotg = hs_ep->parent;
4119 	unsigned long flags;
4120 	int ret;
4121 
4122 	spin_lock_irqsave(&hsotg->lock, flags);
4123 	ret = dwc2_hsotg_ep_disable(ep);
4124 	spin_unlock_irqrestore(&hsotg->lock, flags);
4125 	return ret;
4126 }
4127 
4128 /**
4129  * on_list - check request is on the given endpoint
4130  * @ep: The endpoint to check.
4131  * @test: The request to test if it is on the endpoint.
4132  */
4133 static bool on_list(struct dwc2_hsotg_ep *ep, struct dwc2_hsotg_req *test)
4134 {
4135 	struct dwc2_hsotg_req *req, *treq;
4136 
4137 	list_for_each_entry_safe(req, treq, &ep->queue, queue) {
4138 		if (req == test)
4139 			return true;
4140 	}
4141 
4142 	return false;
4143 }
4144 
4145 /**
4146  * dwc2_hsotg_ep_dequeue - dequeue given endpoint
4147  * @ep: The endpoint to dequeue.
4148  * @req: The request to be removed from a queue.
4149  */
4150 static int dwc2_hsotg_ep_dequeue(struct usb_ep *ep, struct usb_request *req)
4151 {
4152 	struct dwc2_hsotg_req *hs_req = our_req(req);
4153 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
4154 	struct dwc2_hsotg *hs = hs_ep->parent;
4155 	unsigned long flags;
4156 
4157 	dev_dbg(hs->dev, "ep_dequeue(%p,%p)\n", ep, req);
4158 
4159 	spin_lock_irqsave(&hs->lock, flags);
4160 
4161 	if (!on_list(hs_ep, hs_req)) {
4162 		spin_unlock_irqrestore(&hs->lock, flags);
4163 		return -EINVAL;
4164 	}
4165 
4166 	/* Dequeue already started request */
4167 	if (req == &hs_ep->req->req)
4168 		dwc2_hsotg_ep_stop_xfr(hs, hs_ep);
4169 
4170 	dwc2_hsotg_complete_request(hs, hs_ep, hs_req, -ECONNRESET);
4171 	spin_unlock_irqrestore(&hs->lock, flags);
4172 
4173 	return 0;
4174 }
4175 
4176 /**
4177  * dwc2_hsotg_ep_sethalt - set halt on a given endpoint
4178  * @ep: The endpoint to set halt.
4179  * @value: Set or unset the halt.
4180  * @now: If true, stall the endpoint now. Otherwise return -EAGAIN if
4181  *       the endpoint is busy processing requests.
4182  *
4183  * We need to stall the endpoint immediately if request comes from set_feature
4184  * protocol command handler.
4185  */
4186 static int dwc2_hsotg_ep_sethalt(struct usb_ep *ep, int value, bool now)
4187 {
4188 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
4189 	struct dwc2_hsotg *hs = hs_ep->parent;
4190 	int index = hs_ep->index;
4191 	u32 epreg;
4192 	u32 epctl;
4193 	u32 xfertype;
4194 
4195 	dev_info(hs->dev, "%s(ep %p %s, %d)\n", __func__, ep, ep->name, value);
4196 
4197 	if (index == 0) {
4198 		if (value)
4199 			dwc2_hsotg_stall_ep0(hs);
4200 		else
4201 			dev_warn(hs->dev,
4202 				 "%s: can't clear halt on ep0\n", __func__);
4203 		return 0;
4204 	}
4205 
4206 	if (hs_ep->isochronous) {
4207 		dev_err(hs->dev, "%s is Isochronous Endpoint\n", ep->name);
4208 		return -EINVAL;
4209 	}
4210 
4211 	if (!now && value && !list_empty(&hs_ep->queue)) {
4212 		dev_dbg(hs->dev, "%s request is pending, cannot halt\n",
4213 			ep->name);
4214 		return -EAGAIN;
4215 	}
4216 
4217 	if (hs_ep->dir_in) {
4218 		epreg = DIEPCTL(index);
4219 		epctl = dwc2_readl(hs, epreg);
4220 
4221 		if (value) {
4222 			epctl |= DXEPCTL_STALL | DXEPCTL_SNAK;
4223 			if (epctl & DXEPCTL_EPENA)
4224 				epctl |= DXEPCTL_EPDIS;
4225 		} else {
4226 			epctl &= ~DXEPCTL_STALL;
4227 			xfertype = epctl & DXEPCTL_EPTYPE_MASK;
4228 			if (xfertype == DXEPCTL_EPTYPE_BULK ||
4229 			    xfertype == DXEPCTL_EPTYPE_INTERRUPT)
4230 				epctl |= DXEPCTL_SETD0PID;
4231 		}
4232 		dwc2_writel(hs, epctl, epreg);
4233 	} else {
4234 		epreg = DOEPCTL(index);
4235 		epctl = dwc2_readl(hs, epreg);
4236 
4237 		if (value) {
4238 			epctl |= DXEPCTL_STALL;
4239 		} else {
4240 			epctl &= ~DXEPCTL_STALL;
4241 			xfertype = epctl & DXEPCTL_EPTYPE_MASK;
4242 			if (xfertype == DXEPCTL_EPTYPE_BULK ||
4243 			    xfertype == DXEPCTL_EPTYPE_INTERRUPT)
4244 				epctl |= DXEPCTL_SETD0PID;
4245 		}
4246 		dwc2_writel(hs, epctl, epreg);
4247 	}
4248 
4249 	hs_ep->halted = value;
4250 
4251 	return 0;
4252 }
4253 
4254 /**
4255  * dwc2_hsotg_ep_sethalt_lock - set halt on a given endpoint with lock held
4256  * @ep: The endpoint to set halt.
4257  * @value: Set or unset the halt.
4258  */
4259 static int dwc2_hsotg_ep_sethalt_lock(struct usb_ep *ep, int value)
4260 {
4261 	struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
4262 	struct dwc2_hsotg *hs = hs_ep->parent;
4263 	unsigned long flags = 0;
4264 	int ret = 0;
4265 
4266 	spin_lock_irqsave(&hs->lock, flags);
4267 	ret = dwc2_hsotg_ep_sethalt(ep, value, false);
4268 	spin_unlock_irqrestore(&hs->lock, flags);
4269 
4270 	return ret;
4271 }
4272 
4273 static const struct usb_ep_ops dwc2_hsotg_ep_ops = {
4274 	.enable		= dwc2_hsotg_ep_enable,
4275 	.disable	= dwc2_hsotg_ep_disable_lock,
4276 	.alloc_request	= dwc2_hsotg_ep_alloc_request,
4277 	.free_request	= dwc2_hsotg_ep_free_request,
4278 	.queue		= dwc2_hsotg_ep_queue_lock,
4279 	.dequeue	= dwc2_hsotg_ep_dequeue,
4280 	.set_halt	= dwc2_hsotg_ep_sethalt_lock,
4281 	/* note, don't believe we have any call for the fifo routines */
4282 };
4283 
4284 /**
4285  * dwc2_hsotg_init - initialize the usb core
4286  * @hsotg: The driver state
4287  */
4288 static void dwc2_hsotg_init(struct dwc2_hsotg *hsotg)
4289 {
4290 	u32 trdtim;
4291 	u32 usbcfg;
4292 	/* unmask subset of endpoint interrupts */
4293 
4294 	dwc2_writel(hsotg, DIEPMSK_TIMEOUTMSK | DIEPMSK_AHBERRMSK |
4295 		    DIEPMSK_EPDISBLDMSK | DIEPMSK_XFERCOMPLMSK,
4296 		    DIEPMSK);
4297 
4298 	dwc2_writel(hsotg, DOEPMSK_SETUPMSK | DOEPMSK_AHBERRMSK |
4299 		    DOEPMSK_EPDISBLDMSK | DOEPMSK_XFERCOMPLMSK,
4300 		    DOEPMSK);
4301 
4302 	dwc2_writel(hsotg, 0, DAINTMSK);
4303 
4304 	/* Be in disconnected state until gadget is registered */
4305 	dwc2_set_bit(hsotg, DCTL, DCTL_SFTDISCON);
4306 
4307 	/* setup fifos */
4308 
4309 	dev_dbg(hsotg->dev, "GRXFSIZ=0x%08x, GNPTXFSIZ=0x%08x\n",
4310 		dwc2_readl(hsotg, GRXFSIZ),
4311 		dwc2_readl(hsotg, GNPTXFSIZ));
4312 
4313 	dwc2_hsotg_init_fifo(hsotg);
4314 
4315 	/* keep other bits untouched (so e.g. forced modes are not lost) */
4316 	usbcfg = dwc2_readl(hsotg, GUSBCFG);
4317 	usbcfg &= ~(GUSBCFG_TOUTCAL_MASK | GUSBCFG_PHYIF16 | GUSBCFG_SRPCAP |
4318 		GUSBCFG_HNPCAP | GUSBCFG_USBTRDTIM_MASK);
4319 
4320 	/* set the PLL on, remove the HNP/SRP and set the PHY */
4321 	trdtim = (hsotg->phyif == GUSBCFG_PHYIF8) ? 9 : 5;
4322 	usbcfg |= hsotg->phyif | GUSBCFG_TOUTCAL(7) |
4323 		(trdtim << GUSBCFG_USBTRDTIM_SHIFT);
4324 	dwc2_writel(hsotg, usbcfg, GUSBCFG);
4325 
4326 	if (using_dma(hsotg))
4327 		dwc2_set_bit(hsotg, GAHBCFG, GAHBCFG_DMA_EN);
4328 }
4329 
4330 /**
4331  * dwc2_hsotg_udc_start - prepare the udc for work
4332  * @gadget: The usb gadget state
4333  * @driver: The usb gadget driver
4334  *
4335  * Perform initialization to prepare udc device and driver
4336  * to work.
4337  */
4338 static int dwc2_hsotg_udc_start(struct usb_gadget *gadget,
4339 				struct usb_gadget_driver *driver)
4340 {
4341 	struct dwc2_hsotg *hsotg = to_hsotg(gadget);
4342 	unsigned long flags;
4343 	int ret;
4344 
4345 	if (!hsotg) {
4346 		pr_err("%s: called with no device\n", __func__);
4347 		return -ENODEV;
4348 	}
4349 
4350 	if (!driver) {
4351 		dev_err(hsotg->dev, "%s: no driver\n", __func__);
4352 		return -EINVAL;
4353 	}
4354 
4355 	if (driver->max_speed < USB_SPEED_FULL)
4356 		dev_err(hsotg->dev, "%s: bad speed\n", __func__);
4357 
4358 	if (!driver->setup) {
4359 		dev_err(hsotg->dev, "%s: missing entry points\n", __func__);
4360 		return -EINVAL;
4361 	}
4362 
4363 	WARN_ON(hsotg->driver);
4364 
4365 	driver->driver.bus = NULL;
4366 	hsotg->driver = driver;
4367 	hsotg->gadget.dev.of_node = hsotg->dev->of_node;
4368 	hsotg->gadget.speed = USB_SPEED_UNKNOWN;
4369 
4370 	if (hsotg->dr_mode == USB_DR_MODE_PERIPHERAL) {
4371 		ret = dwc2_lowlevel_hw_enable(hsotg);
4372 		if (ret)
4373 			goto err;
4374 	}
4375 
4376 	if (!IS_ERR_OR_NULL(hsotg->uphy))
4377 		otg_set_peripheral(hsotg->uphy->otg, &hsotg->gadget);
4378 
4379 	spin_lock_irqsave(&hsotg->lock, flags);
4380 	if (dwc2_hw_is_device(hsotg)) {
4381 		dwc2_hsotg_init(hsotg);
4382 		dwc2_hsotg_core_init_disconnected(hsotg, false);
4383 	}
4384 
4385 	hsotg->enabled = 0;
4386 	spin_unlock_irqrestore(&hsotg->lock, flags);
4387 
4388 	dev_info(hsotg->dev, "bound driver %s\n", driver->driver.name);
4389 
4390 	return 0;
4391 
4392 err:
4393 	hsotg->driver = NULL;
4394 	return ret;
4395 }
4396 
4397 /**
4398  * dwc2_hsotg_udc_stop - stop the udc
4399  * @gadget: The usb gadget state
4400  *
4401  * Stop udc hw block and stay tunned for future transmissions
4402  */
4403 static int dwc2_hsotg_udc_stop(struct usb_gadget *gadget)
4404 {
4405 	struct dwc2_hsotg *hsotg = to_hsotg(gadget);
4406 	unsigned long flags = 0;
4407 	int ep;
4408 
4409 	if (!hsotg)
4410 		return -ENODEV;
4411 
4412 	/* all endpoints should be shutdown */
4413 	for (ep = 1; ep < hsotg->num_of_eps; ep++) {
4414 		if (hsotg->eps_in[ep])
4415 			dwc2_hsotg_ep_disable_lock(&hsotg->eps_in[ep]->ep);
4416 		if (hsotg->eps_out[ep])
4417 			dwc2_hsotg_ep_disable_lock(&hsotg->eps_out[ep]->ep);
4418 	}
4419 
4420 	spin_lock_irqsave(&hsotg->lock, flags);
4421 
4422 	hsotg->driver = NULL;
4423 	hsotg->gadget.speed = USB_SPEED_UNKNOWN;
4424 	hsotg->enabled = 0;
4425 
4426 	spin_unlock_irqrestore(&hsotg->lock, flags);
4427 
4428 	if (!IS_ERR_OR_NULL(hsotg->uphy))
4429 		otg_set_peripheral(hsotg->uphy->otg, NULL);
4430 
4431 	if (hsotg->dr_mode == USB_DR_MODE_PERIPHERAL)
4432 		dwc2_lowlevel_hw_disable(hsotg);
4433 
4434 	return 0;
4435 }
4436 
4437 /**
4438  * dwc2_hsotg_gadget_getframe - read the frame number
4439  * @gadget: The usb gadget state
4440  *
4441  * Read the {micro} frame number
4442  */
4443 static int dwc2_hsotg_gadget_getframe(struct usb_gadget *gadget)
4444 {
4445 	return dwc2_hsotg_read_frameno(to_hsotg(gadget));
4446 }
4447 
4448 /**
4449  * dwc2_hsotg_pullup - connect/disconnect the USB PHY
4450  * @gadget: The usb gadget state
4451  * @is_on: Current state of the USB PHY
4452  *
4453  * Connect/Disconnect the USB PHY pullup
4454  */
4455 static int dwc2_hsotg_pullup(struct usb_gadget *gadget, int is_on)
4456 {
4457 	struct dwc2_hsotg *hsotg = to_hsotg(gadget);
4458 	unsigned long flags = 0;
4459 
4460 	dev_dbg(hsotg->dev, "%s: is_on: %d op_state: %d\n", __func__, is_on,
4461 		hsotg->op_state);
4462 
4463 	/* Don't modify pullup state while in host mode */
4464 	if (hsotg->op_state != OTG_STATE_B_PERIPHERAL) {
4465 		hsotg->enabled = is_on;
4466 		return 0;
4467 	}
4468 
4469 	spin_lock_irqsave(&hsotg->lock, flags);
4470 	if (is_on) {
4471 		hsotg->enabled = 1;
4472 		dwc2_hsotg_core_init_disconnected(hsotg, false);
4473 		/* Enable ACG feature in device mode,if supported */
4474 		dwc2_enable_acg(hsotg);
4475 		dwc2_hsotg_core_connect(hsotg);
4476 	} else {
4477 		dwc2_hsotg_core_disconnect(hsotg);
4478 		dwc2_hsotg_disconnect(hsotg);
4479 		hsotg->enabled = 0;
4480 	}
4481 
4482 	hsotg->gadget.speed = USB_SPEED_UNKNOWN;
4483 	spin_unlock_irqrestore(&hsotg->lock, flags);
4484 
4485 	return 0;
4486 }
4487 
4488 static int dwc2_hsotg_vbus_session(struct usb_gadget *gadget, int is_active)
4489 {
4490 	struct dwc2_hsotg *hsotg = to_hsotg(gadget);
4491 	unsigned long flags;
4492 
4493 	dev_dbg(hsotg->dev, "%s: is_active: %d\n", __func__, is_active);
4494 	spin_lock_irqsave(&hsotg->lock, flags);
4495 
4496 	/*
4497 	 * If controller is hibernated, it must exit from power_down
4498 	 * before being initialized / de-initialized
4499 	 */
4500 	if (hsotg->lx_state == DWC2_L2)
4501 		dwc2_exit_partial_power_down(hsotg, false);
4502 
4503 	if (is_active) {
4504 		hsotg->op_state = OTG_STATE_B_PERIPHERAL;
4505 
4506 		dwc2_hsotg_core_init_disconnected(hsotg, false);
4507 		if (hsotg->enabled) {
4508 			/* Enable ACG feature in device mode,if supported */
4509 			dwc2_enable_acg(hsotg);
4510 			dwc2_hsotg_core_connect(hsotg);
4511 		}
4512 	} else {
4513 		dwc2_hsotg_core_disconnect(hsotg);
4514 		dwc2_hsotg_disconnect(hsotg);
4515 	}
4516 
4517 	spin_unlock_irqrestore(&hsotg->lock, flags);
4518 	return 0;
4519 }
4520 
4521 /**
4522  * dwc2_hsotg_vbus_draw - report bMaxPower field
4523  * @gadget: The usb gadget state
4524  * @mA: Amount of current
4525  *
4526  * Report how much power the device may consume to the phy.
4527  */
4528 static int dwc2_hsotg_vbus_draw(struct usb_gadget *gadget, unsigned int mA)
4529 {
4530 	struct dwc2_hsotg *hsotg = to_hsotg(gadget);
4531 
4532 	if (IS_ERR_OR_NULL(hsotg->uphy))
4533 		return -ENOTSUPP;
4534 	return usb_phy_set_power(hsotg->uphy, mA);
4535 }
4536 
4537 static const struct usb_gadget_ops dwc2_hsotg_gadget_ops = {
4538 	.get_frame	= dwc2_hsotg_gadget_getframe,
4539 	.udc_start		= dwc2_hsotg_udc_start,
4540 	.udc_stop		= dwc2_hsotg_udc_stop,
4541 	.pullup                 = dwc2_hsotg_pullup,
4542 	.vbus_session		= dwc2_hsotg_vbus_session,
4543 	.vbus_draw		= dwc2_hsotg_vbus_draw,
4544 };
4545 
4546 /**
4547  * dwc2_hsotg_initep - initialise a single endpoint
4548  * @hsotg: The device state.
4549  * @hs_ep: The endpoint to be initialised.
4550  * @epnum: The endpoint number
4551  * @dir_in: True if direction is in.
4552  *
4553  * Initialise the given endpoint (as part of the probe and device state
4554  * creation) to give to the gadget driver. Setup the endpoint name, any
4555  * direction information and other state that may be required.
4556  */
4557 static void dwc2_hsotg_initep(struct dwc2_hsotg *hsotg,
4558 			      struct dwc2_hsotg_ep *hs_ep,
4559 				       int epnum,
4560 				       bool dir_in)
4561 {
4562 	char *dir;
4563 
4564 	if (epnum == 0)
4565 		dir = "";
4566 	else if (dir_in)
4567 		dir = "in";
4568 	else
4569 		dir = "out";
4570 
4571 	hs_ep->dir_in = dir_in;
4572 	hs_ep->index = epnum;
4573 
4574 	snprintf(hs_ep->name, sizeof(hs_ep->name), "ep%d%s", epnum, dir);
4575 
4576 	INIT_LIST_HEAD(&hs_ep->queue);
4577 	INIT_LIST_HEAD(&hs_ep->ep.ep_list);
4578 
4579 	/* add to the list of endpoints known by the gadget driver */
4580 	if (epnum)
4581 		list_add_tail(&hs_ep->ep.ep_list, &hsotg->gadget.ep_list);
4582 
4583 	hs_ep->parent = hsotg;
4584 	hs_ep->ep.name = hs_ep->name;
4585 
4586 	if (hsotg->params.speed == DWC2_SPEED_PARAM_LOW)
4587 		usb_ep_set_maxpacket_limit(&hs_ep->ep, 8);
4588 	else
4589 		usb_ep_set_maxpacket_limit(&hs_ep->ep,
4590 					   epnum ? 1024 : EP0_MPS_LIMIT);
4591 	hs_ep->ep.ops = &dwc2_hsotg_ep_ops;
4592 
4593 	if (epnum == 0) {
4594 		hs_ep->ep.caps.type_control = true;
4595 	} else {
4596 		if (hsotg->params.speed != DWC2_SPEED_PARAM_LOW) {
4597 			hs_ep->ep.caps.type_iso = true;
4598 			hs_ep->ep.caps.type_bulk = true;
4599 		}
4600 		hs_ep->ep.caps.type_int = true;
4601 	}
4602 
4603 	if (dir_in)
4604 		hs_ep->ep.caps.dir_in = true;
4605 	else
4606 		hs_ep->ep.caps.dir_out = true;
4607 
4608 	/*
4609 	 * if we're using dma, we need to set the next-endpoint pointer
4610 	 * to be something valid.
4611 	 */
4612 
4613 	if (using_dma(hsotg)) {
4614 		u32 next = DXEPCTL_NEXTEP((epnum + 1) % 15);
4615 
4616 		if (dir_in)
4617 			dwc2_writel(hsotg, next, DIEPCTL(epnum));
4618 		else
4619 			dwc2_writel(hsotg, next, DOEPCTL(epnum));
4620 	}
4621 }
4622 
4623 /**
4624  * dwc2_hsotg_hw_cfg - read HW configuration registers
4625  * @hsotg: Programming view of the DWC_otg controller
4626  *
4627  * Read the USB core HW configuration registers
4628  */
4629 static int dwc2_hsotg_hw_cfg(struct dwc2_hsotg *hsotg)
4630 {
4631 	u32 cfg;
4632 	u32 ep_type;
4633 	u32 i;
4634 
4635 	/* check hardware configuration */
4636 
4637 	hsotg->num_of_eps = hsotg->hw_params.num_dev_ep;
4638 
4639 	/* Add ep0 */
4640 	hsotg->num_of_eps++;
4641 
4642 	hsotg->eps_in[0] = devm_kzalloc(hsotg->dev,
4643 					sizeof(struct dwc2_hsotg_ep),
4644 					GFP_KERNEL);
4645 	if (!hsotg->eps_in[0])
4646 		return -ENOMEM;
4647 	/* Same dwc2_hsotg_ep is used in both directions for ep0 */
4648 	hsotg->eps_out[0] = hsotg->eps_in[0];
4649 
4650 	cfg = hsotg->hw_params.dev_ep_dirs;
4651 	for (i = 1, cfg >>= 2; i < hsotg->num_of_eps; i++, cfg >>= 2) {
4652 		ep_type = cfg & 3;
4653 		/* Direction in or both */
4654 		if (!(ep_type & 2)) {
4655 			hsotg->eps_in[i] = devm_kzalloc(hsotg->dev,
4656 				sizeof(struct dwc2_hsotg_ep), GFP_KERNEL);
4657 			if (!hsotg->eps_in[i])
4658 				return -ENOMEM;
4659 		}
4660 		/* Direction out or both */
4661 		if (!(ep_type & 1)) {
4662 			hsotg->eps_out[i] = devm_kzalloc(hsotg->dev,
4663 				sizeof(struct dwc2_hsotg_ep), GFP_KERNEL);
4664 			if (!hsotg->eps_out[i])
4665 				return -ENOMEM;
4666 		}
4667 	}
4668 
4669 	hsotg->fifo_mem = hsotg->hw_params.total_fifo_size;
4670 	hsotg->dedicated_fifos = hsotg->hw_params.en_multiple_tx_fifo;
4671 
4672 	dev_info(hsotg->dev, "EPs: %d, %s fifos, %d entries in SPRAM\n",
4673 		 hsotg->num_of_eps,
4674 		 hsotg->dedicated_fifos ? "dedicated" : "shared",
4675 		 hsotg->fifo_mem);
4676 	return 0;
4677 }
4678 
4679 /**
4680  * dwc2_hsotg_dump - dump state of the udc
4681  * @hsotg: Programming view of the DWC_otg controller
4682  *
4683  */
4684 static void dwc2_hsotg_dump(struct dwc2_hsotg *hsotg)
4685 {
4686 #ifdef DEBUG
4687 	struct device *dev = hsotg->dev;
4688 	u32 val;
4689 	int idx;
4690 
4691 	dev_info(dev, "DCFG=0x%08x, DCTL=0x%08x, DIEPMSK=%08x\n",
4692 		 dwc2_readl(hsotg, DCFG), dwc2_readl(hsotg, DCTL),
4693 		 dwc2_readl(hsotg, DIEPMSK));
4694 
4695 	dev_info(dev, "GAHBCFG=0x%08x, GHWCFG1=0x%08x\n",
4696 		 dwc2_readl(hsotg, GAHBCFG), dwc2_readl(hsotg, GHWCFG1));
4697 
4698 	dev_info(dev, "GRXFSIZ=0x%08x, GNPTXFSIZ=0x%08x\n",
4699 		 dwc2_readl(hsotg, GRXFSIZ), dwc2_readl(hsotg, GNPTXFSIZ));
4700 
4701 	/* show periodic fifo settings */
4702 
4703 	for (idx = 1; idx < hsotg->num_of_eps; idx++) {
4704 		val = dwc2_readl(hsotg, DPTXFSIZN(idx));
4705 		dev_info(dev, "DPTx[%d] FSize=%d, StAddr=0x%08x\n", idx,
4706 			 val >> FIFOSIZE_DEPTH_SHIFT,
4707 			 val & FIFOSIZE_STARTADDR_MASK);
4708 	}
4709 
4710 	for (idx = 0; idx < hsotg->num_of_eps; idx++) {
4711 		dev_info(dev,
4712 			 "ep%d-in: EPCTL=0x%08x, SIZ=0x%08x, DMA=0x%08x\n", idx,
4713 			 dwc2_readl(hsotg, DIEPCTL(idx)),
4714 			 dwc2_readl(hsotg, DIEPTSIZ(idx)),
4715 			 dwc2_readl(hsotg, DIEPDMA(idx)));
4716 
4717 		val = dwc2_readl(hsotg, DOEPCTL(idx));
4718 		dev_info(dev,
4719 			 "ep%d-out: EPCTL=0x%08x, SIZ=0x%08x, DMA=0x%08x\n",
4720 			 idx, dwc2_readl(hsotg, DOEPCTL(idx)),
4721 			 dwc2_readl(hsotg, DOEPTSIZ(idx)),
4722 			 dwc2_readl(hsotg, DOEPDMA(idx)));
4723 	}
4724 
4725 	dev_info(dev, "DVBUSDIS=0x%08x, DVBUSPULSE=%08x\n",
4726 		 dwc2_readl(hsotg, DVBUSDIS), dwc2_readl(hsotg, DVBUSPULSE));
4727 #endif
4728 }
4729 
4730 /**
4731  * dwc2_gadget_init - init function for gadget
4732  * @hsotg: Programming view of the DWC_otg controller
4733  *
4734  */
4735 int dwc2_gadget_init(struct dwc2_hsotg *hsotg)
4736 {
4737 	struct device *dev = hsotg->dev;
4738 	int epnum;
4739 	int ret;
4740 
4741 	/* Dump fifo information */
4742 	dev_dbg(dev, "NonPeriodic TXFIFO size: %d\n",
4743 		hsotg->params.g_np_tx_fifo_size);
4744 	dev_dbg(dev, "RXFIFO size: %d\n", hsotg->params.g_rx_fifo_size);
4745 
4746 	hsotg->gadget.max_speed = USB_SPEED_HIGH;
4747 	hsotg->gadget.ops = &dwc2_hsotg_gadget_ops;
4748 	hsotg->gadget.name = dev_name(dev);
4749 	hsotg->remote_wakeup_allowed = 0;
4750 
4751 	if (hsotg->params.lpm)
4752 		hsotg->gadget.lpm_capable = true;
4753 
4754 	if (hsotg->dr_mode == USB_DR_MODE_OTG)
4755 		hsotg->gadget.is_otg = 1;
4756 	else if (hsotg->dr_mode == USB_DR_MODE_PERIPHERAL)
4757 		hsotg->op_state = OTG_STATE_B_PERIPHERAL;
4758 
4759 	ret = dwc2_hsotg_hw_cfg(hsotg);
4760 	if (ret) {
4761 		dev_err(hsotg->dev, "Hardware configuration failed: %d\n", ret);
4762 		return ret;
4763 	}
4764 
4765 	hsotg->ctrl_buff = devm_kzalloc(hsotg->dev,
4766 			DWC2_CTRL_BUFF_SIZE, GFP_KERNEL);
4767 	if (!hsotg->ctrl_buff)
4768 		return -ENOMEM;
4769 
4770 	hsotg->ep0_buff = devm_kzalloc(hsotg->dev,
4771 			DWC2_CTRL_BUFF_SIZE, GFP_KERNEL);
4772 	if (!hsotg->ep0_buff)
4773 		return -ENOMEM;
4774 
4775 	if (using_desc_dma(hsotg)) {
4776 		ret = dwc2_gadget_alloc_ctrl_desc_chains(hsotg);
4777 		if (ret < 0)
4778 			return ret;
4779 	}
4780 
4781 	ret = devm_request_irq(hsotg->dev, hsotg->irq, dwc2_hsotg_irq,
4782 			       IRQF_SHARED, dev_name(hsotg->dev), hsotg);
4783 	if (ret < 0) {
4784 		dev_err(dev, "cannot claim IRQ for gadget\n");
4785 		return ret;
4786 	}
4787 
4788 	/* hsotg->num_of_eps holds number of EPs other than ep0 */
4789 
4790 	if (hsotg->num_of_eps == 0) {
4791 		dev_err(dev, "wrong number of EPs (zero)\n");
4792 		return -EINVAL;
4793 	}
4794 
4795 	/* setup endpoint information */
4796 
4797 	INIT_LIST_HEAD(&hsotg->gadget.ep_list);
4798 	hsotg->gadget.ep0 = &hsotg->eps_out[0]->ep;
4799 
4800 	/* allocate EP0 request */
4801 
4802 	hsotg->ctrl_req = dwc2_hsotg_ep_alloc_request(&hsotg->eps_out[0]->ep,
4803 						     GFP_KERNEL);
4804 	if (!hsotg->ctrl_req) {
4805 		dev_err(dev, "failed to allocate ctrl req\n");
4806 		return -ENOMEM;
4807 	}
4808 
4809 	/* initialise the endpoints now the core has been initialised */
4810 	for (epnum = 0; epnum < hsotg->num_of_eps; epnum++) {
4811 		if (hsotg->eps_in[epnum])
4812 			dwc2_hsotg_initep(hsotg, hsotg->eps_in[epnum],
4813 					  epnum, 1);
4814 		if (hsotg->eps_out[epnum])
4815 			dwc2_hsotg_initep(hsotg, hsotg->eps_out[epnum],
4816 					  epnum, 0);
4817 	}
4818 
4819 	ret = usb_add_gadget_udc(dev, &hsotg->gadget);
4820 	if (ret) {
4821 		dwc2_hsotg_ep_free_request(&hsotg->eps_out[0]->ep,
4822 					   hsotg->ctrl_req);
4823 		return ret;
4824 	}
4825 	dwc2_hsotg_dump(hsotg);
4826 
4827 	return 0;
4828 }
4829 
4830 /**
4831  * dwc2_hsotg_remove - remove function for hsotg driver
4832  * @hsotg: Programming view of the DWC_otg controller
4833  *
4834  */
4835 int dwc2_hsotg_remove(struct dwc2_hsotg *hsotg)
4836 {
4837 	usb_del_gadget_udc(&hsotg->gadget);
4838 	dwc2_hsotg_ep_free_request(&hsotg->eps_out[0]->ep, hsotg->ctrl_req);
4839 
4840 	return 0;
4841 }
4842 
4843 int dwc2_hsotg_suspend(struct dwc2_hsotg *hsotg)
4844 {
4845 	unsigned long flags;
4846 
4847 	if (hsotg->lx_state != DWC2_L0)
4848 		return 0;
4849 
4850 	if (hsotg->driver) {
4851 		int ep;
4852 
4853 		dev_info(hsotg->dev, "suspending usb gadget %s\n",
4854 			 hsotg->driver->driver.name);
4855 
4856 		spin_lock_irqsave(&hsotg->lock, flags);
4857 		if (hsotg->enabled)
4858 			dwc2_hsotg_core_disconnect(hsotg);
4859 		dwc2_hsotg_disconnect(hsotg);
4860 		hsotg->gadget.speed = USB_SPEED_UNKNOWN;
4861 		spin_unlock_irqrestore(&hsotg->lock, flags);
4862 
4863 		for (ep = 0; ep < hsotg->num_of_eps; ep++) {
4864 			if (hsotg->eps_in[ep])
4865 				dwc2_hsotg_ep_disable_lock(&hsotg->eps_in[ep]->ep);
4866 			if (hsotg->eps_out[ep])
4867 				dwc2_hsotg_ep_disable_lock(&hsotg->eps_out[ep]->ep);
4868 		}
4869 	}
4870 
4871 	return 0;
4872 }
4873 
4874 int dwc2_hsotg_resume(struct dwc2_hsotg *hsotg)
4875 {
4876 	unsigned long flags;
4877 
4878 	if (hsotg->lx_state == DWC2_L2)
4879 		return 0;
4880 
4881 	if (hsotg->driver) {
4882 		dev_info(hsotg->dev, "resuming usb gadget %s\n",
4883 			 hsotg->driver->driver.name);
4884 
4885 		spin_lock_irqsave(&hsotg->lock, flags);
4886 		dwc2_hsotg_core_init_disconnected(hsotg, false);
4887 		if (hsotg->enabled) {
4888 			/* Enable ACG feature in device mode,if supported */
4889 			dwc2_enable_acg(hsotg);
4890 			dwc2_hsotg_core_connect(hsotg);
4891 		}
4892 		spin_unlock_irqrestore(&hsotg->lock, flags);
4893 	}
4894 
4895 	return 0;
4896 }
4897 
4898 /**
4899  * dwc2_backup_device_registers() - Backup controller device registers.
4900  * When suspending usb bus, registers needs to be backuped
4901  * if controller power is disabled once suspended.
4902  *
4903  * @hsotg: Programming view of the DWC_otg controller
4904  */
4905 int dwc2_backup_device_registers(struct dwc2_hsotg *hsotg)
4906 {
4907 	struct dwc2_dregs_backup *dr;
4908 	int i;
4909 
4910 	dev_dbg(hsotg->dev, "%s\n", __func__);
4911 
4912 	/* Backup dev regs */
4913 	dr = &hsotg->dr_backup;
4914 
4915 	dr->dcfg = dwc2_readl(hsotg, DCFG);
4916 	dr->dctl = dwc2_readl(hsotg, DCTL);
4917 	dr->daintmsk = dwc2_readl(hsotg, DAINTMSK);
4918 	dr->diepmsk = dwc2_readl(hsotg, DIEPMSK);
4919 	dr->doepmsk = dwc2_readl(hsotg, DOEPMSK);
4920 
4921 	for (i = 0; i < hsotg->num_of_eps; i++) {
4922 		/* Backup IN EPs */
4923 		dr->diepctl[i] = dwc2_readl(hsotg, DIEPCTL(i));
4924 
4925 		/* Ensure DATA PID is correctly configured */
4926 		if (dr->diepctl[i] & DXEPCTL_DPID)
4927 			dr->diepctl[i] |= DXEPCTL_SETD1PID;
4928 		else
4929 			dr->diepctl[i] |= DXEPCTL_SETD0PID;
4930 
4931 		dr->dieptsiz[i] = dwc2_readl(hsotg, DIEPTSIZ(i));
4932 		dr->diepdma[i] = dwc2_readl(hsotg, DIEPDMA(i));
4933 
4934 		/* Backup OUT EPs */
4935 		dr->doepctl[i] = dwc2_readl(hsotg, DOEPCTL(i));
4936 
4937 		/* Ensure DATA PID is correctly configured */
4938 		if (dr->doepctl[i] & DXEPCTL_DPID)
4939 			dr->doepctl[i] |= DXEPCTL_SETD1PID;
4940 		else
4941 			dr->doepctl[i] |= DXEPCTL_SETD0PID;
4942 
4943 		dr->doeptsiz[i] = dwc2_readl(hsotg, DOEPTSIZ(i));
4944 		dr->doepdma[i] = dwc2_readl(hsotg, DOEPDMA(i));
4945 		dr->dtxfsiz[i] = dwc2_readl(hsotg, DPTXFSIZN(i));
4946 	}
4947 	dr->valid = true;
4948 	return 0;
4949 }
4950 
4951 /**
4952  * dwc2_restore_device_registers() - Restore controller device registers.
4953  * When resuming usb bus, device registers needs to be restored
4954  * if controller power were disabled.
4955  *
4956  * @hsotg: Programming view of the DWC_otg controller
4957  * @remote_wakeup: Indicates whether resume is initiated by Device or Host.
4958  *
4959  * Return: 0 if successful, negative error code otherwise
4960  */
4961 int dwc2_restore_device_registers(struct dwc2_hsotg *hsotg, int remote_wakeup)
4962 {
4963 	struct dwc2_dregs_backup *dr;
4964 	int i;
4965 
4966 	dev_dbg(hsotg->dev, "%s\n", __func__);
4967 
4968 	/* Restore dev regs */
4969 	dr = &hsotg->dr_backup;
4970 	if (!dr->valid) {
4971 		dev_err(hsotg->dev, "%s: no device registers to restore\n",
4972 			__func__);
4973 		return -EINVAL;
4974 	}
4975 	dr->valid = false;
4976 
4977 	if (!remote_wakeup)
4978 		dwc2_writel(hsotg, dr->dctl, DCTL);
4979 
4980 	dwc2_writel(hsotg, dr->daintmsk, DAINTMSK);
4981 	dwc2_writel(hsotg, dr->diepmsk, DIEPMSK);
4982 	dwc2_writel(hsotg, dr->doepmsk, DOEPMSK);
4983 
4984 	for (i = 0; i < hsotg->num_of_eps; i++) {
4985 		/* Restore IN EPs */
4986 		dwc2_writel(hsotg, dr->dieptsiz[i], DIEPTSIZ(i));
4987 		dwc2_writel(hsotg, dr->diepdma[i], DIEPDMA(i));
4988 		dwc2_writel(hsotg, dr->doeptsiz[i], DOEPTSIZ(i));
4989 		/** WA for enabled EPx's IN in DDMA mode. On entering to
4990 		 * hibernation wrong value read and saved from DIEPDMAx,
4991 		 * as result BNA interrupt asserted on hibernation exit
4992 		 * by restoring from saved area.
4993 		 */
4994 		if (hsotg->params.g_dma_desc &&
4995 		    (dr->diepctl[i] & DXEPCTL_EPENA))
4996 			dr->diepdma[i] = hsotg->eps_in[i]->desc_list_dma;
4997 		dwc2_writel(hsotg, dr->dtxfsiz[i], DPTXFSIZN(i));
4998 		dwc2_writel(hsotg, dr->diepctl[i], DIEPCTL(i));
4999 		/* Restore OUT EPs */
5000 		dwc2_writel(hsotg, dr->doeptsiz[i], DOEPTSIZ(i));
5001 		/* WA for enabled EPx's OUT in DDMA mode. On entering to
5002 		 * hibernation wrong value read and saved from DOEPDMAx,
5003 		 * as result BNA interrupt asserted on hibernation exit
5004 		 * by restoring from saved area.
5005 		 */
5006 		if (hsotg->params.g_dma_desc &&
5007 		    (dr->doepctl[i] & DXEPCTL_EPENA))
5008 			dr->doepdma[i] = hsotg->eps_out[i]->desc_list_dma;
5009 		dwc2_writel(hsotg, dr->doepdma[i], DOEPDMA(i));
5010 		dwc2_writel(hsotg, dr->doepctl[i], DOEPCTL(i));
5011 	}
5012 
5013 	return 0;
5014 }
5015 
5016 /**
5017  * dwc2_gadget_init_lpm - Configure the core to support LPM in device mode
5018  *
5019  * @hsotg: Programming view of DWC_otg controller
5020  *
5021  */
5022 void dwc2_gadget_init_lpm(struct dwc2_hsotg *hsotg)
5023 {
5024 	u32 val;
5025 
5026 	if (!hsotg->params.lpm)
5027 		return;
5028 
5029 	val = GLPMCFG_LPMCAP | GLPMCFG_APPL1RES;
5030 	val |= hsotg->params.hird_threshold_en ? GLPMCFG_HIRD_THRES_EN : 0;
5031 	val |= hsotg->params.lpm_clock_gating ? GLPMCFG_ENBLSLPM : 0;
5032 	val |= hsotg->params.hird_threshold << GLPMCFG_HIRD_THRES_SHIFT;
5033 	val |= hsotg->params.besl ? GLPMCFG_ENBESL : 0;
5034 	val |= GLPMCFG_LPM_ACCEPT_CTRL_ISOC;
5035 	dwc2_writel(hsotg, val, GLPMCFG);
5036 	dev_dbg(hsotg->dev, "GLPMCFG=0x%08x\n", dwc2_readl(hsotg, GLPMCFG));
5037 
5038 	/* Unmask WKUP_ALERT Interrupt */
5039 	if (hsotg->params.service_interval)
5040 		dwc2_set_bit(hsotg, GINTMSK2, GINTMSK2_WKUP_ALERT_INT_MSK);
5041 }
5042 
5043 /**
5044  * dwc2_gadget_program_ref_clk - Program GREFCLK register in device mode
5045  *
5046  * @hsotg: Programming view of DWC_otg controller
5047  *
5048  */
5049 void dwc2_gadget_program_ref_clk(struct dwc2_hsotg *hsotg)
5050 {
5051 	u32 val = 0;
5052 
5053 	val |= GREFCLK_REF_CLK_MODE;
5054 	val |= hsotg->params.ref_clk_per << GREFCLK_REFCLKPER_SHIFT;
5055 	val |= hsotg->params.sof_cnt_wkup_alert <<
5056 	       GREFCLK_SOF_CNT_WKUP_ALERT_SHIFT;
5057 
5058 	dwc2_writel(hsotg, val, GREFCLK);
5059 	dev_dbg(hsotg->dev, "GREFCLK=0x%08x\n", dwc2_readl(hsotg, GREFCLK));
5060 }
5061 
5062 /**
5063  * dwc2_gadget_enter_hibernation() - Put controller in Hibernation.
5064  *
5065  * @hsotg: Programming view of the DWC_otg controller
5066  *
5067  * Return non-zero if failed to enter to hibernation.
5068  */
5069 int dwc2_gadget_enter_hibernation(struct dwc2_hsotg *hsotg)
5070 {
5071 	u32 gpwrdn;
5072 	int ret = 0;
5073 
5074 	/* Change to L2(suspend) state */
5075 	hsotg->lx_state = DWC2_L2;
5076 	dev_dbg(hsotg->dev, "Start of hibernation completed\n");
5077 	ret = dwc2_backup_global_registers(hsotg);
5078 	if (ret) {
5079 		dev_err(hsotg->dev, "%s: failed to backup global registers\n",
5080 			__func__);
5081 		return ret;
5082 	}
5083 	ret = dwc2_backup_device_registers(hsotg);
5084 	if (ret) {
5085 		dev_err(hsotg->dev, "%s: failed to backup device registers\n",
5086 			__func__);
5087 		return ret;
5088 	}
5089 
5090 	gpwrdn = GPWRDN_PWRDNRSTN;
5091 	gpwrdn |= GPWRDN_PMUACTV;
5092 	dwc2_writel(hsotg, gpwrdn, GPWRDN);
5093 	udelay(10);
5094 
5095 	/* Set flag to indicate that we are in hibernation */
5096 	hsotg->hibernated = 1;
5097 
5098 	/* Enable interrupts from wake up logic */
5099 	gpwrdn = dwc2_readl(hsotg, GPWRDN);
5100 	gpwrdn |= GPWRDN_PMUINTSEL;
5101 	dwc2_writel(hsotg, gpwrdn, GPWRDN);
5102 	udelay(10);
5103 
5104 	/* Unmask device mode interrupts in GPWRDN */
5105 	gpwrdn = dwc2_readl(hsotg, GPWRDN);
5106 	gpwrdn |= GPWRDN_RST_DET_MSK;
5107 	gpwrdn |= GPWRDN_LNSTSCHG_MSK;
5108 	gpwrdn |= GPWRDN_STS_CHGINT_MSK;
5109 	dwc2_writel(hsotg, gpwrdn, GPWRDN);
5110 	udelay(10);
5111 
5112 	/* Enable Power Down Clamp */
5113 	gpwrdn = dwc2_readl(hsotg, GPWRDN);
5114 	gpwrdn |= GPWRDN_PWRDNCLMP;
5115 	dwc2_writel(hsotg, gpwrdn, GPWRDN);
5116 	udelay(10);
5117 
5118 	/* Switch off VDD */
5119 	gpwrdn = dwc2_readl(hsotg, GPWRDN);
5120 	gpwrdn |= GPWRDN_PWRDNSWTCH;
5121 	dwc2_writel(hsotg, gpwrdn, GPWRDN);
5122 	udelay(10);
5123 
5124 	/* Save gpwrdn register for further usage if stschng interrupt */
5125 	hsotg->gr_backup.gpwrdn = dwc2_readl(hsotg, GPWRDN);
5126 	dev_dbg(hsotg->dev, "Hibernation completed\n");
5127 
5128 	return ret;
5129 }
5130 
5131 /**
5132  * dwc2_gadget_exit_hibernation()
5133  * This function is for exiting from Device mode hibernation by host initiated
5134  * resume/reset and device initiated remote-wakeup.
5135  *
5136  * @hsotg: Programming view of the DWC_otg controller
5137  * @rem_wakeup: indicates whether resume is initiated by Device or Host.
5138  * @reset: indicates whether resume is initiated by Reset.
5139  *
5140  * Return non-zero if failed to exit from hibernation.
5141  */
5142 int dwc2_gadget_exit_hibernation(struct dwc2_hsotg *hsotg,
5143 				 int rem_wakeup, int reset)
5144 {
5145 	u32 pcgcctl;
5146 	u32 gpwrdn;
5147 	u32 dctl;
5148 	int ret = 0;
5149 	struct dwc2_gregs_backup *gr;
5150 	struct dwc2_dregs_backup *dr;
5151 
5152 	gr = &hsotg->gr_backup;
5153 	dr = &hsotg->dr_backup;
5154 
5155 	if (!hsotg->hibernated) {
5156 		dev_dbg(hsotg->dev, "Already exited from Hibernation\n");
5157 		return 1;
5158 	}
5159 	dev_dbg(hsotg->dev,
5160 		"%s: called with rem_wakeup = %d reset = %d\n",
5161 		__func__, rem_wakeup, reset);
5162 
5163 	dwc2_hib_restore_common(hsotg, rem_wakeup, 0);
5164 
5165 	if (!reset) {
5166 		/* Clear all pending interupts */
5167 		dwc2_writel(hsotg, 0xffffffff, GINTSTS);
5168 	}
5169 
5170 	/* De-assert Restore */
5171 	gpwrdn = dwc2_readl(hsotg, GPWRDN);
5172 	gpwrdn &= ~GPWRDN_RESTORE;
5173 	dwc2_writel(hsotg, gpwrdn, GPWRDN);
5174 	udelay(10);
5175 
5176 	if (!rem_wakeup) {
5177 		pcgcctl = dwc2_readl(hsotg, PCGCTL);
5178 		pcgcctl &= ~PCGCTL_RSTPDWNMODULE;
5179 		dwc2_writel(hsotg, pcgcctl, PCGCTL);
5180 	}
5181 
5182 	/* Restore GUSBCFG, DCFG and DCTL */
5183 	dwc2_writel(hsotg, gr->gusbcfg, GUSBCFG);
5184 	dwc2_writel(hsotg, dr->dcfg, DCFG);
5185 	dwc2_writel(hsotg, dr->dctl, DCTL);
5186 
5187 	/* De-assert Wakeup Logic */
5188 	gpwrdn = dwc2_readl(hsotg, GPWRDN);
5189 	gpwrdn &= ~GPWRDN_PMUACTV;
5190 	dwc2_writel(hsotg, gpwrdn, GPWRDN);
5191 
5192 	if (rem_wakeup) {
5193 		udelay(10);
5194 		/* Start Remote Wakeup Signaling */
5195 		dwc2_writel(hsotg, dr->dctl | DCTL_RMTWKUPSIG, DCTL);
5196 	} else {
5197 		udelay(50);
5198 		/* Set Device programming done bit */
5199 		dctl = dwc2_readl(hsotg, DCTL);
5200 		dctl |= DCTL_PWRONPRGDONE;
5201 		dwc2_writel(hsotg, dctl, DCTL);
5202 	}
5203 	/* Wait for interrupts which must be cleared */
5204 	mdelay(2);
5205 	/* Clear all pending interupts */
5206 	dwc2_writel(hsotg, 0xffffffff, GINTSTS);
5207 
5208 	/* Restore global registers */
5209 	ret = dwc2_restore_global_registers(hsotg);
5210 	if (ret) {
5211 		dev_err(hsotg->dev, "%s: failed to restore registers\n",
5212 			__func__);
5213 		return ret;
5214 	}
5215 
5216 	/* Restore device registers */
5217 	ret = dwc2_restore_device_registers(hsotg, rem_wakeup);
5218 	if (ret) {
5219 		dev_err(hsotg->dev, "%s: failed to restore device registers\n",
5220 			__func__);
5221 		return ret;
5222 	}
5223 
5224 	if (rem_wakeup) {
5225 		mdelay(10);
5226 		dctl = dwc2_readl(hsotg, DCTL);
5227 		dctl &= ~DCTL_RMTWKUPSIG;
5228 		dwc2_writel(hsotg, dctl, DCTL);
5229 	}
5230 
5231 	hsotg->hibernated = 0;
5232 	hsotg->lx_state = DWC2_L0;
5233 	dev_dbg(hsotg->dev, "Hibernation recovery completes here\n");
5234 
5235 	return ret;
5236 }
5237