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