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