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