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