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