xref: /linux/drivers/usb/dwc3/gadget.c (revision ea518afc992032f7570c0a89ac9240b387dc0faf)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * gadget.c - DesignWare USB3 DRD Controller Gadget Framework Link
4  *
5  * Copyright (C) 2010-2011 Texas Instruments Incorporated - https://www.ti.com
6  *
7  * Authors: Felipe Balbi <balbi@ti.com>,
8  *	    Sebastian Andrzej Siewior <bigeasy@linutronix.de>
9  */
10 
11 #include <linux/kernel.h>
12 #include <linux/delay.h>
13 #include <linux/slab.h>
14 #include <linux/spinlock.h>
15 #include <linux/platform_device.h>
16 #include <linux/pm_runtime.h>
17 #include <linux/interrupt.h>
18 #include <linux/io.h>
19 #include <linux/list.h>
20 #include <linux/dma-mapping.h>
21 
22 #include <linux/usb/ch9.h>
23 #include <linux/usb/gadget.h>
24 
25 #include "debug.h"
26 #include "core.h"
27 #include "gadget.h"
28 #include "io.h"
29 
30 #define DWC3_ALIGN_FRAME(d, n)	(((d)->frame_number + ((d)->interval * (n))) \
31 					& ~((d)->interval - 1))
32 
33 /**
34  * dwc3_gadget_set_test_mode - enables usb2 test modes
35  * @dwc: pointer to our context structure
36  * @mode: the mode to set (J, K SE0 NAK, Force Enable)
37  *
38  * Caller should take care of locking. This function will return 0 on
39  * success or -EINVAL if wrong Test Selector is passed.
40  */
41 int dwc3_gadget_set_test_mode(struct dwc3 *dwc, int mode)
42 {
43 	u32		reg;
44 
45 	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
46 	reg &= ~DWC3_DCTL_TSTCTRL_MASK;
47 
48 	switch (mode) {
49 	case USB_TEST_J:
50 	case USB_TEST_K:
51 	case USB_TEST_SE0_NAK:
52 	case USB_TEST_PACKET:
53 	case USB_TEST_FORCE_ENABLE:
54 		reg |= mode << 1;
55 		break;
56 	default:
57 		return -EINVAL;
58 	}
59 
60 	dwc3_gadget_dctl_write_safe(dwc, reg);
61 
62 	return 0;
63 }
64 
65 /**
66  * dwc3_gadget_get_link_state - gets current state of usb link
67  * @dwc: pointer to our context structure
68  *
69  * Caller should take care of locking. This function will
70  * return the link state on success (>= 0) or -ETIMEDOUT.
71  */
72 int dwc3_gadget_get_link_state(struct dwc3 *dwc)
73 {
74 	u32		reg;
75 
76 	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
77 
78 	return DWC3_DSTS_USBLNKST(reg);
79 }
80 
81 /**
82  * dwc3_gadget_set_link_state - sets usb link to a particular state
83  * @dwc: pointer to our context structure
84  * @state: the state to put link into
85  *
86  * Caller should take care of locking. This function will
87  * return 0 on success or -ETIMEDOUT.
88  */
89 int dwc3_gadget_set_link_state(struct dwc3 *dwc, enum dwc3_link_state state)
90 {
91 	int		retries = 10000;
92 	u32		reg;
93 
94 	/*
95 	 * Wait until device controller is ready. Only applies to 1.94a and
96 	 * later RTL.
97 	 */
98 	if (!DWC3_VER_IS_PRIOR(DWC3, 194A)) {
99 		while (--retries) {
100 			reg = dwc3_readl(dwc->regs, DWC3_DSTS);
101 			if (reg & DWC3_DSTS_DCNRD)
102 				udelay(5);
103 			else
104 				break;
105 		}
106 
107 		if (retries <= 0)
108 			return -ETIMEDOUT;
109 	}
110 
111 	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
112 	reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
113 
114 	/* set no action before sending new link state change */
115 	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
116 
117 	/* set requested state */
118 	reg |= DWC3_DCTL_ULSTCHNGREQ(state);
119 	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
120 
121 	/*
122 	 * The following code is racy when called from dwc3_gadget_wakeup,
123 	 * and is not needed, at least on newer versions
124 	 */
125 	if (!DWC3_VER_IS_PRIOR(DWC3, 194A))
126 		return 0;
127 
128 	/* wait for a change in DSTS */
129 	retries = 10000;
130 	while (--retries) {
131 		reg = dwc3_readl(dwc->regs, DWC3_DSTS);
132 
133 		if (DWC3_DSTS_USBLNKST(reg) == state)
134 			return 0;
135 
136 		udelay(5);
137 	}
138 
139 	return -ETIMEDOUT;
140 }
141 
142 static void dwc3_ep0_reset_state(struct dwc3 *dwc)
143 {
144 	unsigned int	dir;
145 
146 	if (dwc->ep0state != EP0_SETUP_PHASE) {
147 		dir = !!dwc->ep0_expect_in;
148 		if (dwc->ep0state == EP0_DATA_PHASE)
149 			dwc3_ep0_end_control_data(dwc, dwc->eps[dir]);
150 		else
151 			dwc3_ep0_end_control_data(dwc, dwc->eps[!dir]);
152 
153 		dwc->eps[0]->trb_enqueue = 0;
154 		dwc->eps[1]->trb_enqueue = 0;
155 
156 		dwc3_ep0_stall_and_restart(dwc);
157 	}
158 }
159 
160 /**
161  * dwc3_ep_inc_trb - increment a trb index.
162  * @index: Pointer to the TRB index to increment.
163  *
164  * The index should never point to the link TRB. After incrementing,
165  * if it is point to the link TRB, wrap around to the beginning. The
166  * link TRB is always at the last TRB entry.
167  */
168 static void dwc3_ep_inc_trb(u8 *index)
169 {
170 	(*index)++;
171 	if (*index == (DWC3_TRB_NUM - 1))
172 		*index = 0;
173 }
174 
175 /**
176  * dwc3_ep_inc_enq - increment endpoint's enqueue pointer
177  * @dep: The endpoint whose enqueue pointer we're incrementing
178  */
179 static void dwc3_ep_inc_enq(struct dwc3_ep *dep)
180 {
181 	dwc3_ep_inc_trb(&dep->trb_enqueue);
182 }
183 
184 /**
185  * dwc3_ep_inc_deq - increment endpoint's dequeue pointer
186  * @dep: The endpoint whose enqueue pointer we're incrementing
187  */
188 static void dwc3_ep_inc_deq(struct dwc3_ep *dep)
189 {
190 	dwc3_ep_inc_trb(&dep->trb_dequeue);
191 }
192 
193 static void dwc3_gadget_del_and_unmap_request(struct dwc3_ep *dep,
194 		struct dwc3_request *req, int status)
195 {
196 	struct dwc3			*dwc = dep->dwc;
197 
198 	list_del(&req->list);
199 	req->remaining = 0;
200 	req->needs_extra_trb = false;
201 	req->num_trbs = 0;
202 
203 	if (req->request.status == -EINPROGRESS)
204 		req->request.status = status;
205 
206 	if (req->trb)
207 		usb_gadget_unmap_request_by_dev(dwc->sysdev,
208 				&req->request, req->direction);
209 
210 	req->trb = NULL;
211 	trace_dwc3_gadget_giveback(req);
212 
213 	if (dep->number > 1)
214 		pm_runtime_put(dwc->dev);
215 }
216 
217 /**
218  * dwc3_gadget_giveback - call struct usb_request's ->complete callback
219  * @dep: The endpoint to whom the request belongs to
220  * @req: The request we're giving back
221  * @status: completion code for the request
222  *
223  * Must be called with controller's lock held and interrupts disabled. This
224  * function will unmap @req and call its ->complete() callback to notify upper
225  * layers that it has completed.
226  */
227 void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
228 		int status)
229 {
230 	struct dwc3			*dwc = dep->dwc;
231 
232 	dwc3_gadget_del_and_unmap_request(dep, req, status);
233 	req->status = DWC3_REQUEST_STATUS_COMPLETED;
234 
235 	spin_unlock(&dwc->lock);
236 	usb_gadget_giveback_request(&dep->endpoint, &req->request);
237 	spin_lock(&dwc->lock);
238 }
239 
240 /**
241  * dwc3_send_gadget_generic_command - issue a generic command for the controller
242  * @dwc: pointer to the controller context
243  * @cmd: the command to be issued
244  * @param: command parameter
245  *
246  * Caller should take care of locking. Issue @cmd with a given @param to @dwc
247  * and wait for its completion.
248  */
249 int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned int cmd,
250 		u32 param)
251 {
252 	u32		timeout = 500;
253 	int		status = 0;
254 	int		ret = 0;
255 	u32		reg;
256 
257 	dwc3_writel(dwc->regs, DWC3_DGCMDPAR, param);
258 	dwc3_writel(dwc->regs, DWC3_DGCMD, cmd | DWC3_DGCMD_CMDACT);
259 
260 	do {
261 		reg = dwc3_readl(dwc->regs, DWC3_DGCMD);
262 		if (!(reg & DWC3_DGCMD_CMDACT)) {
263 			status = DWC3_DGCMD_STATUS(reg);
264 			if (status)
265 				ret = -EINVAL;
266 			break;
267 		}
268 	} while (--timeout);
269 
270 	if (!timeout) {
271 		ret = -ETIMEDOUT;
272 		status = -ETIMEDOUT;
273 	}
274 
275 	trace_dwc3_gadget_generic_cmd(cmd, param, status);
276 
277 	return ret;
278 }
279 
280 static int __dwc3_gadget_wakeup(struct dwc3 *dwc, bool async);
281 
282 /**
283  * dwc3_send_gadget_ep_cmd - issue an endpoint command
284  * @dep: the endpoint to which the command is going to be issued
285  * @cmd: the command to be issued
286  * @params: parameters to the command
287  *
288  * Caller should handle locking. This function will issue @cmd with given
289  * @params to @dep and wait for its completion.
290  */
291 int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned int cmd,
292 		struct dwc3_gadget_ep_cmd_params *params)
293 {
294 	const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
295 	struct dwc3		*dwc = dep->dwc;
296 	u32			timeout = 5000;
297 	u32			saved_config = 0;
298 	u32			reg;
299 
300 	int			cmd_status = 0;
301 	int			ret = -EINVAL;
302 
303 	/*
304 	 * When operating in USB 2.0 speeds (HS/FS), if GUSB2PHYCFG.ENBLSLPM or
305 	 * GUSB2PHYCFG.SUSPHY is set, it must be cleared before issuing an
306 	 * endpoint command.
307 	 *
308 	 * Save and clear both GUSB2PHYCFG.ENBLSLPM and GUSB2PHYCFG.SUSPHY
309 	 * settings. Restore them after the command is completed.
310 	 *
311 	 * DWC_usb3 3.30a and DWC_usb31 1.90a programming guide section 3.2.2
312 	 */
313 	if (dwc->gadget->speed <= USB_SPEED_HIGH ||
314 	    DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_ENDTRANSFER) {
315 		reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
316 		if (unlikely(reg & DWC3_GUSB2PHYCFG_SUSPHY)) {
317 			saved_config |= DWC3_GUSB2PHYCFG_SUSPHY;
318 			reg &= ~DWC3_GUSB2PHYCFG_SUSPHY;
319 		}
320 
321 		if (reg & DWC3_GUSB2PHYCFG_ENBLSLPM) {
322 			saved_config |= DWC3_GUSB2PHYCFG_ENBLSLPM;
323 			reg &= ~DWC3_GUSB2PHYCFG_ENBLSLPM;
324 		}
325 
326 		if (saved_config)
327 			dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
328 	}
329 
330 	if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
331 		int link_state;
332 
333 		/*
334 		 * Initiate remote wakeup if the link state is in U3 when
335 		 * operating in SS/SSP or L1/L2 when operating in HS/FS. If the
336 		 * link state is in U1/U2, no remote wakeup is needed. The Start
337 		 * Transfer command will initiate the link recovery.
338 		 */
339 		link_state = dwc3_gadget_get_link_state(dwc);
340 		switch (link_state) {
341 		case DWC3_LINK_STATE_U2:
342 			if (dwc->gadget->speed >= USB_SPEED_SUPER)
343 				break;
344 
345 			fallthrough;
346 		case DWC3_LINK_STATE_U3:
347 			ret = __dwc3_gadget_wakeup(dwc, false);
348 			dev_WARN_ONCE(dwc->dev, ret, "wakeup failed --> %d\n",
349 					ret);
350 			break;
351 		}
352 	}
353 
354 	/*
355 	 * For some commands such as Update Transfer command, DEPCMDPARn
356 	 * registers are reserved. Since the driver often sends Update Transfer
357 	 * command, don't write to DEPCMDPARn to avoid register write delays and
358 	 * improve performance.
359 	 */
360 	if (DWC3_DEPCMD_CMD(cmd) != DWC3_DEPCMD_UPDATETRANSFER) {
361 		dwc3_writel(dep->regs, DWC3_DEPCMDPAR0, params->param0);
362 		dwc3_writel(dep->regs, DWC3_DEPCMDPAR1, params->param1);
363 		dwc3_writel(dep->regs, DWC3_DEPCMDPAR2, params->param2);
364 	}
365 
366 	/*
367 	 * Synopsys Databook 2.60a states in section 6.3.2.5.6 of that if we're
368 	 * not relying on XferNotReady, we can make use of a special "No
369 	 * Response Update Transfer" command where we should clear both CmdAct
370 	 * and CmdIOC bits.
371 	 *
372 	 * With this, we don't need to wait for command completion and can
373 	 * straight away issue further commands to the endpoint.
374 	 *
375 	 * NOTICE: We're making an assumption that control endpoints will never
376 	 * make use of Update Transfer command. This is a safe assumption
377 	 * because we can never have more than one request at a time with
378 	 * Control Endpoints. If anybody changes that assumption, this chunk
379 	 * needs to be updated accordingly.
380 	 */
381 	if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_UPDATETRANSFER &&
382 			!usb_endpoint_xfer_isoc(desc))
383 		cmd &= ~(DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_CMDACT);
384 	else
385 		cmd |= DWC3_DEPCMD_CMDACT;
386 
387 	dwc3_writel(dep->regs, DWC3_DEPCMD, cmd);
388 
389 	if (!(cmd & DWC3_DEPCMD_CMDACT) ||
390 		(DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_ENDTRANSFER &&
391 		!(cmd & DWC3_DEPCMD_CMDIOC))) {
392 		ret = 0;
393 		goto skip_status;
394 	}
395 
396 	do {
397 		reg = dwc3_readl(dep->regs, DWC3_DEPCMD);
398 		if (!(reg & DWC3_DEPCMD_CMDACT)) {
399 			cmd_status = DWC3_DEPCMD_STATUS(reg);
400 
401 			switch (cmd_status) {
402 			case 0:
403 				ret = 0;
404 				break;
405 			case DEPEVT_TRANSFER_NO_RESOURCE:
406 				dev_WARN(dwc->dev, "No resource for %s\n",
407 					 dep->name);
408 				ret = -EINVAL;
409 				break;
410 			case DEPEVT_TRANSFER_BUS_EXPIRY:
411 				/*
412 				 * SW issues START TRANSFER command to
413 				 * isochronous ep with future frame interval. If
414 				 * future interval time has already passed when
415 				 * core receives the command, it will respond
416 				 * with an error status of 'Bus Expiry'.
417 				 *
418 				 * Instead of always returning -EINVAL, let's
419 				 * give a hint to the gadget driver that this is
420 				 * the case by returning -EAGAIN.
421 				 */
422 				ret = -EAGAIN;
423 				break;
424 			default:
425 				dev_WARN(dwc->dev, "UNKNOWN cmd status\n");
426 			}
427 
428 			break;
429 		}
430 	} while (--timeout);
431 
432 	if (timeout == 0) {
433 		ret = -ETIMEDOUT;
434 		cmd_status = -ETIMEDOUT;
435 	}
436 
437 skip_status:
438 	trace_dwc3_gadget_ep_cmd(dep, cmd, params, cmd_status);
439 
440 	if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
441 		if (ret == 0)
442 			dep->flags |= DWC3_EP_TRANSFER_STARTED;
443 
444 		if (ret != -ETIMEDOUT)
445 			dwc3_gadget_ep_get_transfer_index(dep);
446 	}
447 
448 	if (saved_config) {
449 		reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
450 		reg |= saved_config;
451 		dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
452 	}
453 
454 	return ret;
455 }
456 
457 static int dwc3_send_clear_stall_ep_cmd(struct dwc3_ep *dep)
458 {
459 	struct dwc3 *dwc = dep->dwc;
460 	struct dwc3_gadget_ep_cmd_params params;
461 	u32 cmd = DWC3_DEPCMD_CLEARSTALL;
462 
463 	/*
464 	 * As of core revision 2.60a the recommended programming model
465 	 * is to set the ClearPendIN bit when issuing a Clear Stall EP
466 	 * command for IN endpoints. This is to prevent an issue where
467 	 * some (non-compliant) hosts may not send ACK TPs for pending
468 	 * IN transfers due to a mishandled error condition. Synopsys
469 	 * STAR 9000614252.
470 	 */
471 	if (dep->direction &&
472 	    !DWC3_VER_IS_PRIOR(DWC3, 260A) &&
473 	    (dwc->gadget->speed >= USB_SPEED_SUPER))
474 		cmd |= DWC3_DEPCMD_CLEARPENDIN;
475 
476 	memset(&params, 0, sizeof(params));
477 
478 	return dwc3_send_gadget_ep_cmd(dep, cmd, &params);
479 }
480 
481 static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep,
482 		struct dwc3_trb *trb)
483 {
484 	u32		offset = (char *) trb - (char *) dep->trb_pool;
485 
486 	return dep->trb_pool_dma + offset;
487 }
488 
489 static int dwc3_alloc_trb_pool(struct dwc3_ep *dep)
490 {
491 	struct dwc3		*dwc = dep->dwc;
492 
493 	if (dep->trb_pool)
494 		return 0;
495 
496 	dep->trb_pool = dma_alloc_coherent(dwc->sysdev,
497 			sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
498 			&dep->trb_pool_dma, GFP_KERNEL);
499 	if (!dep->trb_pool) {
500 		dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n",
501 				dep->name);
502 		return -ENOMEM;
503 	}
504 
505 	return 0;
506 }
507 
508 static void dwc3_free_trb_pool(struct dwc3_ep *dep)
509 {
510 	struct dwc3		*dwc = dep->dwc;
511 
512 	dma_free_coherent(dwc->sysdev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
513 			dep->trb_pool, dep->trb_pool_dma);
514 
515 	dep->trb_pool = NULL;
516 	dep->trb_pool_dma = 0;
517 }
518 
519 static int dwc3_gadget_set_xfer_resource(struct dwc3_ep *dep)
520 {
521 	struct dwc3_gadget_ep_cmd_params params;
522 
523 	memset(&params, 0x00, sizeof(params));
524 
525 	params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1);
526 
527 	return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETTRANSFRESOURCE,
528 			&params);
529 }
530 
531 /**
532  * dwc3_gadget_start_config - configure ep resources
533  * @dep: endpoint that is being enabled
534  *
535  * Issue a %DWC3_DEPCMD_DEPSTARTCFG command to @dep. After the command's
536  * completion, it will set Transfer Resource for all available endpoints.
537  *
538  * The assignment of transfer resources cannot perfectly follow the data book
539  * due to the fact that the controller driver does not have all knowledge of the
540  * configuration in advance. It is given this information piecemeal by the
541  * composite gadget framework after every SET_CONFIGURATION and
542  * SET_INTERFACE. Trying to follow the databook programming model in this
543  * scenario can cause errors. For two reasons:
544  *
545  * 1) The databook says to do %DWC3_DEPCMD_DEPSTARTCFG for every
546  * %USB_REQ_SET_CONFIGURATION and %USB_REQ_SET_INTERFACE (8.1.5). This is
547  * incorrect in the scenario of multiple interfaces.
548  *
549  * 2) The databook does not mention doing more %DWC3_DEPCMD_DEPXFERCFG for new
550  * endpoint on alt setting (8.1.6).
551  *
552  * The following simplified method is used instead:
553  *
554  * All hardware endpoints can be assigned a transfer resource and this setting
555  * will stay persistent until either a core reset or hibernation. So whenever we
556  * do a %DWC3_DEPCMD_DEPSTARTCFG(0) we can go ahead and do
557  * %DWC3_DEPCMD_DEPXFERCFG for every hardware endpoint as well. We are
558  * guaranteed that there are as many transfer resources as endpoints.
559  *
560  * This function is called for each endpoint when it is being enabled but is
561  * triggered only when called for EP0-out, which always happens first, and which
562  * should only happen in one of the above conditions.
563  */
564 static int dwc3_gadget_start_config(struct dwc3_ep *dep)
565 {
566 	struct dwc3_gadget_ep_cmd_params params;
567 	struct dwc3		*dwc;
568 	u32			cmd;
569 	int			i;
570 	int			ret;
571 
572 	if (dep->number)
573 		return 0;
574 
575 	memset(&params, 0x00, sizeof(params));
576 	cmd = DWC3_DEPCMD_DEPSTARTCFG;
577 	dwc = dep->dwc;
578 
579 	ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
580 	if (ret)
581 		return ret;
582 
583 	for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
584 		struct dwc3_ep *dep = dwc->eps[i];
585 
586 		if (!dep)
587 			continue;
588 
589 		ret = dwc3_gadget_set_xfer_resource(dep);
590 		if (ret)
591 			return ret;
592 	}
593 
594 	return 0;
595 }
596 
597 static int dwc3_gadget_set_ep_config(struct dwc3_ep *dep, unsigned int action)
598 {
599 	const struct usb_ss_ep_comp_descriptor *comp_desc;
600 	const struct usb_endpoint_descriptor *desc;
601 	struct dwc3_gadget_ep_cmd_params params;
602 	struct dwc3 *dwc = dep->dwc;
603 
604 	comp_desc = dep->endpoint.comp_desc;
605 	desc = dep->endpoint.desc;
606 
607 	memset(&params, 0x00, sizeof(params));
608 
609 	params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc))
610 		| DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc));
611 
612 	/* Burst size is only needed in SuperSpeed mode */
613 	if (dwc->gadget->speed >= USB_SPEED_SUPER) {
614 		u32 burst = dep->endpoint.maxburst;
615 
616 		params.param0 |= DWC3_DEPCFG_BURST_SIZE(burst - 1);
617 	}
618 
619 	params.param0 |= action;
620 	if (action == DWC3_DEPCFG_ACTION_RESTORE)
621 		params.param2 |= dep->saved_state;
622 
623 	if (usb_endpoint_xfer_control(desc))
624 		params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN;
625 
626 	if (dep->number <= 1 || usb_endpoint_xfer_isoc(desc))
627 		params.param1 |= DWC3_DEPCFG_XFER_NOT_READY_EN;
628 
629 	if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) {
630 		params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE
631 			| DWC3_DEPCFG_XFER_COMPLETE_EN
632 			| DWC3_DEPCFG_STREAM_EVENT_EN;
633 		dep->stream_capable = true;
634 	}
635 
636 	if (!usb_endpoint_xfer_control(desc))
637 		params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN;
638 
639 	/*
640 	 * We are doing 1:1 mapping for endpoints, meaning
641 	 * Physical Endpoints 2 maps to Logical Endpoint 2 and
642 	 * so on. We consider the direction bit as part of the physical
643 	 * endpoint number. So USB endpoint 0x81 is 0x03.
644 	 */
645 	params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number);
646 
647 	/*
648 	 * We must use the lower 16 TX FIFOs even though
649 	 * HW might have more
650 	 */
651 	if (dep->direction)
652 		params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1);
653 
654 	if (desc->bInterval) {
655 		u8 bInterval_m1;
656 
657 		/*
658 		 * Valid range for DEPCFG.bInterval_m1 is from 0 to 13.
659 		 *
660 		 * NOTE: The programming guide incorrectly stated bInterval_m1
661 		 * must be set to 0 when operating in fullspeed. Internally the
662 		 * controller does not have this limitation. See DWC_usb3x
663 		 * programming guide section 3.2.2.1.
664 		 */
665 		bInterval_m1 = min_t(u8, desc->bInterval - 1, 13);
666 
667 		if (usb_endpoint_type(desc) == USB_ENDPOINT_XFER_INT &&
668 		    dwc->gadget->speed == USB_SPEED_FULL)
669 			dep->interval = desc->bInterval;
670 		else
671 			dep->interval = 1 << (desc->bInterval - 1);
672 
673 		params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(bInterval_m1);
674 	}
675 
676 	if (dep->endpoint.fifo_mode) {
677 		if (!(dwc->hwparams.hwparams4 & DWC3_EXT_BUFF_CONTROL))
678 			return -EINVAL;
679 		params.param1 |= DWC3_DEPCFG_EBC_HWO_NOWB | DWC3_DEPCFG_USE_EBC;
680 	}
681 
682 	return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETEPCONFIG, &params);
683 }
684 
685 /**
686  * dwc3_gadget_calc_tx_fifo_size - calculates the txfifo size value
687  * @dwc: pointer to the DWC3 context
688  * @mult: multiplier to be used when calculating the fifo_size
689  *
690  * Calculates the size value based on the equation below:
691  *
692  * DWC3 revision 280A and prior:
693  * fifo_size = mult * (max_packet / mdwidth) + 1;
694  *
695  * DWC3 revision 290A and onwards:
696  * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
697  *
698  * The max packet size is set to 1024, as the txfifo requirements mainly apply
699  * to super speed USB use cases.  However, it is safe to overestimate the fifo
700  * allocations for other scenarios, i.e. high speed USB.
701  */
702 static int dwc3_gadget_calc_tx_fifo_size(struct dwc3 *dwc, int mult)
703 {
704 	int max_packet = 1024;
705 	int fifo_size;
706 	int mdwidth;
707 
708 	mdwidth = dwc3_mdwidth(dwc);
709 
710 	/* MDWIDTH is represented in bits, we need it in bytes */
711 	mdwidth >>= 3;
712 
713 	if (DWC3_VER_IS_PRIOR(DWC3, 290A))
714 		fifo_size = mult * (max_packet / mdwidth) + 1;
715 	else
716 		fifo_size = mult * ((max_packet + mdwidth) / mdwidth) + 1;
717 	return fifo_size;
718 }
719 
720 /**
721  * dwc3_gadget_clear_tx_fifos - Clears txfifo allocation
722  * @dwc: pointer to the DWC3 context
723  *
724  * Iterates through all the endpoint registers and clears the previous txfifo
725  * allocations.
726  */
727 void dwc3_gadget_clear_tx_fifos(struct dwc3 *dwc)
728 {
729 	struct dwc3_ep *dep;
730 	int fifo_depth;
731 	int size;
732 	int num;
733 
734 	if (!dwc->do_fifo_resize)
735 		return;
736 
737 	/* Read ep0IN related TXFIFO size */
738 	dep = dwc->eps[1];
739 	size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(0));
740 	if (DWC3_IP_IS(DWC3))
741 		fifo_depth = DWC3_GTXFIFOSIZ_TXFDEP(size);
742 	else
743 		fifo_depth = DWC31_GTXFIFOSIZ_TXFDEP(size);
744 
745 	dwc->last_fifo_depth = fifo_depth;
746 	/* Clear existing TXFIFO for all IN eps except ep0 */
747 	for (num = 3; num < min_t(int, dwc->num_eps, DWC3_ENDPOINTS_NUM);
748 	     num += 2) {
749 		dep = dwc->eps[num];
750 		/* Don't change TXFRAMNUM on usb31 version */
751 		size = DWC3_IP_IS(DWC3) ? 0 :
752 			dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(num >> 1)) &
753 				   DWC31_GTXFIFOSIZ_TXFRAMNUM;
754 
755 		dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(num >> 1), size);
756 		dep->flags &= ~DWC3_EP_TXFIFO_RESIZED;
757 	}
758 	dwc->num_ep_resized = 0;
759 }
760 
761 /*
762  * dwc3_gadget_resize_tx_fifos - reallocate fifo spaces for current use-case
763  * @dwc: pointer to our context structure
764  *
765  * This function will a best effort FIFO allocation in order
766  * to improve FIFO usage and throughput, while still allowing
767  * us to enable as many endpoints as possible.
768  *
769  * Keep in mind that this operation will be highly dependent
770  * on the configured size for RAM1 - which contains TxFifo -,
771  * the amount of endpoints enabled on coreConsultant tool, and
772  * the width of the Master Bus.
773  *
774  * In general, FIFO depths are represented with the following equation:
775  *
776  * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
777  *
778  * In conjunction with dwc3_gadget_check_config(), this resizing logic will
779  * ensure that all endpoints will have enough internal memory for one max
780  * packet per endpoint.
781  */
782 static int dwc3_gadget_resize_tx_fifos(struct dwc3_ep *dep)
783 {
784 	struct dwc3 *dwc = dep->dwc;
785 	int fifo_0_start;
786 	int ram1_depth;
787 	int fifo_size;
788 	int min_depth;
789 	int num_in_ep;
790 	int remaining;
791 	int num_fifos = 1;
792 	int fifo;
793 	int tmp;
794 
795 	if (!dwc->do_fifo_resize)
796 		return 0;
797 
798 	/* resize IN endpoints except ep0 */
799 	if (!usb_endpoint_dir_in(dep->endpoint.desc) || dep->number <= 1)
800 		return 0;
801 
802 	/* bail if already resized */
803 	if (dep->flags & DWC3_EP_TXFIFO_RESIZED)
804 		return 0;
805 
806 	ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7);
807 
808 	if ((dep->endpoint.maxburst > 1 &&
809 	     usb_endpoint_xfer_bulk(dep->endpoint.desc)) ||
810 	    usb_endpoint_xfer_isoc(dep->endpoint.desc))
811 		num_fifos = 3;
812 
813 	if (dep->endpoint.maxburst > 6 &&
814 	    (usb_endpoint_xfer_bulk(dep->endpoint.desc) ||
815 	     usb_endpoint_xfer_isoc(dep->endpoint.desc)) && DWC3_IP_IS(DWC31))
816 		num_fifos = dwc->tx_fifo_resize_max_num;
817 
818 	/* FIFO size for a single buffer */
819 	fifo = dwc3_gadget_calc_tx_fifo_size(dwc, 1);
820 
821 	/* Calculate the number of remaining EPs w/o any FIFO */
822 	num_in_ep = dwc->max_cfg_eps;
823 	num_in_ep -= dwc->num_ep_resized;
824 
825 	/* Reserve at least one FIFO for the number of IN EPs */
826 	min_depth = num_in_ep * (fifo + 1);
827 	remaining = ram1_depth - min_depth - dwc->last_fifo_depth;
828 	remaining = max_t(int, 0, remaining);
829 	/*
830 	 * We've already reserved 1 FIFO per EP, so check what we can fit in
831 	 * addition to it.  If there is not enough remaining space, allocate
832 	 * all the remaining space to the EP.
833 	 */
834 	fifo_size = (num_fifos - 1) * fifo;
835 	if (remaining < fifo_size)
836 		fifo_size = remaining;
837 
838 	fifo_size += fifo;
839 	/* Last increment according to the TX FIFO size equation */
840 	fifo_size++;
841 
842 	/* Check if TXFIFOs start at non-zero addr */
843 	tmp = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(0));
844 	fifo_0_start = DWC3_GTXFIFOSIZ_TXFSTADDR(tmp);
845 
846 	fifo_size |= (fifo_0_start + (dwc->last_fifo_depth << 16));
847 	if (DWC3_IP_IS(DWC3))
848 		dwc->last_fifo_depth += DWC3_GTXFIFOSIZ_TXFDEP(fifo_size);
849 	else
850 		dwc->last_fifo_depth += DWC31_GTXFIFOSIZ_TXFDEP(fifo_size);
851 
852 	/* Check fifo size allocation doesn't exceed available RAM size. */
853 	if (dwc->last_fifo_depth >= ram1_depth) {
854 		dev_err(dwc->dev, "Fifosize(%d) > RAM size(%d) %s depth:%d\n",
855 			dwc->last_fifo_depth, ram1_depth,
856 			dep->endpoint.name, fifo_size);
857 		if (DWC3_IP_IS(DWC3))
858 			fifo_size = DWC3_GTXFIFOSIZ_TXFDEP(fifo_size);
859 		else
860 			fifo_size = DWC31_GTXFIFOSIZ_TXFDEP(fifo_size);
861 
862 		dwc->last_fifo_depth -= fifo_size;
863 		return -ENOMEM;
864 	}
865 
866 	dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1), fifo_size);
867 	dep->flags |= DWC3_EP_TXFIFO_RESIZED;
868 	dwc->num_ep_resized++;
869 
870 	return 0;
871 }
872 
873 /**
874  * __dwc3_gadget_ep_enable - initializes a hw endpoint
875  * @dep: endpoint to be initialized
876  * @action: one of INIT, MODIFY or RESTORE
877  *
878  * Caller should take care of locking. Execute all necessary commands to
879  * initialize a HW endpoint so it can be used by a gadget driver.
880  */
881 static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action)
882 {
883 	const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
884 	struct dwc3		*dwc = dep->dwc;
885 
886 	u32			reg;
887 	int			ret;
888 
889 	if (!(dep->flags & DWC3_EP_ENABLED)) {
890 		ret = dwc3_gadget_resize_tx_fifos(dep);
891 		if (ret)
892 			return ret;
893 
894 		ret = dwc3_gadget_start_config(dep);
895 		if (ret)
896 			return ret;
897 	}
898 
899 	ret = dwc3_gadget_set_ep_config(dep, action);
900 	if (ret)
901 		return ret;
902 
903 	if (!(dep->flags & DWC3_EP_ENABLED)) {
904 		struct dwc3_trb	*trb_st_hw;
905 		struct dwc3_trb	*trb_link;
906 
907 		dep->type = usb_endpoint_type(desc);
908 		dep->flags |= DWC3_EP_ENABLED;
909 
910 		reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
911 		reg |= DWC3_DALEPENA_EP(dep->number);
912 		dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
913 
914 		dep->trb_dequeue = 0;
915 		dep->trb_enqueue = 0;
916 
917 		if (usb_endpoint_xfer_control(desc))
918 			goto out;
919 
920 		/* Initialize the TRB ring */
921 		memset(dep->trb_pool, 0,
922 		       sizeof(struct dwc3_trb) * DWC3_TRB_NUM);
923 
924 		/* Link TRB. The HWO bit is never reset */
925 		trb_st_hw = &dep->trb_pool[0];
926 
927 		trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
928 		trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
929 		trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
930 		trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
931 		trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
932 	}
933 
934 	/*
935 	 * Issue StartTransfer here with no-op TRB so we can always rely on No
936 	 * Response Update Transfer command.
937 	 */
938 	if (usb_endpoint_xfer_bulk(desc) ||
939 			usb_endpoint_xfer_int(desc)) {
940 		struct dwc3_gadget_ep_cmd_params params;
941 		struct dwc3_trb	*trb;
942 		dma_addr_t trb_dma;
943 		u32 cmd;
944 
945 		memset(&params, 0, sizeof(params));
946 		trb = &dep->trb_pool[0];
947 		trb_dma = dwc3_trb_dma_offset(dep, trb);
948 
949 		params.param0 = upper_32_bits(trb_dma);
950 		params.param1 = lower_32_bits(trb_dma);
951 
952 		cmd = DWC3_DEPCMD_STARTTRANSFER;
953 
954 		ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
955 		if (ret < 0)
956 			return ret;
957 
958 		if (dep->stream_capable) {
959 			/*
960 			 * For streams, at start, there maybe a race where the
961 			 * host primes the endpoint before the function driver
962 			 * queues a request to initiate a stream. In that case,
963 			 * the controller will not see the prime to generate the
964 			 * ERDY and start stream. To workaround this, issue a
965 			 * no-op TRB as normal, but end it immediately. As a
966 			 * result, when the function driver queues the request,
967 			 * the next START_TRANSFER command will cause the
968 			 * controller to generate an ERDY to initiate the
969 			 * stream.
970 			 */
971 			dwc3_stop_active_transfer(dep, true, true);
972 
973 			/*
974 			 * All stream eps will reinitiate stream on NoStream
975 			 * rejection until we can determine that the host can
976 			 * prime after the first transfer.
977 			 *
978 			 * However, if the controller is capable of
979 			 * TXF_FLUSH_BYPASS, then IN direction endpoints will
980 			 * automatically restart the stream without the driver
981 			 * initiation.
982 			 */
983 			if (!dep->direction ||
984 			    !(dwc->hwparams.hwparams9 &
985 			      DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS))
986 				dep->flags |= DWC3_EP_FORCE_RESTART_STREAM;
987 		}
988 	}
989 
990 out:
991 	trace_dwc3_gadget_ep_enable(dep);
992 
993 	return 0;
994 }
995 
996 void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status)
997 {
998 	struct dwc3_request		*req;
999 
1000 	dwc3_stop_active_transfer(dep, true, false);
1001 
1002 	/* If endxfer is delayed, avoid unmapping requests */
1003 	if (dep->flags & DWC3_EP_DELAY_STOP)
1004 		return;
1005 
1006 	/* - giveback all requests to gadget driver */
1007 	while (!list_empty(&dep->started_list)) {
1008 		req = next_request(&dep->started_list);
1009 
1010 		dwc3_gadget_giveback(dep, req, status);
1011 	}
1012 
1013 	while (!list_empty(&dep->pending_list)) {
1014 		req = next_request(&dep->pending_list);
1015 
1016 		dwc3_gadget_giveback(dep, req, status);
1017 	}
1018 
1019 	while (!list_empty(&dep->cancelled_list)) {
1020 		req = next_request(&dep->cancelled_list);
1021 
1022 		dwc3_gadget_giveback(dep, req, status);
1023 	}
1024 }
1025 
1026 /**
1027  * __dwc3_gadget_ep_disable - disables a hw endpoint
1028  * @dep: the endpoint to disable
1029  *
1030  * This function undoes what __dwc3_gadget_ep_enable did and also removes
1031  * requests which are currently being processed by the hardware and those which
1032  * are not yet scheduled.
1033  *
1034  * Caller should take care of locking.
1035  */
1036 static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
1037 {
1038 	struct dwc3		*dwc = dep->dwc;
1039 	u32			reg;
1040 	u32			mask;
1041 
1042 	trace_dwc3_gadget_ep_disable(dep);
1043 
1044 	/* make sure HW endpoint isn't stalled */
1045 	if (dep->flags & DWC3_EP_STALL)
1046 		__dwc3_gadget_ep_set_halt(dep, 0, false);
1047 
1048 	reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
1049 	reg &= ~DWC3_DALEPENA_EP(dep->number);
1050 	dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
1051 
1052 	dwc3_remove_requests(dwc, dep, -ESHUTDOWN);
1053 
1054 	dep->stream_capable = false;
1055 	dep->type = 0;
1056 	mask = DWC3_EP_TXFIFO_RESIZED;
1057 	/*
1058 	 * dwc3_remove_requests() can exit early if DWC3 EP delayed stop is
1059 	 * set.  Do not clear DEP flags, so that the end transfer command will
1060 	 * be reattempted during the next SETUP stage.
1061 	 */
1062 	if (dep->flags & DWC3_EP_DELAY_STOP)
1063 		mask |= (DWC3_EP_DELAY_STOP | DWC3_EP_TRANSFER_STARTED);
1064 	dep->flags &= mask;
1065 
1066 	/* Clear out the ep descriptors for non-ep0 */
1067 	if (dep->number > 1) {
1068 		dep->endpoint.comp_desc = NULL;
1069 		dep->endpoint.desc = NULL;
1070 	}
1071 
1072 	return 0;
1073 }
1074 
1075 /* -------------------------------------------------------------------------- */
1076 
1077 static int dwc3_gadget_ep0_enable(struct usb_ep *ep,
1078 		const struct usb_endpoint_descriptor *desc)
1079 {
1080 	return -EINVAL;
1081 }
1082 
1083 static int dwc3_gadget_ep0_disable(struct usb_ep *ep)
1084 {
1085 	return -EINVAL;
1086 }
1087 
1088 /* -------------------------------------------------------------------------- */
1089 
1090 static int dwc3_gadget_ep_enable(struct usb_ep *ep,
1091 		const struct usb_endpoint_descriptor *desc)
1092 {
1093 	struct dwc3_ep			*dep;
1094 	struct dwc3			*dwc;
1095 	unsigned long			flags;
1096 	int				ret;
1097 
1098 	if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
1099 		pr_debug("dwc3: invalid parameters\n");
1100 		return -EINVAL;
1101 	}
1102 
1103 	if (!desc->wMaxPacketSize) {
1104 		pr_debug("dwc3: missing wMaxPacketSize\n");
1105 		return -EINVAL;
1106 	}
1107 
1108 	dep = to_dwc3_ep(ep);
1109 	dwc = dep->dwc;
1110 
1111 	if (dev_WARN_ONCE(dwc->dev, dep->flags & DWC3_EP_ENABLED,
1112 					"%s is already enabled\n",
1113 					dep->name))
1114 		return 0;
1115 
1116 	spin_lock_irqsave(&dwc->lock, flags);
1117 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
1118 	spin_unlock_irqrestore(&dwc->lock, flags);
1119 
1120 	return ret;
1121 }
1122 
1123 static int dwc3_gadget_ep_disable(struct usb_ep *ep)
1124 {
1125 	struct dwc3_ep			*dep;
1126 	struct dwc3			*dwc;
1127 	unsigned long			flags;
1128 	int				ret;
1129 
1130 	if (!ep) {
1131 		pr_debug("dwc3: invalid parameters\n");
1132 		return -EINVAL;
1133 	}
1134 
1135 	dep = to_dwc3_ep(ep);
1136 	dwc = dep->dwc;
1137 
1138 	if (dev_WARN_ONCE(dwc->dev, !(dep->flags & DWC3_EP_ENABLED),
1139 					"%s is already disabled\n",
1140 					dep->name))
1141 		return 0;
1142 
1143 	spin_lock_irqsave(&dwc->lock, flags);
1144 	ret = __dwc3_gadget_ep_disable(dep);
1145 	spin_unlock_irqrestore(&dwc->lock, flags);
1146 
1147 	return ret;
1148 }
1149 
1150 static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep,
1151 		gfp_t gfp_flags)
1152 {
1153 	struct dwc3_request		*req;
1154 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1155 
1156 	req = kzalloc(sizeof(*req), gfp_flags);
1157 	if (!req)
1158 		return NULL;
1159 
1160 	req->direction	= dep->direction;
1161 	req->epnum	= dep->number;
1162 	req->dep	= dep;
1163 	req->status	= DWC3_REQUEST_STATUS_UNKNOWN;
1164 
1165 	trace_dwc3_alloc_request(req);
1166 
1167 	return &req->request;
1168 }
1169 
1170 static void dwc3_gadget_ep_free_request(struct usb_ep *ep,
1171 		struct usb_request *request)
1172 {
1173 	struct dwc3_request		*req = to_dwc3_request(request);
1174 
1175 	trace_dwc3_free_request(req);
1176 	kfree(req);
1177 }
1178 
1179 /**
1180  * dwc3_ep_prev_trb - returns the previous TRB in the ring
1181  * @dep: The endpoint with the TRB ring
1182  * @index: The index of the current TRB in the ring
1183  *
1184  * Returns the TRB prior to the one pointed to by the index. If the
1185  * index is 0, we will wrap backwards, skip the link TRB, and return
1186  * the one just before that.
1187  */
1188 static struct dwc3_trb *dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index)
1189 {
1190 	u8 tmp = index;
1191 
1192 	if (!tmp)
1193 		tmp = DWC3_TRB_NUM - 1;
1194 
1195 	return &dep->trb_pool[tmp - 1];
1196 }
1197 
1198 static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep)
1199 {
1200 	u8			trbs_left;
1201 
1202 	/*
1203 	 * If the enqueue & dequeue are equal then the TRB ring is either full
1204 	 * or empty. It's considered full when there are DWC3_TRB_NUM-1 of TRBs
1205 	 * pending to be processed by the driver.
1206 	 */
1207 	if (dep->trb_enqueue == dep->trb_dequeue) {
1208 		/*
1209 		 * If there is any request remained in the started_list at
1210 		 * this point, that means there is no TRB available.
1211 		 */
1212 		if (!list_empty(&dep->started_list))
1213 			return 0;
1214 
1215 		return DWC3_TRB_NUM - 1;
1216 	}
1217 
1218 	trbs_left = dep->trb_dequeue - dep->trb_enqueue;
1219 	trbs_left &= (DWC3_TRB_NUM - 1);
1220 
1221 	if (dep->trb_dequeue < dep->trb_enqueue)
1222 		trbs_left--;
1223 
1224 	return trbs_left;
1225 }
1226 
1227 /**
1228  * dwc3_prepare_one_trb - setup one TRB from one request
1229  * @dep: endpoint for which this request is prepared
1230  * @req: dwc3_request pointer
1231  * @trb_length: buffer size of the TRB
1232  * @chain: should this TRB be chained to the next?
1233  * @node: only for isochronous endpoints. First TRB needs different type.
1234  * @use_bounce_buffer: set to use bounce buffer
1235  * @must_interrupt: set to interrupt on TRB completion
1236  */
1237 static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
1238 		struct dwc3_request *req, unsigned int trb_length,
1239 		unsigned int chain, unsigned int node, bool use_bounce_buffer,
1240 		bool must_interrupt)
1241 {
1242 	struct dwc3_trb		*trb;
1243 	dma_addr_t		dma;
1244 	unsigned int		stream_id = req->request.stream_id;
1245 	unsigned int		short_not_ok = req->request.short_not_ok;
1246 	unsigned int		no_interrupt = req->request.no_interrupt;
1247 	unsigned int		is_last = req->request.is_last;
1248 	struct dwc3		*dwc = dep->dwc;
1249 	struct usb_gadget	*gadget = dwc->gadget;
1250 	enum usb_device_speed	speed = gadget->speed;
1251 
1252 	if (use_bounce_buffer)
1253 		dma = dep->dwc->bounce_addr;
1254 	else if (req->request.num_sgs > 0)
1255 		dma = sg_dma_address(req->start_sg);
1256 	else
1257 		dma = req->request.dma;
1258 
1259 	trb = &dep->trb_pool[dep->trb_enqueue];
1260 
1261 	if (!req->trb) {
1262 		dwc3_gadget_move_started_request(req);
1263 		req->trb = trb;
1264 		req->trb_dma = dwc3_trb_dma_offset(dep, trb);
1265 	}
1266 
1267 	req->num_trbs++;
1268 
1269 	trb->size = DWC3_TRB_SIZE_LENGTH(trb_length);
1270 	trb->bpl = lower_32_bits(dma);
1271 	trb->bph = upper_32_bits(dma);
1272 
1273 	switch (usb_endpoint_type(dep->endpoint.desc)) {
1274 	case USB_ENDPOINT_XFER_CONTROL:
1275 		trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP;
1276 		break;
1277 
1278 	case USB_ENDPOINT_XFER_ISOC:
1279 		if (!node) {
1280 			trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST;
1281 
1282 			/*
1283 			 * USB Specification 2.0 Section 5.9.2 states that: "If
1284 			 * there is only a single transaction in the microframe,
1285 			 * only a DATA0 data packet PID is used.  If there are
1286 			 * two transactions per microframe, DATA1 is used for
1287 			 * the first transaction data packet and DATA0 is used
1288 			 * for the second transaction data packet.  If there are
1289 			 * three transactions per microframe, DATA2 is used for
1290 			 * the first transaction data packet, DATA1 is used for
1291 			 * the second, and DATA0 is used for the third."
1292 			 *
1293 			 * IOW, we should satisfy the following cases:
1294 			 *
1295 			 * 1) length <= maxpacket
1296 			 *	- DATA0
1297 			 *
1298 			 * 2) maxpacket < length <= (2 * maxpacket)
1299 			 *	- DATA1, DATA0
1300 			 *
1301 			 * 3) (2 * maxpacket) < length <= (3 * maxpacket)
1302 			 *	- DATA2, DATA1, DATA0
1303 			 */
1304 			if (speed == USB_SPEED_HIGH) {
1305 				struct usb_ep *ep = &dep->endpoint;
1306 				unsigned int mult = 2;
1307 				unsigned int maxp = usb_endpoint_maxp(ep->desc);
1308 
1309 				if (req->request.length <= (2 * maxp))
1310 					mult--;
1311 
1312 				if (req->request.length <= maxp)
1313 					mult--;
1314 
1315 				trb->size |= DWC3_TRB_SIZE_PCM1(mult);
1316 			}
1317 		} else {
1318 			trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS;
1319 		}
1320 
1321 		if (!no_interrupt && !chain)
1322 			trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1323 		break;
1324 
1325 	case USB_ENDPOINT_XFER_BULK:
1326 	case USB_ENDPOINT_XFER_INT:
1327 		trb->ctrl = DWC3_TRBCTL_NORMAL;
1328 		break;
1329 	default:
1330 		/*
1331 		 * This is only possible with faulty memory because we
1332 		 * checked it already :)
1333 		 */
1334 		dev_WARN(dwc->dev, "Unknown endpoint type %d\n",
1335 				usb_endpoint_type(dep->endpoint.desc));
1336 	}
1337 
1338 	/*
1339 	 * Enable Continue on Short Packet
1340 	 * when endpoint is not a stream capable
1341 	 */
1342 	if (usb_endpoint_dir_out(dep->endpoint.desc)) {
1343 		if (!dep->stream_capable)
1344 			trb->ctrl |= DWC3_TRB_CTRL_CSP;
1345 
1346 		if (short_not_ok)
1347 			trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1348 	}
1349 
1350 	/* All TRBs setup for MST must set CSP=1 when LST=0 */
1351 	if (dep->stream_capable && DWC3_MST_CAPABLE(&dwc->hwparams))
1352 		trb->ctrl |= DWC3_TRB_CTRL_CSP;
1353 
1354 	if ((!no_interrupt && !chain) || must_interrupt)
1355 		trb->ctrl |= DWC3_TRB_CTRL_IOC;
1356 
1357 	if (chain)
1358 		trb->ctrl |= DWC3_TRB_CTRL_CHN;
1359 	else if (dep->stream_capable && is_last &&
1360 		 !DWC3_MST_CAPABLE(&dwc->hwparams))
1361 		trb->ctrl |= DWC3_TRB_CTRL_LST;
1362 
1363 	if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable)
1364 		trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(stream_id);
1365 
1366 	/*
1367 	 * As per data book 4.2.3.2TRB Control Bit Rules section
1368 	 *
1369 	 * The controller autonomously checks the HWO field of a TRB to determine if the
1370 	 * entire TRB is valid. Therefore, software must ensure that the rest of the TRB
1371 	 * is valid before setting the HWO field to '1'. In most systems, this means that
1372 	 * software must update the fourth DWORD of a TRB last.
1373 	 *
1374 	 * However there is a possibility of CPU re-ordering here which can cause
1375 	 * controller to observe the HWO bit set prematurely.
1376 	 * Add a write memory barrier to prevent CPU re-ordering.
1377 	 */
1378 	wmb();
1379 	trb->ctrl |= DWC3_TRB_CTRL_HWO;
1380 
1381 	dwc3_ep_inc_enq(dep);
1382 
1383 	trace_dwc3_prepare_trb(dep, trb);
1384 }
1385 
1386 static bool dwc3_needs_extra_trb(struct dwc3_ep *dep, struct dwc3_request *req)
1387 {
1388 	unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1389 	unsigned int rem = req->request.length % maxp;
1390 
1391 	if ((req->request.length && req->request.zero && !rem &&
1392 			!usb_endpoint_xfer_isoc(dep->endpoint.desc)) ||
1393 			(!req->direction && rem))
1394 		return true;
1395 
1396 	return false;
1397 }
1398 
1399 /**
1400  * dwc3_prepare_last_sg - prepare TRBs for the last SG entry
1401  * @dep: The endpoint that the request belongs to
1402  * @req: The request to prepare
1403  * @entry_length: The last SG entry size
1404  * @node: Indicates whether this is not the first entry (for isoc only)
1405  *
1406  * Return the number of TRBs prepared.
1407  */
1408 static int dwc3_prepare_last_sg(struct dwc3_ep *dep,
1409 		struct dwc3_request *req, unsigned int entry_length,
1410 		unsigned int node)
1411 {
1412 	unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1413 	unsigned int rem = req->request.length % maxp;
1414 	unsigned int num_trbs = 1;
1415 
1416 	if (dwc3_needs_extra_trb(dep, req))
1417 		num_trbs++;
1418 
1419 	if (dwc3_calc_trbs_left(dep) < num_trbs)
1420 		return 0;
1421 
1422 	req->needs_extra_trb = num_trbs > 1;
1423 
1424 	/* Prepare a normal TRB */
1425 	if (req->direction || req->request.length)
1426 		dwc3_prepare_one_trb(dep, req, entry_length,
1427 				req->needs_extra_trb, node, false, false);
1428 
1429 	/* Prepare extra TRBs for ZLP and MPS OUT transfer alignment */
1430 	if ((!req->direction && !req->request.length) || req->needs_extra_trb)
1431 		dwc3_prepare_one_trb(dep, req,
1432 				req->direction ? 0 : maxp - rem,
1433 				false, 1, true, false);
1434 
1435 	return num_trbs;
1436 }
1437 
1438 static int dwc3_prepare_trbs_sg(struct dwc3_ep *dep,
1439 		struct dwc3_request *req)
1440 {
1441 	struct scatterlist *sg = req->start_sg;
1442 	struct scatterlist *s;
1443 	int		i;
1444 	unsigned int length = req->request.length;
1445 	unsigned int remaining = req->request.num_mapped_sgs
1446 		- req->num_queued_sgs;
1447 	unsigned int num_trbs = req->num_trbs;
1448 	bool needs_extra_trb = dwc3_needs_extra_trb(dep, req);
1449 
1450 	/*
1451 	 * If we resume preparing the request, then get the remaining length of
1452 	 * the request and resume where we left off.
1453 	 */
1454 	for_each_sg(req->request.sg, s, req->num_queued_sgs, i)
1455 		length -= sg_dma_len(s);
1456 
1457 	for_each_sg(sg, s, remaining, i) {
1458 		unsigned int num_trbs_left = dwc3_calc_trbs_left(dep);
1459 		unsigned int trb_length;
1460 		bool must_interrupt = false;
1461 		bool last_sg = false;
1462 
1463 		trb_length = min_t(unsigned int, length, sg_dma_len(s));
1464 
1465 		length -= trb_length;
1466 
1467 		/*
1468 		 * IOMMU driver is coalescing the list of sgs which shares a
1469 		 * page boundary into one and giving it to USB driver. With
1470 		 * this the number of sgs mapped is not equal to the number of
1471 		 * sgs passed. So mark the chain bit to false if it isthe last
1472 		 * mapped sg.
1473 		 */
1474 		if ((i == remaining - 1) || !length)
1475 			last_sg = true;
1476 
1477 		if (!num_trbs_left)
1478 			break;
1479 
1480 		if (last_sg) {
1481 			if (!dwc3_prepare_last_sg(dep, req, trb_length, i))
1482 				break;
1483 		} else {
1484 			/*
1485 			 * Look ahead to check if we have enough TRBs for the
1486 			 * next SG entry. If not, set interrupt on this TRB to
1487 			 * resume preparing the next SG entry when more TRBs are
1488 			 * free.
1489 			 */
1490 			if (num_trbs_left == 1 || (needs_extra_trb &&
1491 					num_trbs_left <= 2 &&
1492 					sg_dma_len(sg_next(s)) >= length)) {
1493 				struct dwc3_request *r;
1494 
1495 				/* Check if previous requests already set IOC */
1496 				list_for_each_entry(r, &dep->started_list, list) {
1497 					if (r != req && !r->request.no_interrupt)
1498 						break;
1499 
1500 					if (r == req)
1501 						must_interrupt = true;
1502 				}
1503 			}
1504 
1505 			dwc3_prepare_one_trb(dep, req, trb_length, 1, i, false,
1506 					must_interrupt);
1507 		}
1508 
1509 		/*
1510 		 * There can be a situation where all sgs in sglist are not
1511 		 * queued because of insufficient trb number. To handle this
1512 		 * case, update start_sg to next sg to be queued, so that
1513 		 * we have free trbs we can continue queuing from where we
1514 		 * previously stopped
1515 		 */
1516 		if (!last_sg)
1517 			req->start_sg = sg_next(s);
1518 
1519 		req->num_queued_sgs++;
1520 		req->num_pending_sgs--;
1521 
1522 		/*
1523 		 * The number of pending SG entries may not correspond to the
1524 		 * number of mapped SG entries. If all the data are queued, then
1525 		 * don't include unused SG entries.
1526 		 */
1527 		if (length == 0) {
1528 			req->num_pending_sgs = 0;
1529 			break;
1530 		}
1531 
1532 		if (must_interrupt)
1533 			break;
1534 	}
1535 
1536 	return req->num_trbs - num_trbs;
1537 }
1538 
1539 static int dwc3_prepare_trbs_linear(struct dwc3_ep *dep,
1540 		struct dwc3_request *req)
1541 {
1542 	return dwc3_prepare_last_sg(dep, req, req->request.length, 0);
1543 }
1544 
1545 /*
1546  * dwc3_prepare_trbs - setup TRBs from requests
1547  * @dep: endpoint for which requests are being prepared
1548  *
1549  * The function goes through the requests list and sets up TRBs for the
1550  * transfers. The function returns once there are no more TRBs available or
1551  * it runs out of requests.
1552  *
1553  * Returns the number of TRBs prepared or negative errno.
1554  */
1555 static int dwc3_prepare_trbs(struct dwc3_ep *dep)
1556 {
1557 	struct dwc3_request	*req, *n;
1558 	int			ret = 0;
1559 
1560 	BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
1561 
1562 	/*
1563 	 * We can get in a situation where there's a request in the started list
1564 	 * but there weren't enough TRBs to fully kick it in the first time
1565 	 * around, so it has been waiting for more TRBs to be freed up.
1566 	 *
1567 	 * In that case, we should check if we have a request with pending_sgs
1568 	 * in the started list and prepare TRBs for that request first,
1569 	 * otherwise we will prepare TRBs completely out of order and that will
1570 	 * break things.
1571 	 */
1572 	list_for_each_entry(req, &dep->started_list, list) {
1573 		if (req->num_pending_sgs > 0) {
1574 			ret = dwc3_prepare_trbs_sg(dep, req);
1575 			if (!ret || req->num_pending_sgs)
1576 				return ret;
1577 		}
1578 
1579 		if (!dwc3_calc_trbs_left(dep))
1580 			return ret;
1581 
1582 		/*
1583 		 * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1584 		 * burst capability may try to read and use TRBs beyond the
1585 		 * active transfer instead of stopping.
1586 		 */
1587 		if (dep->stream_capable && req->request.is_last &&
1588 		    !DWC3_MST_CAPABLE(&dep->dwc->hwparams))
1589 			return ret;
1590 	}
1591 
1592 	list_for_each_entry_safe(req, n, &dep->pending_list, list) {
1593 		struct dwc3	*dwc = dep->dwc;
1594 
1595 		ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request,
1596 						    dep->direction);
1597 		if (ret)
1598 			return ret;
1599 
1600 		req->sg			= req->request.sg;
1601 		req->start_sg		= req->sg;
1602 		req->num_queued_sgs	= 0;
1603 		req->num_pending_sgs	= req->request.num_mapped_sgs;
1604 
1605 		if (req->num_pending_sgs > 0) {
1606 			ret = dwc3_prepare_trbs_sg(dep, req);
1607 			if (req->num_pending_sgs)
1608 				return ret;
1609 		} else {
1610 			ret = dwc3_prepare_trbs_linear(dep, req);
1611 		}
1612 
1613 		if (!ret || !dwc3_calc_trbs_left(dep))
1614 			return ret;
1615 
1616 		/*
1617 		 * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1618 		 * burst capability may try to read and use TRBs beyond the
1619 		 * active transfer instead of stopping.
1620 		 */
1621 		if (dep->stream_capable && req->request.is_last &&
1622 		    !DWC3_MST_CAPABLE(&dwc->hwparams))
1623 			return ret;
1624 	}
1625 
1626 	return ret;
1627 }
1628 
1629 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep);
1630 
1631 static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep)
1632 {
1633 	struct dwc3_gadget_ep_cmd_params params;
1634 	struct dwc3_request		*req;
1635 	int				starting;
1636 	int				ret;
1637 	u32				cmd;
1638 
1639 	/*
1640 	 * Note that it's normal to have no new TRBs prepared (i.e. ret == 0).
1641 	 * This happens when we need to stop and restart a transfer such as in
1642 	 * the case of reinitiating a stream or retrying an isoc transfer.
1643 	 */
1644 	ret = dwc3_prepare_trbs(dep);
1645 	if (ret < 0)
1646 		return ret;
1647 
1648 	starting = !(dep->flags & DWC3_EP_TRANSFER_STARTED);
1649 
1650 	/*
1651 	 * If there's no new TRB prepared and we don't need to restart a
1652 	 * transfer, there's no need to update the transfer.
1653 	 */
1654 	if (!ret && !starting)
1655 		return ret;
1656 
1657 	req = next_request(&dep->started_list);
1658 	if (!req) {
1659 		dep->flags |= DWC3_EP_PENDING_REQUEST;
1660 		return 0;
1661 	}
1662 
1663 	memset(&params, 0, sizeof(params));
1664 
1665 	if (starting) {
1666 		params.param0 = upper_32_bits(req->trb_dma);
1667 		params.param1 = lower_32_bits(req->trb_dma);
1668 		cmd = DWC3_DEPCMD_STARTTRANSFER;
1669 
1670 		if (dep->stream_capable)
1671 			cmd |= DWC3_DEPCMD_PARAM(req->request.stream_id);
1672 
1673 		if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
1674 			cmd |= DWC3_DEPCMD_PARAM(dep->frame_number);
1675 	} else {
1676 		cmd = DWC3_DEPCMD_UPDATETRANSFER |
1677 			DWC3_DEPCMD_PARAM(dep->resource_index);
1678 	}
1679 
1680 	ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1681 	if (ret < 0) {
1682 		struct dwc3_request *tmp;
1683 
1684 		if (ret == -EAGAIN)
1685 			return ret;
1686 
1687 		dwc3_stop_active_transfer(dep, true, true);
1688 
1689 		list_for_each_entry_safe(req, tmp, &dep->started_list, list)
1690 			dwc3_gadget_move_cancelled_request(req, DWC3_REQUEST_STATUS_DEQUEUED);
1691 
1692 		/* If ep isn't started, then there's no end transfer pending */
1693 		if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
1694 			dwc3_gadget_ep_cleanup_cancelled_requests(dep);
1695 
1696 		return ret;
1697 	}
1698 
1699 	if (dep->stream_capable && req->request.is_last &&
1700 	    !DWC3_MST_CAPABLE(&dep->dwc->hwparams))
1701 		dep->flags |= DWC3_EP_WAIT_TRANSFER_COMPLETE;
1702 
1703 	return 0;
1704 }
1705 
1706 static int __dwc3_gadget_get_frame(struct dwc3 *dwc)
1707 {
1708 	u32			reg;
1709 
1710 	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1711 	return DWC3_DSTS_SOFFN(reg);
1712 }
1713 
1714 /**
1715  * __dwc3_stop_active_transfer - stop the current active transfer
1716  * @dep: isoc endpoint
1717  * @force: set forcerm bit in the command
1718  * @interrupt: command complete interrupt after End Transfer command
1719  *
1720  * When setting force, the ForceRM bit will be set. In that case
1721  * the controller won't update the TRB progress on command
1722  * completion. It also won't clear the HWO bit in the TRB.
1723  * The command will also not complete immediately in that case.
1724  */
1725 static int __dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force, bool interrupt)
1726 {
1727 	struct dwc3 *dwc = dep->dwc;
1728 	struct dwc3_gadget_ep_cmd_params params;
1729 	u32 cmd;
1730 	int ret;
1731 
1732 	cmd = DWC3_DEPCMD_ENDTRANSFER;
1733 	cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
1734 	cmd |= interrupt ? DWC3_DEPCMD_CMDIOC : 0;
1735 	cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
1736 	memset(&params, 0, sizeof(params));
1737 	ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1738 	/*
1739 	 * If the End Transfer command was timed out while the device is
1740 	 * not in SETUP phase, it's possible that an incoming Setup packet
1741 	 * may prevent the command's completion. Let's retry when the
1742 	 * ep0state returns to EP0_SETUP_PHASE.
1743 	 */
1744 	if (ret == -ETIMEDOUT && dep->dwc->ep0state != EP0_SETUP_PHASE) {
1745 		dep->flags |= DWC3_EP_DELAY_STOP;
1746 		return 0;
1747 	}
1748 	WARN_ON_ONCE(ret);
1749 	dep->resource_index = 0;
1750 
1751 	if (!interrupt) {
1752 		if (!DWC3_IP_IS(DWC3) || DWC3_VER_IS_PRIOR(DWC3, 310A))
1753 			mdelay(1);
1754 		dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
1755 	} else if (!ret) {
1756 		dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
1757 	}
1758 
1759 	dep->flags &= ~DWC3_EP_DELAY_STOP;
1760 	return ret;
1761 }
1762 
1763 /**
1764  * dwc3_gadget_start_isoc_quirk - workaround invalid frame number
1765  * @dep: isoc endpoint
1766  *
1767  * This function tests for the correct combination of BIT[15:14] from the 16-bit
1768  * microframe number reported by the XferNotReady event for the future frame
1769  * number to start the isoc transfer.
1770  *
1771  * In DWC_usb31 version 1.70a-ea06 and prior, for highspeed and fullspeed
1772  * isochronous IN, BIT[15:14] of the 16-bit microframe number reported by the
1773  * XferNotReady event are invalid. The driver uses this number to schedule the
1774  * isochronous transfer and passes it to the START TRANSFER command. Because
1775  * this number is invalid, the command may fail. If BIT[15:14] matches the
1776  * internal 16-bit microframe, the START TRANSFER command will pass and the
1777  * transfer will start at the scheduled time, if it is off by 1, the command
1778  * will still pass, but the transfer will start 2 seconds in the future. For all
1779  * other conditions, the START TRANSFER command will fail with bus-expiry.
1780  *
1781  * In order to workaround this issue, we can test for the correct combination of
1782  * BIT[15:14] by sending START TRANSFER commands with different values of
1783  * BIT[15:14]: 'b00, 'b01, 'b10, and 'b11. Each combination is 2^14 uframe apart
1784  * (or 2 seconds). 4 seconds into the future will result in a bus-expiry status.
1785  * As the result, within the 4 possible combinations for BIT[15:14], there will
1786  * be 2 successful and 2 failure START COMMAND status. One of the 2 successful
1787  * command status will result in a 2-second delay start. The smaller BIT[15:14]
1788  * value is the correct combination.
1789  *
1790  * Since there are only 4 outcomes and the results are ordered, we can simply
1791  * test 2 START TRANSFER commands with BIT[15:14] combinations 'b00 and 'b01 to
1792  * deduce the smaller successful combination.
1793  *
1794  * Let test0 = test status for combination 'b00 and test1 = test status for 'b01
1795  * of BIT[15:14]. The correct combination is as follow:
1796  *
1797  * if test0 fails and test1 passes, BIT[15:14] is 'b01
1798  * if test0 fails and test1 fails, BIT[15:14] is 'b10
1799  * if test0 passes and test1 fails, BIT[15:14] is 'b11
1800  * if test0 passes and test1 passes, BIT[15:14] is 'b00
1801  *
1802  * Synopsys STAR 9001202023: Wrong microframe number for isochronous IN
1803  * endpoints.
1804  */
1805 static int dwc3_gadget_start_isoc_quirk(struct dwc3_ep *dep)
1806 {
1807 	int cmd_status = 0;
1808 	bool test0;
1809 	bool test1;
1810 
1811 	while (dep->combo_num < 2) {
1812 		struct dwc3_gadget_ep_cmd_params params;
1813 		u32 test_frame_number;
1814 		u32 cmd;
1815 
1816 		/*
1817 		 * Check if we can start isoc transfer on the next interval or
1818 		 * 4 uframes in the future with BIT[15:14] as dep->combo_num
1819 		 */
1820 		test_frame_number = dep->frame_number & DWC3_FRNUMBER_MASK;
1821 		test_frame_number |= dep->combo_num << 14;
1822 		test_frame_number += max_t(u32, 4, dep->interval);
1823 
1824 		params.param0 = upper_32_bits(dep->dwc->bounce_addr);
1825 		params.param1 = lower_32_bits(dep->dwc->bounce_addr);
1826 
1827 		cmd = DWC3_DEPCMD_STARTTRANSFER;
1828 		cmd |= DWC3_DEPCMD_PARAM(test_frame_number);
1829 		cmd_status = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1830 
1831 		/* Redo if some other failure beside bus-expiry is received */
1832 		if (cmd_status && cmd_status != -EAGAIN) {
1833 			dep->start_cmd_status = 0;
1834 			dep->combo_num = 0;
1835 			return 0;
1836 		}
1837 
1838 		/* Store the first test status */
1839 		if (dep->combo_num == 0)
1840 			dep->start_cmd_status = cmd_status;
1841 
1842 		dep->combo_num++;
1843 
1844 		/*
1845 		 * End the transfer if the START_TRANSFER command is successful
1846 		 * to wait for the next XferNotReady to test the command again
1847 		 */
1848 		if (cmd_status == 0) {
1849 			dwc3_stop_active_transfer(dep, true, true);
1850 			return 0;
1851 		}
1852 	}
1853 
1854 	/* test0 and test1 are both completed at this point */
1855 	test0 = (dep->start_cmd_status == 0);
1856 	test1 = (cmd_status == 0);
1857 
1858 	if (!test0 && test1)
1859 		dep->combo_num = 1;
1860 	else if (!test0 && !test1)
1861 		dep->combo_num = 2;
1862 	else if (test0 && !test1)
1863 		dep->combo_num = 3;
1864 	else if (test0 && test1)
1865 		dep->combo_num = 0;
1866 
1867 	dep->frame_number &= DWC3_FRNUMBER_MASK;
1868 	dep->frame_number |= dep->combo_num << 14;
1869 	dep->frame_number += max_t(u32, 4, dep->interval);
1870 
1871 	/* Reinitialize test variables */
1872 	dep->start_cmd_status = 0;
1873 	dep->combo_num = 0;
1874 
1875 	return __dwc3_gadget_kick_transfer(dep);
1876 }
1877 
1878 static int __dwc3_gadget_start_isoc(struct dwc3_ep *dep)
1879 {
1880 	const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
1881 	struct dwc3 *dwc = dep->dwc;
1882 	int ret;
1883 	int i;
1884 
1885 	if (list_empty(&dep->pending_list) &&
1886 	    list_empty(&dep->started_list)) {
1887 		dep->flags |= DWC3_EP_PENDING_REQUEST;
1888 		return -EAGAIN;
1889 	}
1890 
1891 	if (!dwc->dis_start_transfer_quirk &&
1892 	    (DWC3_VER_IS_PRIOR(DWC31, 170A) ||
1893 	     DWC3_VER_TYPE_IS_WITHIN(DWC31, 170A, EA01, EA06))) {
1894 		if (dwc->gadget->speed <= USB_SPEED_HIGH && dep->direction)
1895 			return dwc3_gadget_start_isoc_quirk(dep);
1896 	}
1897 
1898 	if (desc->bInterval <= 14 &&
1899 	    dwc->gadget->speed >= USB_SPEED_HIGH) {
1900 		u32 frame = __dwc3_gadget_get_frame(dwc);
1901 		bool rollover = frame <
1902 				(dep->frame_number & DWC3_FRNUMBER_MASK);
1903 
1904 		/*
1905 		 * frame_number is set from XferNotReady and may be already
1906 		 * out of date. DSTS only provides the lower 14 bit of the
1907 		 * current frame number. So add the upper two bits of
1908 		 * frame_number and handle a possible rollover.
1909 		 * This will provide the correct frame_number unless more than
1910 		 * rollover has happened since XferNotReady.
1911 		 */
1912 
1913 		dep->frame_number = (dep->frame_number & ~DWC3_FRNUMBER_MASK) |
1914 				     frame;
1915 		if (rollover)
1916 			dep->frame_number += BIT(14);
1917 	}
1918 
1919 	for (i = 0; i < DWC3_ISOC_MAX_RETRIES; i++) {
1920 		int future_interval = i + 1;
1921 
1922 		/* Give the controller at least 500us to schedule transfers */
1923 		if (desc->bInterval < 3)
1924 			future_interval += 3 - desc->bInterval;
1925 
1926 		dep->frame_number = DWC3_ALIGN_FRAME(dep, future_interval);
1927 
1928 		ret = __dwc3_gadget_kick_transfer(dep);
1929 		if (ret != -EAGAIN)
1930 			break;
1931 	}
1932 
1933 	/*
1934 	 * After a number of unsuccessful start attempts due to bus-expiry
1935 	 * status, issue END_TRANSFER command and retry on the next XferNotReady
1936 	 * event.
1937 	 */
1938 	if (ret == -EAGAIN)
1939 		ret = __dwc3_stop_active_transfer(dep, false, true);
1940 
1941 	return ret;
1942 }
1943 
1944 static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
1945 {
1946 	struct dwc3		*dwc = dep->dwc;
1947 
1948 	if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) {
1949 		dev_dbg(dwc->dev, "%s: can't queue to disabled endpoint\n",
1950 				dep->name);
1951 		return -ESHUTDOWN;
1952 	}
1953 
1954 	if (WARN(req->dep != dep, "request %pK belongs to '%s'\n",
1955 				&req->request, req->dep->name))
1956 		return -EINVAL;
1957 
1958 	if (WARN(req->status < DWC3_REQUEST_STATUS_COMPLETED,
1959 				"%s: request %pK already in flight\n",
1960 				dep->name, &req->request))
1961 		return -EINVAL;
1962 
1963 	pm_runtime_get(dwc->dev);
1964 
1965 	req->request.actual	= 0;
1966 	req->request.status	= -EINPROGRESS;
1967 
1968 	trace_dwc3_ep_queue(req);
1969 
1970 	list_add_tail(&req->list, &dep->pending_list);
1971 	req->status = DWC3_REQUEST_STATUS_QUEUED;
1972 
1973 	if (dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE)
1974 		return 0;
1975 
1976 	/*
1977 	 * Start the transfer only after the END_TRANSFER is completed
1978 	 * and endpoint STALL is cleared.
1979 	 */
1980 	if ((dep->flags & DWC3_EP_END_TRANSFER_PENDING) ||
1981 	    (dep->flags & DWC3_EP_WEDGE) ||
1982 	    (dep->flags & DWC3_EP_DELAY_STOP) ||
1983 	    (dep->flags & DWC3_EP_STALL)) {
1984 		dep->flags |= DWC3_EP_DELAY_START;
1985 		return 0;
1986 	}
1987 
1988 	/*
1989 	 * NOTICE: Isochronous endpoints should NEVER be prestarted. We must
1990 	 * wait for a XferNotReady event so we will know what's the current
1991 	 * (micro-)frame number.
1992 	 *
1993 	 * Without this trick, we are very, very likely gonna get Bus Expiry
1994 	 * errors which will force us issue EndTransfer command.
1995 	 */
1996 	if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1997 		if (!(dep->flags & DWC3_EP_TRANSFER_STARTED)) {
1998 			if ((dep->flags & DWC3_EP_PENDING_REQUEST))
1999 				return __dwc3_gadget_start_isoc(dep);
2000 
2001 			return 0;
2002 		}
2003 	}
2004 
2005 	__dwc3_gadget_kick_transfer(dep);
2006 
2007 	return 0;
2008 }
2009 
2010 static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
2011 	gfp_t gfp_flags)
2012 {
2013 	struct dwc3_request		*req = to_dwc3_request(request);
2014 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
2015 	struct dwc3			*dwc = dep->dwc;
2016 
2017 	unsigned long			flags;
2018 
2019 	int				ret;
2020 
2021 	spin_lock_irqsave(&dwc->lock, flags);
2022 	ret = __dwc3_gadget_ep_queue(dep, req);
2023 	spin_unlock_irqrestore(&dwc->lock, flags);
2024 
2025 	return ret;
2026 }
2027 
2028 static void dwc3_gadget_ep_skip_trbs(struct dwc3_ep *dep, struct dwc3_request *req)
2029 {
2030 	int i;
2031 
2032 	/* If req->trb is not set, then the request has not started */
2033 	if (!req->trb)
2034 		return;
2035 
2036 	/*
2037 	 * If request was already started, this means we had to
2038 	 * stop the transfer. With that we also need to ignore
2039 	 * all TRBs used by the request, however TRBs can only
2040 	 * be modified after completion of END_TRANSFER
2041 	 * command. So what we do here is that we wait for
2042 	 * END_TRANSFER completion and only after that, we jump
2043 	 * over TRBs by clearing HWO and incrementing dequeue
2044 	 * pointer.
2045 	 */
2046 	for (i = 0; i < req->num_trbs; i++) {
2047 		struct dwc3_trb *trb;
2048 
2049 		trb = &dep->trb_pool[dep->trb_dequeue];
2050 		trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2051 		dwc3_ep_inc_deq(dep);
2052 	}
2053 
2054 	req->num_trbs = 0;
2055 }
2056 
2057 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep)
2058 {
2059 	struct dwc3_request		*req;
2060 	struct dwc3			*dwc = dep->dwc;
2061 
2062 	while (!list_empty(&dep->cancelled_list)) {
2063 		req = next_request(&dep->cancelled_list);
2064 		dwc3_gadget_ep_skip_trbs(dep, req);
2065 		switch (req->status) {
2066 		case DWC3_REQUEST_STATUS_DISCONNECTED:
2067 			dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
2068 			break;
2069 		case DWC3_REQUEST_STATUS_DEQUEUED:
2070 			dwc3_gadget_giveback(dep, req, -ECONNRESET);
2071 			break;
2072 		case DWC3_REQUEST_STATUS_STALLED:
2073 			dwc3_gadget_giveback(dep, req, -EPIPE);
2074 			break;
2075 		default:
2076 			dev_err(dwc->dev, "request cancelled with wrong reason:%d\n", req->status);
2077 			dwc3_gadget_giveback(dep, req, -ECONNRESET);
2078 			break;
2079 		}
2080 		/*
2081 		 * The endpoint is disabled, let the dwc3_remove_requests()
2082 		 * handle the cleanup.
2083 		 */
2084 		if (!dep->endpoint.desc)
2085 			break;
2086 	}
2087 }
2088 
2089 static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
2090 		struct usb_request *request)
2091 {
2092 	struct dwc3_request		*req = to_dwc3_request(request);
2093 	struct dwc3_request		*r = NULL;
2094 
2095 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
2096 	struct dwc3			*dwc = dep->dwc;
2097 
2098 	unsigned long			flags;
2099 	int				ret = 0;
2100 
2101 	trace_dwc3_ep_dequeue(req);
2102 
2103 	spin_lock_irqsave(&dwc->lock, flags);
2104 
2105 	list_for_each_entry(r, &dep->cancelled_list, list) {
2106 		if (r == req)
2107 			goto out;
2108 	}
2109 
2110 	list_for_each_entry(r, &dep->pending_list, list) {
2111 		if (r == req) {
2112 			/*
2113 			 * Explicitly check for EP0/1 as dequeue for those
2114 			 * EPs need to be handled differently.  Control EP
2115 			 * only deals with one USB req, and giveback will
2116 			 * occur during dwc3_ep0_stall_and_restart().  EP0
2117 			 * requests are never added to started_list.
2118 			 */
2119 			if (dep->number > 1)
2120 				dwc3_gadget_giveback(dep, req, -ECONNRESET);
2121 			else
2122 				dwc3_ep0_reset_state(dwc);
2123 			goto out;
2124 		}
2125 	}
2126 
2127 	list_for_each_entry(r, &dep->started_list, list) {
2128 		if (r == req) {
2129 			struct dwc3_request *t;
2130 
2131 			/* wait until it is processed */
2132 			dwc3_stop_active_transfer(dep, true, true);
2133 
2134 			/*
2135 			 * Remove any started request if the transfer is
2136 			 * cancelled.
2137 			 */
2138 			list_for_each_entry_safe(r, t, &dep->started_list, list)
2139 				dwc3_gadget_move_cancelled_request(r,
2140 						DWC3_REQUEST_STATUS_DEQUEUED);
2141 
2142 			dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
2143 
2144 			goto out;
2145 		}
2146 	}
2147 
2148 	dev_err(dwc->dev, "request %pK was not queued to %s\n",
2149 		request, ep->name);
2150 	ret = -EINVAL;
2151 out:
2152 	spin_unlock_irqrestore(&dwc->lock, flags);
2153 
2154 	return ret;
2155 }
2156 
2157 int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
2158 {
2159 	struct dwc3_gadget_ep_cmd_params	params;
2160 	struct dwc3				*dwc = dep->dwc;
2161 	struct dwc3_request			*req;
2162 	struct dwc3_request			*tmp;
2163 	int					ret;
2164 
2165 	if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
2166 		dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
2167 		return -EINVAL;
2168 	}
2169 
2170 	memset(&params, 0x00, sizeof(params));
2171 
2172 	if (value) {
2173 		struct dwc3_trb *trb;
2174 
2175 		unsigned int transfer_in_flight;
2176 		unsigned int started;
2177 
2178 		if (dep->number > 1)
2179 			trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
2180 		else
2181 			trb = &dwc->ep0_trb[dep->trb_enqueue];
2182 
2183 		transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO;
2184 		started = !list_empty(&dep->started_list);
2185 
2186 		if (!protocol && ((dep->direction && transfer_in_flight) ||
2187 				(!dep->direction && started))) {
2188 			return -EAGAIN;
2189 		}
2190 
2191 		ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL,
2192 				&params);
2193 		if (ret)
2194 			dev_err(dwc->dev, "failed to set STALL on %s\n",
2195 					dep->name);
2196 		else
2197 			dep->flags |= DWC3_EP_STALL;
2198 	} else {
2199 		/*
2200 		 * Don't issue CLEAR_STALL command to control endpoints. The
2201 		 * controller automatically clears the STALL when it receives
2202 		 * the SETUP token.
2203 		 */
2204 		if (dep->number <= 1) {
2205 			dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
2206 			return 0;
2207 		}
2208 
2209 		dwc3_stop_active_transfer(dep, true, true);
2210 
2211 		list_for_each_entry_safe(req, tmp, &dep->started_list, list)
2212 			dwc3_gadget_move_cancelled_request(req, DWC3_REQUEST_STATUS_STALLED);
2213 
2214 		if (dep->flags & DWC3_EP_END_TRANSFER_PENDING ||
2215 		    (dep->flags & DWC3_EP_DELAY_STOP)) {
2216 			dep->flags |= DWC3_EP_PENDING_CLEAR_STALL;
2217 			if (protocol)
2218 				dwc->clear_stall_protocol = dep->number;
2219 
2220 			return 0;
2221 		}
2222 
2223 		dwc3_gadget_ep_cleanup_cancelled_requests(dep);
2224 
2225 		ret = dwc3_send_clear_stall_ep_cmd(dep);
2226 		if (ret) {
2227 			dev_err(dwc->dev, "failed to clear STALL on %s\n",
2228 					dep->name);
2229 			return ret;
2230 		}
2231 
2232 		dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
2233 
2234 		if ((dep->flags & DWC3_EP_DELAY_START) &&
2235 		    !usb_endpoint_xfer_isoc(dep->endpoint.desc))
2236 			__dwc3_gadget_kick_transfer(dep);
2237 
2238 		dep->flags &= ~DWC3_EP_DELAY_START;
2239 	}
2240 
2241 	return ret;
2242 }
2243 
2244 static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
2245 {
2246 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
2247 	struct dwc3			*dwc = dep->dwc;
2248 
2249 	unsigned long			flags;
2250 
2251 	int				ret;
2252 
2253 	spin_lock_irqsave(&dwc->lock, flags);
2254 	ret = __dwc3_gadget_ep_set_halt(dep, value, false);
2255 	spin_unlock_irqrestore(&dwc->lock, flags);
2256 
2257 	return ret;
2258 }
2259 
2260 static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
2261 {
2262 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
2263 	struct dwc3			*dwc = dep->dwc;
2264 	unsigned long			flags;
2265 	int				ret;
2266 
2267 	spin_lock_irqsave(&dwc->lock, flags);
2268 	dep->flags |= DWC3_EP_WEDGE;
2269 
2270 	if (dep->number == 0 || dep->number == 1)
2271 		ret = __dwc3_gadget_ep0_set_halt(ep, 1);
2272 	else
2273 		ret = __dwc3_gadget_ep_set_halt(dep, 1, false);
2274 	spin_unlock_irqrestore(&dwc->lock, flags);
2275 
2276 	return ret;
2277 }
2278 
2279 /* -------------------------------------------------------------------------- */
2280 
2281 static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
2282 	.bLength	= USB_DT_ENDPOINT_SIZE,
2283 	.bDescriptorType = USB_DT_ENDPOINT,
2284 	.bmAttributes	= USB_ENDPOINT_XFER_CONTROL,
2285 };
2286 
2287 static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
2288 	.enable		= dwc3_gadget_ep0_enable,
2289 	.disable	= dwc3_gadget_ep0_disable,
2290 	.alloc_request	= dwc3_gadget_ep_alloc_request,
2291 	.free_request	= dwc3_gadget_ep_free_request,
2292 	.queue		= dwc3_gadget_ep0_queue,
2293 	.dequeue	= dwc3_gadget_ep_dequeue,
2294 	.set_halt	= dwc3_gadget_ep0_set_halt,
2295 	.set_wedge	= dwc3_gadget_ep_set_wedge,
2296 };
2297 
2298 static const struct usb_ep_ops dwc3_gadget_ep_ops = {
2299 	.enable		= dwc3_gadget_ep_enable,
2300 	.disable	= dwc3_gadget_ep_disable,
2301 	.alloc_request	= dwc3_gadget_ep_alloc_request,
2302 	.free_request	= dwc3_gadget_ep_free_request,
2303 	.queue		= dwc3_gadget_ep_queue,
2304 	.dequeue	= dwc3_gadget_ep_dequeue,
2305 	.set_halt	= dwc3_gadget_ep_set_halt,
2306 	.set_wedge	= dwc3_gadget_ep_set_wedge,
2307 };
2308 
2309 /* -------------------------------------------------------------------------- */
2310 
2311 static void dwc3_gadget_enable_linksts_evts(struct dwc3 *dwc, bool set)
2312 {
2313 	u32 reg;
2314 
2315 	if (DWC3_VER_IS_PRIOR(DWC3, 250A))
2316 		return;
2317 
2318 	reg = dwc3_readl(dwc->regs, DWC3_DEVTEN);
2319 	if (set)
2320 		reg |= DWC3_DEVTEN_ULSTCNGEN;
2321 	else
2322 		reg &= ~DWC3_DEVTEN_ULSTCNGEN;
2323 
2324 	dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
2325 }
2326 
2327 static int dwc3_gadget_get_frame(struct usb_gadget *g)
2328 {
2329 	struct dwc3		*dwc = gadget_to_dwc(g);
2330 
2331 	return __dwc3_gadget_get_frame(dwc);
2332 }
2333 
2334 static int __dwc3_gadget_wakeup(struct dwc3 *dwc, bool async)
2335 {
2336 	int			retries;
2337 
2338 	int			ret;
2339 	u32			reg;
2340 
2341 	u8			link_state;
2342 
2343 	/*
2344 	 * According to the Databook Remote wakeup request should
2345 	 * be issued only when the device is in early suspend state.
2346 	 *
2347 	 * We can check that via USB Link State bits in DSTS register.
2348 	 */
2349 	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2350 
2351 	link_state = DWC3_DSTS_USBLNKST(reg);
2352 
2353 	switch (link_state) {
2354 	case DWC3_LINK_STATE_RESET:
2355 	case DWC3_LINK_STATE_RX_DET:	/* in HS, means Early Suspend */
2356 	case DWC3_LINK_STATE_U3:	/* in HS, means SUSPEND */
2357 	case DWC3_LINK_STATE_U2:	/* in HS, means Sleep (L1) */
2358 	case DWC3_LINK_STATE_U1:
2359 	case DWC3_LINK_STATE_RESUME:
2360 		break;
2361 	default:
2362 		return -EINVAL;
2363 	}
2364 
2365 	if (async)
2366 		dwc3_gadget_enable_linksts_evts(dwc, true);
2367 
2368 	ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
2369 	if (ret < 0) {
2370 		dev_err(dwc->dev, "failed to put link in Recovery\n");
2371 		dwc3_gadget_enable_linksts_evts(dwc, false);
2372 		return ret;
2373 	}
2374 
2375 	/* Recent versions do this automatically */
2376 	if (DWC3_VER_IS_PRIOR(DWC3, 194A)) {
2377 		/* write zeroes to Link Change Request */
2378 		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2379 		reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
2380 		dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2381 	}
2382 
2383 	/*
2384 	 * Since link status change events are enabled we will receive
2385 	 * an U0 event when wakeup is successful. So bail out.
2386 	 */
2387 	if (async)
2388 		return 0;
2389 
2390 	/* poll until Link State changes to ON */
2391 	retries = 20000;
2392 
2393 	while (retries--) {
2394 		reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2395 
2396 		/* in HS, means ON */
2397 		if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
2398 			break;
2399 	}
2400 
2401 	if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
2402 		dev_err(dwc->dev, "failed to send remote wakeup\n");
2403 		return -EINVAL;
2404 	}
2405 
2406 	return 0;
2407 }
2408 
2409 static int dwc3_gadget_wakeup(struct usb_gadget *g)
2410 {
2411 	struct dwc3		*dwc = gadget_to_dwc(g);
2412 	unsigned long		flags;
2413 	int			ret;
2414 
2415 	if (!dwc->wakeup_configured) {
2416 		dev_err(dwc->dev, "remote wakeup not configured\n");
2417 		return -EINVAL;
2418 	}
2419 
2420 	spin_lock_irqsave(&dwc->lock, flags);
2421 	if (!dwc->gadget->wakeup_armed) {
2422 		dev_err(dwc->dev, "not armed for remote wakeup\n");
2423 		spin_unlock_irqrestore(&dwc->lock, flags);
2424 		return -EINVAL;
2425 	}
2426 	ret = __dwc3_gadget_wakeup(dwc, true);
2427 
2428 	spin_unlock_irqrestore(&dwc->lock, flags);
2429 
2430 	return ret;
2431 }
2432 
2433 static void dwc3_resume_gadget(struct dwc3 *dwc);
2434 
2435 static int dwc3_gadget_func_wakeup(struct usb_gadget *g, int intf_id)
2436 {
2437 	struct  dwc3		*dwc = gadget_to_dwc(g);
2438 	unsigned long		flags;
2439 	int			ret;
2440 	int			link_state;
2441 
2442 	if (!dwc->wakeup_configured) {
2443 		dev_err(dwc->dev, "remote wakeup not configured\n");
2444 		return -EINVAL;
2445 	}
2446 
2447 	spin_lock_irqsave(&dwc->lock, flags);
2448 	/*
2449 	 * If the link is in U3, signal for remote wakeup and wait for the
2450 	 * link to transition to U0 before sending device notification.
2451 	 */
2452 	link_state = dwc3_gadget_get_link_state(dwc);
2453 	if (link_state == DWC3_LINK_STATE_U3) {
2454 		ret = __dwc3_gadget_wakeup(dwc, false);
2455 		if (ret) {
2456 			spin_unlock_irqrestore(&dwc->lock, flags);
2457 			return -EINVAL;
2458 		}
2459 		dwc3_resume_gadget(dwc);
2460 		dwc->suspended = false;
2461 		dwc->link_state = DWC3_LINK_STATE_U0;
2462 	}
2463 
2464 	ret = dwc3_send_gadget_generic_command(dwc, DWC3_DGCMD_DEV_NOTIFICATION,
2465 					       DWC3_DGCMDPAR_DN_FUNC_WAKE |
2466 					       DWC3_DGCMDPAR_INTF_SEL(intf_id));
2467 	if (ret)
2468 		dev_err(dwc->dev, "function remote wakeup failed, ret:%d\n", ret);
2469 
2470 	spin_unlock_irqrestore(&dwc->lock, flags);
2471 
2472 	return ret;
2473 }
2474 
2475 static int dwc3_gadget_set_remote_wakeup(struct usb_gadget *g, int set)
2476 {
2477 	struct dwc3		*dwc = gadget_to_dwc(g);
2478 	unsigned long		flags;
2479 
2480 	spin_lock_irqsave(&dwc->lock, flags);
2481 	dwc->wakeup_configured = !!set;
2482 	spin_unlock_irqrestore(&dwc->lock, flags);
2483 
2484 	return 0;
2485 }
2486 
2487 static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
2488 		int is_selfpowered)
2489 {
2490 	struct dwc3		*dwc = gadget_to_dwc(g);
2491 	unsigned long		flags;
2492 
2493 	spin_lock_irqsave(&dwc->lock, flags);
2494 	g->is_selfpowered = !!is_selfpowered;
2495 	spin_unlock_irqrestore(&dwc->lock, flags);
2496 
2497 	return 0;
2498 }
2499 
2500 static void dwc3_stop_active_transfers(struct dwc3 *dwc)
2501 {
2502 	u32 epnum;
2503 
2504 	for (epnum = 2; epnum < dwc->num_eps; epnum++) {
2505 		struct dwc3_ep *dep;
2506 
2507 		dep = dwc->eps[epnum];
2508 		if (!dep)
2509 			continue;
2510 
2511 		dwc3_remove_requests(dwc, dep, -ESHUTDOWN);
2512 	}
2513 }
2514 
2515 static void __dwc3_gadget_set_ssp_rate(struct dwc3 *dwc)
2516 {
2517 	enum usb_ssp_rate	ssp_rate = dwc->gadget_ssp_rate;
2518 	u32			reg;
2519 
2520 	if (ssp_rate == USB_SSP_GEN_UNKNOWN)
2521 		ssp_rate = dwc->max_ssp_rate;
2522 
2523 	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2524 	reg &= ~DWC3_DCFG_SPEED_MASK;
2525 	reg &= ~DWC3_DCFG_NUMLANES(~0);
2526 
2527 	if (ssp_rate == USB_SSP_GEN_1x2)
2528 		reg |= DWC3_DCFG_SUPERSPEED;
2529 	else if (dwc->max_ssp_rate != USB_SSP_GEN_1x2)
2530 		reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2531 
2532 	if (ssp_rate != USB_SSP_GEN_2x1 &&
2533 	    dwc->max_ssp_rate != USB_SSP_GEN_2x1)
2534 		reg |= DWC3_DCFG_NUMLANES(1);
2535 
2536 	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2537 }
2538 
2539 static void __dwc3_gadget_set_speed(struct dwc3 *dwc)
2540 {
2541 	enum usb_device_speed	speed;
2542 	u32			reg;
2543 
2544 	speed = dwc->gadget_max_speed;
2545 	if (speed == USB_SPEED_UNKNOWN || speed > dwc->maximum_speed)
2546 		speed = dwc->maximum_speed;
2547 
2548 	if (speed == USB_SPEED_SUPER_PLUS &&
2549 	    DWC3_IP_IS(DWC32)) {
2550 		__dwc3_gadget_set_ssp_rate(dwc);
2551 		return;
2552 	}
2553 
2554 	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2555 	reg &= ~(DWC3_DCFG_SPEED_MASK);
2556 
2557 	/*
2558 	 * WORKAROUND: DWC3 revision < 2.20a have an issue
2559 	 * which would cause metastability state on Run/Stop
2560 	 * bit if we try to force the IP to USB2-only mode.
2561 	 *
2562 	 * Because of that, we cannot configure the IP to any
2563 	 * speed other than the SuperSpeed
2564 	 *
2565 	 * Refers to:
2566 	 *
2567 	 * STAR#9000525659: Clock Domain Crossing on DCTL in
2568 	 * USB 2.0 Mode
2569 	 */
2570 	if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
2571 	    !dwc->dis_metastability_quirk) {
2572 		reg |= DWC3_DCFG_SUPERSPEED;
2573 	} else {
2574 		switch (speed) {
2575 		case USB_SPEED_FULL:
2576 			reg |= DWC3_DCFG_FULLSPEED;
2577 			break;
2578 		case USB_SPEED_HIGH:
2579 			reg |= DWC3_DCFG_HIGHSPEED;
2580 			break;
2581 		case USB_SPEED_SUPER:
2582 			reg |= DWC3_DCFG_SUPERSPEED;
2583 			break;
2584 		case USB_SPEED_SUPER_PLUS:
2585 			if (DWC3_IP_IS(DWC3))
2586 				reg |= DWC3_DCFG_SUPERSPEED;
2587 			else
2588 				reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2589 			break;
2590 		default:
2591 			dev_err(dwc->dev, "invalid speed (%d)\n", speed);
2592 
2593 			if (DWC3_IP_IS(DWC3))
2594 				reg |= DWC3_DCFG_SUPERSPEED;
2595 			else
2596 				reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2597 		}
2598 	}
2599 
2600 	if (DWC3_IP_IS(DWC32) &&
2601 	    speed > USB_SPEED_UNKNOWN &&
2602 	    speed < USB_SPEED_SUPER_PLUS)
2603 		reg &= ~DWC3_DCFG_NUMLANES(~0);
2604 
2605 	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2606 }
2607 
2608 static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on)
2609 {
2610 	u32			reg;
2611 	u32			timeout = 2000;
2612 
2613 	if (pm_runtime_suspended(dwc->dev))
2614 		return 0;
2615 
2616 	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2617 	if (is_on) {
2618 		if (DWC3_VER_IS_WITHIN(DWC3, ANY, 187A)) {
2619 			reg &= ~DWC3_DCTL_TRGTULST_MASK;
2620 			reg |= DWC3_DCTL_TRGTULST_RX_DET;
2621 		}
2622 
2623 		if (!DWC3_VER_IS_PRIOR(DWC3, 194A))
2624 			reg &= ~DWC3_DCTL_KEEP_CONNECT;
2625 		reg |= DWC3_DCTL_RUN_STOP;
2626 
2627 		__dwc3_gadget_set_speed(dwc);
2628 		dwc->pullups_connected = true;
2629 	} else {
2630 		reg &= ~DWC3_DCTL_RUN_STOP;
2631 
2632 		dwc->pullups_connected = false;
2633 	}
2634 
2635 	dwc3_gadget_dctl_write_safe(dwc, reg);
2636 
2637 	do {
2638 		usleep_range(1000, 2000);
2639 		reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2640 		reg &= DWC3_DSTS_DEVCTRLHLT;
2641 	} while (--timeout && !(!is_on ^ !reg));
2642 
2643 	if (!timeout)
2644 		return -ETIMEDOUT;
2645 
2646 	return 0;
2647 }
2648 
2649 static void dwc3_gadget_disable_irq(struct dwc3 *dwc);
2650 static void __dwc3_gadget_stop(struct dwc3 *dwc);
2651 static int __dwc3_gadget_start(struct dwc3 *dwc);
2652 
2653 static int dwc3_gadget_soft_disconnect(struct dwc3 *dwc)
2654 {
2655 	unsigned long flags;
2656 	int ret;
2657 
2658 	spin_lock_irqsave(&dwc->lock, flags);
2659 	dwc->connected = false;
2660 
2661 	/*
2662 	 * Attempt to end pending SETUP status phase, and not wait for the
2663 	 * function to do so.
2664 	 */
2665 	if (dwc->delayed_status)
2666 		dwc3_ep0_send_delayed_status(dwc);
2667 
2668 	/*
2669 	 * In the Synopsys DesignWare Cores USB3 Databook Rev. 3.30a
2670 	 * Section 4.1.8 Table 4-7, it states that for a device-initiated
2671 	 * disconnect, the SW needs to ensure that it sends "a DEPENDXFER
2672 	 * command for any active transfers" before clearing the RunStop
2673 	 * bit.
2674 	 */
2675 	dwc3_stop_active_transfers(dwc);
2676 	spin_unlock_irqrestore(&dwc->lock, flags);
2677 
2678 	/*
2679 	 * Per databook, when we want to stop the gadget, if a control transfer
2680 	 * is still in process, complete it and get the core into setup phase.
2681 	 * In case the host is unresponsive to a SETUP transaction, forcefully
2682 	 * stall the transfer, and move back to the SETUP phase, so that any
2683 	 * pending endxfers can be executed.
2684 	 */
2685 	if (dwc->ep0state != EP0_SETUP_PHASE) {
2686 		reinit_completion(&dwc->ep0_in_setup);
2687 
2688 		ret = wait_for_completion_timeout(&dwc->ep0_in_setup,
2689 				msecs_to_jiffies(DWC3_PULL_UP_TIMEOUT));
2690 		if (ret == 0) {
2691 			dev_warn(dwc->dev, "wait for SETUP phase timed out\n");
2692 			spin_lock_irqsave(&dwc->lock, flags);
2693 			dwc3_ep0_reset_state(dwc);
2694 			spin_unlock_irqrestore(&dwc->lock, flags);
2695 		}
2696 	}
2697 
2698 	/*
2699 	 * Note: if the GEVNTCOUNT indicates events in the event buffer, the
2700 	 * driver needs to acknowledge them before the controller can halt.
2701 	 * Simply let the interrupt handler acknowledges and handle the
2702 	 * remaining event generated by the controller while polling for
2703 	 * DSTS.DEVCTLHLT.
2704 	 */
2705 	ret = dwc3_gadget_run_stop(dwc, false);
2706 
2707 	/*
2708 	 * Stop the gadget after controller is halted, so that if needed, the
2709 	 * events to update EP0 state can still occur while the run/stop
2710 	 * routine polls for the halted state.  DEVTEN is cleared as part of
2711 	 * gadget stop.
2712 	 */
2713 	spin_lock_irqsave(&dwc->lock, flags);
2714 	__dwc3_gadget_stop(dwc);
2715 	spin_unlock_irqrestore(&dwc->lock, flags);
2716 
2717 	return ret;
2718 }
2719 
2720 static int dwc3_gadget_soft_connect(struct dwc3 *dwc)
2721 {
2722 	int ret;
2723 
2724 	/*
2725 	 * In the Synopsys DWC_usb31 1.90a programming guide section
2726 	 * 4.1.9, it specifies that for a reconnect after a
2727 	 * device-initiated disconnect requires a core soft reset
2728 	 * (DCTL.CSftRst) before enabling the run/stop bit.
2729 	 */
2730 	ret = dwc3_core_soft_reset(dwc);
2731 	if (ret)
2732 		return ret;
2733 
2734 	dwc3_event_buffers_setup(dwc);
2735 	__dwc3_gadget_start(dwc);
2736 	return dwc3_gadget_run_stop(dwc, true);
2737 }
2738 
2739 static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
2740 {
2741 	struct dwc3		*dwc = gadget_to_dwc(g);
2742 	int			ret;
2743 
2744 	is_on = !!is_on;
2745 
2746 	dwc->softconnect = is_on;
2747 
2748 	/*
2749 	 * Avoid issuing a runtime resume if the device is already in the
2750 	 * suspended state during gadget disconnect.  DWC3 gadget was already
2751 	 * halted/stopped during runtime suspend.
2752 	 */
2753 	if (!is_on) {
2754 		pm_runtime_barrier(dwc->dev);
2755 		if (pm_runtime_suspended(dwc->dev))
2756 			return 0;
2757 	}
2758 
2759 	/*
2760 	 * Check the return value for successful resume, or error.  For a
2761 	 * successful resume, the DWC3 runtime PM resume routine will handle
2762 	 * the run stop sequence, so avoid duplicate operations here.
2763 	 */
2764 	ret = pm_runtime_get_sync(dwc->dev);
2765 	if (!ret || ret < 0) {
2766 		pm_runtime_put(dwc->dev);
2767 		if (ret < 0)
2768 			pm_runtime_set_suspended(dwc->dev);
2769 		return ret;
2770 	}
2771 
2772 	if (dwc->pullups_connected == is_on) {
2773 		pm_runtime_put(dwc->dev);
2774 		return 0;
2775 	}
2776 
2777 	synchronize_irq(dwc->irq_gadget);
2778 
2779 	if (!is_on)
2780 		ret = dwc3_gadget_soft_disconnect(dwc);
2781 	else
2782 		ret = dwc3_gadget_soft_connect(dwc);
2783 
2784 	pm_runtime_put(dwc->dev);
2785 
2786 	return ret;
2787 }
2788 
2789 static void dwc3_gadget_enable_irq(struct dwc3 *dwc)
2790 {
2791 	u32			reg;
2792 
2793 	/* Enable all but Start and End of Frame IRQs */
2794 	reg = (DWC3_DEVTEN_EVNTOVERFLOWEN |
2795 			DWC3_DEVTEN_CMDCMPLTEN |
2796 			DWC3_DEVTEN_ERRTICERREN |
2797 			DWC3_DEVTEN_WKUPEVTEN |
2798 			DWC3_DEVTEN_CONNECTDONEEN |
2799 			DWC3_DEVTEN_USBRSTEN |
2800 			DWC3_DEVTEN_DISCONNEVTEN);
2801 
2802 	if (DWC3_VER_IS_PRIOR(DWC3, 250A))
2803 		reg |= DWC3_DEVTEN_ULSTCNGEN;
2804 
2805 	/* On 2.30a and above this bit enables U3/L2-L1 Suspend Events */
2806 	if (!DWC3_VER_IS_PRIOR(DWC3, 230A))
2807 		reg |= DWC3_DEVTEN_U3L2L1SUSPEN;
2808 
2809 	dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
2810 }
2811 
2812 static void dwc3_gadget_disable_irq(struct dwc3 *dwc)
2813 {
2814 	/* mask all interrupts */
2815 	dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
2816 }
2817 
2818 static irqreturn_t dwc3_interrupt(int irq, void *_dwc);
2819 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc);
2820 
2821 /**
2822  * dwc3_gadget_setup_nump - calculate and initialize NUMP field of %DWC3_DCFG
2823  * @dwc: pointer to our context structure
2824  *
2825  * The following looks like complex but it's actually very simple. In order to
2826  * calculate the number of packets we can burst at once on OUT transfers, we're
2827  * gonna use RxFIFO size.
2828  *
2829  * To calculate RxFIFO size we need two numbers:
2830  * MDWIDTH = size, in bits, of the internal memory bus
2831  * RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)
2832  *
2833  * Given these two numbers, the formula is simple:
2834  *
2835  * RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;
2836  *
2837  * 24 bytes is for 3x SETUP packets
2838  * 16 bytes is a clock domain crossing tolerance
2839  *
2840  * Given RxFIFO Size, NUMP = RxFIFOSize / 1024;
2841  */
2842 static void dwc3_gadget_setup_nump(struct dwc3 *dwc)
2843 {
2844 	u32 ram2_depth;
2845 	u32 mdwidth;
2846 	u32 nump;
2847 	u32 reg;
2848 
2849 	ram2_depth = DWC3_GHWPARAMS7_RAM2_DEPTH(dwc->hwparams.hwparams7);
2850 	mdwidth = dwc3_mdwidth(dwc);
2851 
2852 	nump = ((ram2_depth * mdwidth / 8) - 24 - 16) / 1024;
2853 	nump = min_t(u32, nump, 16);
2854 
2855 	/* update NumP */
2856 	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2857 	reg &= ~DWC3_DCFG_NUMP_MASK;
2858 	reg |= nump << DWC3_DCFG_NUMP_SHIFT;
2859 	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2860 }
2861 
2862 static int __dwc3_gadget_start(struct dwc3 *dwc)
2863 {
2864 	struct dwc3_ep		*dep;
2865 	int			ret = 0;
2866 	u32			reg;
2867 
2868 	/*
2869 	 * Use IMOD if enabled via dwc->imod_interval. Otherwise, if
2870 	 * the core supports IMOD, disable it.
2871 	 */
2872 	if (dwc->imod_interval) {
2873 		dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
2874 		dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
2875 	} else if (dwc3_has_imod(dwc)) {
2876 		dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), 0);
2877 	}
2878 
2879 	/*
2880 	 * We are telling dwc3 that we want to use DCFG.NUMP as ACK TP's NUMP
2881 	 * field instead of letting dwc3 itself calculate that automatically.
2882 	 *
2883 	 * This way, we maximize the chances that we'll be able to get several
2884 	 * bursts of data without going through any sort of endpoint throttling.
2885 	 */
2886 	reg = dwc3_readl(dwc->regs, DWC3_GRXTHRCFG);
2887 	if (DWC3_IP_IS(DWC3))
2888 		reg &= ~DWC3_GRXTHRCFG_PKTCNTSEL;
2889 	else
2890 		reg &= ~DWC31_GRXTHRCFG_PKTCNTSEL;
2891 
2892 	dwc3_writel(dwc->regs, DWC3_GRXTHRCFG, reg);
2893 
2894 	dwc3_gadget_setup_nump(dwc);
2895 
2896 	/*
2897 	 * Currently the controller handles single stream only. So, Ignore
2898 	 * Packet Pending bit for stream selection and don't search for another
2899 	 * stream if the host sends Data Packet with PP=0 (for OUT direction) or
2900 	 * ACK with NumP=0 and PP=0 (for IN direction). This slightly improves
2901 	 * the stream performance.
2902 	 */
2903 	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2904 	reg |= DWC3_DCFG_IGNSTRMPP;
2905 	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2906 
2907 	/* Enable MST by default if the device is capable of MST */
2908 	if (DWC3_MST_CAPABLE(&dwc->hwparams)) {
2909 		reg = dwc3_readl(dwc->regs, DWC3_DCFG1);
2910 		reg &= ~DWC3_DCFG1_DIS_MST_ENH;
2911 		dwc3_writel(dwc->regs, DWC3_DCFG1, reg);
2912 	}
2913 
2914 	/* Start with SuperSpeed Default */
2915 	dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2916 
2917 	dep = dwc->eps[0];
2918 	dep->flags = 0;
2919 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2920 	if (ret) {
2921 		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2922 		goto err0;
2923 	}
2924 
2925 	dep = dwc->eps[1];
2926 	dep->flags = 0;
2927 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2928 	if (ret) {
2929 		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2930 		goto err1;
2931 	}
2932 
2933 	/* begin to receive SETUP packets */
2934 	dwc->ep0state = EP0_SETUP_PHASE;
2935 	dwc->ep0_bounced = false;
2936 	dwc->link_state = DWC3_LINK_STATE_SS_DIS;
2937 	dwc->delayed_status = false;
2938 	dwc3_ep0_out_start(dwc);
2939 
2940 	dwc3_gadget_enable_irq(dwc);
2941 
2942 	return 0;
2943 
2944 err1:
2945 	__dwc3_gadget_ep_disable(dwc->eps[0]);
2946 
2947 err0:
2948 	return ret;
2949 }
2950 
2951 static int dwc3_gadget_start(struct usb_gadget *g,
2952 		struct usb_gadget_driver *driver)
2953 {
2954 	struct dwc3		*dwc = gadget_to_dwc(g);
2955 	unsigned long		flags;
2956 	int			ret;
2957 	int			irq;
2958 
2959 	irq = dwc->irq_gadget;
2960 	ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt,
2961 			IRQF_SHARED, "dwc3", dwc->ev_buf);
2962 	if (ret) {
2963 		dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
2964 				irq, ret);
2965 		return ret;
2966 	}
2967 
2968 	spin_lock_irqsave(&dwc->lock, flags);
2969 	dwc->gadget_driver	= driver;
2970 	spin_unlock_irqrestore(&dwc->lock, flags);
2971 
2972 	return 0;
2973 }
2974 
2975 static void __dwc3_gadget_stop(struct dwc3 *dwc)
2976 {
2977 	dwc3_gadget_disable_irq(dwc);
2978 	__dwc3_gadget_ep_disable(dwc->eps[0]);
2979 	__dwc3_gadget_ep_disable(dwc->eps[1]);
2980 }
2981 
2982 static int dwc3_gadget_stop(struct usb_gadget *g)
2983 {
2984 	struct dwc3		*dwc = gadget_to_dwc(g);
2985 	unsigned long		flags;
2986 
2987 	spin_lock_irqsave(&dwc->lock, flags);
2988 	dwc->gadget_driver	= NULL;
2989 	dwc->max_cfg_eps = 0;
2990 	spin_unlock_irqrestore(&dwc->lock, flags);
2991 
2992 	free_irq(dwc->irq_gadget, dwc->ev_buf);
2993 
2994 	return 0;
2995 }
2996 
2997 static void dwc3_gadget_config_params(struct usb_gadget *g,
2998 				      struct usb_dcd_config_params *params)
2999 {
3000 	struct dwc3		*dwc = gadget_to_dwc(g);
3001 
3002 	params->besl_baseline = USB_DEFAULT_BESL_UNSPECIFIED;
3003 	params->besl_deep = USB_DEFAULT_BESL_UNSPECIFIED;
3004 
3005 	/* Recommended BESL */
3006 	if (!dwc->dis_enblslpm_quirk) {
3007 		/*
3008 		 * If the recommended BESL baseline is 0 or if the BESL deep is
3009 		 * less than 2, Microsoft's Windows 10 host usb stack will issue
3010 		 * a usb reset immediately after it receives the extended BOS
3011 		 * descriptor and the enumeration will fail. To maintain
3012 		 * compatibility with the Windows' usb stack, let's set the
3013 		 * recommended BESL baseline to 1 and clamp the BESL deep to be
3014 		 * within 2 to 15.
3015 		 */
3016 		params->besl_baseline = 1;
3017 		if (dwc->is_utmi_l1_suspend)
3018 			params->besl_deep =
3019 				clamp_t(u8, dwc->hird_threshold, 2, 15);
3020 	}
3021 
3022 	/* U1 Device exit Latency */
3023 	if (dwc->dis_u1_entry_quirk)
3024 		params->bU1devExitLat = 0;
3025 	else
3026 		params->bU1devExitLat = DWC3_DEFAULT_U1_DEV_EXIT_LAT;
3027 
3028 	/* U2 Device exit Latency */
3029 	if (dwc->dis_u2_entry_quirk)
3030 		params->bU2DevExitLat = 0;
3031 	else
3032 		params->bU2DevExitLat =
3033 				cpu_to_le16(DWC3_DEFAULT_U2_DEV_EXIT_LAT);
3034 }
3035 
3036 static void dwc3_gadget_set_speed(struct usb_gadget *g,
3037 				  enum usb_device_speed speed)
3038 {
3039 	struct dwc3		*dwc = gadget_to_dwc(g);
3040 	unsigned long		flags;
3041 
3042 	spin_lock_irqsave(&dwc->lock, flags);
3043 	dwc->gadget_max_speed = speed;
3044 	spin_unlock_irqrestore(&dwc->lock, flags);
3045 }
3046 
3047 static void dwc3_gadget_set_ssp_rate(struct usb_gadget *g,
3048 				     enum usb_ssp_rate rate)
3049 {
3050 	struct dwc3		*dwc = gadget_to_dwc(g);
3051 	unsigned long		flags;
3052 
3053 	spin_lock_irqsave(&dwc->lock, flags);
3054 	dwc->gadget_max_speed = USB_SPEED_SUPER_PLUS;
3055 	dwc->gadget_ssp_rate = rate;
3056 	spin_unlock_irqrestore(&dwc->lock, flags);
3057 }
3058 
3059 static int dwc3_gadget_vbus_draw(struct usb_gadget *g, unsigned int mA)
3060 {
3061 	struct dwc3		*dwc = gadget_to_dwc(g);
3062 	union power_supply_propval	val = {0};
3063 	int				ret;
3064 
3065 	if (dwc->usb2_phy)
3066 		return usb_phy_set_power(dwc->usb2_phy, mA);
3067 
3068 	if (!dwc->usb_psy)
3069 		return -EOPNOTSUPP;
3070 
3071 	val.intval = 1000 * mA;
3072 	ret = power_supply_set_property(dwc->usb_psy, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, &val);
3073 
3074 	return ret;
3075 }
3076 
3077 /**
3078  * dwc3_gadget_check_config - ensure dwc3 can support the USB configuration
3079  * @g: pointer to the USB gadget
3080  *
3081  * Used to record the maximum number of endpoints being used in a USB composite
3082  * device. (across all configurations)  This is to be used in the calculation
3083  * of the TXFIFO sizes when resizing internal memory for individual endpoints.
3084  * It will help ensured that the resizing logic reserves enough space for at
3085  * least one max packet.
3086  */
3087 static int dwc3_gadget_check_config(struct usb_gadget *g)
3088 {
3089 	struct dwc3 *dwc = gadget_to_dwc(g);
3090 	struct usb_ep *ep;
3091 	int fifo_size = 0;
3092 	int ram1_depth;
3093 	int ep_num = 0;
3094 
3095 	if (!dwc->do_fifo_resize)
3096 		return 0;
3097 
3098 	list_for_each_entry(ep, &g->ep_list, ep_list) {
3099 		/* Only interested in the IN endpoints */
3100 		if (ep->claimed && (ep->address & USB_DIR_IN))
3101 			ep_num++;
3102 	}
3103 
3104 	if (ep_num <= dwc->max_cfg_eps)
3105 		return 0;
3106 
3107 	/* Update the max number of eps in the composition */
3108 	dwc->max_cfg_eps = ep_num;
3109 
3110 	fifo_size = dwc3_gadget_calc_tx_fifo_size(dwc, dwc->max_cfg_eps);
3111 	/* Based on the equation, increment by one for every ep */
3112 	fifo_size += dwc->max_cfg_eps;
3113 
3114 	/* Check if we can fit a single fifo per endpoint */
3115 	ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7);
3116 	if (fifo_size > ram1_depth)
3117 		return -ENOMEM;
3118 
3119 	return 0;
3120 }
3121 
3122 static void dwc3_gadget_async_callbacks(struct usb_gadget *g, bool enable)
3123 {
3124 	struct dwc3		*dwc = gadget_to_dwc(g);
3125 	unsigned long		flags;
3126 
3127 	spin_lock_irqsave(&dwc->lock, flags);
3128 	dwc->async_callbacks = enable;
3129 	spin_unlock_irqrestore(&dwc->lock, flags);
3130 }
3131 
3132 static const struct usb_gadget_ops dwc3_gadget_ops = {
3133 	.get_frame		= dwc3_gadget_get_frame,
3134 	.wakeup			= dwc3_gadget_wakeup,
3135 	.func_wakeup		= dwc3_gadget_func_wakeup,
3136 	.set_remote_wakeup	= dwc3_gadget_set_remote_wakeup,
3137 	.set_selfpowered	= dwc3_gadget_set_selfpowered,
3138 	.pullup			= dwc3_gadget_pullup,
3139 	.udc_start		= dwc3_gadget_start,
3140 	.udc_stop		= dwc3_gadget_stop,
3141 	.udc_set_speed		= dwc3_gadget_set_speed,
3142 	.udc_set_ssp_rate	= dwc3_gadget_set_ssp_rate,
3143 	.get_config_params	= dwc3_gadget_config_params,
3144 	.vbus_draw		= dwc3_gadget_vbus_draw,
3145 	.check_config		= dwc3_gadget_check_config,
3146 	.udc_async_callbacks	= dwc3_gadget_async_callbacks,
3147 };
3148 
3149 /* -------------------------------------------------------------------------- */
3150 
3151 static int dwc3_gadget_init_control_endpoint(struct dwc3_ep *dep)
3152 {
3153 	struct dwc3 *dwc = dep->dwc;
3154 
3155 	usb_ep_set_maxpacket_limit(&dep->endpoint, 512);
3156 	dep->endpoint.maxburst = 1;
3157 	dep->endpoint.ops = &dwc3_gadget_ep0_ops;
3158 	if (!dep->direction)
3159 		dwc->gadget->ep0 = &dep->endpoint;
3160 
3161 	dep->endpoint.caps.type_control = true;
3162 
3163 	return 0;
3164 }
3165 
3166 static int dwc3_gadget_init_in_endpoint(struct dwc3_ep *dep)
3167 {
3168 	struct dwc3 *dwc = dep->dwc;
3169 	u32 mdwidth;
3170 	int size;
3171 	int maxpacket;
3172 
3173 	mdwidth = dwc3_mdwidth(dwc);
3174 
3175 	/* MDWIDTH is represented in bits, we need it in bytes */
3176 	mdwidth /= 8;
3177 
3178 	size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1));
3179 	if (DWC3_IP_IS(DWC3))
3180 		size = DWC3_GTXFIFOSIZ_TXFDEP(size);
3181 	else
3182 		size = DWC31_GTXFIFOSIZ_TXFDEP(size);
3183 
3184 	/*
3185 	 * maxpacket size is determined as part of the following, after assuming
3186 	 * a mult value of one maxpacket:
3187 	 * DWC3 revision 280A and prior:
3188 	 * fifo_size = mult * (max_packet / mdwidth) + 1;
3189 	 * maxpacket = mdwidth * (fifo_size - 1);
3190 	 *
3191 	 * DWC3 revision 290A and onwards:
3192 	 * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
3193 	 * maxpacket = mdwidth * ((fifo_size - 1) - 1) - mdwidth;
3194 	 */
3195 	if (DWC3_VER_IS_PRIOR(DWC3, 290A))
3196 		maxpacket = mdwidth * (size - 1);
3197 	else
3198 		maxpacket = mdwidth * ((size - 1) - 1) - mdwidth;
3199 
3200 	/* Functionally, space for one max packet is sufficient */
3201 	size = min_t(int, maxpacket, 1024);
3202 	usb_ep_set_maxpacket_limit(&dep->endpoint, size);
3203 
3204 	dep->endpoint.max_streams = 16;
3205 	dep->endpoint.ops = &dwc3_gadget_ep_ops;
3206 	list_add_tail(&dep->endpoint.ep_list,
3207 			&dwc->gadget->ep_list);
3208 	dep->endpoint.caps.type_iso = true;
3209 	dep->endpoint.caps.type_bulk = true;
3210 	dep->endpoint.caps.type_int = true;
3211 
3212 	return dwc3_alloc_trb_pool(dep);
3213 }
3214 
3215 static int dwc3_gadget_init_out_endpoint(struct dwc3_ep *dep)
3216 {
3217 	struct dwc3 *dwc = dep->dwc;
3218 	u32 mdwidth;
3219 	int size;
3220 
3221 	mdwidth = dwc3_mdwidth(dwc);
3222 
3223 	/* MDWIDTH is represented in bits, convert to bytes */
3224 	mdwidth /= 8;
3225 
3226 	/* All OUT endpoints share a single RxFIFO space */
3227 	size = dwc3_readl(dwc->regs, DWC3_GRXFIFOSIZ(0));
3228 	if (DWC3_IP_IS(DWC3))
3229 		size = DWC3_GRXFIFOSIZ_RXFDEP(size);
3230 	else
3231 		size = DWC31_GRXFIFOSIZ_RXFDEP(size);
3232 
3233 	/* FIFO depth is in MDWDITH bytes */
3234 	size *= mdwidth;
3235 
3236 	/*
3237 	 * To meet performance requirement, a minimum recommended RxFIFO size
3238 	 * is defined as follow:
3239 	 * RxFIFO size >= (3 x MaxPacketSize) +
3240 	 * (3 x 8 bytes setup packets size) + (16 bytes clock crossing margin)
3241 	 *
3242 	 * Then calculate the max packet limit as below.
3243 	 */
3244 	size -= (3 * 8) + 16;
3245 	if (size < 0)
3246 		size = 0;
3247 	else
3248 		size /= 3;
3249 
3250 	usb_ep_set_maxpacket_limit(&dep->endpoint, size);
3251 	dep->endpoint.max_streams = 16;
3252 	dep->endpoint.ops = &dwc3_gadget_ep_ops;
3253 	list_add_tail(&dep->endpoint.ep_list,
3254 			&dwc->gadget->ep_list);
3255 	dep->endpoint.caps.type_iso = true;
3256 	dep->endpoint.caps.type_bulk = true;
3257 	dep->endpoint.caps.type_int = true;
3258 
3259 	return dwc3_alloc_trb_pool(dep);
3260 }
3261 
3262 static int dwc3_gadget_init_endpoint(struct dwc3 *dwc, u8 epnum)
3263 {
3264 	struct dwc3_ep			*dep;
3265 	bool				direction = epnum & 1;
3266 	int				ret;
3267 	u8				num = epnum >> 1;
3268 
3269 	dep = kzalloc(sizeof(*dep), GFP_KERNEL);
3270 	if (!dep)
3271 		return -ENOMEM;
3272 
3273 	dep->dwc = dwc;
3274 	dep->number = epnum;
3275 	dep->direction = direction;
3276 	dep->regs = dwc->regs + DWC3_DEP_BASE(epnum);
3277 	dwc->eps[epnum] = dep;
3278 	dep->combo_num = 0;
3279 	dep->start_cmd_status = 0;
3280 
3281 	snprintf(dep->name, sizeof(dep->name), "ep%u%s", num,
3282 			direction ? "in" : "out");
3283 
3284 	dep->endpoint.name = dep->name;
3285 
3286 	if (!(dep->number > 1)) {
3287 		dep->endpoint.desc = &dwc3_gadget_ep0_desc;
3288 		dep->endpoint.comp_desc = NULL;
3289 	}
3290 
3291 	if (num == 0)
3292 		ret = dwc3_gadget_init_control_endpoint(dep);
3293 	else if (direction)
3294 		ret = dwc3_gadget_init_in_endpoint(dep);
3295 	else
3296 		ret = dwc3_gadget_init_out_endpoint(dep);
3297 
3298 	if (ret)
3299 		return ret;
3300 
3301 	dep->endpoint.caps.dir_in = direction;
3302 	dep->endpoint.caps.dir_out = !direction;
3303 
3304 	INIT_LIST_HEAD(&dep->pending_list);
3305 	INIT_LIST_HEAD(&dep->started_list);
3306 	INIT_LIST_HEAD(&dep->cancelled_list);
3307 
3308 	dwc3_debugfs_create_endpoint_dir(dep);
3309 
3310 	return 0;
3311 }
3312 
3313 static int dwc3_gadget_init_endpoints(struct dwc3 *dwc, u8 total)
3314 {
3315 	u8				epnum;
3316 
3317 	INIT_LIST_HEAD(&dwc->gadget->ep_list);
3318 
3319 	for (epnum = 0; epnum < total; epnum++) {
3320 		int			ret;
3321 
3322 		ret = dwc3_gadget_init_endpoint(dwc, epnum);
3323 		if (ret)
3324 			return ret;
3325 	}
3326 
3327 	return 0;
3328 }
3329 
3330 static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
3331 {
3332 	struct dwc3_ep			*dep;
3333 	u8				epnum;
3334 
3335 	for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
3336 		dep = dwc->eps[epnum];
3337 		if (!dep)
3338 			continue;
3339 		/*
3340 		 * Physical endpoints 0 and 1 are special; they form the
3341 		 * bi-directional USB endpoint 0.
3342 		 *
3343 		 * For those two physical endpoints, we don't allocate a TRB
3344 		 * pool nor do we add them the endpoints list. Due to that, we
3345 		 * shouldn't do these two operations otherwise we would end up
3346 		 * with all sorts of bugs when removing dwc3.ko.
3347 		 */
3348 		if (epnum != 0 && epnum != 1) {
3349 			dwc3_free_trb_pool(dep);
3350 			list_del(&dep->endpoint.ep_list);
3351 		}
3352 
3353 		dwc3_debugfs_remove_endpoint_dir(dep);
3354 		kfree(dep);
3355 	}
3356 }
3357 
3358 /* -------------------------------------------------------------------------- */
3359 
3360 static int dwc3_gadget_ep_reclaim_completed_trb(struct dwc3_ep *dep,
3361 		struct dwc3_request *req, struct dwc3_trb *trb,
3362 		const struct dwc3_event_depevt *event, int status, int chain)
3363 {
3364 	unsigned int		count;
3365 
3366 	dwc3_ep_inc_deq(dep);
3367 
3368 	trace_dwc3_complete_trb(dep, trb);
3369 	req->num_trbs--;
3370 
3371 	/*
3372 	 * If we're in the middle of series of chained TRBs and we
3373 	 * receive a short transfer along the way, DWC3 will skip
3374 	 * through all TRBs including the last TRB in the chain (the
3375 	 * where CHN bit is zero. DWC3 will also avoid clearing HWO
3376 	 * bit and SW has to do it manually.
3377 	 *
3378 	 * We're going to do that here to avoid problems of HW trying
3379 	 * to use bogus TRBs for transfers.
3380 	 */
3381 	if (chain && (trb->ctrl & DWC3_TRB_CTRL_HWO))
3382 		trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
3383 
3384 	/*
3385 	 * For isochronous transfers, the first TRB in a service interval must
3386 	 * have the Isoc-First type. Track and report its interval frame number.
3387 	 */
3388 	if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
3389 	    (trb->ctrl & DWC3_TRBCTL_ISOCHRONOUS_FIRST)) {
3390 		unsigned int frame_number;
3391 
3392 		frame_number = DWC3_TRB_CTRL_GET_SID_SOFN(trb->ctrl);
3393 		frame_number &= ~(dep->interval - 1);
3394 		req->request.frame_number = frame_number;
3395 	}
3396 
3397 	/*
3398 	 * We use bounce buffer for requests that needs extra TRB or OUT ZLP. If
3399 	 * this TRB points to the bounce buffer address, it's a MPS alignment
3400 	 * TRB. Don't add it to req->remaining calculation.
3401 	 */
3402 	if (trb->bpl == lower_32_bits(dep->dwc->bounce_addr) &&
3403 	    trb->bph == upper_32_bits(dep->dwc->bounce_addr)) {
3404 		trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
3405 		return 1;
3406 	}
3407 
3408 	count = trb->size & DWC3_TRB_SIZE_MASK;
3409 	req->remaining += count;
3410 
3411 	if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
3412 		return 1;
3413 
3414 	if (event->status & DEPEVT_STATUS_SHORT && !chain)
3415 		return 1;
3416 
3417 	if ((trb->ctrl & DWC3_TRB_CTRL_ISP_IMI) &&
3418 	    DWC3_TRB_SIZE_TRBSTS(trb->size) == DWC3_TRBSTS_MISSED_ISOC)
3419 		return 1;
3420 
3421 	if ((trb->ctrl & DWC3_TRB_CTRL_IOC) ||
3422 	    (trb->ctrl & DWC3_TRB_CTRL_LST))
3423 		return 1;
3424 
3425 	return 0;
3426 }
3427 
3428 static int dwc3_gadget_ep_reclaim_trb_sg(struct dwc3_ep *dep,
3429 		struct dwc3_request *req, const struct dwc3_event_depevt *event,
3430 		int status)
3431 {
3432 	struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
3433 	struct scatterlist *sg = req->sg;
3434 	struct scatterlist *s;
3435 	unsigned int num_queued = req->num_queued_sgs;
3436 	unsigned int i;
3437 	int ret = 0;
3438 
3439 	for_each_sg(sg, s, num_queued, i) {
3440 		trb = &dep->trb_pool[dep->trb_dequeue];
3441 
3442 		req->sg = sg_next(s);
3443 		req->num_queued_sgs--;
3444 
3445 		ret = dwc3_gadget_ep_reclaim_completed_trb(dep, req,
3446 				trb, event, status, true);
3447 		if (ret)
3448 			break;
3449 	}
3450 
3451 	return ret;
3452 }
3453 
3454 static int dwc3_gadget_ep_reclaim_trb_linear(struct dwc3_ep *dep,
3455 		struct dwc3_request *req, const struct dwc3_event_depevt *event,
3456 		int status)
3457 {
3458 	struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
3459 
3460 	return dwc3_gadget_ep_reclaim_completed_trb(dep, req, trb,
3461 			event, status, false);
3462 }
3463 
3464 static bool dwc3_gadget_ep_request_completed(struct dwc3_request *req)
3465 {
3466 	return req->num_pending_sgs == 0 && req->num_queued_sgs == 0;
3467 }
3468 
3469 static int dwc3_gadget_ep_cleanup_completed_request(struct dwc3_ep *dep,
3470 		const struct dwc3_event_depevt *event,
3471 		struct dwc3_request *req, int status)
3472 {
3473 	int request_status;
3474 	int ret;
3475 
3476 	if (req->request.num_mapped_sgs)
3477 		ret = dwc3_gadget_ep_reclaim_trb_sg(dep, req, event,
3478 				status);
3479 	else
3480 		ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
3481 				status);
3482 
3483 	req->request.actual = req->request.length - req->remaining;
3484 
3485 	if (!dwc3_gadget_ep_request_completed(req))
3486 		goto out;
3487 
3488 	if (req->needs_extra_trb) {
3489 		ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
3490 				status);
3491 		req->needs_extra_trb = false;
3492 	}
3493 
3494 	/*
3495 	 * The event status only reflects the status of the TRB with IOC set.
3496 	 * For the requests that don't set interrupt on completion, the driver
3497 	 * needs to check and return the status of the completed TRBs associated
3498 	 * with the request. Use the status of the last TRB of the request.
3499 	 */
3500 	if (req->request.no_interrupt) {
3501 		struct dwc3_trb *trb;
3502 
3503 		trb = dwc3_ep_prev_trb(dep, dep->trb_dequeue);
3504 		switch (DWC3_TRB_SIZE_TRBSTS(trb->size)) {
3505 		case DWC3_TRBSTS_MISSED_ISOC:
3506 			/* Isoc endpoint only */
3507 			request_status = -EXDEV;
3508 			break;
3509 		case DWC3_TRB_STS_XFER_IN_PROG:
3510 			/* Applicable when End Transfer with ForceRM=0 */
3511 		case DWC3_TRBSTS_SETUP_PENDING:
3512 			/* Control endpoint only */
3513 		case DWC3_TRBSTS_OK:
3514 		default:
3515 			request_status = 0;
3516 			break;
3517 		}
3518 	} else {
3519 		request_status = status;
3520 	}
3521 
3522 	dwc3_gadget_giveback(dep, req, request_status);
3523 
3524 out:
3525 	return ret;
3526 }
3527 
3528 static void dwc3_gadget_ep_cleanup_completed_requests(struct dwc3_ep *dep,
3529 		const struct dwc3_event_depevt *event, int status)
3530 {
3531 	struct dwc3_request	*req;
3532 
3533 	while (!list_empty(&dep->started_list)) {
3534 		int ret;
3535 
3536 		req = next_request(&dep->started_list);
3537 		ret = dwc3_gadget_ep_cleanup_completed_request(dep, event,
3538 				req, status);
3539 		if (ret)
3540 			break;
3541 		/*
3542 		 * The endpoint is disabled, let the dwc3_remove_requests()
3543 		 * handle the cleanup.
3544 		 */
3545 		if (!dep->endpoint.desc)
3546 			break;
3547 	}
3548 }
3549 
3550 static bool dwc3_gadget_ep_should_continue(struct dwc3_ep *dep)
3551 {
3552 	struct dwc3_request	*req;
3553 	struct dwc3		*dwc = dep->dwc;
3554 
3555 	if (!dep->endpoint.desc || !dwc->pullups_connected ||
3556 	    !dwc->connected)
3557 		return false;
3558 
3559 	if (!list_empty(&dep->pending_list))
3560 		return true;
3561 
3562 	/*
3563 	 * We only need to check the first entry of the started list. We can
3564 	 * assume the completed requests are removed from the started list.
3565 	 */
3566 	req = next_request(&dep->started_list);
3567 	if (!req)
3568 		return false;
3569 
3570 	return !dwc3_gadget_ep_request_completed(req);
3571 }
3572 
3573 static void dwc3_gadget_endpoint_frame_from_event(struct dwc3_ep *dep,
3574 		const struct dwc3_event_depevt *event)
3575 {
3576 	dep->frame_number = event->parameters;
3577 }
3578 
3579 static bool dwc3_gadget_endpoint_trbs_complete(struct dwc3_ep *dep,
3580 		const struct dwc3_event_depevt *event, int status)
3581 {
3582 	struct dwc3		*dwc = dep->dwc;
3583 	bool			no_started_trb = true;
3584 
3585 	dwc3_gadget_ep_cleanup_completed_requests(dep, event, status);
3586 
3587 	if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
3588 		goto out;
3589 
3590 	if (!dep->endpoint.desc)
3591 		return no_started_trb;
3592 
3593 	if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
3594 		list_empty(&dep->started_list) &&
3595 		(list_empty(&dep->pending_list) || status == -EXDEV))
3596 		dwc3_stop_active_transfer(dep, true, true);
3597 	else if (dwc3_gadget_ep_should_continue(dep))
3598 		if (__dwc3_gadget_kick_transfer(dep) == 0)
3599 			no_started_trb = false;
3600 
3601 out:
3602 	/*
3603 	 * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
3604 	 * See dwc3_gadget_linksts_change_interrupt() for 1st half.
3605 	 */
3606 	if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
3607 		u32		reg;
3608 		int		i;
3609 
3610 		for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
3611 			dep = dwc->eps[i];
3612 
3613 			if (!(dep->flags & DWC3_EP_ENABLED))
3614 				continue;
3615 
3616 			if (!list_empty(&dep->started_list))
3617 				return no_started_trb;
3618 		}
3619 
3620 		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3621 		reg |= dwc->u1u2;
3622 		dwc3_writel(dwc->regs, DWC3_DCTL, reg);
3623 
3624 		dwc->u1u2 = 0;
3625 	}
3626 
3627 	return no_started_trb;
3628 }
3629 
3630 static void dwc3_gadget_endpoint_transfer_in_progress(struct dwc3_ep *dep,
3631 		const struct dwc3_event_depevt *event)
3632 {
3633 	int status = 0;
3634 
3635 	if (!dep->endpoint.desc)
3636 		return;
3637 
3638 	if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
3639 		dwc3_gadget_endpoint_frame_from_event(dep, event);
3640 
3641 	if (event->status & DEPEVT_STATUS_BUSERR)
3642 		status = -ECONNRESET;
3643 
3644 	if (event->status & DEPEVT_STATUS_MISSED_ISOC)
3645 		status = -EXDEV;
3646 
3647 	dwc3_gadget_endpoint_trbs_complete(dep, event, status);
3648 }
3649 
3650 static void dwc3_gadget_endpoint_transfer_complete(struct dwc3_ep *dep,
3651 		const struct dwc3_event_depevt *event)
3652 {
3653 	int status = 0;
3654 
3655 	dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3656 
3657 	if (event->status & DEPEVT_STATUS_BUSERR)
3658 		status = -ECONNRESET;
3659 
3660 	if (dwc3_gadget_endpoint_trbs_complete(dep, event, status))
3661 		dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
3662 }
3663 
3664 static void dwc3_gadget_endpoint_transfer_not_ready(struct dwc3_ep *dep,
3665 		const struct dwc3_event_depevt *event)
3666 {
3667 	dwc3_gadget_endpoint_frame_from_event(dep, event);
3668 
3669 	/*
3670 	 * The XferNotReady event is generated only once before the endpoint
3671 	 * starts. It will be generated again when END_TRANSFER command is
3672 	 * issued. For some controller versions, the XferNotReady event may be
3673 	 * generated while the END_TRANSFER command is still in process. Ignore
3674 	 * it and wait for the next XferNotReady event after the command is
3675 	 * completed.
3676 	 */
3677 	if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
3678 		return;
3679 
3680 	(void) __dwc3_gadget_start_isoc(dep);
3681 }
3682 
3683 static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep,
3684 		const struct dwc3_event_depevt *event)
3685 {
3686 	u8 cmd = DEPEVT_PARAMETER_CMD(event->parameters);
3687 
3688 	if (cmd != DWC3_DEPCMD_ENDTRANSFER)
3689 		return;
3690 
3691 	/*
3692 	 * The END_TRANSFER command will cause the controller to generate a
3693 	 * NoStream Event, and it's not due to the host DP NoStream rejection.
3694 	 * Ignore the next NoStream event.
3695 	 */
3696 	if (dep->stream_capable)
3697 		dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM;
3698 
3699 	dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
3700 	dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3701 	dwc3_gadget_ep_cleanup_cancelled_requests(dep);
3702 
3703 	if (dep->flags & DWC3_EP_PENDING_CLEAR_STALL) {
3704 		struct dwc3 *dwc = dep->dwc;
3705 
3706 		dep->flags &= ~DWC3_EP_PENDING_CLEAR_STALL;
3707 		if (dwc3_send_clear_stall_ep_cmd(dep)) {
3708 			struct usb_ep *ep0 = &dwc->eps[0]->endpoint;
3709 
3710 			dev_err(dwc->dev, "failed to clear STALL on %s\n", dep->name);
3711 			if (dwc->delayed_status)
3712 				__dwc3_gadget_ep0_set_halt(ep0, 1);
3713 			return;
3714 		}
3715 
3716 		dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
3717 		if (dwc->clear_stall_protocol == dep->number)
3718 			dwc3_ep0_send_delayed_status(dwc);
3719 	}
3720 
3721 	if ((dep->flags & DWC3_EP_DELAY_START) &&
3722 	    !usb_endpoint_xfer_isoc(dep->endpoint.desc))
3723 		__dwc3_gadget_kick_transfer(dep);
3724 
3725 	dep->flags &= ~DWC3_EP_DELAY_START;
3726 }
3727 
3728 static void dwc3_gadget_endpoint_stream_event(struct dwc3_ep *dep,
3729 		const struct dwc3_event_depevt *event)
3730 {
3731 	struct dwc3 *dwc = dep->dwc;
3732 
3733 	if (event->status == DEPEVT_STREAMEVT_FOUND) {
3734 		dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3735 		goto out;
3736 	}
3737 
3738 	/* Note: NoStream rejection event param value is 0 and not 0xFFFF */
3739 	switch (event->parameters) {
3740 	case DEPEVT_STREAM_PRIME:
3741 		/*
3742 		 * If the host can properly transition the endpoint state from
3743 		 * idle to prime after a NoStream rejection, there's no need to
3744 		 * force restarting the endpoint to reinitiate the stream. To
3745 		 * simplify the check, assume the host follows the USB spec if
3746 		 * it primed the endpoint more than once.
3747 		 */
3748 		if (dep->flags & DWC3_EP_FORCE_RESTART_STREAM) {
3749 			if (dep->flags & DWC3_EP_FIRST_STREAM_PRIMED)
3750 				dep->flags &= ~DWC3_EP_FORCE_RESTART_STREAM;
3751 			else
3752 				dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3753 		}
3754 
3755 		break;
3756 	case DEPEVT_STREAM_NOSTREAM:
3757 		if ((dep->flags & DWC3_EP_IGNORE_NEXT_NOSTREAM) ||
3758 		    !(dep->flags & DWC3_EP_FORCE_RESTART_STREAM) ||
3759 		    (!DWC3_MST_CAPABLE(&dwc->hwparams) &&
3760 		     !(dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE)))
3761 			break;
3762 
3763 		/*
3764 		 * If the host rejects a stream due to no active stream, by the
3765 		 * USB and xHCI spec, the endpoint will be put back to idle
3766 		 * state. When the host is ready (buffer added/updated), it will
3767 		 * prime the endpoint to inform the usb device controller. This
3768 		 * triggers the device controller to issue ERDY to restart the
3769 		 * stream. However, some hosts don't follow this and keep the
3770 		 * endpoint in the idle state. No prime will come despite host
3771 		 * streams are updated, and the device controller will not be
3772 		 * triggered to generate ERDY to move the next stream data. To
3773 		 * workaround this and maintain compatibility with various
3774 		 * hosts, force to reinitiate the stream until the host is ready
3775 		 * instead of waiting for the host to prime the endpoint.
3776 		 */
3777 		if (DWC3_VER_IS_WITHIN(DWC32, 100A, ANY)) {
3778 			unsigned int cmd = DWC3_DGCMD_SET_ENDPOINT_PRIME;
3779 
3780 			dwc3_send_gadget_generic_command(dwc, cmd, dep->number);
3781 		} else {
3782 			dep->flags |= DWC3_EP_DELAY_START;
3783 			dwc3_stop_active_transfer(dep, true, true);
3784 			return;
3785 		}
3786 		break;
3787 	}
3788 
3789 out:
3790 	dep->flags &= ~DWC3_EP_IGNORE_NEXT_NOSTREAM;
3791 }
3792 
3793 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
3794 		const struct dwc3_event_depevt *event)
3795 {
3796 	struct dwc3_ep		*dep;
3797 	u8			epnum = event->endpoint_number;
3798 
3799 	dep = dwc->eps[epnum];
3800 
3801 	if (!(dep->flags & DWC3_EP_ENABLED)) {
3802 		if ((epnum > 1) && !(dep->flags & DWC3_EP_TRANSFER_STARTED))
3803 			return;
3804 
3805 		/* Handle only EPCMDCMPLT when EP disabled */
3806 		if ((event->endpoint_event != DWC3_DEPEVT_EPCMDCMPLT) &&
3807 			!(epnum <= 1 && event->endpoint_event == DWC3_DEPEVT_XFERCOMPLETE))
3808 			return;
3809 	}
3810 
3811 	if (epnum == 0 || epnum == 1) {
3812 		dwc3_ep0_interrupt(dwc, event);
3813 		return;
3814 	}
3815 
3816 	switch (event->endpoint_event) {
3817 	case DWC3_DEPEVT_XFERINPROGRESS:
3818 		dwc3_gadget_endpoint_transfer_in_progress(dep, event);
3819 		break;
3820 	case DWC3_DEPEVT_XFERNOTREADY:
3821 		dwc3_gadget_endpoint_transfer_not_ready(dep, event);
3822 		break;
3823 	case DWC3_DEPEVT_EPCMDCMPLT:
3824 		dwc3_gadget_endpoint_command_complete(dep, event);
3825 		break;
3826 	case DWC3_DEPEVT_XFERCOMPLETE:
3827 		dwc3_gadget_endpoint_transfer_complete(dep, event);
3828 		break;
3829 	case DWC3_DEPEVT_STREAMEVT:
3830 		dwc3_gadget_endpoint_stream_event(dep, event);
3831 		break;
3832 	case DWC3_DEPEVT_RXTXFIFOEVT:
3833 		break;
3834 	default:
3835 		dev_err(dwc->dev, "unknown endpoint event %d\n", event->endpoint_event);
3836 		break;
3837 	}
3838 }
3839 
3840 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
3841 {
3842 	if (dwc->async_callbacks && dwc->gadget_driver->disconnect) {
3843 		spin_unlock(&dwc->lock);
3844 		dwc->gadget_driver->disconnect(dwc->gadget);
3845 		spin_lock(&dwc->lock);
3846 	}
3847 }
3848 
3849 static void dwc3_suspend_gadget(struct dwc3 *dwc)
3850 {
3851 	if (dwc->async_callbacks && dwc->gadget_driver->suspend) {
3852 		spin_unlock(&dwc->lock);
3853 		dwc->gadget_driver->suspend(dwc->gadget);
3854 		spin_lock(&dwc->lock);
3855 	}
3856 }
3857 
3858 static void dwc3_resume_gadget(struct dwc3 *dwc)
3859 {
3860 	if (dwc->async_callbacks && dwc->gadget_driver->resume) {
3861 		spin_unlock(&dwc->lock);
3862 		dwc->gadget_driver->resume(dwc->gadget);
3863 		spin_lock(&dwc->lock);
3864 	}
3865 }
3866 
3867 static void dwc3_reset_gadget(struct dwc3 *dwc)
3868 {
3869 	if (!dwc->gadget_driver)
3870 		return;
3871 
3872 	if (dwc->async_callbacks && dwc->gadget->speed != USB_SPEED_UNKNOWN) {
3873 		spin_unlock(&dwc->lock);
3874 		usb_gadget_udc_reset(dwc->gadget, dwc->gadget_driver);
3875 		spin_lock(&dwc->lock);
3876 	}
3877 }
3878 
3879 void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force,
3880 	bool interrupt)
3881 {
3882 	struct dwc3 *dwc = dep->dwc;
3883 
3884 	/*
3885 	 * Only issue End Transfer command to the control endpoint of a started
3886 	 * Data Phase. Typically we should only do so in error cases such as
3887 	 * invalid/unexpected direction as described in the control transfer
3888 	 * flow of the programming guide.
3889 	 */
3890 	if (dep->number <= 1 && dwc->ep0state != EP0_DATA_PHASE)
3891 		return;
3892 
3893 	if (interrupt && (dep->flags & DWC3_EP_DELAY_STOP))
3894 		return;
3895 
3896 	if (!(dep->flags & DWC3_EP_TRANSFER_STARTED) ||
3897 	    (dep->flags & DWC3_EP_END_TRANSFER_PENDING))
3898 		return;
3899 
3900 	/*
3901 	 * If a Setup packet is received but yet to DMA out, the controller will
3902 	 * not process the End Transfer command of any endpoint. Polling of its
3903 	 * DEPCMD.CmdAct may block setting up TRB for Setup packet, causing a
3904 	 * timeout. Delay issuing the End Transfer command until the Setup TRB is
3905 	 * prepared.
3906 	 */
3907 	if (dwc->ep0state != EP0_SETUP_PHASE && !dwc->delayed_status) {
3908 		dep->flags |= DWC3_EP_DELAY_STOP;
3909 		return;
3910 	}
3911 
3912 	/*
3913 	 * NOTICE: We are violating what the Databook says about the
3914 	 * EndTransfer command. Ideally we would _always_ wait for the
3915 	 * EndTransfer Command Completion IRQ, but that's causing too
3916 	 * much trouble synchronizing between us and gadget driver.
3917 	 *
3918 	 * We have discussed this with the IP Provider and it was
3919 	 * suggested to giveback all requests here.
3920 	 *
3921 	 * Note also that a similar handling was tested by Synopsys
3922 	 * (thanks a lot Paul) and nothing bad has come out of it.
3923 	 * In short, what we're doing is issuing EndTransfer with
3924 	 * CMDIOC bit set and delay kicking transfer until the
3925 	 * EndTransfer command had completed.
3926 	 *
3927 	 * As of IP version 3.10a of the DWC_usb3 IP, the controller
3928 	 * supports a mode to work around the above limitation. The
3929 	 * software can poll the CMDACT bit in the DEPCMD register
3930 	 * after issuing a EndTransfer command. This mode is enabled
3931 	 * by writing GUCTL2[14]. This polling is already done in the
3932 	 * dwc3_send_gadget_ep_cmd() function so if the mode is
3933 	 * enabled, the EndTransfer command will have completed upon
3934 	 * returning from this function.
3935 	 *
3936 	 * This mode is NOT available on the DWC_usb31 IP.  In this
3937 	 * case, if the IOC bit is not set, then delay by 1ms
3938 	 * after issuing the EndTransfer command.  This allows for the
3939 	 * controller to handle the command completely before DWC3
3940 	 * remove requests attempts to unmap USB request buffers.
3941 	 */
3942 
3943 	__dwc3_stop_active_transfer(dep, force, interrupt);
3944 }
3945 
3946 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
3947 {
3948 	u32 epnum;
3949 
3950 	for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
3951 		struct dwc3_ep *dep;
3952 		int ret;
3953 
3954 		dep = dwc->eps[epnum];
3955 		if (!dep)
3956 			continue;
3957 
3958 		if (!(dep->flags & DWC3_EP_STALL))
3959 			continue;
3960 
3961 		dep->flags &= ~DWC3_EP_STALL;
3962 
3963 		ret = dwc3_send_clear_stall_ep_cmd(dep);
3964 		WARN_ON_ONCE(ret);
3965 	}
3966 }
3967 
3968 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
3969 {
3970 	int			reg;
3971 
3972 	dwc->suspended = false;
3973 
3974 	dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RX_DET);
3975 
3976 	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3977 	reg &= ~DWC3_DCTL_INITU1ENA;
3978 	reg &= ~DWC3_DCTL_INITU2ENA;
3979 	dwc3_gadget_dctl_write_safe(dwc, reg);
3980 
3981 	dwc->connected = false;
3982 
3983 	dwc3_disconnect_gadget(dwc);
3984 
3985 	dwc->gadget->speed = USB_SPEED_UNKNOWN;
3986 	dwc->setup_packet_pending = false;
3987 	dwc->gadget->wakeup_armed = false;
3988 	dwc3_gadget_enable_linksts_evts(dwc, false);
3989 	usb_gadget_set_state(dwc->gadget, USB_STATE_NOTATTACHED);
3990 
3991 	dwc3_ep0_reset_state(dwc);
3992 
3993 	/*
3994 	 * Request PM idle to address condition where usage count is
3995 	 * already decremented to zero, but waiting for the disconnect
3996 	 * interrupt to set dwc->connected to FALSE.
3997 	 */
3998 	pm_request_idle(dwc->dev);
3999 }
4000 
4001 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
4002 {
4003 	u32			reg;
4004 
4005 	dwc->suspended = false;
4006 
4007 	/*
4008 	 * Ideally, dwc3_reset_gadget() would trigger the function
4009 	 * drivers to stop any active transfers through ep disable.
4010 	 * However, for functions which defer ep disable, such as mass
4011 	 * storage, we will need to rely on the call to stop active
4012 	 * transfers here, and avoid allowing of request queuing.
4013 	 */
4014 	dwc->connected = false;
4015 
4016 	/*
4017 	 * WORKAROUND: DWC3 revisions <1.88a have an issue which
4018 	 * would cause a missing Disconnect Event if there's a
4019 	 * pending Setup Packet in the FIFO.
4020 	 *
4021 	 * There's no suggested workaround on the official Bug
4022 	 * report, which states that "unless the driver/application
4023 	 * is doing any special handling of a disconnect event,
4024 	 * there is no functional issue".
4025 	 *
4026 	 * Unfortunately, it turns out that we _do_ some special
4027 	 * handling of a disconnect event, namely complete all
4028 	 * pending transfers, notify gadget driver of the
4029 	 * disconnection, and so on.
4030 	 *
4031 	 * Our suggested workaround is to follow the Disconnect
4032 	 * Event steps here, instead, based on a setup_packet_pending
4033 	 * flag. Such flag gets set whenever we have a SETUP_PENDING
4034 	 * status for EP0 TRBs and gets cleared on XferComplete for the
4035 	 * same endpoint.
4036 	 *
4037 	 * Refers to:
4038 	 *
4039 	 * STAR#9000466709: RTL: Device : Disconnect event not
4040 	 * generated if setup packet pending in FIFO
4041 	 */
4042 	if (DWC3_VER_IS_PRIOR(DWC3, 188A)) {
4043 		if (dwc->setup_packet_pending)
4044 			dwc3_gadget_disconnect_interrupt(dwc);
4045 	}
4046 
4047 	dwc3_reset_gadget(dwc);
4048 
4049 	/*
4050 	 * From SNPS databook section 8.1.2, the EP0 should be in setup
4051 	 * phase. So ensure that EP0 is in setup phase by issuing a stall
4052 	 * and restart if EP0 is not in setup phase.
4053 	 */
4054 	dwc3_ep0_reset_state(dwc);
4055 
4056 	/*
4057 	 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
4058 	 * Section 4.1.2 Table 4-2, it states that during a USB reset, the SW
4059 	 * needs to ensure that it sends "a DEPENDXFER command for any active
4060 	 * transfers."
4061 	 */
4062 	dwc3_stop_active_transfers(dwc);
4063 	dwc->connected = true;
4064 
4065 	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
4066 	reg &= ~DWC3_DCTL_TSTCTRL_MASK;
4067 	dwc3_gadget_dctl_write_safe(dwc, reg);
4068 	dwc->test_mode = false;
4069 	dwc->gadget->wakeup_armed = false;
4070 	dwc3_gadget_enable_linksts_evts(dwc, false);
4071 	dwc3_clear_stall_all_ep(dwc);
4072 
4073 	/* Reset device address to zero */
4074 	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
4075 	reg &= ~(DWC3_DCFG_DEVADDR_MASK);
4076 	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
4077 }
4078 
4079 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
4080 {
4081 	struct dwc3_ep		*dep;
4082 	int			ret;
4083 	u32			reg;
4084 	u8			lanes = 1;
4085 	u8			speed;
4086 
4087 	if (!dwc->softconnect)
4088 		return;
4089 
4090 	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
4091 	speed = reg & DWC3_DSTS_CONNECTSPD;
4092 	dwc->speed = speed;
4093 
4094 	if (DWC3_IP_IS(DWC32))
4095 		lanes = DWC3_DSTS_CONNLANES(reg) + 1;
4096 
4097 	dwc->gadget->ssp_rate = USB_SSP_GEN_UNKNOWN;
4098 
4099 	/*
4100 	 * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
4101 	 * each time on Connect Done.
4102 	 *
4103 	 * Currently we always use the reset value. If any platform
4104 	 * wants to set this to a different value, we need to add a
4105 	 * setting and update GCTL.RAMCLKSEL here.
4106 	 */
4107 
4108 	switch (speed) {
4109 	case DWC3_DSTS_SUPERSPEED_PLUS:
4110 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
4111 		dwc->gadget->ep0->maxpacket = 512;
4112 		dwc->gadget->speed = USB_SPEED_SUPER_PLUS;
4113 
4114 		if (lanes > 1)
4115 			dwc->gadget->ssp_rate = USB_SSP_GEN_2x2;
4116 		else
4117 			dwc->gadget->ssp_rate = USB_SSP_GEN_2x1;
4118 		break;
4119 	case DWC3_DSTS_SUPERSPEED:
4120 		/*
4121 		 * WORKAROUND: DWC3 revisions <1.90a have an issue which
4122 		 * would cause a missing USB3 Reset event.
4123 		 *
4124 		 * In such situations, we should force a USB3 Reset
4125 		 * event by calling our dwc3_gadget_reset_interrupt()
4126 		 * routine.
4127 		 *
4128 		 * Refers to:
4129 		 *
4130 		 * STAR#9000483510: RTL: SS : USB3 reset event may
4131 		 * not be generated always when the link enters poll
4132 		 */
4133 		if (DWC3_VER_IS_PRIOR(DWC3, 190A))
4134 			dwc3_gadget_reset_interrupt(dwc);
4135 
4136 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
4137 		dwc->gadget->ep0->maxpacket = 512;
4138 		dwc->gadget->speed = USB_SPEED_SUPER;
4139 
4140 		if (lanes > 1) {
4141 			dwc->gadget->speed = USB_SPEED_SUPER_PLUS;
4142 			dwc->gadget->ssp_rate = USB_SSP_GEN_1x2;
4143 		}
4144 		break;
4145 	case DWC3_DSTS_HIGHSPEED:
4146 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
4147 		dwc->gadget->ep0->maxpacket = 64;
4148 		dwc->gadget->speed = USB_SPEED_HIGH;
4149 		break;
4150 	case DWC3_DSTS_FULLSPEED:
4151 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
4152 		dwc->gadget->ep0->maxpacket = 64;
4153 		dwc->gadget->speed = USB_SPEED_FULL;
4154 		break;
4155 	}
4156 
4157 	dwc->eps[1]->endpoint.maxpacket = dwc->gadget->ep0->maxpacket;
4158 
4159 	/* Enable USB2 LPM Capability */
4160 
4161 	if (!DWC3_VER_IS_WITHIN(DWC3, ANY, 194A) &&
4162 	    !dwc->usb2_gadget_lpm_disable &&
4163 	    (speed != DWC3_DSTS_SUPERSPEED) &&
4164 	    (speed != DWC3_DSTS_SUPERSPEED_PLUS)) {
4165 		reg = dwc3_readl(dwc->regs, DWC3_DCFG);
4166 		reg |= DWC3_DCFG_LPM_CAP;
4167 		dwc3_writel(dwc->regs, DWC3_DCFG, reg);
4168 
4169 		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
4170 		reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
4171 
4172 		reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold |
4173 					    (dwc->is_utmi_l1_suspend << 4));
4174 
4175 		/*
4176 		 * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
4177 		 * DCFG.LPMCap is set, core responses with an ACK and the
4178 		 * BESL value in the LPM token is less than or equal to LPM
4179 		 * NYET threshold.
4180 		 */
4181 		WARN_ONCE(DWC3_VER_IS_PRIOR(DWC3, 240A) && dwc->has_lpm_erratum,
4182 				"LPM Erratum not available on dwc3 revisions < 2.40a\n");
4183 
4184 		if (dwc->has_lpm_erratum && !DWC3_VER_IS_PRIOR(DWC3, 240A))
4185 			reg |= DWC3_DCTL_NYET_THRES(dwc->lpm_nyet_threshold);
4186 
4187 		dwc3_gadget_dctl_write_safe(dwc, reg);
4188 	} else {
4189 		if (dwc->usb2_gadget_lpm_disable) {
4190 			reg = dwc3_readl(dwc->regs, DWC3_DCFG);
4191 			reg &= ~DWC3_DCFG_LPM_CAP;
4192 			dwc3_writel(dwc->regs, DWC3_DCFG, reg);
4193 		}
4194 
4195 		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
4196 		reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
4197 		dwc3_gadget_dctl_write_safe(dwc, reg);
4198 	}
4199 
4200 	dep = dwc->eps[0];
4201 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
4202 	if (ret) {
4203 		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
4204 		return;
4205 	}
4206 
4207 	dep = dwc->eps[1];
4208 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
4209 	if (ret) {
4210 		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
4211 		return;
4212 	}
4213 
4214 	/*
4215 	 * Configure PHY via GUSB3PIPECTLn if required.
4216 	 *
4217 	 * Update GTXFIFOSIZn
4218 	 *
4219 	 * In both cases reset values should be sufficient.
4220 	 */
4221 }
4222 
4223 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc, unsigned int evtinfo)
4224 {
4225 	dwc->suspended = false;
4226 
4227 	/*
4228 	 * TODO take core out of low power mode when that's
4229 	 * implemented.
4230 	 */
4231 
4232 	if (dwc->async_callbacks && dwc->gadget_driver->resume) {
4233 		spin_unlock(&dwc->lock);
4234 		dwc->gadget_driver->resume(dwc->gadget);
4235 		spin_lock(&dwc->lock);
4236 	}
4237 
4238 	dwc->link_state = evtinfo & DWC3_LINK_STATE_MASK;
4239 }
4240 
4241 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
4242 		unsigned int evtinfo)
4243 {
4244 	enum dwc3_link_state	next = evtinfo & DWC3_LINK_STATE_MASK;
4245 	unsigned int		pwropt;
4246 
4247 	/*
4248 	 * WORKAROUND: DWC3 < 2.50a have an issue when configured without
4249 	 * Hibernation mode enabled which would show up when device detects
4250 	 * host-initiated U3 exit.
4251 	 *
4252 	 * In that case, device will generate a Link State Change Interrupt
4253 	 * from U3 to RESUME which is only necessary if Hibernation is
4254 	 * configured in.
4255 	 *
4256 	 * There are no functional changes due to such spurious event and we
4257 	 * just need to ignore it.
4258 	 *
4259 	 * Refers to:
4260 	 *
4261 	 * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
4262 	 * operational mode
4263 	 */
4264 	pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
4265 	if (DWC3_VER_IS_PRIOR(DWC3, 250A) &&
4266 			(pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
4267 		if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
4268 				(next == DWC3_LINK_STATE_RESUME)) {
4269 			return;
4270 		}
4271 	}
4272 
4273 	/*
4274 	 * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
4275 	 * on the link partner, the USB session might do multiple entry/exit
4276 	 * of low power states before a transfer takes place.
4277 	 *
4278 	 * Due to this problem, we might experience lower throughput. The
4279 	 * suggested workaround is to disable DCTL[12:9] bits if we're
4280 	 * transitioning from U1/U2 to U0 and enable those bits again
4281 	 * after a transfer completes and there are no pending transfers
4282 	 * on any of the enabled endpoints.
4283 	 *
4284 	 * This is the first half of that workaround.
4285 	 *
4286 	 * Refers to:
4287 	 *
4288 	 * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
4289 	 * core send LGO_Ux entering U0
4290 	 */
4291 	if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
4292 		if (next == DWC3_LINK_STATE_U0) {
4293 			u32	u1u2;
4294 			u32	reg;
4295 
4296 			switch (dwc->link_state) {
4297 			case DWC3_LINK_STATE_U1:
4298 			case DWC3_LINK_STATE_U2:
4299 				reg = dwc3_readl(dwc->regs, DWC3_DCTL);
4300 				u1u2 = reg & (DWC3_DCTL_INITU2ENA
4301 						| DWC3_DCTL_ACCEPTU2ENA
4302 						| DWC3_DCTL_INITU1ENA
4303 						| DWC3_DCTL_ACCEPTU1ENA);
4304 
4305 				if (!dwc->u1u2)
4306 					dwc->u1u2 = reg & u1u2;
4307 
4308 				reg &= ~u1u2;
4309 
4310 				dwc3_gadget_dctl_write_safe(dwc, reg);
4311 				break;
4312 			default:
4313 				/* do nothing */
4314 				break;
4315 			}
4316 		}
4317 	}
4318 
4319 	switch (next) {
4320 	case DWC3_LINK_STATE_U0:
4321 		if (dwc->gadget->wakeup_armed) {
4322 			dwc3_gadget_enable_linksts_evts(dwc, false);
4323 			dwc3_resume_gadget(dwc);
4324 			dwc->suspended = false;
4325 		}
4326 		break;
4327 	case DWC3_LINK_STATE_U1:
4328 		if (dwc->speed == USB_SPEED_SUPER)
4329 			dwc3_suspend_gadget(dwc);
4330 		break;
4331 	case DWC3_LINK_STATE_U2:
4332 	case DWC3_LINK_STATE_U3:
4333 		dwc3_suspend_gadget(dwc);
4334 		break;
4335 	case DWC3_LINK_STATE_RESUME:
4336 		dwc3_resume_gadget(dwc);
4337 		break;
4338 	default:
4339 		/* do nothing */
4340 		break;
4341 	}
4342 
4343 	dwc->link_state = next;
4344 }
4345 
4346 static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc,
4347 					  unsigned int evtinfo)
4348 {
4349 	enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
4350 
4351 	if (!dwc->suspended && next == DWC3_LINK_STATE_U3) {
4352 		dwc->suspended = true;
4353 		dwc3_suspend_gadget(dwc);
4354 	}
4355 
4356 	dwc->link_state = next;
4357 }
4358 
4359 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
4360 		const struct dwc3_event_devt *event)
4361 {
4362 	switch (event->type) {
4363 	case DWC3_DEVICE_EVENT_DISCONNECT:
4364 		dwc3_gadget_disconnect_interrupt(dwc);
4365 		break;
4366 	case DWC3_DEVICE_EVENT_RESET:
4367 		dwc3_gadget_reset_interrupt(dwc);
4368 		break;
4369 	case DWC3_DEVICE_EVENT_CONNECT_DONE:
4370 		dwc3_gadget_conndone_interrupt(dwc);
4371 		break;
4372 	case DWC3_DEVICE_EVENT_WAKEUP:
4373 		dwc3_gadget_wakeup_interrupt(dwc, event->event_info);
4374 		break;
4375 	case DWC3_DEVICE_EVENT_HIBER_REQ:
4376 		dev_WARN_ONCE(dwc->dev, true, "unexpected hibernation event\n");
4377 		break;
4378 	case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
4379 		dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
4380 		break;
4381 	case DWC3_DEVICE_EVENT_SUSPEND:
4382 		/* It changed to be suspend event for version 2.30a and above */
4383 		if (!DWC3_VER_IS_PRIOR(DWC3, 230A))
4384 			dwc3_gadget_suspend_interrupt(dwc, event->event_info);
4385 		break;
4386 	case DWC3_DEVICE_EVENT_SOF:
4387 	case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
4388 	case DWC3_DEVICE_EVENT_CMD_CMPL:
4389 	case DWC3_DEVICE_EVENT_OVERFLOW:
4390 		break;
4391 	default:
4392 		dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
4393 	}
4394 }
4395 
4396 static void dwc3_process_event_entry(struct dwc3 *dwc,
4397 		const union dwc3_event *event)
4398 {
4399 	trace_dwc3_event(event->raw, dwc);
4400 
4401 	if (!event->type.is_devspec)
4402 		dwc3_endpoint_interrupt(dwc, &event->depevt);
4403 	else if (event->type.type == DWC3_EVENT_TYPE_DEV)
4404 		dwc3_gadget_interrupt(dwc, &event->devt);
4405 	else
4406 		dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
4407 }
4408 
4409 static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt)
4410 {
4411 	struct dwc3 *dwc = evt->dwc;
4412 	irqreturn_t ret = IRQ_NONE;
4413 	int left;
4414 
4415 	left = evt->count;
4416 
4417 	if (!(evt->flags & DWC3_EVENT_PENDING))
4418 		return IRQ_NONE;
4419 
4420 	while (left > 0) {
4421 		union dwc3_event event;
4422 
4423 		event.raw = *(u32 *) (evt->cache + evt->lpos);
4424 
4425 		dwc3_process_event_entry(dwc, &event);
4426 
4427 		/*
4428 		 * FIXME we wrap around correctly to the next entry as
4429 		 * almost all entries are 4 bytes in size. There is one
4430 		 * entry which has 12 bytes which is a regular entry
4431 		 * followed by 8 bytes data. ATM I don't know how
4432 		 * things are organized if we get next to the a
4433 		 * boundary so I worry about that once we try to handle
4434 		 * that.
4435 		 */
4436 		evt->lpos = (evt->lpos + 4) % evt->length;
4437 		left -= 4;
4438 	}
4439 
4440 	evt->count = 0;
4441 	ret = IRQ_HANDLED;
4442 
4443 	/* Unmask interrupt */
4444 	dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0),
4445 		    DWC3_GEVNTSIZ_SIZE(evt->length));
4446 
4447 	if (dwc->imod_interval) {
4448 		dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
4449 		dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
4450 	}
4451 
4452 	/* Keep the clearing of DWC3_EVENT_PENDING at the end */
4453 	evt->flags &= ~DWC3_EVENT_PENDING;
4454 
4455 	return ret;
4456 }
4457 
4458 static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt)
4459 {
4460 	struct dwc3_event_buffer *evt = _evt;
4461 	struct dwc3 *dwc = evt->dwc;
4462 	unsigned long flags;
4463 	irqreturn_t ret = IRQ_NONE;
4464 
4465 	local_bh_disable();
4466 	spin_lock_irqsave(&dwc->lock, flags);
4467 	ret = dwc3_process_event_buf(evt);
4468 	spin_unlock_irqrestore(&dwc->lock, flags);
4469 	local_bh_enable();
4470 
4471 	return ret;
4472 }
4473 
4474 static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt)
4475 {
4476 	struct dwc3 *dwc = evt->dwc;
4477 	u32 amount;
4478 	u32 count;
4479 
4480 	if (pm_runtime_suspended(dwc->dev)) {
4481 		dwc->pending_events = true;
4482 		/*
4483 		 * Trigger runtime resume. The get() function will be balanced
4484 		 * after processing the pending events in dwc3_process_pending
4485 		 * events().
4486 		 */
4487 		pm_runtime_get(dwc->dev);
4488 		disable_irq_nosync(dwc->irq_gadget);
4489 		return IRQ_HANDLED;
4490 	}
4491 
4492 	/*
4493 	 * With PCIe legacy interrupt, test shows that top-half irq handler can
4494 	 * be called again after HW interrupt deassertion. Check if bottom-half
4495 	 * irq event handler completes before caching new event to prevent
4496 	 * losing events.
4497 	 */
4498 	if (evt->flags & DWC3_EVENT_PENDING)
4499 		return IRQ_HANDLED;
4500 
4501 	count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
4502 	count &= DWC3_GEVNTCOUNT_MASK;
4503 	if (!count)
4504 		return IRQ_NONE;
4505 
4506 	evt->count = count;
4507 	evt->flags |= DWC3_EVENT_PENDING;
4508 
4509 	/* Mask interrupt */
4510 	dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0),
4511 		    DWC3_GEVNTSIZ_INTMASK | DWC3_GEVNTSIZ_SIZE(evt->length));
4512 
4513 	amount = min(count, evt->length - evt->lpos);
4514 	memcpy(evt->cache + evt->lpos, evt->buf + evt->lpos, amount);
4515 
4516 	if (amount < count)
4517 		memcpy(evt->cache, evt->buf, count - amount);
4518 
4519 	dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
4520 
4521 	return IRQ_WAKE_THREAD;
4522 }
4523 
4524 static irqreturn_t dwc3_interrupt(int irq, void *_evt)
4525 {
4526 	struct dwc3_event_buffer	*evt = _evt;
4527 
4528 	return dwc3_check_event_buf(evt);
4529 }
4530 
4531 static int dwc3_gadget_get_irq(struct dwc3 *dwc)
4532 {
4533 	struct platform_device *dwc3_pdev = to_platform_device(dwc->dev);
4534 	int irq;
4535 
4536 	irq = platform_get_irq_byname_optional(dwc3_pdev, "peripheral");
4537 	if (irq > 0)
4538 		goto out;
4539 
4540 	if (irq == -EPROBE_DEFER)
4541 		goto out;
4542 
4543 	irq = platform_get_irq_byname_optional(dwc3_pdev, "dwc_usb3");
4544 	if (irq > 0)
4545 		goto out;
4546 
4547 	if (irq == -EPROBE_DEFER)
4548 		goto out;
4549 
4550 	irq = platform_get_irq(dwc3_pdev, 0);
4551 
4552 out:
4553 	return irq;
4554 }
4555 
4556 static void dwc_gadget_release(struct device *dev)
4557 {
4558 	struct usb_gadget *gadget = container_of(dev, struct usb_gadget, dev);
4559 
4560 	kfree(gadget);
4561 }
4562 
4563 /**
4564  * dwc3_gadget_init - initializes gadget related registers
4565  * @dwc: pointer to our controller context structure
4566  *
4567  * Returns 0 on success otherwise negative errno.
4568  */
4569 int dwc3_gadget_init(struct dwc3 *dwc)
4570 {
4571 	int ret;
4572 	int irq;
4573 	struct device *dev;
4574 
4575 	irq = dwc3_gadget_get_irq(dwc);
4576 	if (irq < 0) {
4577 		ret = irq;
4578 		goto err0;
4579 	}
4580 
4581 	dwc->irq_gadget = irq;
4582 
4583 	dwc->ep0_trb = dma_alloc_coherent(dwc->sysdev,
4584 					  sizeof(*dwc->ep0_trb) * 2,
4585 					  &dwc->ep0_trb_addr, GFP_KERNEL);
4586 	if (!dwc->ep0_trb) {
4587 		dev_err(dwc->dev, "failed to allocate ep0 trb\n");
4588 		ret = -ENOMEM;
4589 		goto err0;
4590 	}
4591 
4592 	dwc->setup_buf = kzalloc(DWC3_EP0_SETUP_SIZE, GFP_KERNEL);
4593 	if (!dwc->setup_buf) {
4594 		ret = -ENOMEM;
4595 		goto err1;
4596 	}
4597 
4598 	dwc->bounce = dma_alloc_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE,
4599 			&dwc->bounce_addr, GFP_KERNEL);
4600 	if (!dwc->bounce) {
4601 		ret = -ENOMEM;
4602 		goto err2;
4603 	}
4604 
4605 	init_completion(&dwc->ep0_in_setup);
4606 	dwc->gadget = kzalloc(sizeof(struct usb_gadget), GFP_KERNEL);
4607 	if (!dwc->gadget) {
4608 		ret = -ENOMEM;
4609 		goto err3;
4610 	}
4611 
4612 
4613 	usb_initialize_gadget(dwc->dev, dwc->gadget, dwc_gadget_release);
4614 	dev				= &dwc->gadget->dev;
4615 	dev->platform_data		= dwc;
4616 	dwc->gadget->ops		= &dwc3_gadget_ops;
4617 	dwc->gadget->speed		= USB_SPEED_UNKNOWN;
4618 	dwc->gadget->ssp_rate		= USB_SSP_GEN_UNKNOWN;
4619 	dwc->gadget->sg_supported	= true;
4620 	dwc->gadget->name		= "dwc3-gadget";
4621 	dwc->gadget->lpm_capable	= !dwc->usb2_gadget_lpm_disable;
4622 	dwc->gadget->wakeup_capable	= true;
4623 
4624 	/*
4625 	 * FIXME We might be setting max_speed to <SUPER, however versions
4626 	 * <2.20a of dwc3 have an issue with metastability (documented
4627 	 * elsewhere in this driver) which tells us we can't set max speed to
4628 	 * anything lower than SUPER.
4629 	 *
4630 	 * Because gadget.max_speed is only used by composite.c and function
4631 	 * drivers (i.e. it won't go into dwc3's registers) we are allowing this
4632 	 * to happen so we avoid sending SuperSpeed Capability descriptor
4633 	 * together with our BOS descriptor as that could confuse host into
4634 	 * thinking we can handle super speed.
4635 	 *
4636 	 * Note that, in fact, we won't even support GetBOS requests when speed
4637 	 * is less than super speed because we don't have means, yet, to tell
4638 	 * composite.c that we are USB 2.0 + LPM ECN.
4639 	 */
4640 	if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
4641 	    !dwc->dis_metastability_quirk)
4642 		dev_info(dwc->dev, "changing max_speed on rev %08x\n",
4643 				dwc->revision);
4644 
4645 	dwc->gadget->max_speed		= dwc->maximum_speed;
4646 	dwc->gadget->max_ssp_rate	= dwc->max_ssp_rate;
4647 
4648 	/*
4649 	 * REVISIT: Here we should clear all pending IRQs to be
4650 	 * sure we're starting from a well known location.
4651 	 */
4652 
4653 	ret = dwc3_gadget_init_endpoints(dwc, dwc->num_eps);
4654 	if (ret)
4655 		goto err4;
4656 
4657 	ret = usb_add_gadget(dwc->gadget);
4658 	if (ret) {
4659 		dev_err(dwc->dev, "failed to add gadget\n");
4660 		goto err5;
4661 	}
4662 
4663 	if (DWC3_IP_IS(DWC32) && dwc->maximum_speed == USB_SPEED_SUPER_PLUS)
4664 		dwc3_gadget_set_ssp_rate(dwc->gadget, dwc->max_ssp_rate);
4665 	else
4666 		dwc3_gadget_set_speed(dwc->gadget, dwc->maximum_speed);
4667 
4668 	return 0;
4669 
4670 err5:
4671 	dwc3_gadget_free_endpoints(dwc);
4672 err4:
4673 	usb_put_gadget(dwc->gadget);
4674 	dwc->gadget = NULL;
4675 err3:
4676 	dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
4677 			dwc->bounce_addr);
4678 
4679 err2:
4680 	kfree(dwc->setup_buf);
4681 
4682 err1:
4683 	dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
4684 			dwc->ep0_trb, dwc->ep0_trb_addr);
4685 
4686 err0:
4687 	return ret;
4688 }
4689 
4690 /* -------------------------------------------------------------------------- */
4691 
4692 void dwc3_gadget_exit(struct dwc3 *dwc)
4693 {
4694 	if (!dwc->gadget)
4695 		return;
4696 
4697 	usb_del_gadget(dwc->gadget);
4698 	dwc3_gadget_free_endpoints(dwc);
4699 	usb_put_gadget(dwc->gadget);
4700 	dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
4701 			  dwc->bounce_addr);
4702 	kfree(dwc->setup_buf);
4703 	dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
4704 			  dwc->ep0_trb, dwc->ep0_trb_addr);
4705 }
4706 
4707 int dwc3_gadget_suspend(struct dwc3 *dwc)
4708 {
4709 	unsigned long flags;
4710 	int ret;
4711 
4712 	if (!dwc->gadget_driver)
4713 		return 0;
4714 
4715 	ret = dwc3_gadget_soft_disconnect(dwc);
4716 	if (ret)
4717 		goto err;
4718 
4719 	spin_lock_irqsave(&dwc->lock, flags);
4720 	dwc3_disconnect_gadget(dwc);
4721 	spin_unlock_irqrestore(&dwc->lock, flags);
4722 
4723 	return 0;
4724 
4725 err:
4726 	/*
4727 	 * Attempt to reset the controller's state. Likely no
4728 	 * communication can be established until the host
4729 	 * performs a port reset.
4730 	 */
4731 	if (dwc->softconnect)
4732 		dwc3_gadget_soft_connect(dwc);
4733 
4734 	return ret;
4735 }
4736 
4737 int dwc3_gadget_resume(struct dwc3 *dwc)
4738 {
4739 	if (!dwc->gadget_driver || !dwc->softconnect)
4740 		return 0;
4741 
4742 	return dwc3_gadget_soft_connect(dwc);
4743 }
4744 
4745 void dwc3_gadget_process_pending_events(struct dwc3 *dwc)
4746 {
4747 	if (dwc->pending_events) {
4748 		dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf);
4749 		dwc3_thread_interrupt(dwc->irq_gadget, dwc->ev_buf);
4750 		pm_runtime_put(dwc->dev);
4751 		dwc->pending_events = false;
4752 		enable_irq(dwc->irq_gadget);
4753 	}
4754 }
4755