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