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