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