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