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