xref: /openbmc/linux/drivers/usb/dwc3/gadget.c (revision 96de2506)
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 - http://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)	(((d)->frame_number + (d)->interval) \
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 TEST_J:
50 	case TEST_K:
51 	case TEST_SE0_NAK:
52 	case TEST_PACKET:
53 	case TEST_FORCE_EN:
54 		reg |= mode << 1;
55 		break;
56 	default:
57 		return -EINVAL;
58 	}
59 
60 	dwc3_writel(dwc->regs, DWC3_DCTL, 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 (dwc->revision >= DWC3_REVISION_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 requested state */
115 	reg |= DWC3_DCTL_ULSTCHNGREQ(state);
116 	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
117 
118 	/*
119 	 * The following code is racy when called from dwc3_gadget_wakeup,
120 	 * and is not needed, at least on newer versions
121 	 */
122 	if (dwc->revision >= DWC3_REVISION_194A)
123 		return 0;
124 
125 	/* wait for a change in DSTS */
126 	retries = 10000;
127 	while (--retries) {
128 		reg = dwc3_readl(dwc->regs, DWC3_DSTS);
129 
130 		if (DWC3_DSTS_USBLNKST(reg) == state)
131 			return 0;
132 
133 		udelay(5);
134 	}
135 
136 	return -ETIMEDOUT;
137 }
138 
139 /**
140  * dwc3_ep_inc_trb - increment a trb index.
141  * @index: Pointer to the TRB index to increment.
142  *
143  * The index should never point to the link TRB. After incrementing,
144  * if it is point to the link TRB, wrap around to the beginning. The
145  * link TRB is always at the last TRB entry.
146  */
147 static void dwc3_ep_inc_trb(u8 *index)
148 {
149 	(*index)++;
150 	if (*index == (DWC3_TRB_NUM - 1))
151 		*index = 0;
152 }
153 
154 /**
155  * dwc3_ep_inc_enq - increment endpoint's enqueue pointer
156  * @dep: The endpoint whose enqueue pointer we're incrementing
157  */
158 static void dwc3_ep_inc_enq(struct dwc3_ep *dep)
159 {
160 	dwc3_ep_inc_trb(&dep->trb_enqueue);
161 }
162 
163 /**
164  * dwc3_ep_inc_deq - increment endpoint's dequeue pointer
165  * @dep: The endpoint whose enqueue pointer we're incrementing
166  */
167 static void dwc3_ep_inc_deq(struct dwc3_ep *dep)
168 {
169 	dwc3_ep_inc_trb(&dep->trb_dequeue);
170 }
171 
172 static void dwc3_gadget_del_and_unmap_request(struct dwc3_ep *dep,
173 		struct dwc3_request *req, int status)
174 {
175 	struct dwc3			*dwc = dep->dwc;
176 
177 	req->started = false;
178 	list_del(&req->list);
179 	req->remaining = 0;
180 
181 	if (req->request.status == -EINPROGRESS)
182 		req->request.status = status;
183 
184 	if (req->trb)
185 		usb_gadget_unmap_request_by_dev(dwc->sysdev,
186 				&req->request, req->direction);
187 
188 	req->trb = NULL;
189 	trace_dwc3_gadget_giveback(req);
190 
191 	if (dep->number > 1)
192 		pm_runtime_put(dwc->dev);
193 }
194 
195 /**
196  * dwc3_gadget_giveback - call struct usb_request's ->complete callback
197  * @dep: The endpoint to whom the request belongs to
198  * @req: The request we're giving back
199  * @status: completion code for the request
200  *
201  * Must be called with controller's lock held and interrupts disabled. This
202  * function will unmap @req and call its ->complete() callback to notify upper
203  * layers that it has completed.
204  */
205 void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
206 		int status)
207 {
208 	struct dwc3			*dwc = dep->dwc;
209 
210 	dwc3_gadget_del_and_unmap_request(dep, req, status);
211 
212 	spin_unlock(&dwc->lock);
213 	usb_gadget_giveback_request(&dep->endpoint, &req->request);
214 	spin_lock(&dwc->lock);
215 }
216 
217 /**
218  * dwc3_send_gadget_generic_command - issue a generic command for the controller
219  * @dwc: pointer to the controller context
220  * @cmd: the command to be issued
221  * @param: command parameter
222  *
223  * Caller should take care of locking. Issue @cmd with a given @param to @dwc
224  * and wait for its completion.
225  */
226 int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned cmd, u32 param)
227 {
228 	u32		timeout = 500;
229 	int		status = 0;
230 	int		ret = 0;
231 	u32		reg;
232 
233 	dwc3_writel(dwc->regs, DWC3_DGCMDPAR, param);
234 	dwc3_writel(dwc->regs, DWC3_DGCMD, cmd | DWC3_DGCMD_CMDACT);
235 
236 	do {
237 		reg = dwc3_readl(dwc->regs, DWC3_DGCMD);
238 		if (!(reg & DWC3_DGCMD_CMDACT)) {
239 			status = DWC3_DGCMD_STATUS(reg);
240 			if (status)
241 				ret = -EINVAL;
242 			break;
243 		}
244 	} while (--timeout);
245 
246 	if (!timeout) {
247 		ret = -ETIMEDOUT;
248 		status = -ETIMEDOUT;
249 	}
250 
251 	trace_dwc3_gadget_generic_cmd(cmd, param, status);
252 
253 	return ret;
254 }
255 
256 static int __dwc3_gadget_wakeup(struct dwc3 *dwc);
257 
258 /**
259  * dwc3_send_gadget_ep_cmd - issue an endpoint command
260  * @dep: the endpoint to which the command is going to be issued
261  * @cmd: the command to be issued
262  * @params: parameters to the command
263  *
264  * Caller should handle locking. This function will issue @cmd with given
265  * @params to @dep and wait for its completion.
266  */
267 int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned cmd,
268 		struct dwc3_gadget_ep_cmd_params *params)
269 {
270 	const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
271 	struct dwc3		*dwc = dep->dwc;
272 	u32			timeout = 1000;
273 	u32			reg;
274 
275 	int			cmd_status = 0;
276 	int			susphy = false;
277 	int			ret = -EINVAL;
278 
279 	/*
280 	 * Synopsys Databook 2.60a states, on section 6.3.2.5.[1-8], that if
281 	 * we're issuing an endpoint command, we must check if
282 	 * GUSB2PHYCFG.SUSPHY bit is set. If it is, then we need to clear it.
283 	 *
284 	 * We will also set SUSPHY bit to what it was before returning as stated
285 	 * by the same section on Synopsys databook.
286 	 */
287 	if (dwc->gadget.speed <= USB_SPEED_HIGH) {
288 		reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
289 		if (unlikely(reg & DWC3_GUSB2PHYCFG_SUSPHY)) {
290 			susphy = true;
291 			reg &= ~DWC3_GUSB2PHYCFG_SUSPHY;
292 			dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
293 		}
294 	}
295 
296 	if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
297 		int		needs_wakeup;
298 
299 		needs_wakeup = (dwc->link_state == DWC3_LINK_STATE_U1 ||
300 				dwc->link_state == DWC3_LINK_STATE_U2 ||
301 				dwc->link_state == DWC3_LINK_STATE_U3);
302 
303 		if (unlikely(needs_wakeup)) {
304 			ret = __dwc3_gadget_wakeup(dwc);
305 			dev_WARN_ONCE(dwc->dev, ret, "wakeup failed --> %d\n",
306 					ret);
307 		}
308 	}
309 
310 	dwc3_writel(dep->regs, DWC3_DEPCMDPAR0, params->param0);
311 	dwc3_writel(dep->regs, DWC3_DEPCMDPAR1, params->param1);
312 	dwc3_writel(dep->regs, DWC3_DEPCMDPAR2, params->param2);
313 
314 	/*
315 	 * Synopsys Databook 2.60a states in section 6.3.2.5.6 of that if we're
316 	 * not relying on XferNotReady, we can make use of a special "No
317 	 * Response Update Transfer" command where we should clear both CmdAct
318 	 * and CmdIOC bits.
319 	 *
320 	 * With this, we don't need to wait for command completion and can
321 	 * straight away issue further commands to the endpoint.
322 	 *
323 	 * NOTICE: We're making an assumption that control endpoints will never
324 	 * make use of Update Transfer command. This is a safe assumption
325 	 * because we can never have more than one request at a time with
326 	 * Control Endpoints. If anybody changes that assumption, this chunk
327 	 * needs to be updated accordingly.
328 	 */
329 	if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_UPDATETRANSFER &&
330 			!usb_endpoint_xfer_isoc(desc))
331 		cmd &= ~(DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_CMDACT);
332 	else
333 		cmd |= DWC3_DEPCMD_CMDACT;
334 
335 	dwc3_writel(dep->regs, DWC3_DEPCMD, cmd);
336 	do {
337 		reg = dwc3_readl(dep->regs, DWC3_DEPCMD);
338 		if (!(reg & DWC3_DEPCMD_CMDACT)) {
339 			cmd_status = DWC3_DEPCMD_STATUS(reg);
340 
341 			switch (cmd_status) {
342 			case 0:
343 				ret = 0;
344 				break;
345 			case DEPEVT_TRANSFER_NO_RESOURCE:
346 				ret = -EINVAL;
347 				break;
348 			case DEPEVT_TRANSFER_BUS_EXPIRY:
349 				/*
350 				 * SW issues START TRANSFER command to
351 				 * isochronous ep with future frame interval. If
352 				 * future interval time has already passed when
353 				 * core receives the command, it will respond
354 				 * with an error status of 'Bus Expiry'.
355 				 *
356 				 * Instead of always returning -EINVAL, let's
357 				 * give a hint to the gadget driver that this is
358 				 * the case by returning -EAGAIN.
359 				 */
360 				ret = -EAGAIN;
361 				break;
362 			default:
363 				dev_WARN(dwc->dev, "UNKNOWN cmd status\n");
364 			}
365 
366 			break;
367 		}
368 	} while (--timeout);
369 
370 	if (timeout == 0) {
371 		ret = -ETIMEDOUT;
372 		cmd_status = -ETIMEDOUT;
373 	}
374 
375 	trace_dwc3_gadget_ep_cmd(dep, cmd, params, cmd_status);
376 
377 	if (ret == 0) {
378 		switch (DWC3_DEPCMD_CMD(cmd)) {
379 		case DWC3_DEPCMD_STARTTRANSFER:
380 			dep->flags |= DWC3_EP_TRANSFER_STARTED;
381 			dwc3_gadget_ep_get_transfer_index(dep);
382 			break;
383 		case DWC3_DEPCMD_ENDTRANSFER:
384 			dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
385 			break;
386 		default:
387 			/* nothing */
388 			break;
389 		}
390 	}
391 
392 	if (unlikely(susphy)) {
393 		reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
394 		reg |= DWC3_GUSB2PHYCFG_SUSPHY;
395 		dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
396 	}
397 
398 	return ret;
399 }
400 
401 static int dwc3_send_clear_stall_ep_cmd(struct dwc3_ep *dep)
402 {
403 	struct dwc3 *dwc = dep->dwc;
404 	struct dwc3_gadget_ep_cmd_params params;
405 	u32 cmd = DWC3_DEPCMD_CLEARSTALL;
406 
407 	/*
408 	 * As of core revision 2.60a the recommended programming model
409 	 * is to set the ClearPendIN bit when issuing a Clear Stall EP
410 	 * command for IN endpoints. This is to prevent an issue where
411 	 * some (non-compliant) hosts may not send ACK TPs for pending
412 	 * IN transfers due to a mishandled error condition. Synopsys
413 	 * STAR 9000614252.
414 	 */
415 	if (dep->direction && (dwc->revision >= DWC3_REVISION_260A) &&
416 	    (dwc->gadget.speed >= USB_SPEED_SUPER))
417 		cmd |= DWC3_DEPCMD_CLEARPENDIN;
418 
419 	memset(&params, 0, sizeof(params));
420 
421 	return dwc3_send_gadget_ep_cmd(dep, cmd, &params);
422 }
423 
424 static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep,
425 		struct dwc3_trb *trb)
426 {
427 	u32		offset = (char *) trb - (char *) dep->trb_pool;
428 
429 	return dep->trb_pool_dma + offset;
430 }
431 
432 static int dwc3_alloc_trb_pool(struct dwc3_ep *dep)
433 {
434 	struct dwc3		*dwc = dep->dwc;
435 
436 	if (dep->trb_pool)
437 		return 0;
438 
439 	dep->trb_pool = dma_alloc_coherent(dwc->sysdev,
440 			sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
441 			&dep->trb_pool_dma, GFP_KERNEL);
442 	if (!dep->trb_pool) {
443 		dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n",
444 				dep->name);
445 		return -ENOMEM;
446 	}
447 
448 	return 0;
449 }
450 
451 static void dwc3_free_trb_pool(struct dwc3_ep *dep)
452 {
453 	struct dwc3		*dwc = dep->dwc;
454 
455 	dma_free_coherent(dwc->sysdev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
456 			dep->trb_pool, dep->trb_pool_dma);
457 
458 	dep->trb_pool = NULL;
459 	dep->trb_pool_dma = 0;
460 }
461 
462 static int dwc3_gadget_set_xfer_resource(struct dwc3_ep *dep)
463 {
464 	struct dwc3_gadget_ep_cmd_params params;
465 
466 	memset(&params, 0x00, sizeof(params));
467 
468 	params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1);
469 
470 	return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETTRANSFRESOURCE,
471 			&params);
472 }
473 
474 /**
475  * dwc3_gadget_start_config - configure ep resources
476  * @dep: endpoint that is being enabled
477  *
478  * Issue a %DWC3_DEPCMD_DEPSTARTCFG command to @dep. After the command's
479  * completion, it will set Transfer Resource for all available endpoints.
480  *
481  * The assignment of transfer resources cannot perfectly follow the data book
482  * due to the fact that the controller driver does not have all knowledge of the
483  * configuration in advance. It is given this information piecemeal by the
484  * composite gadget framework after every SET_CONFIGURATION and
485  * SET_INTERFACE. Trying to follow the databook programming model in this
486  * scenario can cause errors. For two reasons:
487  *
488  * 1) The databook says to do %DWC3_DEPCMD_DEPSTARTCFG for every
489  * %USB_REQ_SET_CONFIGURATION and %USB_REQ_SET_INTERFACE (8.1.5). This is
490  * incorrect in the scenario of multiple interfaces.
491  *
492  * 2) The databook does not mention doing more %DWC3_DEPCMD_DEPXFERCFG for new
493  * endpoint on alt setting (8.1.6).
494  *
495  * The following simplified method is used instead:
496  *
497  * All hardware endpoints can be assigned a transfer resource and this setting
498  * will stay persistent until either a core reset or hibernation. So whenever we
499  * do a %DWC3_DEPCMD_DEPSTARTCFG(0) we can go ahead and do
500  * %DWC3_DEPCMD_DEPXFERCFG for every hardware endpoint as well. We are
501  * guaranteed that there are as many transfer resources as endpoints.
502  *
503  * This function is called for each endpoint when it is being enabled but is
504  * triggered only when called for EP0-out, which always happens first, and which
505  * should only happen in one of the above conditions.
506  */
507 static int dwc3_gadget_start_config(struct dwc3_ep *dep)
508 {
509 	struct dwc3_gadget_ep_cmd_params params;
510 	struct dwc3		*dwc;
511 	u32			cmd;
512 	int			i;
513 	int			ret;
514 
515 	if (dep->number)
516 		return 0;
517 
518 	memset(&params, 0x00, sizeof(params));
519 	cmd = DWC3_DEPCMD_DEPSTARTCFG;
520 	dwc = dep->dwc;
521 
522 	ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
523 	if (ret)
524 		return ret;
525 
526 	for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
527 		struct dwc3_ep *dep = dwc->eps[i];
528 
529 		if (!dep)
530 			continue;
531 
532 		ret = dwc3_gadget_set_xfer_resource(dep);
533 		if (ret)
534 			return ret;
535 	}
536 
537 	return 0;
538 }
539 
540 static int dwc3_gadget_set_ep_config(struct dwc3_ep *dep, unsigned int action)
541 {
542 	const struct usb_ss_ep_comp_descriptor *comp_desc;
543 	const struct usb_endpoint_descriptor *desc;
544 	struct dwc3_gadget_ep_cmd_params params;
545 	struct dwc3 *dwc = dep->dwc;
546 
547 	comp_desc = dep->endpoint.comp_desc;
548 	desc = dep->endpoint.desc;
549 
550 	memset(&params, 0x00, sizeof(params));
551 
552 	params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc))
553 		| DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc));
554 
555 	/* Burst size is only needed in SuperSpeed mode */
556 	if (dwc->gadget.speed >= USB_SPEED_SUPER) {
557 		u32 burst = dep->endpoint.maxburst;
558 		params.param0 |= DWC3_DEPCFG_BURST_SIZE(burst - 1);
559 	}
560 
561 	params.param0 |= action;
562 	if (action == DWC3_DEPCFG_ACTION_RESTORE)
563 		params.param2 |= dep->saved_state;
564 
565 	if (usb_endpoint_xfer_control(desc))
566 		params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN;
567 
568 	if (dep->number <= 1 || usb_endpoint_xfer_isoc(desc))
569 		params.param1 |= DWC3_DEPCFG_XFER_NOT_READY_EN;
570 
571 	if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) {
572 		params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE
573 			| DWC3_DEPCFG_STREAM_EVENT_EN;
574 		dep->stream_capable = true;
575 	}
576 
577 	if (!usb_endpoint_xfer_control(desc))
578 		params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN;
579 
580 	/*
581 	 * We are doing 1:1 mapping for endpoints, meaning
582 	 * Physical Endpoints 2 maps to Logical Endpoint 2 and
583 	 * so on. We consider the direction bit as part of the physical
584 	 * endpoint number. So USB endpoint 0x81 is 0x03.
585 	 */
586 	params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number);
587 
588 	/*
589 	 * We must use the lower 16 TX FIFOs even though
590 	 * HW might have more
591 	 */
592 	if (dep->direction)
593 		params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1);
594 
595 	if (desc->bInterval) {
596 		params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(desc->bInterval - 1);
597 		dep->interval = 1 << (desc->bInterval - 1);
598 	}
599 
600 	return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETEPCONFIG, &params);
601 }
602 
603 /**
604  * __dwc3_gadget_ep_enable - initializes a hw endpoint
605  * @dep: endpoint to be initialized
606  * @action: one of INIT, MODIFY or RESTORE
607  *
608  * Caller should take care of locking. Execute all necessary commands to
609  * initialize a HW endpoint so it can be used by a gadget driver.
610  */
611 static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action)
612 {
613 	const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
614 	struct dwc3		*dwc = dep->dwc;
615 
616 	u32			reg;
617 	int			ret;
618 
619 	if (!(dep->flags & DWC3_EP_ENABLED)) {
620 		ret = dwc3_gadget_start_config(dep);
621 		if (ret)
622 			return ret;
623 	}
624 
625 	ret = dwc3_gadget_set_ep_config(dep, action);
626 	if (ret)
627 		return ret;
628 
629 	if (!(dep->flags & DWC3_EP_ENABLED)) {
630 		struct dwc3_trb	*trb_st_hw;
631 		struct dwc3_trb	*trb_link;
632 
633 		dep->type = usb_endpoint_type(desc);
634 		dep->flags |= DWC3_EP_ENABLED;
635 		dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
636 
637 		reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
638 		reg |= DWC3_DALEPENA_EP(dep->number);
639 		dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
640 
641 		init_waitqueue_head(&dep->wait_end_transfer);
642 
643 		if (usb_endpoint_xfer_control(desc))
644 			goto out;
645 
646 		/* Initialize the TRB ring */
647 		dep->trb_dequeue = 0;
648 		dep->trb_enqueue = 0;
649 		memset(dep->trb_pool, 0,
650 		       sizeof(struct dwc3_trb) * DWC3_TRB_NUM);
651 
652 		/* Link TRB. The HWO bit is never reset */
653 		trb_st_hw = &dep->trb_pool[0];
654 
655 		trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
656 		trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
657 		trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
658 		trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
659 		trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
660 	}
661 
662 	/*
663 	 * Issue StartTransfer here with no-op TRB so we can always rely on No
664 	 * Response Update Transfer command.
665 	 */
666 	if (usb_endpoint_xfer_bulk(desc) ||
667 			usb_endpoint_xfer_int(desc)) {
668 		struct dwc3_gadget_ep_cmd_params params;
669 		struct dwc3_trb	*trb;
670 		dma_addr_t trb_dma;
671 		u32 cmd;
672 
673 		memset(&params, 0, sizeof(params));
674 		trb = &dep->trb_pool[0];
675 		trb_dma = dwc3_trb_dma_offset(dep, trb);
676 
677 		params.param0 = upper_32_bits(trb_dma);
678 		params.param1 = lower_32_bits(trb_dma);
679 
680 		cmd = DWC3_DEPCMD_STARTTRANSFER;
681 
682 		ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
683 		if (ret < 0)
684 			return ret;
685 	}
686 
687 out:
688 	trace_dwc3_gadget_ep_enable(dep);
689 
690 	return 0;
691 }
692 
693 static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force);
694 static void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep)
695 {
696 	struct dwc3_request		*req;
697 
698 	dwc3_stop_active_transfer(dep, true);
699 
700 	/* - giveback all requests to gadget driver */
701 	while (!list_empty(&dep->started_list)) {
702 		req = next_request(&dep->started_list);
703 
704 		dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
705 	}
706 
707 	while (!list_empty(&dep->pending_list)) {
708 		req = next_request(&dep->pending_list);
709 
710 		dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
711 	}
712 }
713 
714 /**
715  * __dwc3_gadget_ep_disable - disables a hw endpoint
716  * @dep: the endpoint to disable
717  *
718  * This function undoes what __dwc3_gadget_ep_enable did and also removes
719  * requests which are currently being processed by the hardware and those which
720  * are not yet scheduled.
721  *
722  * Caller should take care of locking.
723  */
724 static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
725 {
726 	struct dwc3		*dwc = dep->dwc;
727 	u32			reg;
728 
729 	trace_dwc3_gadget_ep_disable(dep);
730 
731 	dwc3_remove_requests(dwc, dep);
732 
733 	/* make sure HW endpoint isn't stalled */
734 	if (dep->flags & DWC3_EP_STALL)
735 		__dwc3_gadget_ep_set_halt(dep, 0, false);
736 
737 	reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
738 	reg &= ~DWC3_DALEPENA_EP(dep->number);
739 	dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
740 
741 	dep->stream_capable = false;
742 	dep->type = 0;
743 	dep->flags &= DWC3_EP_END_TRANSFER_PENDING;
744 
745 	/* Clear out the ep descriptors for non-ep0 */
746 	if (dep->number > 1) {
747 		dep->endpoint.comp_desc = NULL;
748 		dep->endpoint.desc = NULL;
749 	}
750 
751 	return 0;
752 }
753 
754 /* -------------------------------------------------------------------------- */
755 
756 static int dwc3_gadget_ep0_enable(struct usb_ep *ep,
757 		const struct usb_endpoint_descriptor *desc)
758 {
759 	return -EINVAL;
760 }
761 
762 static int dwc3_gadget_ep0_disable(struct usb_ep *ep)
763 {
764 	return -EINVAL;
765 }
766 
767 /* -------------------------------------------------------------------------- */
768 
769 static int dwc3_gadget_ep_enable(struct usb_ep *ep,
770 		const struct usb_endpoint_descriptor *desc)
771 {
772 	struct dwc3_ep			*dep;
773 	struct dwc3			*dwc;
774 	unsigned long			flags;
775 	int				ret;
776 
777 	if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
778 		pr_debug("dwc3: invalid parameters\n");
779 		return -EINVAL;
780 	}
781 
782 	if (!desc->wMaxPacketSize) {
783 		pr_debug("dwc3: missing wMaxPacketSize\n");
784 		return -EINVAL;
785 	}
786 
787 	dep = to_dwc3_ep(ep);
788 	dwc = dep->dwc;
789 
790 	if (dev_WARN_ONCE(dwc->dev, dep->flags & DWC3_EP_ENABLED,
791 					"%s is already enabled\n",
792 					dep->name))
793 		return 0;
794 
795 	spin_lock_irqsave(&dwc->lock, flags);
796 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
797 	spin_unlock_irqrestore(&dwc->lock, flags);
798 
799 	return ret;
800 }
801 
802 static int dwc3_gadget_ep_disable(struct usb_ep *ep)
803 {
804 	struct dwc3_ep			*dep;
805 	struct dwc3			*dwc;
806 	unsigned long			flags;
807 	int				ret;
808 
809 	if (!ep) {
810 		pr_debug("dwc3: invalid parameters\n");
811 		return -EINVAL;
812 	}
813 
814 	dep = to_dwc3_ep(ep);
815 	dwc = dep->dwc;
816 
817 	if (dev_WARN_ONCE(dwc->dev, !(dep->flags & DWC3_EP_ENABLED),
818 					"%s is already disabled\n",
819 					dep->name))
820 		return 0;
821 
822 	spin_lock_irqsave(&dwc->lock, flags);
823 	ret = __dwc3_gadget_ep_disable(dep);
824 	spin_unlock_irqrestore(&dwc->lock, flags);
825 
826 	return ret;
827 }
828 
829 static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep,
830 		gfp_t gfp_flags)
831 {
832 	struct dwc3_request		*req;
833 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
834 
835 	req = kzalloc(sizeof(*req), gfp_flags);
836 	if (!req)
837 		return NULL;
838 
839 	req->direction	= dep->direction;
840 	req->epnum	= dep->number;
841 	req->dep	= dep;
842 
843 	trace_dwc3_alloc_request(req);
844 
845 	return &req->request;
846 }
847 
848 static void dwc3_gadget_ep_free_request(struct usb_ep *ep,
849 		struct usb_request *request)
850 {
851 	struct dwc3_request		*req = to_dwc3_request(request);
852 
853 	trace_dwc3_free_request(req);
854 	kfree(req);
855 }
856 
857 /**
858  * dwc3_ep_prev_trb - returns the previous TRB in the ring
859  * @dep: The endpoint with the TRB ring
860  * @index: The index of the current TRB in the ring
861  *
862  * Returns the TRB prior to the one pointed to by the index. If the
863  * index is 0, we will wrap backwards, skip the link TRB, and return
864  * the one just before that.
865  */
866 static struct dwc3_trb *dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index)
867 {
868 	u8 tmp = index;
869 
870 	if (!tmp)
871 		tmp = DWC3_TRB_NUM - 1;
872 
873 	return &dep->trb_pool[tmp - 1];
874 }
875 
876 static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep)
877 {
878 	struct dwc3_trb		*tmp;
879 	u8			trbs_left;
880 
881 	/*
882 	 * If enqueue & dequeue are equal than it is either full or empty.
883 	 *
884 	 * One way to know for sure is if the TRB right before us has HWO bit
885 	 * set or not. If it has, then we're definitely full and can't fit any
886 	 * more transfers in our ring.
887 	 */
888 	if (dep->trb_enqueue == dep->trb_dequeue) {
889 		tmp = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
890 		if (tmp->ctrl & DWC3_TRB_CTRL_HWO)
891 			return 0;
892 
893 		return DWC3_TRB_NUM - 1;
894 	}
895 
896 	trbs_left = dep->trb_dequeue - dep->trb_enqueue;
897 	trbs_left &= (DWC3_TRB_NUM - 1);
898 
899 	if (dep->trb_dequeue < dep->trb_enqueue)
900 		trbs_left--;
901 
902 	return trbs_left;
903 }
904 
905 static void __dwc3_prepare_one_trb(struct dwc3_ep *dep, struct dwc3_trb *trb,
906 		dma_addr_t dma, unsigned length, unsigned chain, unsigned node,
907 		unsigned stream_id, unsigned short_not_ok, unsigned no_interrupt)
908 {
909 	struct dwc3		*dwc = dep->dwc;
910 	struct usb_gadget	*gadget = &dwc->gadget;
911 	enum usb_device_speed	speed = gadget->speed;
912 
913 	dwc3_ep_inc_enq(dep);
914 
915 	trb->size = DWC3_TRB_SIZE_LENGTH(length);
916 	trb->bpl = lower_32_bits(dma);
917 	trb->bph = upper_32_bits(dma);
918 
919 	switch (usb_endpoint_type(dep->endpoint.desc)) {
920 	case USB_ENDPOINT_XFER_CONTROL:
921 		trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP;
922 		break;
923 
924 	case USB_ENDPOINT_XFER_ISOC:
925 		if (!node) {
926 			trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST;
927 
928 			/*
929 			 * USB Specification 2.0 Section 5.9.2 states that: "If
930 			 * there is only a single transaction in the microframe,
931 			 * only a DATA0 data packet PID is used.  If there are
932 			 * two transactions per microframe, DATA1 is used for
933 			 * the first transaction data packet and DATA0 is used
934 			 * for the second transaction data packet.  If there are
935 			 * three transactions per microframe, DATA2 is used for
936 			 * the first transaction data packet, DATA1 is used for
937 			 * the second, and DATA0 is used for the third."
938 			 *
939 			 * IOW, we should satisfy the following cases:
940 			 *
941 			 * 1) length <= maxpacket
942 			 *	- DATA0
943 			 *
944 			 * 2) maxpacket < length <= (2 * maxpacket)
945 			 *	- DATA1, DATA0
946 			 *
947 			 * 3) (2 * maxpacket) < length <= (3 * maxpacket)
948 			 *	- DATA2, DATA1, DATA0
949 			 */
950 			if (speed == USB_SPEED_HIGH) {
951 				struct usb_ep *ep = &dep->endpoint;
952 				unsigned int mult = 2;
953 				unsigned int maxp = usb_endpoint_maxp(ep->desc);
954 
955 				if (length <= (2 * maxp))
956 					mult--;
957 
958 				if (length <= maxp)
959 					mult--;
960 
961 				trb->size |= DWC3_TRB_SIZE_PCM1(mult);
962 			}
963 		} else {
964 			trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS;
965 		}
966 
967 		/* always enable Interrupt on Missed ISOC */
968 		trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
969 		break;
970 
971 	case USB_ENDPOINT_XFER_BULK:
972 	case USB_ENDPOINT_XFER_INT:
973 		trb->ctrl = DWC3_TRBCTL_NORMAL;
974 		break;
975 	default:
976 		/*
977 		 * This is only possible with faulty memory because we
978 		 * checked it already :)
979 		 */
980 		dev_WARN(dwc->dev, "Unknown endpoint type %d\n",
981 				usb_endpoint_type(dep->endpoint.desc));
982 	}
983 
984 	/* always enable Continue on Short Packet */
985 	if (usb_endpoint_dir_out(dep->endpoint.desc)) {
986 		trb->ctrl |= DWC3_TRB_CTRL_CSP;
987 
988 		if (short_not_ok)
989 			trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
990 	}
991 
992 	if ((!no_interrupt && !chain) ||
993 			(dwc3_calc_trbs_left(dep) == 0))
994 		trb->ctrl |= DWC3_TRB_CTRL_IOC;
995 
996 	if (chain)
997 		trb->ctrl |= DWC3_TRB_CTRL_CHN;
998 
999 	if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable)
1000 		trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(stream_id);
1001 
1002 	trb->ctrl |= DWC3_TRB_CTRL_HWO;
1003 
1004 	trace_dwc3_prepare_trb(dep, trb);
1005 }
1006 
1007 /**
1008  * dwc3_prepare_one_trb - setup one TRB from one request
1009  * @dep: endpoint for which this request is prepared
1010  * @req: dwc3_request pointer
1011  * @chain: should this TRB be chained to the next?
1012  * @node: only for isochronous endpoints. First TRB needs different type.
1013  */
1014 static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
1015 		struct dwc3_request *req, unsigned chain, unsigned node)
1016 {
1017 	struct dwc3_trb		*trb;
1018 	unsigned int		length;
1019 	dma_addr_t		dma;
1020 	unsigned		stream_id = req->request.stream_id;
1021 	unsigned		short_not_ok = req->request.short_not_ok;
1022 	unsigned		no_interrupt = req->request.no_interrupt;
1023 
1024 	if (req->request.num_sgs > 0) {
1025 		length = sg_dma_len(req->start_sg);
1026 		dma = sg_dma_address(req->start_sg);
1027 	} else {
1028 		length = req->request.length;
1029 		dma = req->request.dma;
1030 	}
1031 
1032 	trb = &dep->trb_pool[dep->trb_enqueue];
1033 
1034 	if (!req->trb) {
1035 		dwc3_gadget_move_started_request(req);
1036 		req->trb = trb;
1037 		req->trb_dma = dwc3_trb_dma_offset(dep, trb);
1038 	}
1039 
1040 	__dwc3_prepare_one_trb(dep, trb, dma, length, chain, node,
1041 			stream_id, short_not_ok, no_interrupt);
1042 }
1043 
1044 static void dwc3_prepare_one_trb_sg(struct dwc3_ep *dep,
1045 		struct dwc3_request *req)
1046 {
1047 	struct scatterlist *sg = req->start_sg;
1048 	struct scatterlist *s;
1049 	int		i;
1050 
1051 	unsigned int remaining = req->request.num_mapped_sgs
1052 		- req->num_queued_sgs;
1053 
1054 	for_each_sg(sg, s, remaining, i) {
1055 		unsigned int length = req->request.length;
1056 		unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1057 		unsigned int rem = length % maxp;
1058 		unsigned chain = true;
1059 
1060 		if (sg_is_last(s))
1061 			chain = false;
1062 
1063 		if (rem && usb_endpoint_dir_out(dep->endpoint.desc) && !chain) {
1064 			struct dwc3	*dwc = dep->dwc;
1065 			struct dwc3_trb	*trb;
1066 
1067 			req->unaligned = true;
1068 
1069 			/* prepare normal TRB */
1070 			dwc3_prepare_one_trb(dep, req, true, i);
1071 
1072 			/* Now prepare one extra TRB to align transfer size */
1073 			trb = &dep->trb_pool[dep->trb_enqueue];
1074 			__dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr,
1075 					maxp - rem, false, 0,
1076 					req->request.stream_id,
1077 					req->request.short_not_ok,
1078 					req->request.no_interrupt);
1079 		} else {
1080 			dwc3_prepare_one_trb(dep, req, chain, i);
1081 		}
1082 
1083 		/*
1084 		 * There can be a situation where all sgs in sglist are not
1085 		 * queued because of insufficient trb number. To handle this
1086 		 * case, update start_sg to next sg to be queued, so that
1087 		 * we have free trbs we can continue queuing from where we
1088 		 * previously stopped
1089 		 */
1090 		if (chain)
1091 			req->start_sg = sg_next(s);
1092 
1093 		req->num_queued_sgs++;
1094 
1095 		if (!dwc3_calc_trbs_left(dep))
1096 			break;
1097 	}
1098 }
1099 
1100 static void dwc3_prepare_one_trb_linear(struct dwc3_ep *dep,
1101 		struct dwc3_request *req)
1102 {
1103 	unsigned int length = req->request.length;
1104 	unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1105 	unsigned int rem = length % maxp;
1106 
1107 	if (rem && usb_endpoint_dir_out(dep->endpoint.desc)) {
1108 		struct dwc3	*dwc = dep->dwc;
1109 		struct dwc3_trb	*trb;
1110 
1111 		req->unaligned = true;
1112 
1113 		/* prepare normal TRB */
1114 		dwc3_prepare_one_trb(dep, req, true, 0);
1115 
1116 		/* Now prepare one extra TRB to align transfer size */
1117 		trb = &dep->trb_pool[dep->trb_enqueue];
1118 		__dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr, maxp - rem,
1119 				false, 0, req->request.stream_id,
1120 				req->request.short_not_ok,
1121 				req->request.no_interrupt);
1122 	} else if (req->request.zero && req->request.length &&
1123 		   (IS_ALIGNED(req->request.length, maxp))) {
1124 		struct dwc3	*dwc = dep->dwc;
1125 		struct dwc3_trb	*trb;
1126 
1127 		req->zero = true;
1128 
1129 		/* prepare normal TRB */
1130 		dwc3_prepare_one_trb(dep, req, true, 0);
1131 
1132 		/* Now prepare one extra TRB to handle ZLP */
1133 		trb = &dep->trb_pool[dep->trb_enqueue];
1134 		__dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr, 0,
1135 				false, 0, req->request.stream_id,
1136 				req->request.short_not_ok,
1137 				req->request.no_interrupt);
1138 	} else {
1139 		dwc3_prepare_one_trb(dep, req, false, 0);
1140 	}
1141 }
1142 
1143 /*
1144  * dwc3_prepare_trbs - setup TRBs from requests
1145  * @dep: endpoint for which requests are being prepared
1146  *
1147  * The function goes through the requests list and sets up TRBs for the
1148  * transfers. The function returns once there are no more TRBs available or
1149  * it runs out of requests.
1150  */
1151 static void dwc3_prepare_trbs(struct dwc3_ep *dep)
1152 {
1153 	struct dwc3_request	*req, *n;
1154 
1155 	BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
1156 
1157 	/*
1158 	 * We can get in a situation where there's a request in the started list
1159 	 * but there weren't enough TRBs to fully kick it in the first time
1160 	 * around, so it has been waiting for more TRBs to be freed up.
1161 	 *
1162 	 * In that case, we should check if we have a request with pending_sgs
1163 	 * in the started list and prepare TRBs for that request first,
1164 	 * otherwise we will prepare TRBs completely out of order and that will
1165 	 * break things.
1166 	 */
1167 	list_for_each_entry(req, &dep->started_list, list) {
1168 		if (req->num_pending_sgs > 0)
1169 			dwc3_prepare_one_trb_sg(dep, req);
1170 
1171 		if (!dwc3_calc_trbs_left(dep))
1172 			return;
1173 	}
1174 
1175 	list_for_each_entry_safe(req, n, &dep->pending_list, list) {
1176 		struct dwc3	*dwc = dep->dwc;
1177 		int		ret;
1178 
1179 		ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request,
1180 						    dep->direction);
1181 		if (ret)
1182 			return;
1183 
1184 		req->sg			= req->request.sg;
1185 		req->start_sg		= req->sg;
1186 		req->num_queued_sgs	= 0;
1187 		req->num_pending_sgs	= req->request.num_mapped_sgs;
1188 
1189 		if (req->num_pending_sgs > 0)
1190 			dwc3_prepare_one_trb_sg(dep, req);
1191 		else
1192 			dwc3_prepare_one_trb_linear(dep, req);
1193 
1194 		if (!dwc3_calc_trbs_left(dep))
1195 			return;
1196 	}
1197 }
1198 
1199 static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep)
1200 {
1201 	struct dwc3_gadget_ep_cmd_params params;
1202 	struct dwc3_request		*req;
1203 	int				starting;
1204 	int				ret;
1205 	u32				cmd;
1206 
1207 	if (!dwc3_calc_trbs_left(dep))
1208 		return 0;
1209 
1210 	starting = !(dep->flags & DWC3_EP_TRANSFER_STARTED);
1211 
1212 	dwc3_prepare_trbs(dep);
1213 	req = next_request(&dep->started_list);
1214 	if (!req) {
1215 		dep->flags |= DWC3_EP_PENDING_REQUEST;
1216 		return 0;
1217 	}
1218 
1219 	memset(&params, 0, sizeof(params));
1220 
1221 	if (starting) {
1222 		params.param0 = upper_32_bits(req->trb_dma);
1223 		params.param1 = lower_32_bits(req->trb_dma);
1224 		cmd = DWC3_DEPCMD_STARTTRANSFER;
1225 
1226 		if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
1227 			cmd |= DWC3_DEPCMD_PARAM(dep->frame_number);
1228 	} else {
1229 		cmd = DWC3_DEPCMD_UPDATETRANSFER |
1230 			DWC3_DEPCMD_PARAM(dep->resource_index);
1231 	}
1232 
1233 	ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1234 	if (ret < 0) {
1235 		/*
1236 		 * FIXME we need to iterate over the list of requests
1237 		 * here and stop, unmap, free and del each of the linked
1238 		 * requests instead of what we do now.
1239 		 */
1240 		if (req->trb)
1241 			memset(req->trb, 0, sizeof(struct dwc3_trb));
1242 		dwc3_gadget_del_and_unmap_request(dep, req, ret);
1243 		return ret;
1244 	}
1245 
1246 	return 0;
1247 }
1248 
1249 static int __dwc3_gadget_get_frame(struct dwc3 *dwc)
1250 {
1251 	u32			reg;
1252 
1253 	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1254 	return DWC3_DSTS_SOFFN(reg);
1255 }
1256 
1257 static void __dwc3_gadget_start_isoc(struct dwc3_ep *dep)
1258 {
1259 	if (list_empty(&dep->pending_list)) {
1260 		dev_info(dep->dwc->dev, "%s: ran out of requests\n",
1261 				dep->name);
1262 		dep->flags |= DWC3_EP_PENDING_REQUEST;
1263 		return;
1264 	}
1265 
1266 	dep->frame_number = DWC3_ALIGN_FRAME(dep);
1267 	__dwc3_gadget_kick_transfer(dep);
1268 }
1269 
1270 static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
1271 {
1272 	struct dwc3		*dwc = dep->dwc;
1273 
1274 	if (!dep->endpoint.desc) {
1275 		dev_err(dwc->dev, "%s: can't queue to disabled endpoint\n",
1276 				dep->name);
1277 		return -ESHUTDOWN;
1278 	}
1279 
1280 	if (WARN(req->dep != dep, "request %pK belongs to '%s'\n",
1281 				&req->request, req->dep->name))
1282 		return -EINVAL;
1283 
1284 	pm_runtime_get(dwc->dev);
1285 
1286 	req->request.actual	= 0;
1287 	req->request.status	= -EINPROGRESS;
1288 
1289 	trace_dwc3_ep_queue(req);
1290 
1291 	list_add_tail(&req->list, &dep->pending_list);
1292 
1293 	/*
1294 	 * NOTICE: Isochronous endpoints should NEVER be prestarted. We must
1295 	 * wait for a XferNotReady event so we will know what's the current
1296 	 * (micro-)frame number.
1297 	 *
1298 	 * Without this trick, we are very, very likely gonna get Bus Expiry
1299 	 * errors which will force us issue EndTransfer command.
1300 	 */
1301 	if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1302 		if (!(dep->flags & DWC3_EP_PENDING_REQUEST) &&
1303 				!(dep->flags & DWC3_EP_TRANSFER_STARTED))
1304 			return 0;
1305 
1306 		if ((dep->flags & DWC3_EP_PENDING_REQUEST)) {
1307 			if (!(dep->flags & DWC3_EP_TRANSFER_STARTED)) {
1308 				__dwc3_gadget_start_isoc(dep);
1309 				return 0;
1310 			}
1311 		}
1312 	}
1313 
1314 	return __dwc3_gadget_kick_transfer(dep);
1315 }
1316 
1317 static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
1318 	gfp_t gfp_flags)
1319 {
1320 	struct dwc3_request		*req = to_dwc3_request(request);
1321 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1322 	struct dwc3			*dwc = dep->dwc;
1323 
1324 	unsigned long			flags;
1325 
1326 	int				ret;
1327 
1328 	spin_lock_irqsave(&dwc->lock, flags);
1329 	ret = __dwc3_gadget_ep_queue(dep, req);
1330 	spin_unlock_irqrestore(&dwc->lock, flags);
1331 
1332 	return ret;
1333 }
1334 
1335 static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
1336 		struct usb_request *request)
1337 {
1338 	struct dwc3_request		*req = to_dwc3_request(request);
1339 	struct dwc3_request		*r = NULL;
1340 
1341 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1342 	struct dwc3			*dwc = dep->dwc;
1343 
1344 	unsigned long			flags;
1345 	int				ret = 0;
1346 
1347 	trace_dwc3_ep_dequeue(req);
1348 
1349 	spin_lock_irqsave(&dwc->lock, flags);
1350 
1351 	list_for_each_entry(r, &dep->pending_list, list) {
1352 		if (r == req)
1353 			break;
1354 	}
1355 
1356 	if (r != req) {
1357 		list_for_each_entry(r, &dep->started_list, list) {
1358 			if (r == req)
1359 				break;
1360 		}
1361 		if (r == req) {
1362 			/* wait until it is processed */
1363 			dwc3_stop_active_transfer(dep, true);
1364 
1365 			/*
1366 			 * If request was already started, this means we had to
1367 			 * stop the transfer. With that we also need to ignore
1368 			 * all TRBs used by the request, however TRBs can only
1369 			 * be modified after completion of END_TRANSFER
1370 			 * command. So what we do here is that we wait for
1371 			 * END_TRANSFER completion and only after that, we jump
1372 			 * over TRBs by clearing HWO and incrementing dequeue
1373 			 * pointer.
1374 			 *
1375 			 * Note that we have 2 possible types of transfers here:
1376 			 *
1377 			 * i) Linear buffer request
1378 			 * ii) SG-list based request
1379 			 *
1380 			 * SG-list based requests will have r->num_pending_sgs
1381 			 * set to a valid number (> 0). Linear requests,
1382 			 * normally use a single TRB.
1383 			 *
1384 			 * For each of these two cases, if r->unaligned flag is
1385 			 * set, one extra TRB has been used to align transfer
1386 			 * size to wMaxPacketSize.
1387 			 *
1388 			 * All of these cases need to be taken into
1389 			 * consideration so we don't mess up our TRB ring
1390 			 * pointers.
1391 			 */
1392 			wait_event_lock_irq(dep->wait_end_transfer,
1393 					!(dep->flags & DWC3_EP_END_TRANSFER_PENDING),
1394 					dwc->lock);
1395 
1396 			if (!r->trb)
1397 				goto out0;
1398 
1399 			if (r->num_pending_sgs) {
1400 				struct dwc3_trb *trb;
1401 				int i = 0;
1402 
1403 				for (i = 0; i < r->num_pending_sgs; i++) {
1404 					trb = r->trb + i;
1405 					trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1406 					dwc3_ep_inc_deq(dep);
1407 				}
1408 
1409 				if (r->unaligned || r->zero) {
1410 					trb = r->trb + r->num_pending_sgs + 1;
1411 					trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1412 					dwc3_ep_inc_deq(dep);
1413 				}
1414 			} else {
1415 				struct dwc3_trb *trb = r->trb;
1416 
1417 				trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1418 				dwc3_ep_inc_deq(dep);
1419 
1420 				if (r->unaligned || r->zero) {
1421 					trb = r->trb + 1;
1422 					trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1423 					dwc3_ep_inc_deq(dep);
1424 				}
1425 			}
1426 			goto out1;
1427 		}
1428 		dev_err(dwc->dev, "request %pK was not queued to %s\n",
1429 				request, ep->name);
1430 		ret = -EINVAL;
1431 		goto out0;
1432 	}
1433 
1434 out1:
1435 	/* giveback the request */
1436 
1437 	dwc3_gadget_giveback(dep, req, -ECONNRESET);
1438 
1439 out0:
1440 	spin_unlock_irqrestore(&dwc->lock, flags);
1441 
1442 	return ret;
1443 }
1444 
1445 int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
1446 {
1447 	struct dwc3_gadget_ep_cmd_params	params;
1448 	struct dwc3				*dwc = dep->dwc;
1449 	int					ret;
1450 
1451 	if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1452 		dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
1453 		return -EINVAL;
1454 	}
1455 
1456 	memset(&params, 0x00, sizeof(params));
1457 
1458 	if (value) {
1459 		struct dwc3_trb *trb;
1460 
1461 		unsigned transfer_in_flight;
1462 		unsigned started;
1463 
1464 		if (dep->flags & DWC3_EP_STALL)
1465 			return 0;
1466 
1467 		if (dep->number > 1)
1468 			trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
1469 		else
1470 			trb = &dwc->ep0_trb[dep->trb_enqueue];
1471 
1472 		transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO;
1473 		started = !list_empty(&dep->started_list);
1474 
1475 		if (!protocol && ((dep->direction && transfer_in_flight) ||
1476 				(!dep->direction && started))) {
1477 			return -EAGAIN;
1478 		}
1479 
1480 		ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL,
1481 				&params);
1482 		if (ret)
1483 			dev_err(dwc->dev, "failed to set STALL on %s\n",
1484 					dep->name);
1485 		else
1486 			dep->flags |= DWC3_EP_STALL;
1487 	} else {
1488 		if (!(dep->flags & DWC3_EP_STALL))
1489 			return 0;
1490 
1491 		ret = dwc3_send_clear_stall_ep_cmd(dep);
1492 		if (ret)
1493 			dev_err(dwc->dev, "failed to clear STALL on %s\n",
1494 					dep->name);
1495 		else
1496 			dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
1497 	}
1498 
1499 	return ret;
1500 }
1501 
1502 static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
1503 {
1504 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1505 	struct dwc3			*dwc = dep->dwc;
1506 
1507 	unsigned long			flags;
1508 
1509 	int				ret;
1510 
1511 	spin_lock_irqsave(&dwc->lock, flags);
1512 	ret = __dwc3_gadget_ep_set_halt(dep, value, false);
1513 	spin_unlock_irqrestore(&dwc->lock, flags);
1514 
1515 	return ret;
1516 }
1517 
1518 static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
1519 {
1520 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1521 	struct dwc3			*dwc = dep->dwc;
1522 	unsigned long			flags;
1523 	int				ret;
1524 
1525 	spin_lock_irqsave(&dwc->lock, flags);
1526 	dep->flags |= DWC3_EP_WEDGE;
1527 
1528 	if (dep->number == 0 || dep->number == 1)
1529 		ret = __dwc3_gadget_ep0_set_halt(ep, 1);
1530 	else
1531 		ret = __dwc3_gadget_ep_set_halt(dep, 1, false);
1532 	spin_unlock_irqrestore(&dwc->lock, flags);
1533 
1534 	return ret;
1535 }
1536 
1537 /* -------------------------------------------------------------------------- */
1538 
1539 static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
1540 	.bLength	= USB_DT_ENDPOINT_SIZE,
1541 	.bDescriptorType = USB_DT_ENDPOINT,
1542 	.bmAttributes	= USB_ENDPOINT_XFER_CONTROL,
1543 };
1544 
1545 static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
1546 	.enable		= dwc3_gadget_ep0_enable,
1547 	.disable	= dwc3_gadget_ep0_disable,
1548 	.alloc_request	= dwc3_gadget_ep_alloc_request,
1549 	.free_request	= dwc3_gadget_ep_free_request,
1550 	.queue		= dwc3_gadget_ep0_queue,
1551 	.dequeue	= dwc3_gadget_ep_dequeue,
1552 	.set_halt	= dwc3_gadget_ep0_set_halt,
1553 	.set_wedge	= dwc3_gadget_ep_set_wedge,
1554 };
1555 
1556 static const struct usb_ep_ops dwc3_gadget_ep_ops = {
1557 	.enable		= dwc3_gadget_ep_enable,
1558 	.disable	= dwc3_gadget_ep_disable,
1559 	.alloc_request	= dwc3_gadget_ep_alloc_request,
1560 	.free_request	= dwc3_gadget_ep_free_request,
1561 	.queue		= dwc3_gadget_ep_queue,
1562 	.dequeue	= dwc3_gadget_ep_dequeue,
1563 	.set_halt	= dwc3_gadget_ep_set_halt,
1564 	.set_wedge	= dwc3_gadget_ep_set_wedge,
1565 };
1566 
1567 /* -------------------------------------------------------------------------- */
1568 
1569 static int dwc3_gadget_get_frame(struct usb_gadget *g)
1570 {
1571 	struct dwc3		*dwc = gadget_to_dwc(g);
1572 
1573 	return __dwc3_gadget_get_frame(dwc);
1574 }
1575 
1576 static int __dwc3_gadget_wakeup(struct dwc3 *dwc)
1577 {
1578 	int			retries;
1579 
1580 	int			ret;
1581 	u32			reg;
1582 
1583 	u8			link_state;
1584 	u8			speed;
1585 
1586 	/*
1587 	 * According to the Databook Remote wakeup request should
1588 	 * be issued only when the device is in early suspend state.
1589 	 *
1590 	 * We can check that via USB Link State bits in DSTS register.
1591 	 */
1592 	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1593 
1594 	speed = reg & DWC3_DSTS_CONNECTSPD;
1595 	if ((speed == DWC3_DSTS_SUPERSPEED) ||
1596 	    (speed == DWC3_DSTS_SUPERSPEED_PLUS))
1597 		return 0;
1598 
1599 	link_state = DWC3_DSTS_USBLNKST(reg);
1600 
1601 	switch (link_state) {
1602 	case DWC3_LINK_STATE_RX_DET:	/* in HS, means Early Suspend */
1603 	case DWC3_LINK_STATE_U3:	/* in HS, means SUSPEND */
1604 		break;
1605 	default:
1606 		return -EINVAL;
1607 	}
1608 
1609 	ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
1610 	if (ret < 0) {
1611 		dev_err(dwc->dev, "failed to put link in Recovery\n");
1612 		return ret;
1613 	}
1614 
1615 	/* Recent versions do this automatically */
1616 	if (dwc->revision < DWC3_REVISION_194A) {
1617 		/* write zeroes to Link Change Request */
1618 		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1619 		reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
1620 		dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1621 	}
1622 
1623 	/* poll until Link State changes to ON */
1624 	retries = 20000;
1625 
1626 	while (retries--) {
1627 		reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1628 
1629 		/* in HS, means ON */
1630 		if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
1631 			break;
1632 	}
1633 
1634 	if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
1635 		dev_err(dwc->dev, "failed to send remote wakeup\n");
1636 		return -EINVAL;
1637 	}
1638 
1639 	return 0;
1640 }
1641 
1642 static int dwc3_gadget_wakeup(struct usb_gadget *g)
1643 {
1644 	struct dwc3		*dwc = gadget_to_dwc(g);
1645 	unsigned long		flags;
1646 	int			ret;
1647 
1648 	spin_lock_irqsave(&dwc->lock, flags);
1649 	ret = __dwc3_gadget_wakeup(dwc);
1650 	spin_unlock_irqrestore(&dwc->lock, flags);
1651 
1652 	return ret;
1653 }
1654 
1655 static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
1656 		int is_selfpowered)
1657 {
1658 	struct dwc3		*dwc = gadget_to_dwc(g);
1659 	unsigned long		flags;
1660 
1661 	spin_lock_irqsave(&dwc->lock, flags);
1662 	g->is_selfpowered = !!is_selfpowered;
1663 	spin_unlock_irqrestore(&dwc->lock, flags);
1664 
1665 	return 0;
1666 }
1667 
1668 static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on, int suspend)
1669 {
1670 	u32			reg;
1671 	u32			timeout = 500;
1672 
1673 	if (pm_runtime_suspended(dwc->dev))
1674 		return 0;
1675 
1676 	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1677 	if (is_on) {
1678 		if (dwc->revision <= DWC3_REVISION_187A) {
1679 			reg &= ~DWC3_DCTL_TRGTULST_MASK;
1680 			reg |= DWC3_DCTL_TRGTULST_RX_DET;
1681 		}
1682 
1683 		if (dwc->revision >= DWC3_REVISION_194A)
1684 			reg &= ~DWC3_DCTL_KEEP_CONNECT;
1685 		reg |= DWC3_DCTL_RUN_STOP;
1686 
1687 		if (dwc->has_hibernation)
1688 			reg |= DWC3_DCTL_KEEP_CONNECT;
1689 
1690 		dwc->pullups_connected = true;
1691 	} else {
1692 		reg &= ~DWC3_DCTL_RUN_STOP;
1693 
1694 		if (dwc->has_hibernation && !suspend)
1695 			reg &= ~DWC3_DCTL_KEEP_CONNECT;
1696 
1697 		dwc->pullups_connected = false;
1698 	}
1699 
1700 	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1701 
1702 	do {
1703 		reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1704 		reg &= DWC3_DSTS_DEVCTRLHLT;
1705 	} while (--timeout && !(!is_on ^ !reg));
1706 
1707 	if (!timeout)
1708 		return -ETIMEDOUT;
1709 
1710 	return 0;
1711 }
1712 
1713 static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
1714 {
1715 	struct dwc3		*dwc = gadget_to_dwc(g);
1716 	unsigned long		flags;
1717 	int			ret;
1718 
1719 	is_on = !!is_on;
1720 
1721 	/*
1722 	 * Per databook, when we want to stop the gadget, if a control transfer
1723 	 * is still in process, complete it and get the core into setup phase.
1724 	 */
1725 	if (!is_on && dwc->ep0state != EP0_SETUP_PHASE) {
1726 		reinit_completion(&dwc->ep0_in_setup);
1727 
1728 		ret = wait_for_completion_timeout(&dwc->ep0_in_setup,
1729 				msecs_to_jiffies(DWC3_PULL_UP_TIMEOUT));
1730 		if (ret == 0) {
1731 			dev_err(dwc->dev, "timed out waiting for SETUP phase\n");
1732 			return -ETIMEDOUT;
1733 		}
1734 	}
1735 
1736 	spin_lock_irqsave(&dwc->lock, flags);
1737 	ret = dwc3_gadget_run_stop(dwc, is_on, false);
1738 	spin_unlock_irqrestore(&dwc->lock, flags);
1739 
1740 	return ret;
1741 }
1742 
1743 static void dwc3_gadget_enable_irq(struct dwc3 *dwc)
1744 {
1745 	u32			reg;
1746 
1747 	/* Enable all but Start and End of Frame IRQs */
1748 	reg = (DWC3_DEVTEN_VNDRDEVTSTRCVEDEN |
1749 			DWC3_DEVTEN_EVNTOVERFLOWEN |
1750 			DWC3_DEVTEN_CMDCMPLTEN |
1751 			DWC3_DEVTEN_ERRTICERREN |
1752 			DWC3_DEVTEN_WKUPEVTEN |
1753 			DWC3_DEVTEN_CONNECTDONEEN |
1754 			DWC3_DEVTEN_USBRSTEN |
1755 			DWC3_DEVTEN_DISCONNEVTEN);
1756 
1757 	if (dwc->revision < DWC3_REVISION_250A)
1758 		reg |= DWC3_DEVTEN_ULSTCNGEN;
1759 
1760 	dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
1761 }
1762 
1763 static void dwc3_gadget_disable_irq(struct dwc3 *dwc)
1764 {
1765 	/* mask all interrupts */
1766 	dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
1767 }
1768 
1769 static irqreturn_t dwc3_interrupt(int irq, void *_dwc);
1770 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc);
1771 
1772 /**
1773  * dwc3_gadget_setup_nump - calculate and initialize NUMP field of %DWC3_DCFG
1774  * @dwc: pointer to our context structure
1775  *
1776  * The following looks like complex but it's actually very simple. In order to
1777  * calculate the number of packets we can burst at once on OUT transfers, we're
1778  * gonna use RxFIFO size.
1779  *
1780  * To calculate RxFIFO size we need two numbers:
1781  * MDWIDTH = size, in bits, of the internal memory bus
1782  * RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)
1783  *
1784  * Given these two numbers, the formula is simple:
1785  *
1786  * RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;
1787  *
1788  * 24 bytes is for 3x SETUP packets
1789  * 16 bytes is a clock domain crossing tolerance
1790  *
1791  * Given RxFIFO Size, NUMP = RxFIFOSize / 1024;
1792  */
1793 static void dwc3_gadget_setup_nump(struct dwc3 *dwc)
1794 {
1795 	u32 ram2_depth;
1796 	u32 mdwidth;
1797 	u32 nump;
1798 	u32 reg;
1799 
1800 	ram2_depth = DWC3_GHWPARAMS7_RAM2_DEPTH(dwc->hwparams.hwparams7);
1801 	mdwidth = DWC3_GHWPARAMS0_MDWIDTH(dwc->hwparams.hwparams0);
1802 
1803 	nump = ((ram2_depth * mdwidth / 8) - 24 - 16) / 1024;
1804 	nump = min_t(u32, nump, 16);
1805 
1806 	/* update NumP */
1807 	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
1808 	reg &= ~DWC3_DCFG_NUMP_MASK;
1809 	reg |= nump << DWC3_DCFG_NUMP_SHIFT;
1810 	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
1811 }
1812 
1813 static int __dwc3_gadget_start(struct dwc3 *dwc)
1814 {
1815 	struct dwc3_ep		*dep;
1816 	int			ret = 0;
1817 	u32			reg;
1818 
1819 	/*
1820 	 * Use IMOD if enabled via dwc->imod_interval. Otherwise, if
1821 	 * the core supports IMOD, disable it.
1822 	 */
1823 	if (dwc->imod_interval) {
1824 		dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
1825 		dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
1826 	} else if (dwc3_has_imod(dwc)) {
1827 		dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), 0);
1828 	}
1829 
1830 	/*
1831 	 * We are telling dwc3 that we want to use DCFG.NUMP as ACK TP's NUMP
1832 	 * field instead of letting dwc3 itself calculate that automatically.
1833 	 *
1834 	 * This way, we maximize the chances that we'll be able to get several
1835 	 * bursts of data without going through any sort of endpoint throttling.
1836 	 */
1837 	reg = dwc3_readl(dwc->regs, DWC3_GRXTHRCFG);
1838 	if (dwc3_is_usb31(dwc))
1839 		reg &= ~DWC31_GRXTHRCFG_PKTCNTSEL;
1840 	else
1841 		reg &= ~DWC3_GRXTHRCFG_PKTCNTSEL;
1842 
1843 	dwc3_writel(dwc->regs, DWC3_GRXTHRCFG, reg);
1844 
1845 	dwc3_gadget_setup_nump(dwc);
1846 
1847 	/* Start with SuperSpeed Default */
1848 	dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
1849 
1850 	dep = dwc->eps[0];
1851 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
1852 	if (ret) {
1853 		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
1854 		goto err0;
1855 	}
1856 
1857 	dep = dwc->eps[1];
1858 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
1859 	if (ret) {
1860 		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
1861 		goto err1;
1862 	}
1863 
1864 	/* begin to receive SETUP packets */
1865 	dwc->ep0state = EP0_SETUP_PHASE;
1866 	dwc3_ep0_out_start(dwc);
1867 
1868 	dwc3_gadget_enable_irq(dwc);
1869 
1870 	return 0;
1871 
1872 err1:
1873 	__dwc3_gadget_ep_disable(dwc->eps[0]);
1874 
1875 err0:
1876 	return ret;
1877 }
1878 
1879 static int dwc3_gadget_start(struct usb_gadget *g,
1880 		struct usb_gadget_driver *driver)
1881 {
1882 	struct dwc3		*dwc = gadget_to_dwc(g);
1883 	unsigned long		flags;
1884 	int			ret = 0;
1885 	int			irq;
1886 
1887 	irq = dwc->irq_gadget;
1888 	ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt,
1889 			IRQF_SHARED, "dwc3", dwc->ev_buf);
1890 	if (ret) {
1891 		dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
1892 				irq, ret);
1893 		goto err0;
1894 	}
1895 
1896 	spin_lock_irqsave(&dwc->lock, flags);
1897 	if (dwc->gadget_driver) {
1898 		dev_err(dwc->dev, "%s is already bound to %s\n",
1899 				dwc->gadget.name,
1900 				dwc->gadget_driver->driver.name);
1901 		ret = -EBUSY;
1902 		goto err1;
1903 	}
1904 
1905 	dwc->gadget_driver	= driver;
1906 
1907 	if (pm_runtime_active(dwc->dev))
1908 		__dwc3_gadget_start(dwc);
1909 
1910 	spin_unlock_irqrestore(&dwc->lock, flags);
1911 
1912 	return 0;
1913 
1914 err1:
1915 	spin_unlock_irqrestore(&dwc->lock, flags);
1916 	free_irq(irq, dwc);
1917 
1918 err0:
1919 	return ret;
1920 }
1921 
1922 static void __dwc3_gadget_stop(struct dwc3 *dwc)
1923 {
1924 	dwc3_gadget_disable_irq(dwc);
1925 	__dwc3_gadget_ep_disable(dwc->eps[0]);
1926 	__dwc3_gadget_ep_disable(dwc->eps[1]);
1927 }
1928 
1929 static int dwc3_gadget_stop(struct usb_gadget *g)
1930 {
1931 	struct dwc3		*dwc = gadget_to_dwc(g);
1932 	unsigned long		flags;
1933 	int			epnum;
1934 	u32			tmo_eps = 0;
1935 
1936 	spin_lock_irqsave(&dwc->lock, flags);
1937 
1938 	if (pm_runtime_suspended(dwc->dev))
1939 		goto out;
1940 
1941 	__dwc3_gadget_stop(dwc);
1942 
1943 	for (epnum = 2; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
1944 		struct dwc3_ep  *dep = dwc->eps[epnum];
1945 		int ret;
1946 
1947 		if (!dep)
1948 			continue;
1949 
1950 		if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
1951 			continue;
1952 
1953 		ret = wait_event_interruptible_lock_irq_timeout(dep->wait_end_transfer,
1954 			    !(dep->flags & DWC3_EP_END_TRANSFER_PENDING),
1955 			    dwc->lock, msecs_to_jiffies(5));
1956 
1957 		if (ret <= 0) {
1958 			/* Timed out or interrupted! There's nothing much
1959 			 * we can do so we just log here and print which
1960 			 * endpoints timed out at the end.
1961 			 */
1962 			tmo_eps |= 1 << epnum;
1963 			dep->flags &= DWC3_EP_END_TRANSFER_PENDING;
1964 		}
1965 	}
1966 
1967 	if (tmo_eps) {
1968 		dev_err(dwc->dev,
1969 			"end transfer timed out on endpoints 0x%x [bitmap]\n",
1970 			tmo_eps);
1971 	}
1972 
1973 out:
1974 	dwc->gadget_driver	= NULL;
1975 	spin_unlock_irqrestore(&dwc->lock, flags);
1976 
1977 	free_irq(dwc->irq_gadget, dwc->ev_buf);
1978 
1979 	return 0;
1980 }
1981 
1982 static void dwc3_gadget_set_speed(struct usb_gadget *g,
1983 				  enum usb_device_speed speed)
1984 {
1985 	struct dwc3		*dwc = gadget_to_dwc(g);
1986 	unsigned long		flags;
1987 	u32			reg;
1988 
1989 	spin_lock_irqsave(&dwc->lock, flags);
1990 	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
1991 	reg &= ~(DWC3_DCFG_SPEED_MASK);
1992 
1993 	/*
1994 	 * WORKAROUND: DWC3 revision < 2.20a have an issue
1995 	 * which would cause metastability state on Run/Stop
1996 	 * bit if we try to force the IP to USB2-only mode.
1997 	 *
1998 	 * Because of that, we cannot configure the IP to any
1999 	 * speed other than the SuperSpeed
2000 	 *
2001 	 * Refers to:
2002 	 *
2003 	 * STAR#9000525659: Clock Domain Crossing on DCTL in
2004 	 * USB 2.0 Mode
2005 	 */
2006 	if (dwc->revision < DWC3_REVISION_220A &&
2007 	    !dwc->dis_metastability_quirk) {
2008 		reg |= DWC3_DCFG_SUPERSPEED;
2009 	} else {
2010 		switch (speed) {
2011 		case USB_SPEED_LOW:
2012 			reg |= DWC3_DCFG_LOWSPEED;
2013 			break;
2014 		case USB_SPEED_FULL:
2015 			reg |= DWC3_DCFG_FULLSPEED;
2016 			break;
2017 		case USB_SPEED_HIGH:
2018 			reg |= DWC3_DCFG_HIGHSPEED;
2019 			break;
2020 		case USB_SPEED_SUPER:
2021 			reg |= DWC3_DCFG_SUPERSPEED;
2022 			break;
2023 		case USB_SPEED_SUPER_PLUS:
2024 			if (dwc3_is_usb31(dwc))
2025 				reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2026 			else
2027 				reg |= DWC3_DCFG_SUPERSPEED;
2028 			break;
2029 		default:
2030 			dev_err(dwc->dev, "invalid speed (%d)\n", speed);
2031 
2032 			if (dwc->revision & DWC3_REVISION_IS_DWC31)
2033 				reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2034 			else
2035 				reg |= DWC3_DCFG_SUPERSPEED;
2036 		}
2037 	}
2038 	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2039 
2040 	spin_unlock_irqrestore(&dwc->lock, flags);
2041 }
2042 
2043 static const struct usb_gadget_ops dwc3_gadget_ops = {
2044 	.get_frame		= dwc3_gadget_get_frame,
2045 	.wakeup			= dwc3_gadget_wakeup,
2046 	.set_selfpowered	= dwc3_gadget_set_selfpowered,
2047 	.pullup			= dwc3_gadget_pullup,
2048 	.udc_start		= dwc3_gadget_start,
2049 	.udc_stop		= dwc3_gadget_stop,
2050 	.udc_set_speed		= dwc3_gadget_set_speed,
2051 };
2052 
2053 /* -------------------------------------------------------------------------- */
2054 
2055 static int dwc3_gadget_init_control_endpoint(struct dwc3_ep *dep)
2056 {
2057 	struct dwc3 *dwc = dep->dwc;
2058 
2059 	usb_ep_set_maxpacket_limit(&dep->endpoint, 512);
2060 	dep->endpoint.maxburst = 1;
2061 	dep->endpoint.ops = &dwc3_gadget_ep0_ops;
2062 	if (!dep->direction)
2063 		dwc->gadget.ep0 = &dep->endpoint;
2064 
2065 	dep->endpoint.caps.type_control = true;
2066 
2067 	return 0;
2068 }
2069 
2070 static int dwc3_gadget_init_in_endpoint(struct dwc3_ep *dep)
2071 {
2072 	struct dwc3 *dwc = dep->dwc;
2073 	int mdwidth;
2074 	int kbytes;
2075 	int size;
2076 
2077 	mdwidth = DWC3_MDWIDTH(dwc->hwparams.hwparams0);
2078 	/* MDWIDTH is represented in bits, we need it in bytes */
2079 	mdwidth /= 8;
2080 
2081 	size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1));
2082 	if (dwc3_is_usb31(dwc))
2083 		size = DWC31_GTXFIFOSIZ_TXFDEF(size);
2084 	else
2085 		size = DWC3_GTXFIFOSIZ_TXFDEF(size);
2086 
2087 	/* FIFO Depth is in MDWDITH bytes. Multiply */
2088 	size *= mdwidth;
2089 
2090 	kbytes = size / 1024;
2091 	if (kbytes == 0)
2092 		kbytes = 1;
2093 
2094 	/*
2095 	 * FIFO sizes account an extra MDWIDTH * (kbytes + 1) bytes for
2096 	 * internal overhead. We don't really know how these are used,
2097 	 * but documentation say it exists.
2098 	 */
2099 	size -= mdwidth * (kbytes + 1);
2100 	size /= kbytes;
2101 
2102 	usb_ep_set_maxpacket_limit(&dep->endpoint, size);
2103 
2104 	dep->endpoint.max_streams = 15;
2105 	dep->endpoint.ops = &dwc3_gadget_ep_ops;
2106 	list_add_tail(&dep->endpoint.ep_list,
2107 			&dwc->gadget.ep_list);
2108 	dep->endpoint.caps.type_iso = true;
2109 	dep->endpoint.caps.type_bulk = true;
2110 	dep->endpoint.caps.type_int = true;
2111 
2112 	return dwc3_alloc_trb_pool(dep);
2113 }
2114 
2115 static int dwc3_gadget_init_out_endpoint(struct dwc3_ep *dep)
2116 {
2117 	struct dwc3 *dwc = dep->dwc;
2118 
2119 	usb_ep_set_maxpacket_limit(&dep->endpoint, 1024);
2120 	dep->endpoint.max_streams = 15;
2121 	dep->endpoint.ops = &dwc3_gadget_ep_ops;
2122 	list_add_tail(&dep->endpoint.ep_list,
2123 			&dwc->gadget.ep_list);
2124 	dep->endpoint.caps.type_iso = true;
2125 	dep->endpoint.caps.type_bulk = true;
2126 	dep->endpoint.caps.type_int = true;
2127 
2128 	return dwc3_alloc_trb_pool(dep);
2129 }
2130 
2131 static int dwc3_gadget_init_endpoint(struct dwc3 *dwc, u8 epnum)
2132 {
2133 	struct dwc3_ep			*dep;
2134 	bool				direction = epnum & 1;
2135 	int				ret;
2136 	u8				num = epnum >> 1;
2137 
2138 	dep = kzalloc(sizeof(*dep), GFP_KERNEL);
2139 	if (!dep)
2140 		return -ENOMEM;
2141 
2142 	dep->dwc = dwc;
2143 	dep->number = epnum;
2144 	dep->direction = direction;
2145 	dep->regs = dwc->regs + DWC3_DEP_BASE(epnum);
2146 	dwc->eps[epnum] = dep;
2147 
2148 	snprintf(dep->name, sizeof(dep->name), "ep%u%s", num,
2149 			direction ? "in" : "out");
2150 
2151 	dep->endpoint.name = dep->name;
2152 
2153 	if (!(dep->number > 1)) {
2154 		dep->endpoint.desc = &dwc3_gadget_ep0_desc;
2155 		dep->endpoint.comp_desc = NULL;
2156 	}
2157 
2158 	spin_lock_init(&dep->lock);
2159 
2160 	if (num == 0)
2161 		ret = dwc3_gadget_init_control_endpoint(dep);
2162 	else if (direction)
2163 		ret = dwc3_gadget_init_in_endpoint(dep);
2164 	else
2165 		ret = dwc3_gadget_init_out_endpoint(dep);
2166 
2167 	if (ret)
2168 		return ret;
2169 
2170 	dep->endpoint.caps.dir_in = direction;
2171 	dep->endpoint.caps.dir_out = !direction;
2172 
2173 	INIT_LIST_HEAD(&dep->pending_list);
2174 	INIT_LIST_HEAD(&dep->started_list);
2175 
2176 	return 0;
2177 }
2178 
2179 static int dwc3_gadget_init_endpoints(struct dwc3 *dwc, u8 total)
2180 {
2181 	u8				epnum;
2182 
2183 	INIT_LIST_HEAD(&dwc->gadget.ep_list);
2184 
2185 	for (epnum = 0; epnum < total; epnum++) {
2186 		int			ret;
2187 
2188 		ret = dwc3_gadget_init_endpoint(dwc, epnum);
2189 		if (ret)
2190 			return ret;
2191 	}
2192 
2193 	return 0;
2194 }
2195 
2196 static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
2197 {
2198 	struct dwc3_ep			*dep;
2199 	u8				epnum;
2200 
2201 	for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2202 		dep = dwc->eps[epnum];
2203 		if (!dep)
2204 			continue;
2205 		/*
2206 		 * Physical endpoints 0 and 1 are special; they form the
2207 		 * bi-directional USB endpoint 0.
2208 		 *
2209 		 * For those two physical endpoints, we don't allocate a TRB
2210 		 * pool nor do we add them the endpoints list. Due to that, we
2211 		 * shouldn't do these two operations otherwise we would end up
2212 		 * with all sorts of bugs when removing dwc3.ko.
2213 		 */
2214 		if (epnum != 0 && epnum != 1) {
2215 			dwc3_free_trb_pool(dep);
2216 			list_del(&dep->endpoint.ep_list);
2217 		}
2218 
2219 		kfree(dep);
2220 	}
2221 }
2222 
2223 /* -------------------------------------------------------------------------- */
2224 
2225 static int dwc3_gadget_ep_reclaim_completed_trb(struct dwc3_ep *dep,
2226 		struct dwc3_request *req, struct dwc3_trb *trb,
2227 		const struct dwc3_event_depevt *event, int status, int chain)
2228 {
2229 	unsigned int		count;
2230 
2231 	dwc3_ep_inc_deq(dep);
2232 
2233 	trace_dwc3_complete_trb(dep, trb);
2234 
2235 	/*
2236 	 * If we're in the middle of series of chained TRBs and we
2237 	 * receive a short transfer along the way, DWC3 will skip
2238 	 * through all TRBs including the last TRB in the chain (the
2239 	 * where CHN bit is zero. DWC3 will also avoid clearing HWO
2240 	 * bit and SW has to do it manually.
2241 	 *
2242 	 * We're going to do that here to avoid problems of HW trying
2243 	 * to use bogus TRBs for transfers.
2244 	 */
2245 	if (chain && (trb->ctrl & DWC3_TRB_CTRL_HWO))
2246 		trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2247 
2248 	/*
2249 	 * If we're dealing with unaligned size OUT transfer, we will be left
2250 	 * with one TRB pending in the ring. We need to manually clear HWO bit
2251 	 * from that TRB.
2252 	 */
2253 	if ((req->zero || req->unaligned) && (trb->ctrl & DWC3_TRB_CTRL_HWO)) {
2254 		trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2255 		return 1;
2256 	}
2257 
2258 	count = trb->size & DWC3_TRB_SIZE_MASK;
2259 	req->remaining += count;
2260 
2261 	if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
2262 		return 1;
2263 
2264 	if (event->status & DEPEVT_STATUS_SHORT && !chain)
2265 		return 1;
2266 
2267 	if (event->status & DEPEVT_STATUS_IOC)
2268 		return 1;
2269 
2270 	return 0;
2271 }
2272 
2273 static int dwc3_gadget_ep_reclaim_trb_sg(struct dwc3_ep *dep,
2274 		struct dwc3_request *req, const struct dwc3_event_depevt *event,
2275 		int status)
2276 {
2277 	struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
2278 	struct scatterlist *sg = req->sg;
2279 	struct scatterlist *s;
2280 	unsigned int pending = req->num_pending_sgs;
2281 	unsigned int i;
2282 	int ret = 0;
2283 
2284 	for_each_sg(sg, s, pending, i) {
2285 		trb = &dep->trb_pool[dep->trb_dequeue];
2286 
2287 		if (trb->ctrl & DWC3_TRB_CTRL_HWO)
2288 			break;
2289 
2290 		req->sg = sg_next(s);
2291 		req->num_pending_sgs--;
2292 
2293 		ret = dwc3_gadget_ep_reclaim_completed_trb(dep, req,
2294 				trb, event, status, true);
2295 		if (ret)
2296 			break;
2297 	}
2298 
2299 	return ret;
2300 }
2301 
2302 static int dwc3_gadget_ep_reclaim_trb_linear(struct dwc3_ep *dep,
2303 		struct dwc3_request *req, const struct dwc3_event_depevt *event,
2304 		int status)
2305 {
2306 	struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
2307 
2308 	return dwc3_gadget_ep_reclaim_completed_trb(dep, req, trb,
2309 			event, status, false);
2310 }
2311 
2312 static bool dwc3_gadget_ep_request_completed(struct dwc3_request *req)
2313 {
2314 	return req->request.actual == req->request.length;
2315 }
2316 
2317 static int dwc3_gadget_ep_cleanup_completed_request(struct dwc3_ep *dep,
2318 		const struct dwc3_event_depevt *event,
2319 		struct dwc3_request *req, int status)
2320 {
2321 	int ret;
2322 
2323 	if (req->num_pending_sgs)
2324 		ret = dwc3_gadget_ep_reclaim_trb_sg(dep, req, event,
2325 				status);
2326 	else
2327 		ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
2328 				status);
2329 
2330 	if (req->unaligned || req->zero) {
2331 		ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
2332 				status);
2333 		req->unaligned = false;
2334 		req->zero = false;
2335 	}
2336 
2337 	req->request.actual = req->request.length - req->remaining;
2338 
2339 	if (!dwc3_gadget_ep_request_completed(req) &&
2340 			req->num_pending_sgs) {
2341 		__dwc3_gadget_kick_transfer(dep);
2342 		goto out;
2343 	}
2344 
2345 	dwc3_gadget_giveback(dep, req, status);
2346 
2347 out:
2348 	return ret;
2349 }
2350 
2351 static void dwc3_gadget_ep_cleanup_completed_requests(struct dwc3_ep *dep,
2352 		const struct dwc3_event_depevt *event, int status)
2353 {
2354 	struct dwc3_request	*req;
2355 	struct dwc3_request	*tmp;
2356 
2357 	list_for_each_entry_safe(req, tmp, &dep->started_list, list) {
2358 		int ret;
2359 
2360 		ret = dwc3_gadget_ep_cleanup_completed_request(dep, event,
2361 				req, status);
2362 		if (ret)
2363 			break;
2364 	}
2365 }
2366 
2367 static void dwc3_gadget_endpoint_frame_from_event(struct dwc3_ep *dep,
2368 		const struct dwc3_event_depevt *event)
2369 {
2370 	dep->frame_number = event->parameters;
2371 }
2372 
2373 static void dwc3_gadget_endpoint_transfer_in_progress(struct dwc3_ep *dep,
2374 		const struct dwc3_event_depevt *event)
2375 {
2376 	struct dwc3		*dwc = dep->dwc;
2377 	unsigned		status = 0;
2378 	bool			stop = false;
2379 
2380 	dwc3_gadget_endpoint_frame_from_event(dep, event);
2381 
2382 	if (event->status & DEPEVT_STATUS_BUSERR)
2383 		status = -ECONNRESET;
2384 
2385 	if (event->status & DEPEVT_STATUS_MISSED_ISOC) {
2386 		status = -EXDEV;
2387 
2388 		if (list_empty(&dep->started_list))
2389 			stop = true;
2390 	}
2391 
2392 	dwc3_gadget_ep_cleanup_completed_requests(dep, event, status);
2393 
2394 	if (stop) {
2395 		dwc3_stop_active_transfer(dep, true);
2396 		dep->flags = DWC3_EP_ENABLED;
2397 	}
2398 
2399 	/*
2400 	 * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
2401 	 * See dwc3_gadget_linksts_change_interrupt() for 1st half.
2402 	 */
2403 	if (dwc->revision < DWC3_REVISION_183A) {
2404 		u32		reg;
2405 		int		i;
2406 
2407 		for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
2408 			dep = dwc->eps[i];
2409 
2410 			if (!(dep->flags & DWC3_EP_ENABLED))
2411 				continue;
2412 
2413 			if (!list_empty(&dep->started_list))
2414 				return;
2415 		}
2416 
2417 		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2418 		reg |= dwc->u1u2;
2419 		dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2420 
2421 		dwc->u1u2 = 0;
2422 	}
2423 }
2424 
2425 static void dwc3_gadget_endpoint_transfer_not_ready(struct dwc3_ep *dep,
2426 		const struct dwc3_event_depevt *event)
2427 {
2428 	dwc3_gadget_endpoint_frame_from_event(dep, event);
2429 	__dwc3_gadget_start_isoc(dep);
2430 }
2431 
2432 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
2433 		const struct dwc3_event_depevt *event)
2434 {
2435 	struct dwc3_ep		*dep;
2436 	u8			epnum = event->endpoint_number;
2437 	u8			cmd;
2438 
2439 	dep = dwc->eps[epnum];
2440 
2441 	if (!(dep->flags & DWC3_EP_ENABLED)) {
2442 		if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
2443 			return;
2444 
2445 		/* Handle only EPCMDCMPLT when EP disabled */
2446 		if (event->endpoint_event != DWC3_DEPEVT_EPCMDCMPLT)
2447 			return;
2448 	}
2449 
2450 	if (epnum == 0 || epnum == 1) {
2451 		dwc3_ep0_interrupt(dwc, event);
2452 		return;
2453 	}
2454 
2455 	switch (event->endpoint_event) {
2456 	case DWC3_DEPEVT_XFERINPROGRESS:
2457 		dwc3_gadget_endpoint_transfer_in_progress(dep, event);
2458 		break;
2459 	case DWC3_DEPEVT_XFERNOTREADY:
2460 		dwc3_gadget_endpoint_transfer_not_ready(dep, event);
2461 		break;
2462 	case DWC3_DEPEVT_EPCMDCMPLT:
2463 		cmd = DEPEVT_PARAMETER_CMD(event->parameters);
2464 
2465 		if (cmd == DWC3_DEPCMD_ENDTRANSFER) {
2466 			dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
2467 			wake_up(&dep->wait_end_transfer);
2468 		}
2469 		break;
2470 	case DWC3_DEPEVT_STREAMEVT:
2471 	case DWC3_DEPEVT_XFERCOMPLETE:
2472 	case DWC3_DEPEVT_RXTXFIFOEVT:
2473 		break;
2474 	}
2475 }
2476 
2477 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
2478 {
2479 	if (dwc->gadget_driver && dwc->gadget_driver->disconnect) {
2480 		spin_unlock(&dwc->lock);
2481 		dwc->gadget_driver->disconnect(&dwc->gadget);
2482 		spin_lock(&dwc->lock);
2483 	}
2484 }
2485 
2486 static void dwc3_suspend_gadget(struct dwc3 *dwc)
2487 {
2488 	if (dwc->gadget_driver && dwc->gadget_driver->suspend) {
2489 		spin_unlock(&dwc->lock);
2490 		dwc->gadget_driver->suspend(&dwc->gadget);
2491 		spin_lock(&dwc->lock);
2492 	}
2493 }
2494 
2495 static void dwc3_resume_gadget(struct dwc3 *dwc)
2496 {
2497 	if (dwc->gadget_driver && dwc->gadget_driver->resume) {
2498 		spin_unlock(&dwc->lock);
2499 		dwc->gadget_driver->resume(&dwc->gadget);
2500 		spin_lock(&dwc->lock);
2501 	}
2502 }
2503 
2504 static void dwc3_reset_gadget(struct dwc3 *dwc)
2505 {
2506 	if (!dwc->gadget_driver)
2507 		return;
2508 
2509 	if (dwc->gadget.speed != USB_SPEED_UNKNOWN) {
2510 		spin_unlock(&dwc->lock);
2511 		usb_gadget_udc_reset(&dwc->gadget, dwc->gadget_driver);
2512 		spin_lock(&dwc->lock);
2513 	}
2514 }
2515 
2516 static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force)
2517 {
2518 	struct dwc3 *dwc = dep->dwc;
2519 	struct dwc3_gadget_ep_cmd_params params;
2520 	u32 cmd;
2521 	int ret;
2522 
2523 	if ((dep->flags & DWC3_EP_END_TRANSFER_PENDING) ||
2524 	    !dep->resource_index)
2525 		return;
2526 
2527 	/*
2528 	 * NOTICE: We are violating what the Databook says about the
2529 	 * EndTransfer command. Ideally we would _always_ wait for the
2530 	 * EndTransfer Command Completion IRQ, but that's causing too
2531 	 * much trouble synchronizing between us and gadget driver.
2532 	 *
2533 	 * We have discussed this with the IP Provider and it was
2534 	 * suggested to giveback all requests here, but give HW some
2535 	 * extra time to synchronize with the interconnect. We're using
2536 	 * an arbitrary 100us delay for that.
2537 	 *
2538 	 * Note also that a similar handling was tested by Synopsys
2539 	 * (thanks a lot Paul) and nothing bad has come out of it.
2540 	 * In short, what we're doing is:
2541 	 *
2542 	 * - Issue EndTransfer WITH CMDIOC bit set
2543 	 * - Wait 100us
2544 	 *
2545 	 * As of IP version 3.10a of the DWC_usb3 IP, the controller
2546 	 * supports a mode to work around the above limitation. The
2547 	 * software can poll the CMDACT bit in the DEPCMD register
2548 	 * after issuing a EndTransfer command. This mode is enabled
2549 	 * by writing GUCTL2[14]. This polling is already done in the
2550 	 * dwc3_send_gadget_ep_cmd() function so if the mode is
2551 	 * enabled, the EndTransfer command will have completed upon
2552 	 * returning from this function and we don't need to delay for
2553 	 * 100us.
2554 	 *
2555 	 * This mode is NOT available on the DWC_usb31 IP.
2556 	 */
2557 
2558 	cmd = DWC3_DEPCMD_ENDTRANSFER;
2559 	cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
2560 	cmd |= DWC3_DEPCMD_CMDIOC;
2561 	cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
2562 	memset(&params, 0, sizeof(params));
2563 	ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
2564 	WARN_ON_ONCE(ret);
2565 	dep->resource_index = 0;
2566 
2567 	if (dwc3_is_usb31(dwc) || dwc->revision < DWC3_REVISION_310A) {
2568 		dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
2569 		udelay(100);
2570 	}
2571 }
2572 
2573 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
2574 {
2575 	u32 epnum;
2576 
2577 	for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2578 		struct dwc3_ep *dep;
2579 		int ret;
2580 
2581 		dep = dwc->eps[epnum];
2582 		if (!dep)
2583 			continue;
2584 
2585 		if (!(dep->flags & DWC3_EP_STALL))
2586 			continue;
2587 
2588 		dep->flags &= ~DWC3_EP_STALL;
2589 
2590 		ret = dwc3_send_clear_stall_ep_cmd(dep);
2591 		WARN_ON_ONCE(ret);
2592 	}
2593 }
2594 
2595 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
2596 {
2597 	int			reg;
2598 
2599 	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2600 	reg &= ~DWC3_DCTL_INITU1ENA;
2601 	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2602 
2603 	reg &= ~DWC3_DCTL_INITU2ENA;
2604 	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2605 
2606 	dwc3_disconnect_gadget(dwc);
2607 
2608 	dwc->gadget.speed = USB_SPEED_UNKNOWN;
2609 	dwc->setup_packet_pending = false;
2610 	usb_gadget_set_state(&dwc->gadget, USB_STATE_NOTATTACHED);
2611 
2612 	dwc->connected = false;
2613 }
2614 
2615 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
2616 {
2617 	u32			reg;
2618 
2619 	dwc->connected = true;
2620 
2621 	/*
2622 	 * WORKAROUND: DWC3 revisions <1.88a have an issue which
2623 	 * would cause a missing Disconnect Event if there's a
2624 	 * pending Setup Packet in the FIFO.
2625 	 *
2626 	 * There's no suggested workaround on the official Bug
2627 	 * report, which states that "unless the driver/application
2628 	 * is doing any special handling of a disconnect event,
2629 	 * there is no functional issue".
2630 	 *
2631 	 * Unfortunately, it turns out that we _do_ some special
2632 	 * handling of a disconnect event, namely complete all
2633 	 * pending transfers, notify gadget driver of the
2634 	 * disconnection, and so on.
2635 	 *
2636 	 * Our suggested workaround is to follow the Disconnect
2637 	 * Event steps here, instead, based on a setup_packet_pending
2638 	 * flag. Such flag gets set whenever we have a SETUP_PENDING
2639 	 * status for EP0 TRBs and gets cleared on XferComplete for the
2640 	 * same endpoint.
2641 	 *
2642 	 * Refers to:
2643 	 *
2644 	 * STAR#9000466709: RTL: Device : Disconnect event not
2645 	 * generated if setup packet pending in FIFO
2646 	 */
2647 	if (dwc->revision < DWC3_REVISION_188A) {
2648 		if (dwc->setup_packet_pending)
2649 			dwc3_gadget_disconnect_interrupt(dwc);
2650 	}
2651 
2652 	dwc3_reset_gadget(dwc);
2653 
2654 	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2655 	reg &= ~DWC3_DCTL_TSTCTRL_MASK;
2656 	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2657 	dwc->test_mode = false;
2658 	dwc3_clear_stall_all_ep(dwc);
2659 
2660 	/* Reset device address to zero */
2661 	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2662 	reg &= ~(DWC3_DCFG_DEVADDR_MASK);
2663 	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2664 }
2665 
2666 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
2667 {
2668 	struct dwc3_ep		*dep;
2669 	int			ret;
2670 	u32			reg;
2671 	u8			speed;
2672 
2673 	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2674 	speed = reg & DWC3_DSTS_CONNECTSPD;
2675 	dwc->speed = speed;
2676 
2677 	/*
2678 	 * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
2679 	 * each time on Connect Done.
2680 	 *
2681 	 * Currently we always use the reset value. If any platform
2682 	 * wants to set this to a different value, we need to add a
2683 	 * setting and update GCTL.RAMCLKSEL here.
2684 	 */
2685 
2686 	switch (speed) {
2687 	case DWC3_DSTS_SUPERSPEED_PLUS:
2688 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2689 		dwc->gadget.ep0->maxpacket = 512;
2690 		dwc->gadget.speed = USB_SPEED_SUPER_PLUS;
2691 		break;
2692 	case DWC3_DSTS_SUPERSPEED:
2693 		/*
2694 		 * WORKAROUND: DWC3 revisions <1.90a have an issue which
2695 		 * would cause a missing USB3 Reset event.
2696 		 *
2697 		 * In such situations, we should force a USB3 Reset
2698 		 * event by calling our dwc3_gadget_reset_interrupt()
2699 		 * routine.
2700 		 *
2701 		 * Refers to:
2702 		 *
2703 		 * STAR#9000483510: RTL: SS : USB3 reset event may
2704 		 * not be generated always when the link enters poll
2705 		 */
2706 		if (dwc->revision < DWC3_REVISION_190A)
2707 			dwc3_gadget_reset_interrupt(dwc);
2708 
2709 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2710 		dwc->gadget.ep0->maxpacket = 512;
2711 		dwc->gadget.speed = USB_SPEED_SUPER;
2712 		break;
2713 	case DWC3_DSTS_HIGHSPEED:
2714 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
2715 		dwc->gadget.ep0->maxpacket = 64;
2716 		dwc->gadget.speed = USB_SPEED_HIGH;
2717 		break;
2718 	case DWC3_DSTS_FULLSPEED:
2719 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
2720 		dwc->gadget.ep0->maxpacket = 64;
2721 		dwc->gadget.speed = USB_SPEED_FULL;
2722 		break;
2723 	case DWC3_DSTS_LOWSPEED:
2724 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(8);
2725 		dwc->gadget.ep0->maxpacket = 8;
2726 		dwc->gadget.speed = USB_SPEED_LOW;
2727 		break;
2728 	}
2729 
2730 	dwc->eps[1]->endpoint.maxpacket = dwc->gadget.ep0->maxpacket;
2731 
2732 	/* Enable USB2 LPM Capability */
2733 
2734 	if ((dwc->revision > DWC3_REVISION_194A) &&
2735 	    (speed != DWC3_DSTS_SUPERSPEED) &&
2736 	    (speed != DWC3_DSTS_SUPERSPEED_PLUS)) {
2737 		reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2738 		reg |= DWC3_DCFG_LPM_CAP;
2739 		dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2740 
2741 		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2742 		reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
2743 
2744 		reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold);
2745 
2746 		/*
2747 		 * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
2748 		 * DCFG.LPMCap is set, core responses with an ACK and the
2749 		 * BESL value in the LPM token is less than or equal to LPM
2750 		 * NYET threshold.
2751 		 */
2752 		WARN_ONCE(dwc->revision < DWC3_REVISION_240A
2753 				&& dwc->has_lpm_erratum,
2754 				"LPM Erratum not available on dwc3 revisions < 2.40a\n");
2755 
2756 		if (dwc->has_lpm_erratum && dwc->revision >= DWC3_REVISION_240A)
2757 			reg |= DWC3_DCTL_LPM_ERRATA(dwc->lpm_nyet_threshold);
2758 
2759 		dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2760 	} else {
2761 		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2762 		reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
2763 		dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2764 	}
2765 
2766 	dep = dwc->eps[0];
2767 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
2768 	if (ret) {
2769 		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2770 		return;
2771 	}
2772 
2773 	dep = dwc->eps[1];
2774 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
2775 	if (ret) {
2776 		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2777 		return;
2778 	}
2779 
2780 	/*
2781 	 * Configure PHY via GUSB3PIPECTLn if required.
2782 	 *
2783 	 * Update GTXFIFOSIZn
2784 	 *
2785 	 * In both cases reset values should be sufficient.
2786 	 */
2787 }
2788 
2789 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
2790 {
2791 	/*
2792 	 * TODO take core out of low power mode when that's
2793 	 * implemented.
2794 	 */
2795 
2796 	if (dwc->gadget_driver && dwc->gadget_driver->resume) {
2797 		spin_unlock(&dwc->lock);
2798 		dwc->gadget_driver->resume(&dwc->gadget);
2799 		spin_lock(&dwc->lock);
2800 	}
2801 }
2802 
2803 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
2804 		unsigned int evtinfo)
2805 {
2806 	enum dwc3_link_state	next = evtinfo & DWC3_LINK_STATE_MASK;
2807 	unsigned int		pwropt;
2808 
2809 	/*
2810 	 * WORKAROUND: DWC3 < 2.50a have an issue when configured without
2811 	 * Hibernation mode enabled which would show up when device detects
2812 	 * host-initiated U3 exit.
2813 	 *
2814 	 * In that case, device will generate a Link State Change Interrupt
2815 	 * from U3 to RESUME which is only necessary if Hibernation is
2816 	 * configured in.
2817 	 *
2818 	 * There are no functional changes due to such spurious event and we
2819 	 * just need to ignore it.
2820 	 *
2821 	 * Refers to:
2822 	 *
2823 	 * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
2824 	 * operational mode
2825 	 */
2826 	pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
2827 	if ((dwc->revision < DWC3_REVISION_250A) &&
2828 			(pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
2829 		if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
2830 				(next == DWC3_LINK_STATE_RESUME)) {
2831 			return;
2832 		}
2833 	}
2834 
2835 	/*
2836 	 * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
2837 	 * on the link partner, the USB session might do multiple entry/exit
2838 	 * of low power states before a transfer takes place.
2839 	 *
2840 	 * Due to this problem, we might experience lower throughput. The
2841 	 * suggested workaround is to disable DCTL[12:9] bits if we're
2842 	 * transitioning from U1/U2 to U0 and enable those bits again
2843 	 * after a transfer completes and there are no pending transfers
2844 	 * on any of the enabled endpoints.
2845 	 *
2846 	 * This is the first half of that workaround.
2847 	 *
2848 	 * Refers to:
2849 	 *
2850 	 * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
2851 	 * core send LGO_Ux entering U0
2852 	 */
2853 	if (dwc->revision < DWC3_REVISION_183A) {
2854 		if (next == DWC3_LINK_STATE_U0) {
2855 			u32	u1u2;
2856 			u32	reg;
2857 
2858 			switch (dwc->link_state) {
2859 			case DWC3_LINK_STATE_U1:
2860 			case DWC3_LINK_STATE_U2:
2861 				reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2862 				u1u2 = reg & (DWC3_DCTL_INITU2ENA
2863 						| DWC3_DCTL_ACCEPTU2ENA
2864 						| DWC3_DCTL_INITU1ENA
2865 						| DWC3_DCTL_ACCEPTU1ENA);
2866 
2867 				if (!dwc->u1u2)
2868 					dwc->u1u2 = reg & u1u2;
2869 
2870 				reg &= ~u1u2;
2871 
2872 				dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2873 				break;
2874 			default:
2875 				/* do nothing */
2876 				break;
2877 			}
2878 		}
2879 	}
2880 
2881 	switch (next) {
2882 	case DWC3_LINK_STATE_U1:
2883 		if (dwc->speed == USB_SPEED_SUPER)
2884 			dwc3_suspend_gadget(dwc);
2885 		break;
2886 	case DWC3_LINK_STATE_U2:
2887 	case DWC3_LINK_STATE_U3:
2888 		dwc3_suspend_gadget(dwc);
2889 		break;
2890 	case DWC3_LINK_STATE_RESUME:
2891 		dwc3_resume_gadget(dwc);
2892 		break;
2893 	default:
2894 		/* do nothing */
2895 		break;
2896 	}
2897 
2898 	dwc->link_state = next;
2899 }
2900 
2901 static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc,
2902 					  unsigned int evtinfo)
2903 {
2904 	enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
2905 
2906 	if (dwc->link_state != next && next == DWC3_LINK_STATE_U3)
2907 		dwc3_suspend_gadget(dwc);
2908 
2909 	dwc->link_state = next;
2910 }
2911 
2912 static void dwc3_gadget_hibernation_interrupt(struct dwc3 *dwc,
2913 		unsigned int evtinfo)
2914 {
2915 	unsigned int is_ss = evtinfo & BIT(4);
2916 
2917 	/*
2918 	 * WORKAROUND: DWC3 revison 2.20a with hibernation support
2919 	 * have a known issue which can cause USB CV TD.9.23 to fail
2920 	 * randomly.
2921 	 *
2922 	 * Because of this issue, core could generate bogus hibernation
2923 	 * events which SW needs to ignore.
2924 	 *
2925 	 * Refers to:
2926 	 *
2927 	 * STAR#9000546576: Device Mode Hibernation: Issue in USB 2.0
2928 	 * Device Fallback from SuperSpeed
2929 	 */
2930 	if (is_ss ^ (dwc->speed == USB_SPEED_SUPER))
2931 		return;
2932 
2933 	/* enter hibernation here */
2934 }
2935 
2936 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
2937 		const struct dwc3_event_devt *event)
2938 {
2939 	switch (event->type) {
2940 	case DWC3_DEVICE_EVENT_DISCONNECT:
2941 		dwc3_gadget_disconnect_interrupt(dwc);
2942 		break;
2943 	case DWC3_DEVICE_EVENT_RESET:
2944 		dwc3_gadget_reset_interrupt(dwc);
2945 		break;
2946 	case DWC3_DEVICE_EVENT_CONNECT_DONE:
2947 		dwc3_gadget_conndone_interrupt(dwc);
2948 		break;
2949 	case DWC3_DEVICE_EVENT_WAKEUP:
2950 		dwc3_gadget_wakeup_interrupt(dwc);
2951 		break;
2952 	case DWC3_DEVICE_EVENT_HIBER_REQ:
2953 		if (dev_WARN_ONCE(dwc->dev, !dwc->has_hibernation,
2954 					"unexpected hibernation event\n"))
2955 			break;
2956 
2957 		dwc3_gadget_hibernation_interrupt(dwc, event->event_info);
2958 		break;
2959 	case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
2960 		dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
2961 		break;
2962 	case DWC3_DEVICE_EVENT_EOPF:
2963 		/* It changed to be suspend event for version 2.30a and above */
2964 		if (dwc->revision >= DWC3_REVISION_230A) {
2965 			/*
2966 			 * Ignore suspend event until the gadget enters into
2967 			 * USB_STATE_CONFIGURED state.
2968 			 */
2969 			if (dwc->gadget.state >= USB_STATE_CONFIGURED)
2970 				dwc3_gadget_suspend_interrupt(dwc,
2971 						event->event_info);
2972 		}
2973 		break;
2974 	case DWC3_DEVICE_EVENT_SOF:
2975 	case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
2976 	case DWC3_DEVICE_EVENT_CMD_CMPL:
2977 	case DWC3_DEVICE_EVENT_OVERFLOW:
2978 		break;
2979 	default:
2980 		dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
2981 	}
2982 }
2983 
2984 static void dwc3_process_event_entry(struct dwc3 *dwc,
2985 		const union dwc3_event *event)
2986 {
2987 	trace_dwc3_event(event->raw, dwc);
2988 
2989 	if (!event->type.is_devspec)
2990 		dwc3_endpoint_interrupt(dwc, &event->depevt);
2991 	else if (event->type.type == DWC3_EVENT_TYPE_DEV)
2992 		dwc3_gadget_interrupt(dwc, &event->devt);
2993 	else
2994 		dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
2995 }
2996 
2997 static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt)
2998 {
2999 	struct dwc3 *dwc = evt->dwc;
3000 	irqreturn_t ret = IRQ_NONE;
3001 	int left;
3002 	u32 reg;
3003 
3004 	left = evt->count;
3005 
3006 	if (!(evt->flags & DWC3_EVENT_PENDING))
3007 		return IRQ_NONE;
3008 
3009 	while (left > 0) {
3010 		union dwc3_event event;
3011 
3012 		event.raw = *(u32 *) (evt->cache + evt->lpos);
3013 
3014 		dwc3_process_event_entry(dwc, &event);
3015 
3016 		/*
3017 		 * FIXME we wrap around correctly to the next entry as
3018 		 * almost all entries are 4 bytes in size. There is one
3019 		 * entry which has 12 bytes which is a regular entry
3020 		 * followed by 8 bytes data. ATM I don't know how
3021 		 * things are organized if we get next to the a
3022 		 * boundary so I worry about that once we try to handle
3023 		 * that.
3024 		 */
3025 		evt->lpos = (evt->lpos + 4) % evt->length;
3026 		left -= 4;
3027 	}
3028 
3029 	evt->count = 0;
3030 	evt->flags &= ~DWC3_EVENT_PENDING;
3031 	ret = IRQ_HANDLED;
3032 
3033 	/* Unmask interrupt */
3034 	reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
3035 	reg &= ~DWC3_GEVNTSIZ_INTMASK;
3036 	dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
3037 
3038 	if (dwc->imod_interval) {
3039 		dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
3040 		dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
3041 	}
3042 
3043 	return ret;
3044 }
3045 
3046 static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt)
3047 {
3048 	struct dwc3_event_buffer *evt = _evt;
3049 	struct dwc3 *dwc = evt->dwc;
3050 	unsigned long flags;
3051 	irqreturn_t ret = IRQ_NONE;
3052 
3053 	spin_lock_irqsave(&dwc->lock, flags);
3054 	ret = dwc3_process_event_buf(evt);
3055 	spin_unlock_irqrestore(&dwc->lock, flags);
3056 
3057 	return ret;
3058 }
3059 
3060 static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt)
3061 {
3062 	struct dwc3 *dwc = evt->dwc;
3063 	u32 amount;
3064 	u32 count;
3065 	u32 reg;
3066 
3067 	if (pm_runtime_suspended(dwc->dev)) {
3068 		pm_runtime_get(dwc->dev);
3069 		disable_irq_nosync(dwc->irq_gadget);
3070 		dwc->pending_events = true;
3071 		return IRQ_HANDLED;
3072 	}
3073 
3074 	/*
3075 	 * With PCIe legacy interrupt, test shows that top-half irq handler can
3076 	 * be called again after HW interrupt deassertion. Check if bottom-half
3077 	 * irq event handler completes before caching new event to prevent
3078 	 * losing events.
3079 	 */
3080 	if (evt->flags & DWC3_EVENT_PENDING)
3081 		return IRQ_HANDLED;
3082 
3083 	count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
3084 	count &= DWC3_GEVNTCOUNT_MASK;
3085 	if (!count)
3086 		return IRQ_NONE;
3087 
3088 	evt->count = count;
3089 	evt->flags |= DWC3_EVENT_PENDING;
3090 
3091 	/* Mask interrupt */
3092 	reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
3093 	reg |= DWC3_GEVNTSIZ_INTMASK;
3094 	dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
3095 
3096 	amount = min(count, evt->length - evt->lpos);
3097 	memcpy(evt->cache + evt->lpos, evt->buf + evt->lpos, amount);
3098 
3099 	if (amount < count)
3100 		memcpy(evt->cache, evt->buf, count - amount);
3101 
3102 	dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
3103 
3104 	return IRQ_WAKE_THREAD;
3105 }
3106 
3107 static irqreturn_t dwc3_interrupt(int irq, void *_evt)
3108 {
3109 	struct dwc3_event_buffer	*evt = _evt;
3110 
3111 	return dwc3_check_event_buf(evt);
3112 }
3113 
3114 static int dwc3_gadget_get_irq(struct dwc3 *dwc)
3115 {
3116 	struct platform_device *dwc3_pdev = to_platform_device(dwc->dev);
3117 	int irq;
3118 
3119 	irq = platform_get_irq_byname(dwc3_pdev, "peripheral");
3120 	if (irq > 0)
3121 		goto out;
3122 
3123 	if (irq == -EPROBE_DEFER)
3124 		goto out;
3125 
3126 	irq = platform_get_irq_byname(dwc3_pdev, "dwc_usb3");
3127 	if (irq > 0)
3128 		goto out;
3129 
3130 	if (irq == -EPROBE_DEFER)
3131 		goto out;
3132 
3133 	irq = platform_get_irq(dwc3_pdev, 0);
3134 	if (irq > 0)
3135 		goto out;
3136 
3137 	if (irq != -EPROBE_DEFER)
3138 		dev_err(dwc->dev, "missing peripheral IRQ\n");
3139 
3140 	if (!irq)
3141 		irq = -EINVAL;
3142 
3143 out:
3144 	return irq;
3145 }
3146 
3147 /**
3148  * dwc3_gadget_init - initializes gadget related registers
3149  * @dwc: pointer to our controller context structure
3150  *
3151  * Returns 0 on success otherwise negative errno.
3152  */
3153 int dwc3_gadget_init(struct dwc3 *dwc)
3154 {
3155 	int ret;
3156 	int irq;
3157 
3158 	irq = dwc3_gadget_get_irq(dwc);
3159 	if (irq < 0) {
3160 		ret = irq;
3161 		goto err0;
3162 	}
3163 
3164 	dwc->irq_gadget = irq;
3165 
3166 	dwc->ep0_trb = dma_alloc_coherent(dwc->sysdev,
3167 					  sizeof(*dwc->ep0_trb) * 2,
3168 					  &dwc->ep0_trb_addr, GFP_KERNEL);
3169 	if (!dwc->ep0_trb) {
3170 		dev_err(dwc->dev, "failed to allocate ep0 trb\n");
3171 		ret = -ENOMEM;
3172 		goto err0;
3173 	}
3174 
3175 	dwc->setup_buf = kzalloc(DWC3_EP0_SETUP_SIZE, GFP_KERNEL);
3176 	if (!dwc->setup_buf) {
3177 		ret = -ENOMEM;
3178 		goto err1;
3179 	}
3180 
3181 	dwc->bounce = dma_alloc_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE,
3182 			&dwc->bounce_addr, GFP_KERNEL);
3183 	if (!dwc->bounce) {
3184 		ret = -ENOMEM;
3185 		goto err2;
3186 	}
3187 
3188 	init_completion(&dwc->ep0_in_setup);
3189 
3190 	dwc->gadget.ops			= &dwc3_gadget_ops;
3191 	dwc->gadget.speed		= USB_SPEED_UNKNOWN;
3192 	dwc->gadget.sg_supported	= true;
3193 	dwc->gadget.name		= "dwc3-gadget";
3194 	dwc->gadget.is_otg		= dwc->dr_mode == USB_DR_MODE_OTG;
3195 
3196 	/*
3197 	 * FIXME We might be setting max_speed to <SUPER, however versions
3198 	 * <2.20a of dwc3 have an issue with metastability (documented
3199 	 * elsewhere in this driver) which tells us we can't set max speed to
3200 	 * anything lower than SUPER.
3201 	 *
3202 	 * Because gadget.max_speed is only used by composite.c and function
3203 	 * drivers (i.e. it won't go into dwc3's registers) we are allowing this
3204 	 * to happen so we avoid sending SuperSpeed Capability descriptor
3205 	 * together with our BOS descriptor as that could confuse host into
3206 	 * thinking we can handle super speed.
3207 	 *
3208 	 * Note that, in fact, we won't even support GetBOS requests when speed
3209 	 * is less than super speed because we don't have means, yet, to tell
3210 	 * composite.c that we are USB 2.0 + LPM ECN.
3211 	 */
3212 	if (dwc->revision < DWC3_REVISION_220A &&
3213 	    !dwc->dis_metastability_quirk)
3214 		dev_info(dwc->dev, "changing max_speed on rev %08x\n",
3215 				dwc->revision);
3216 
3217 	dwc->gadget.max_speed		= dwc->maximum_speed;
3218 
3219 	/*
3220 	 * REVISIT: Here we should clear all pending IRQs to be
3221 	 * sure we're starting from a well known location.
3222 	 */
3223 
3224 	ret = dwc3_gadget_init_endpoints(dwc, dwc->num_eps);
3225 	if (ret)
3226 		goto err3;
3227 
3228 	ret = usb_add_gadget_udc(dwc->dev, &dwc->gadget);
3229 	if (ret) {
3230 		dev_err(dwc->dev, "failed to register udc\n");
3231 		goto err4;
3232 	}
3233 
3234 	return 0;
3235 
3236 err4:
3237 	dwc3_gadget_free_endpoints(dwc);
3238 
3239 err3:
3240 	dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
3241 			dwc->bounce_addr);
3242 
3243 err2:
3244 	kfree(dwc->setup_buf);
3245 
3246 err1:
3247 	dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
3248 			dwc->ep0_trb, dwc->ep0_trb_addr);
3249 
3250 err0:
3251 	return ret;
3252 }
3253 
3254 /* -------------------------------------------------------------------------- */
3255 
3256 void dwc3_gadget_exit(struct dwc3 *dwc)
3257 {
3258 	usb_del_gadget_udc(&dwc->gadget);
3259 	dwc3_gadget_free_endpoints(dwc);
3260 	dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
3261 			  dwc->bounce_addr);
3262 	kfree(dwc->setup_buf);
3263 	dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
3264 			  dwc->ep0_trb, dwc->ep0_trb_addr);
3265 }
3266 
3267 int dwc3_gadget_suspend(struct dwc3 *dwc)
3268 {
3269 	if (!dwc->gadget_driver)
3270 		return 0;
3271 
3272 	dwc3_gadget_run_stop(dwc, false, false);
3273 	dwc3_disconnect_gadget(dwc);
3274 	__dwc3_gadget_stop(dwc);
3275 
3276 	return 0;
3277 }
3278 
3279 int dwc3_gadget_resume(struct dwc3 *dwc)
3280 {
3281 	int			ret;
3282 
3283 	if (!dwc->gadget_driver)
3284 		return 0;
3285 
3286 	ret = __dwc3_gadget_start(dwc);
3287 	if (ret < 0)
3288 		goto err0;
3289 
3290 	ret = dwc3_gadget_run_stop(dwc, true, false);
3291 	if (ret < 0)
3292 		goto err1;
3293 
3294 	return 0;
3295 
3296 err1:
3297 	__dwc3_gadget_stop(dwc);
3298 
3299 err0:
3300 	return ret;
3301 }
3302 
3303 void dwc3_gadget_process_pending_events(struct dwc3 *dwc)
3304 {
3305 	if (dwc->pending_events) {
3306 		dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf);
3307 		dwc->pending_events = false;
3308 		enable_irq(dwc->irq_gadget);
3309 	}
3310 }
3311