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