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