• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 		reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
296 		if (unlikely(reg & DWC3_GUSB2PHYCFG_SUSPHY)) {
297 			saved_config |= DWC3_GUSB2PHYCFG_SUSPHY;
298 			reg &= ~DWC3_GUSB2PHYCFG_SUSPHY;
299 		}
300 
301 		if (reg & DWC3_GUSB2PHYCFG_ENBLSLPM) {
302 			saved_config |= DWC3_GUSB2PHYCFG_ENBLSLPM;
303 			reg &= ~DWC3_GUSB2PHYCFG_ENBLSLPM;
304 		}
305 
306 		if (saved_config)
307 			dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
308 	}
309 
310 	if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
311 		int link_state;
312 
313 		/*
314 		 * Initiate remote wakeup if the link state is in U3 when
315 		 * operating in SS/SSP or L1/L2 when operating in HS/FS. If the
316 		 * link state is in U1/U2, no remote wakeup is needed. The Start
317 		 * Transfer command will initiate the link recovery.
318 		 */
319 		link_state = dwc3_gadget_get_link_state(dwc);
320 		switch (link_state) {
321 		case DWC3_LINK_STATE_U2:
322 			if (dwc->gadget->speed >= USB_SPEED_SUPER)
323 				break;
324 
325 			fallthrough;
326 		case DWC3_LINK_STATE_U3:
327 			ret = __dwc3_gadget_wakeup(dwc);
328 			dev_WARN_ONCE(dwc->dev, ret, "wakeup failed --> %d\n",
329 					ret);
330 			break;
331 		}
332 	}
333 
334 	dwc3_writel(dep->regs, DWC3_DEPCMDPAR0, params->param0);
335 	dwc3_writel(dep->regs, DWC3_DEPCMDPAR1, params->param1);
336 	dwc3_writel(dep->regs, DWC3_DEPCMDPAR2, params->param2);
337 
338 	/*
339 	 * Synopsys Databook 2.60a states in section 6.3.2.5.6 of that if we're
340 	 * not relying on XferNotReady, we can make use of a special "No
341 	 * Response Update Transfer" command where we should clear both CmdAct
342 	 * and CmdIOC bits.
343 	 *
344 	 * With this, we don't need to wait for command completion and can
345 	 * straight away issue further commands to the endpoint.
346 	 *
347 	 * NOTICE: We're making an assumption that control endpoints will never
348 	 * make use of Update Transfer command. This is a safe assumption
349 	 * because we can never have more than one request at a time with
350 	 * Control Endpoints. If anybody changes that assumption, this chunk
351 	 * needs to be updated accordingly.
352 	 */
353 	if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_UPDATETRANSFER &&
354 			!usb_endpoint_xfer_isoc(desc))
355 		cmd &= ~(DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_CMDACT);
356 	else
357 		cmd |= DWC3_DEPCMD_CMDACT;
358 
359 	dwc3_writel(dep->regs, DWC3_DEPCMD, cmd);
360 	do {
361 		reg = dwc3_readl(dep->regs, DWC3_DEPCMD);
362 		if (!(reg & DWC3_DEPCMD_CMDACT)) {
363 			cmd_status = DWC3_DEPCMD_STATUS(reg);
364 
365 			switch (cmd_status) {
366 			case 0:
367 				ret = 0;
368 				break;
369 			case DEPEVT_TRANSFER_NO_RESOURCE:
370 				dev_WARN(dwc->dev, "No resource for %s\n",
371 					 dep->name);
372 				ret = -EINVAL;
373 				break;
374 			case DEPEVT_TRANSFER_BUS_EXPIRY:
375 				/*
376 				 * SW issues START TRANSFER command to
377 				 * isochronous ep with future frame interval. If
378 				 * future interval time has already passed when
379 				 * core receives the command, it will respond
380 				 * with an error status of 'Bus Expiry'.
381 				 *
382 				 * Instead of always returning -EINVAL, let's
383 				 * give a hint to the gadget driver that this is
384 				 * the case by returning -EAGAIN.
385 				 */
386 				ret = -EAGAIN;
387 				break;
388 			default:
389 				dev_WARN(dwc->dev, "UNKNOWN cmd status\n");
390 			}
391 
392 			break;
393 		}
394 	} while (--timeout);
395 
396 	if (timeout == 0) {
397 		ret = -ETIMEDOUT;
398 		cmd_status = -ETIMEDOUT;
399 	}
400 
401 	trace_dwc3_gadget_ep_cmd(dep, cmd, params, cmd_status);
402 
403 	if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
404 		if (ret == 0)
405 			dep->flags |= DWC3_EP_TRANSFER_STARTED;
406 
407 		if (ret != -ETIMEDOUT)
408 			dwc3_gadget_ep_get_transfer_index(dep);
409 	}
410 
411 	if (saved_config) {
412 		reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
413 		reg |= saved_config;
414 		dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
415 	}
416 
417 	return ret;
418 }
419 
dwc3_send_clear_stall_ep_cmd(struct dwc3_ep * dep)420 static int dwc3_send_clear_stall_ep_cmd(struct dwc3_ep *dep)
421 {
422 	struct dwc3 *dwc = dep->dwc;
423 	struct dwc3_gadget_ep_cmd_params params;
424 	u32 cmd = DWC3_DEPCMD_CLEARSTALL;
425 
426 	/*
427 	 * As of core revision 2.60a the recommended programming model
428 	 * is to set the ClearPendIN bit when issuing a Clear Stall EP
429 	 * command for IN endpoints. This is to prevent an issue where
430 	 * some (non-compliant) hosts may not send ACK TPs for pending
431 	 * IN transfers due to a mishandled error condition. Synopsys
432 	 * STAR 9000614252.
433 	 */
434 	if (dep->direction &&
435 	    !DWC3_VER_IS_PRIOR(DWC3, 260A) &&
436 	    (dwc->gadget->speed >= USB_SPEED_SUPER))
437 		cmd |= DWC3_DEPCMD_CLEARPENDIN;
438 
439 	memset(&params, 0, sizeof(params));
440 
441 	return dwc3_send_gadget_ep_cmd(dep, cmd, &params);
442 }
443 
dwc3_trb_dma_offset(struct dwc3_ep * dep,struct dwc3_trb * trb)444 static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep,
445 		struct dwc3_trb *trb)
446 {
447 	u32		offset = (char *) trb - (char *) dep->trb_pool;
448 
449 	return dep->trb_pool_dma + offset;
450 }
451 
dwc3_alloc_trb_pool(struct dwc3_ep * dep)452 static int dwc3_alloc_trb_pool(struct dwc3_ep *dep)
453 {
454 	struct dwc3		*dwc = dep->dwc;
455 
456 	if (dep->trb_pool)
457 		return 0;
458 
459 	dep->trb_pool = dma_alloc_coherent(dwc->sysdev,
460 			sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
461 			&dep->trb_pool_dma, GFP_KERNEL);
462 	if (!dep->trb_pool) {
463 		dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n",
464 				dep->name);
465 		return -ENOMEM;
466 	}
467 
468 	return 0;
469 }
470 
dwc3_free_trb_pool(struct dwc3_ep * dep)471 static void dwc3_free_trb_pool(struct dwc3_ep *dep)
472 {
473 	struct dwc3		*dwc = dep->dwc;
474 
475 	dma_free_coherent(dwc->sysdev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
476 			dep->trb_pool, dep->trb_pool_dma);
477 
478 	dep->trb_pool = NULL;
479 	dep->trb_pool_dma = 0;
480 }
481 
dwc3_gadget_set_xfer_resource(struct dwc3_ep * dep)482 static int dwc3_gadget_set_xfer_resource(struct dwc3_ep *dep)
483 {
484 	struct dwc3_gadget_ep_cmd_params params;
485 
486 	memset(&params, 0x00, sizeof(params));
487 
488 	params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1);
489 
490 	return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETTRANSFRESOURCE,
491 			&params);
492 }
493 
494 /**
495  * dwc3_gadget_start_config - configure ep resources
496  * @dep: endpoint that is being enabled
497  *
498  * Issue a %DWC3_DEPCMD_DEPSTARTCFG command to @dep. After the command's
499  * completion, it will set Transfer Resource for all available endpoints.
500  *
501  * The assignment of transfer resources cannot perfectly follow the data book
502  * due to the fact that the controller driver does not have all knowledge of the
503  * configuration in advance. It is given this information piecemeal by the
504  * composite gadget framework after every SET_CONFIGURATION and
505  * SET_INTERFACE. Trying to follow the databook programming model in this
506  * scenario can cause errors. For two reasons:
507  *
508  * 1) The databook says to do %DWC3_DEPCMD_DEPSTARTCFG for every
509  * %USB_REQ_SET_CONFIGURATION and %USB_REQ_SET_INTERFACE (8.1.5). This is
510  * incorrect in the scenario of multiple interfaces.
511  *
512  * 2) The databook does not mention doing more %DWC3_DEPCMD_DEPXFERCFG for new
513  * endpoint on alt setting (8.1.6).
514  *
515  * The following simplified method is used instead:
516  *
517  * All hardware endpoints can be assigned a transfer resource and this setting
518  * will stay persistent until either a core reset or hibernation. So whenever we
519  * do a %DWC3_DEPCMD_DEPSTARTCFG(0) we can go ahead and do
520  * %DWC3_DEPCMD_DEPXFERCFG for every hardware endpoint as well. We are
521  * guaranteed that there are as many transfer resources as endpoints.
522  *
523  * This function is called for each endpoint when it is being enabled but is
524  * triggered only when called for EP0-out, which always happens first, and which
525  * should only happen in one of the above conditions.
526  */
dwc3_gadget_start_config(struct dwc3_ep * dep)527 static int dwc3_gadget_start_config(struct dwc3_ep *dep)
528 {
529 	struct dwc3_gadget_ep_cmd_params params;
530 	struct dwc3		*dwc;
531 	u32			cmd;
532 	int			i;
533 	int			ret;
534 
535 	if (dep->number)
536 		return 0;
537 
538 	memset(&params, 0x00, sizeof(params));
539 	cmd = DWC3_DEPCMD_DEPSTARTCFG;
540 	dwc = dep->dwc;
541 
542 	ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
543 	if (ret)
544 		return ret;
545 
546 	for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
547 		struct dwc3_ep *dep = dwc->eps[i];
548 
549 		if (!dep)
550 			continue;
551 
552 		ret = dwc3_gadget_set_xfer_resource(dep);
553 		if (ret)
554 			return ret;
555 	}
556 
557 	return 0;
558 }
559 
dwc3_gadget_set_ep_config(struct dwc3_ep * dep,unsigned int action)560 static int dwc3_gadget_set_ep_config(struct dwc3_ep *dep, unsigned int action)
561 {
562 	const struct usb_ss_ep_comp_descriptor *comp_desc;
563 	const struct usb_endpoint_descriptor *desc;
564 	struct dwc3_gadget_ep_cmd_params params;
565 	struct dwc3 *dwc = dep->dwc;
566 
567 	comp_desc = dep->endpoint.comp_desc;
568 	desc = dep->endpoint.desc;
569 
570 	memset(&params, 0x00, sizeof(params));
571 
572 	params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc))
573 		| DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc));
574 
575 	/* Burst size is only needed in SuperSpeed mode */
576 	if (dwc->gadget->speed >= USB_SPEED_SUPER) {
577 		u32 burst = dep->endpoint.maxburst;
578 
579 		params.param0 |= DWC3_DEPCFG_BURST_SIZE(burst - 1);
580 	}
581 
582 	params.param0 |= action;
583 	if (action == DWC3_DEPCFG_ACTION_RESTORE)
584 		params.param2 |= dep->saved_state;
585 
586 	if (usb_endpoint_xfer_control(desc))
587 		params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN;
588 
589 	if (dep->number <= 1 || usb_endpoint_xfer_isoc(desc))
590 		params.param1 |= DWC3_DEPCFG_XFER_NOT_READY_EN;
591 
592 	if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) {
593 		params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE
594 			| DWC3_DEPCFG_XFER_COMPLETE_EN
595 			| DWC3_DEPCFG_STREAM_EVENT_EN;
596 		dep->stream_capable = true;
597 	}
598 
599 	if (!usb_endpoint_xfer_control(desc))
600 		params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN;
601 
602 	/*
603 	 * We are doing 1:1 mapping for endpoints, meaning
604 	 * Physical Endpoints 2 maps to Logical Endpoint 2 and
605 	 * so on. We consider the direction bit as part of the physical
606 	 * endpoint number. So USB endpoint 0x81 is 0x03.
607 	 */
608 	params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number);
609 
610 	/*
611 	 * We must use the lower 16 TX FIFOs even though
612 	 * HW might have more
613 	 */
614 	if (dep->direction)
615 		params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1);
616 
617 	if (desc->bInterval) {
618 		u8 bInterval_m1;
619 
620 		/*
621 		 * Valid range for DEPCFG.bInterval_m1 is from 0 to 13.
622 		 *
623 		 * NOTE: The programming guide incorrectly stated bInterval_m1
624 		 * must be set to 0 when operating in fullspeed. Internally the
625 		 * controller does not have this limitation. See DWC_usb3x
626 		 * programming guide section 3.2.2.1.
627 		 */
628 		bInterval_m1 = min_t(u8, desc->bInterval - 1, 13);
629 
630 		if (usb_endpoint_type(desc) == USB_ENDPOINT_XFER_INT &&
631 		    dwc->gadget->speed == USB_SPEED_FULL)
632 			dep->interval = desc->bInterval;
633 		else
634 			dep->interval = 1 << (desc->bInterval - 1);
635 
636 		params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(bInterval_m1);
637 	}
638 
639 	return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETEPCONFIG, &params);
640 }
641 
642 static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force,
643 		bool interrupt);
644 
645 /**
646  * __dwc3_gadget_ep_enable - initializes a hw endpoint
647  * @dep: endpoint to be initialized
648  * @action: one of INIT, MODIFY or RESTORE
649  *
650  * Caller should take care of locking. Execute all necessary commands to
651  * initialize a HW endpoint so it can be used by a gadget driver.
652  */
__dwc3_gadget_ep_enable(struct dwc3_ep * dep,unsigned int action)653 static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action)
654 {
655 	const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
656 	struct dwc3		*dwc = dep->dwc;
657 
658 	u32			reg;
659 	int			ret;
660 
661 	if (!(dep->flags & DWC3_EP_ENABLED)) {
662 		ret = dwc3_gadget_start_config(dep);
663 		if (ret)
664 			return ret;
665 	}
666 
667 	ret = dwc3_gadget_set_ep_config(dep, action);
668 	if (ret)
669 		return ret;
670 
671 	if (!(dep->flags & DWC3_EP_ENABLED)) {
672 		struct dwc3_trb	*trb_st_hw;
673 		struct dwc3_trb	*trb_link;
674 
675 		dep->type = usb_endpoint_type(desc);
676 		dep->flags |= DWC3_EP_ENABLED;
677 
678 		reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
679 		reg |= DWC3_DALEPENA_EP(dep->number);
680 		dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
681 
682 		if (usb_endpoint_xfer_control(desc))
683 			goto out;
684 
685 		/* Initialize the TRB ring */
686 		dep->trb_dequeue = 0;
687 		dep->trb_enqueue = 0;
688 		memset(dep->trb_pool, 0,
689 		       sizeof(struct dwc3_trb) * DWC3_TRB_NUM);
690 
691 		/* Link TRB. The HWO bit is never reset */
692 		trb_st_hw = &dep->trb_pool[0];
693 
694 		trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
695 		trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
696 		trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
697 		trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
698 		trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
699 	}
700 
701 	/*
702 	 * Issue StartTransfer here with no-op TRB so we can always rely on No
703 	 * Response Update Transfer command.
704 	 */
705 	if (usb_endpoint_xfer_bulk(desc) ||
706 			usb_endpoint_xfer_int(desc)) {
707 		struct dwc3_gadget_ep_cmd_params params;
708 		struct dwc3_trb	*trb;
709 		dma_addr_t trb_dma;
710 		u32 cmd;
711 
712 		memset(&params, 0, sizeof(params));
713 		trb = &dep->trb_pool[0];
714 		trb_dma = dwc3_trb_dma_offset(dep, trb);
715 
716 		params.param0 = upper_32_bits(trb_dma);
717 		params.param1 = lower_32_bits(trb_dma);
718 
719 		cmd = DWC3_DEPCMD_STARTTRANSFER;
720 
721 		ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
722 		if (ret < 0)
723 			return ret;
724 
725 		if (dep->stream_capable) {
726 			/*
727 			 * For streams, at start, there maybe a race where the
728 			 * host primes the endpoint before the function driver
729 			 * queues a request to initiate a stream. In that case,
730 			 * the controller will not see the prime to generate the
731 			 * ERDY and start stream. To workaround this, issue a
732 			 * no-op TRB as normal, but end it immediately. As a
733 			 * result, when the function driver queues the request,
734 			 * the next START_TRANSFER command will cause the
735 			 * controller to generate an ERDY to initiate the
736 			 * stream.
737 			 */
738 			dwc3_stop_active_transfer(dep, true, true);
739 
740 			/*
741 			 * All stream eps will reinitiate stream on NoStream
742 			 * rejection until we can determine that the host can
743 			 * prime after the first transfer.
744 			 */
745 			dep->flags |= DWC3_EP_FORCE_RESTART_STREAM;
746 		}
747 	}
748 
749 out:
750 	trace_dwc3_gadget_ep_enable(dep);
751 
752 	return 0;
753 }
754 
dwc3_remove_requests(struct dwc3 * dwc,struct dwc3_ep * dep)755 static void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep)
756 {
757 	struct dwc3_request		*req;
758 
759 	dwc3_stop_active_transfer(dep, true, false);
760 
761 	/* - giveback all requests to gadget driver */
762 	while (!list_empty(&dep->started_list)) {
763 		req = next_request(&dep->started_list);
764 
765 		dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
766 	}
767 
768 	while (!list_empty(&dep->pending_list)) {
769 		req = next_request(&dep->pending_list);
770 
771 		dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
772 	}
773 
774 	while (!list_empty(&dep->cancelled_list)) {
775 		req = next_request(&dep->cancelled_list);
776 
777 		dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
778 	}
779 }
780 
781 /**
782  * __dwc3_gadget_ep_disable - disables a hw endpoint
783  * @dep: the endpoint to disable
784  *
785  * This function undoes what __dwc3_gadget_ep_enable did and also removes
786  * requests which are currently being processed by the hardware and those which
787  * are not yet scheduled.
788  *
789  * Caller should take care of locking.
790  */
__dwc3_gadget_ep_disable(struct dwc3_ep * dep)791 static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
792 {
793 	struct dwc3		*dwc = dep->dwc;
794 	u32			reg;
795 
796 	trace_dwc3_gadget_ep_disable(dep);
797 
798 	/* make sure HW endpoint isn't stalled */
799 	if (dep->flags & DWC3_EP_STALL)
800 		__dwc3_gadget_ep_set_halt(dep, 0, false);
801 
802 	reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
803 	reg &= ~DWC3_DALEPENA_EP(dep->number);
804 	dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
805 
806 	/* Clear out the ep descriptors for non-ep0 */
807 	if (dep->number > 1) {
808 		dep->endpoint.comp_desc = NULL;
809 		dep->endpoint.desc = NULL;
810 	}
811 
812 	dwc3_remove_requests(dwc, dep);
813 
814 	dep->stream_capable = false;
815 	dep->type = 0;
816 	dep->flags = 0;
817 
818 	return 0;
819 }
820 
821 /* -------------------------------------------------------------------------- */
822 
dwc3_gadget_ep0_enable(struct usb_ep * ep,const struct usb_endpoint_descriptor * desc)823 static int dwc3_gadget_ep0_enable(struct usb_ep *ep,
824 		const struct usb_endpoint_descriptor *desc)
825 {
826 	return -EINVAL;
827 }
828 
dwc3_gadget_ep0_disable(struct usb_ep * ep)829 static int dwc3_gadget_ep0_disable(struct usb_ep *ep)
830 {
831 	return -EINVAL;
832 }
833 
834 /* -------------------------------------------------------------------------- */
835 
dwc3_gadget_ep_enable(struct usb_ep * ep,const struct usb_endpoint_descriptor * desc)836 static int dwc3_gadget_ep_enable(struct usb_ep *ep,
837 		const struct usb_endpoint_descriptor *desc)
838 {
839 	struct dwc3_ep			*dep;
840 	struct dwc3			*dwc;
841 	unsigned long			flags;
842 	int				ret;
843 
844 	if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
845 		pr_debug("dwc3: invalid parameters\n");
846 		return -EINVAL;
847 	}
848 
849 	if (!desc->wMaxPacketSize) {
850 		pr_debug("dwc3: missing wMaxPacketSize\n");
851 		return -EINVAL;
852 	}
853 
854 	dep = to_dwc3_ep(ep);
855 	dwc = dep->dwc;
856 
857 	if (dev_WARN_ONCE(dwc->dev, dep->flags & DWC3_EP_ENABLED,
858 					"%s is already enabled\n",
859 					dep->name))
860 		return 0;
861 
862 	spin_lock_irqsave(&dwc->lock, flags);
863 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
864 	spin_unlock_irqrestore(&dwc->lock, flags);
865 
866 	return ret;
867 }
868 
dwc3_gadget_ep_disable(struct usb_ep * ep)869 static int dwc3_gadget_ep_disable(struct usb_ep *ep)
870 {
871 	struct dwc3_ep			*dep;
872 	struct dwc3			*dwc;
873 	unsigned long			flags;
874 	int				ret;
875 
876 	if (!ep) {
877 		pr_debug("dwc3: invalid parameters\n");
878 		return -EINVAL;
879 	}
880 
881 	dep = to_dwc3_ep(ep);
882 	dwc = dep->dwc;
883 
884 	if (dev_WARN_ONCE(dwc->dev, !(dep->flags & DWC3_EP_ENABLED),
885 					"%s is already disabled\n",
886 					dep->name))
887 		return 0;
888 
889 	spin_lock_irqsave(&dwc->lock, flags);
890 	ret = __dwc3_gadget_ep_disable(dep);
891 	spin_unlock_irqrestore(&dwc->lock, flags);
892 
893 	return ret;
894 }
895 
dwc3_gadget_ep_alloc_request(struct usb_ep * ep,gfp_t gfp_flags)896 static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep,
897 		gfp_t gfp_flags)
898 {
899 	struct dwc3_request		*req;
900 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
901 
902 	req = kzalloc(sizeof(*req), gfp_flags);
903 	if (!req)
904 		return NULL;
905 
906 	req->direction	= dep->direction;
907 	req->epnum	= dep->number;
908 	req->dep	= dep;
909 	req->status	= DWC3_REQUEST_STATUS_UNKNOWN;
910 
911 	trace_dwc3_alloc_request(req);
912 
913 	return &req->request;
914 }
915 
dwc3_gadget_ep_free_request(struct usb_ep * ep,struct usb_request * request)916 static void dwc3_gadget_ep_free_request(struct usb_ep *ep,
917 		struct usb_request *request)
918 {
919 	struct dwc3_request		*req = to_dwc3_request(request);
920 
921 	trace_dwc3_free_request(req);
922 	kfree(req);
923 }
924 
925 /**
926  * dwc3_ep_prev_trb - returns the previous TRB in the ring
927  * @dep: The endpoint with the TRB ring
928  * @index: The index of the current TRB in the ring
929  *
930  * Returns the TRB prior to the one pointed to by the index. If the
931  * index is 0, we will wrap backwards, skip the link TRB, and return
932  * the one just before that.
933  */
dwc3_ep_prev_trb(struct dwc3_ep * dep,u8 index)934 static struct dwc3_trb *dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index)
935 {
936 	u8 tmp = index;
937 
938 	if (!tmp)
939 		tmp = DWC3_TRB_NUM - 1;
940 
941 	return &dep->trb_pool[tmp - 1];
942 }
943 
dwc3_calc_trbs_left(struct dwc3_ep * dep)944 static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep)
945 {
946 	u8			trbs_left;
947 
948 	/*
949 	 * If the enqueue & dequeue are equal then the TRB ring is either full
950 	 * or empty. It's considered full when there are DWC3_TRB_NUM-1 of TRBs
951 	 * pending to be processed by the driver.
952 	 */
953 	if (dep->trb_enqueue == dep->trb_dequeue) {
954 		/*
955 		 * If there is any request remained in the started_list at
956 		 * this point, that means there is no TRB available.
957 		 */
958 		if (!list_empty(&dep->started_list))
959 			return 0;
960 
961 		return DWC3_TRB_NUM - 1;
962 	}
963 
964 	trbs_left = dep->trb_dequeue - dep->trb_enqueue;
965 	trbs_left &= (DWC3_TRB_NUM - 1);
966 
967 	if (dep->trb_dequeue < dep->trb_enqueue)
968 		trbs_left--;
969 
970 	return trbs_left;
971 }
972 
__dwc3_prepare_one_trb(struct dwc3_ep * dep,struct dwc3_trb * trb,dma_addr_t dma,unsigned int length,unsigned int chain,unsigned int node,unsigned int stream_id,unsigned int short_not_ok,unsigned int no_interrupt,unsigned int is_last,bool must_interrupt)973 static void __dwc3_prepare_one_trb(struct dwc3_ep *dep, struct dwc3_trb *trb,
974 		dma_addr_t dma, unsigned int length, unsigned int chain,
975 		unsigned int node, unsigned int stream_id,
976 		unsigned int short_not_ok, unsigned int no_interrupt,
977 		unsigned int is_last, bool must_interrupt)
978 {
979 	struct dwc3		*dwc = dep->dwc;
980 	struct usb_gadget	*gadget = dwc->gadget;
981 	enum usb_device_speed	speed = gadget->speed;
982 
983 	trb->size = DWC3_TRB_SIZE_LENGTH(length);
984 	trb->bpl = lower_32_bits(dma);
985 	trb->bph = upper_32_bits(dma);
986 
987 	switch (usb_endpoint_type(dep->endpoint.desc)) {
988 	case USB_ENDPOINT_XFER_CONTROL:
989 		trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP;
990 		break;
991 
992 	case USB_ENDPOINT_XFER_ISOC:
993 		if (!node) {
994 			trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST;
995 
996 			/*
997 			 * USB Specification 2.0 Section 5.9.2 states that: "If
998 			 * there is only a single transaction in the microframe,
999 			 * only a DATA0 data packet PID is used.  If there are
1000 			 * two transactions per microframe, DATA1 is used for
1001 			 * the first transaction data packet and DATA0 is used
1002 			 * for the second transaction data packet.  If there are
1003 			 * three transactions per microframe, DATA2 is used for
1004 			 * the first transaction data packet, DATA1 is used for
1005 			 * the second, and DATA0 is used for the third."
1006 			 *
1007 			 * IOW, we should satisfy the following cases:
1008 			 *
1009 			 * 1) length <= maxpacket
1010 			 *	- DATA0
1011 			 *
1012 			 * 2) maxpacket < length <= (2 * maxpacket)
1013 			 *	- DATA1, DATA0
1014 			 *
1015 			 * 3) (2 * maxpacket) < length <= (3 * maxpacket)
1016 			 *	- DATA2, DATA1, DATA0
1017 			 */
1018 			if (speed == USB_SPEED_HIGH) {
1019 				struct usb_ep *ep = &dep->endpoint;
1020 				unsigned int mult = 2;
1021 				unsigned int maxp = usb_endpoint_maxp(ep->desc);
1022 
1023 				if (length <= (2 * maxp))
1024 					mult--;
1025 
1026 				if (length <= maxp)
1027 					mult--;
1028 
1029 				trb->size |= DWC3_TRB_SIZE_PCM1(mult);
1030 			}
1031 		} else {
1032 			trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS;
1033 		}
1034 
1035 		/* always enable Interrupt on Missed ISOC */
1036 		trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1037 		break;
1038 
1039 	case USB_ENDPOINT_XFER_BULK:
1040 	case USB_ENDPOINT_XFER_INT:
1041 		trb->ctrl = DWC3_TRBCTL_NORMAL;
1042 		break;
1043 	default:
1044 		/*
1045 		 * This is only possible with faulty memory because we
1046 		 * checked it already :)
1047 		 */
1048 		dev_WARN(dwc->dev, "Unknown endpoint type %d\n",
1049 				usb_endpoint_type(dep->endpoint.desc));
1050 	}
1051 
1052 	/*
1053 	 * Enable Continue on Short Packet
1054 	 * when endpoint is not a stream capable
1055 	 */
1056 	if (usb_endpoint_dir_out(dep->endpoint.desc)) {
1057 		if (!dep->stream_capable)
1058 			trb->ctrl |= DWC3_TRB_CTRL_CSP;
1059 
1060 		if (short_not_ok)
1061 			trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1062 	}
1063 
1064 	if ((!no_interrupt && !chain) || must_interrupt)
1065 		trb->ctrl |= DWC3_TRB_CTRL_IOC;
1066 
1067 	if (chain)
1068 		trb->ctrl |= DWC3_TRB_CTRL_CHN;
1069 	else if (dep->stream_capable && is_last)
1070 		trb->ctrl |= DWC3_TRB_CTRL_LST;
1071 
1072 	if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable)
1073 		trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(stream_id);
1074 
1075 	trb->ctrl |= DWC3_TRB_CTRL_HWO;
1076 
1077 	dwc3_ep_inc_enq(dep);
1078 
1079 	trace_dwc3_prepare_trb(dep, trb);
1080 }
1081 
1082 /**
1083  * dwc3_prepare_one_trb - setup one TRB from one request
1084  * @dep: endpoint for which this request is prepared
1085  * @req: dwc3_request pointer
1086  * @trb_length: buffer size of the TRB
1087  * @chain: should this TRB be chained to the next?
1088  * @node: only for isochronous endpoints. First TRB needs different type.
1089  * @use_bounce_buffer: set to use bounce buffer
1090  * @must_interrupt: set to interrupt on TRB completion
1091  */
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)1092 static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
1093 		struct dwc3_request *req, unsigned int trb_length,
1094 		unsigned int chain, unsigned int node, bool use_bounce_buffer,
1095 		bool must_interrupt)
1096 {
1097 	struct dwc3_trb		*trb;
1098 	dma_addr_t		dma;
1099 	unsigned int		stream_id = req->request.stream_id;
1100 	unsigned int		short_not_ok = req->request.short_not_ok;
1101 	unsigned int		no_interrupt = req->request.no_interrupt;
1102 	unsigned int		is_last = req->request.is_last;
1103 
1104 	if (use_bounce_buffer)
1105 		dma = dep->dwc->bounce_addr;
1106 	else if (req->request.num_sgs > 0)
1107 		dma = sg_dma_address(req->start_sg);
1108 	else
1109 		dma = req->request.dma;
1110 
1111 	trb = &dep->trb_pool[dep->trb_enqueue];
1112 
1113 	if (!req->trb) {
1114 		dwc3_gadget_move_started_request(req);
1115 		req->trb = trb;
1116 		req->trb_dma = dwc3_trb_dma_offset(dep, trb);
1117 	}
1118 
1119 	req->num_trbs++;
1120 
1121 	__dwc3_prepare_one_trb(dep, trb, dma, trb_length, chain, node,
1122 			stream_id, short_not_ok, no_interrupt, is_last,
1123 			must_interrupt);
1124 }
1125 
dwc3_needs_extra_trb(struct dwc3_ep * dep,struct dwc3_request * req)1126 static bool dwc3_needs_extra_trb(struct dwc3_ep *dep, struct dwc3_request *req)
1127 {
1128 	unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1129 	unsigned int rem = req->request.length % maxp;
1130 
1131 	if ((req->request.length && req->request.zero && !rem &&
1132 			!usb_endpoint_xfer_isoc(dep->endpoint.desc)) ||
1133 			(!req->direction && rem))
1134 		return true;
1135 
1136 	return false;
1137 }
1138 
1139 /**
1140  * dwc3_prepare_last_sg - prepare TRBs for the last SG entry
1141  * @dep: The endpoint that the request belongs to
1142  * @req: The request to prepare
1143  * @entry_length: The last SG entry size
1144  * @node: Indicates whether this is not the first entry (for isoc only)
1145  *
1146  * Return the number of TRBs prepared.
1147  */
dwc3_prepare_last_sg(struct dwc3_ep * dep,struct dwc3_request * req,unsigned int entry_length,unsigned int node)1148 static int dwc3_prepare_last_sg(struct dwc3_ep *dep,
1149 		struct dwc3_request *req, unsigned int entry_length,
1150 		unsigned int node)
1151 {
1152 	unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1153 	unsigned int rem = req->request.length % maxp;
1154 	unsigned int num_trbs = 1;
1155 
1156 	if (dwc3_needs_extra_trb(dep, req))
1157 		num_trbs++;
1158 
1159 	if (dwc3_calc_trbs_left(dep) < num_trbs)
1160 		return 0;
1161 
1162 	req->needs_extra_trb = num_trbs > 1;
1163 
1164 	/* Prepare a normal TRB */
1165 	if (req->direction || req->request.length)
1166 		dwc3_prepare_one_trb(dep, req, entry_length,
1167 				req->needs_extra_trb, node, false, false);
1168 
1169 	/* Prepare extra TRBs for ZLP and MPS OUT transfer alignment */
1170 	if ((!req->direction && !req->request.length) || req->needs_extra_trb)
1171 		dwc3_prepare_one_trb(dep, req,
1172 				req->direction ? 0 : maxp - rem,
1173 				false, 1, true, false);
1174 
1175 	return num_trbs;
1176 }
1177 
dwc3_prepare_trbs_sg(struct dwc3_ep * dep,struct dwc3_request * req)1178 static int dwc3_prepare_trbs_sg(struct dwc3_ep *dep,
1179 		struct dwc3_request *req)
1180 {
1181 	struct scatterlist *sg = req->start_sg;
1182 	struct scatterlist *s;
1183 	int		i;
1184 	unsigned int length = req->request.length;
1185 	unsigned int remaining = req->request.num_mapped_sgs
1186 		- req->num_queued_sgs;
1187 	unsigned int num_trbs = req->num_trbs;
1188 	bool needs_extra_trb = dwc3_needs_extra_trb(dep, req);
1189 
1190 	/*
1191 	 * If we resume preparing the request, then get the remaining length of
1192 	 * the request and resume where we left off.
1193 	 */
1194 	for_each_sg(req->request.sg, s, req->num_queued_sgs, i)
1195 		length -= sg_dma_len(s);
1196 
1197 	for_each_sg(sg, s, remaining, i) {
1198 		unsigned int num_trbs_left = dwc3_calc_trbs_left(dep);
1199 		unsigned int trb_length;
1200 		bool must_interrupt = false;
1201 		bool last_sg = false;
1202 
1203 		trb_length = min_t(unsigned int, length, sg_dma_len(s));
1204 
1205 		length -= trb_length;
1206 
1207 		/*
1208 		 * IOMMU driver is coalescing the list of sgs which shares a
1209 		 * page boundary into one and giving it to USB driver. With
1210 		 * this the number of sgs mapped is not equal to the number of
1211 		 * sgs passed. So mark the chain bit to false if it isthe last
1212 		 * mapped sg.
1213 		 */
1214 		if ((i == remaining - 1) || !length)
1215 			last_sg = true;
1216 
1217 		if (!num_trbs_left)
1218 			break;
1219 
1220 		if (last_sg) {
1221 			if (!dwc3_prepare_last_sg(dep, req, trb_length, i))
1222 				break;
1223 		} else {
1224 			/*
1225 			 * Look ahead to check if we have enough TRBs for the
1226 			 * next SG entry. If not, set interrupt on this TRB to
1227 			 * resume preparing the next SG entry when more TRBs are
1228 			 * free.
1229 			 */
1230 			if (num_trbs_left == 1 || (needs_extra_trb &&
1231 					num_trbs_left <= 2 &&
1232 					sg_dma_len(sg_next(s)) >= length))
1233 				must_interrupt = true;
1234 
1235 			dwc3_prepare_one_trb(dep, req, trb_length, 1, i, false,
1236 					must_interrupt);
1237 		}
1238 
1239 		/*
1240 		 * There can be a situation where all sgs in sglist are not
1241 		 * queued because of insufficient trb number. To handle this
1242 		 * case, update start_sg to next sg to be queued, so that
1243 		 * we have free trbs we can continue queuing from where we
1244 		 * previously stopped
1245 		 */
1246 		if (!last_sg)
1247 			req->start_sg = sg_next(s);
1248 
1249 		req->num_queued_sgs++;
1250 		req->num_pending_sgs--;
1251 
1252 		/*
1253 		 * The number of pending SG entries may not correspond to the
1254 		 * number of mapped SG entries. If all the data are queued, then
1255 		 * don't include unused SG entries.
1256 		 */
1257 		if (length == 0) {
1258 			req->num_pending_sgs = 0;
1259 			break;
1260 		}
1261 
1262 		if (must_interrupt)
1263 			break;
1264 	}
1265 
1266 	return req->num_trbs - num_trbs;
1267 }
1268 
dwc3_prepare_trbs_linear(struct dwc3_ep * dep,struct dwc3_request * req)1269 static int dwc3_prepare_trbs_linear(struct dwc3_ep *dep,
1270 		struct dwc3_request *req)
1271 {
1272 	return dwc3_prepare_last_sg(dep, req, req->request.length, 0);
1273 }
1274 
1275 /*
1276  * dwc3_prepare_trbs - setup TRBs from requests
1277  * @dep: endpoint for which requests are being prepared
1278  *
1279  * The function goes through the requests list and sets up TRBs for the
1280  * transfers. The function returns once there are no more TRBs available or
1281  * it runs out of requests.
1282  *
1283  * Returns the number of TRBs prepared or negative errno.
1284  */
dwc3_prepare_trbs(struct dwc3_ep * dep)1285 static int dwc3_prepare_trbs(struct dwc3_ep *dep)
1286 {
1287 	struct dwc3_request	*req, *n;
1288 	int			ret = 0;
1289 
1290 	BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
1291 
1292 	/*
1293 	 * We can get in a situation where there's a request in the started list
1294 	 * but there weren't enough TRBs to fully kick it in the first time
1295 	 * around, so it has been waiting for more TRBs to be freed up.
1296 	 *
1297 	 * In that case, we should check if we have a request with pending_sgs
1298 	 * in the started list and prepare TRBs for that request first,
1299 	 * otherwise we will prepare TRBs completely out of order and that will
1300 	 * break things.
1301 	 */
1302 	list_for_each_entry(req, &dep->started_list, list) {
1303 		if (req->num_pending_sgs > 0) {
1304 			ret = dwc3_prepare_trbs_sg(dep, req);
1305 			if (!ret || req->num_pending_sgs)
1306 				return ret;
1307 		}
1308 
1309 		if (!dwc3_calc_trbs_left(dep))
1310 			return ret;
1311 
1312 		/*
1313 		 * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1314 		 * burst capability may try to read and use TRBs beyond the
1315 		 * active transfer instead of stopping.
1316 		 */
1317 		if (dep->stream_capable && req->request.is_last)
1318 			return ret;
1319 	}
1320 
1321 	list_for_each_entry_safe(req, n, &dep->pending_list, list) {
1322 		struct dwc3	*dwc = dep->dwc;
1323 
1324 		ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request,
1325 						    dep->direction);
1326 		if (ret)
1327 			return ret;
1328 
1329 		req->sg			= req->request.sg;
1330 		req->start_sg		= req->sg;
1331 		req->num_queued_sgs	= 0;
1332 		req->num_pending_sgs	= req->request.num_mapped_sgs;
1333 
1334 		if (req->num_pending_sgs > 0) {
1335 			ret = dwc3_prepare_trbs_sg(dep, req);
1336 			if (req->num_pending_sgs)
1337 				return ret;
1338 		} else {
1339 			ret = dwc3_prepare_trbs_linear(dep, req);
1340 		}
1341 
1342 		if (!ret || !dwc3_calc_trbs_left(dep))
1343 			return ret;
1344 
1345 		/*
1346 		 * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1347 		 * burst capability may try to read and use TRBs beyond the
1348 		 * active transfer instead of stopping.
1349 		 */
1350 		if (dep->stream_capable && req->request.is_last)
1351 			return ret;
1352 	}
1353 
1354 	return ret;
1355 }
1356 
1357 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep);
1358 
__dwc3_gadget_kick_transfer(struct dwc3_ep * dep)1359 static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep)
1360 {
1361 	struct dwc3_gadget_ep_cmd_params params;
1362 	struct dwc3_request		*req;
1363 	int				starting;
1364 	int				ret;
1365 	u32				cmd;
1366 
1367 	/*
1368 	 * Note that it's normal to have no new TRBs prepared (i.e. ret == 0).
1369 	 * This happens when we need to stop and restart a transfer such as in
1370 	 * the case of reinitiating a stream or retrying an isoc transfer.
1371 	 */
1372 	ret = dwc3_prepare_trbs(dep);
1373 	if (ret < 0)
1374 		return ret;
1375 
1376 	starting = !(dep->flags & DWC3_EP_TRANSFER_STARTED);
1377 
1378 	/*
1379 	 * If there's no new TRB prepared and we don't need to restart a
1380 	 * transfer, there's no need to update the transfer.
1381 	 */
1382 	if (!ret && !starting)
1383 		return ret;
1384 
1385 	req = next_request(&dep->started_list);
1386 	if (!req) {
1387 		dep->flags |= DWC3_EP_PENDING_REQUEST;
1388 		return 0;
1389 	}
1390 
1391 	memset(&params, 0, sizeof(params));
1392 
1393 	if (starting) {
1394 		params.param0 = upper_32_bits(req->trb_dma);
1395 		params.param1 = lower_32_bits(req->trb_dma);
1396 		cmd = DWC3_DEPCMD_STARTTRANSFER;
1397 
1398 		if (dep->stream_capable)
1399 			cmd |= DWC3_DEPCMD_PARAM(req->request.stream_id);
1400 
1401 		if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
1402 			cmd |= DWC3_DEPCMD_PARAM(dep->frame_number);
1403 	} else {
1404 		cmd = DWC3_DEPCMD_UPDATETRANSFER |
1405 			DWC3_DEPCMD_PARAM(dep->resource_index);
1406 	}
1407 
1408 	ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1409 	if (ret < 0) {
1410 		struct dwc3_request *tmp;
1411 
1412 		if (ret == -EAGAIN)
1413 			return ret;
1414 
1415 		dwc3_stop_active_transfer(dep, true, true);
1416 
1417 		list_for_each_entry_safe(req, tmp, &dep->started_list, list)
1418 			dwc3_gadget_move_cancelled_request(req);
1419 
1420 		/* If ep isn't started, then there's no end transfer pending */
1421 		if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
1422 			dwc3_gadget_ep_cleanup_cancelled_requests(dep);
1423 
1424 		return ret;
1425 	}
1426 
1427 	if (dep->stream_capable && req->request.is_last)
1428 		dep->flags |= DWC3_EP_WAIT_TRANSFER_COMPLETE;
1429 
1430 	return 0;
1431 }
1432 
__dwc3_gadget_get_frame(struct dwc3 * dwc)1433 static int __dwc3_gadget_get_frame(struct dwc3 *dwc)
1434 {
1435 	u32			reg;
1436 
1437 	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1438 	return DWC3_DSTS_SOFFN(reg);
1439 }
1440 
1441 /**
1442  * dwc3_gadget_start_isoc_quirk - workaround invalid frame number
1443  * @dep: isoc endpoint
1444  *
1445  * This function tests for the correct combination of BIT[15:14] from the 16-bit
1446  * microframe number reported by the XferNotReady event for the future frame
1447  * number to start the isoc transfer.
1448  *
1449  * In DWC_usb31 version 1.70a-ea06 and prior, for highspeed and fullspeed
1450  * isochronous IN, BIT[15:14] of the 16-bit microframe number reported by the
1451  * XferNotReady event are invalid. The driver uses this number to schedule the
1452  * isochronous transfer and passes it to the START TRANSFER command. Because
1453  * this number is invalid, the command may fail. If BIT[15:14] matches the
1454  * internal 16-bit microframe, the START TRANSFER command will pass and the
1455  * transfer will start at the scheduled time, if it is off by 1, the command
1456  * will still pass, but the transfer will start 2 seconds in the future. For all
1457  * other conditions, the START TRANSFER command will fail with bus-expiry.
1458  *
1459  * In order to workaround this issue, we can test for the correct combination of
1460  * BIT[15:14] by sending START TRANSFER commands with different values of
1461  * BIT[15:14]: 'b00, 'b01, 'b10, and 'b11. Each combination is 2^14 uframe apart
1462  * (or 2 seconds). 4 seconds into the future will result in a bus-expiry status.
1463  * As the result, within the 4 possible combinations for BIT[15:14], there will
1464  * be 2 successful and 2 failure START COMMAND status. One of the 2 successful
1465  * command status will result in a 2-second delay start. The smaller BIT[15:14]
1466  * value is the correct combination.
1467  *
1468  * Since there are only 4 outcomes and the results are ordered, we can simply
1469  * test 2 START TRANSFER commands with BIT[15:14] combinations 'b00 and 'b01 to
1470  * deduce the smaller successful combination.
1471  *
1472  * Let test0 = test status for combination 'b00 and test1 = test status for 'b01
1473  * of BIT[15:14]. The correct combination is as follow:
1474  *
1475  * if test0 fails and test1 passes, BIT[15:14] is 'b01
1476  * if test0 fails and test1 fails, BIT[15:14] is 'b10
1477  * if test0 passes and test1 fails, BIT[15:14] is 'b11
1478  * if test0 passes and test1 passes, BIT[15:14] is 'b00
1479  *
1480  * Synopsys STAR 9001202023: Wrong microframe number for isochronous IN
1481  * endpoints.
1482  */
dwc3_gadget_start_isoc_quirk(struct dwc3_ep * dep)1483 static int dwc3_gadget_start_isoc_quirk(struct dwc3_ep *dep)
1484 {
1485 	int cmd_status = 0;
1486 	bool test0;
1487 	bool test1;
1488 
1489 	while (dep->combo_num < 2) {
1490 		struct dwc3_gadget_ep_cmd_params params;
1491 		u32 test_frame_number;
1492 		u32 cmd;
1493 
1494 		/*
1495 		 * Check if we can start isoc transfer on the next interval or
1496 		 * 4 uframes in the future with BIT[15:14] as dep->combo_num
1497 		 */
1498 		test_frame_number = dep->frame_number & DWC3_FRNUMBER_MASK;
1499 		test_frame_number |= dep->combo_num << 14;
1500 		test_frame_number += max_t(u32, 4, dep->interval);
1501 
1502 		params.param0 = upper_32_bits(dep->dwc->bounce_addr);
1503 		params.param1 = lower_32_bits(dep->dwc->bounce_addr);
1504 
1505 		cmd = DWC3_DEPCMD_STARTTRANSFER;
1506 		cmd |= DWC3_DEPCMD_PARAM(test_frame_number);
1507 		cmd_status = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1508 
1509 		/* Redo if some other failure beside bus-expiry is received */
1510 		if (cmd_status && cmd_status != -EAGAIN) {
1511 			dep->start_cmd_status = 0;
1512 			dep->combo_num = 0;
1513 			return 0;
1514 		}
1515 
1516 		/* Store the first test status */
1517 		if (dep->combo_num == 0)
1518 			dep->start_cmd_status = cmd_status;
1519 
1520 		dep->combo_num++;
1521 
1522 		/*
1523 		 * End the transfer if the START_TRANSFER command is successful
1524 		 * to wait for the next XferNotReady to test the command again
1525 		 */
1526 		if (cmd_status == 0) {
1527 			dwc3_stop_active_transfer(dep, true, true);
1528 			return 0;
1529 		}
1530 	}
1531 
1532 	/* test0 and test1 are both completed at this point */
1533 	test0 = (dep->start_cmd_status == 0);
1534 	test1 = (cmd_status == 0);
1535 
1536 	if (!test0 && test1)
1537 		dep->combo_num = 1;
1538 	else if (!test0 && !test1)
1539 		dep->combo_num = 2;
1540 	else if (test0 && !test1)
1541 		dep->combo_num = 3;
1542 	else if (test0 && test1)
1543 		dep->combo_num = 0;
1544 
1545 	dep->frame_number &= DWC3_FRNUMBER_MASK;
1546 	dep->frame_number |= dep->combo_num << 14;
1547 	dep->frame_number += max_t(u32, 4, dep->interval);
1548 
1549 	/* Reinitialize test variables */
1550 	dep->start_cmd_status = 0;
1551 	dep->combo_num = 0;
1552 
1553 	return __dwc3_gadget_kick_transfer(dep);
1554 }
1555 
__dwc3_gadget_start_isoc(struct dwc3_ep * dep)1556 static int __dwc3_gadget_start_isoc(struct dwc3_ep *dep)
1557 {
1558 	const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
1559 	struct dwc3 *dwc = dep->dwc;
1560 	int ret;
1561 	int i;
1562 
1563 	if (list_empty(&dep->pending_list) &&
1564 	    list_empty(&dep->started_list)) {
1565 		dep->flags |= DWC3_EP_PENDING_REQUEST;
1566 		return -EAGAIN;
1567 	}
1568 
1569 	if (!dwc->dis_start_transfer_quirk &&
1570 	    (DWC3_VER_IS_PRIOR(DWC31, 170A) ||
1571 	     DWC3_VER_TYPE_IS_WITHIN(DWC31, 170A, EA01, EA06))) {
1572 		if (dwc->gadget->speed <= USB_SPEED_HIGH && dep->direction)
1573 			return dwc3_gadget_start_isoc_quirk(dep);
1574 	}
1575 
1576 	if (desc->bInterval <= 14 &&
1577 	    dwc->gadget->speed >= USB_SPEED_HIGH) {
1578 		u32 frame = __dwc3_gadget_get_frame(dwc);
1579 		bool rollover = frame <
1580 				(dep->frame_number & DWC3_FRNUMBER_MASK);
1581 
1582 		/*
1583 		 * frame_number is set from XferNotReady and may be already
1584 		 * out of date. DSTS only provides the lower 14 bit of the
1585 		 * current frame number. So add the upper two bits of
1586 		 * frame_number and handle a possible rollover.
1587 		 * This will provide the correct frame_number unless more than
1588 		 * rollover has happened since XferNotReady.
1589 		 */
1590 
1591 		dep->frame_number = (dep->frame_number & ~DWC3_FRNUMBER_MASK) |
1592 				     frame;
1593 		if (rollover)
1594 			dep->frame_number += BIT(14);
1595 	}
1596 
1597 	for (i = 0; i < DWC3_ISOC_MAX_RETRIES; i++) {
1598 		dep->frame_number = DWC3_ALIGN_FRAME(dep, i + 1);
1599 
1600 		ret = __dwc3_gadget_kick_transfer(dep);
1601 		if (ret != -EAGAIN)
1602 			break;
1603 	}
1604 
1605 	/*
1606 	 * After a number of unsuccessful start attempts due to bus-expiry
1607 	 * status, issue END_TRANSFER command and retry on the next XferNotReady
1608 	 * event.
1609 	 */
1610 	if (ret == -EAGAIN) {
1611 		struct dwc3_gadget_ep_cmd_params params;
1612 		u32 cmd;
1613 
1614 		cmd = DWC3_DEPCMD_ENDTRANSFER |
1615 			DWC3_DEPCMD_CMDIOC |
1616 			DWC3_DEPCMD_PARAM(dep->resource_index);
1617 
1618 		dep->resource_index = 0;
1619 		memset(&params, 0, sizeof(params));
1620 
1621 		ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1622 		if (!ret)
1623 			dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
1624 	}
1625 
1626 	return ret;
1627 }
1628 
__dwc3_gadget_ep_queue(struct dwc3_ep * dep,struct dwc3_request * req)1629 static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
1630 {
1631 	struct dwc3		*dwc = dep->dwc;
1632 
1633 	if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) {
1634 		dev_err(dwc->dev, "%s: can't queue to disabled endpoint\n",
1635 				dep->name);
1636 		return -ESHUTDOWN;
1637 	}
1638 
1639 	if (WARN(req->dep != dep, "request %pK belongs to '%s'\n",
1640 				&req->request, req->dep->name))
1641 		return -EINVAL;
1642 
1643 	if (WARN(req->status < DWC3_REQUEST_STATUS_COMPLETED,
1644 				"%s: request %pK already in flight\n",
1645 				dep->name, &req->request))
1646 		return -EINVAL;
1647 
1648 	pm_runtime_get(dwc->dev);
1649 
1650 	req->request.actual	= 0;
1651 	req->request.status	= -EINPROGRESS;
1652 
1653 	trace_dwc3_ep_queue(req);
1654 
1655 	list_add_tail(&req->list, &dep->pending_list);
1656 	req->status = DWC3_REQUEST_STATUS_QUEUED;
1657 
1658 	if (dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE)
1659 		return 0;
1660 
1661 	/*
1662 	 * Start the transfer only after the END_TRANSFER is completed
1663 	 * and endpoint STALL is cleared.
1664 	 */
1665 	if ((dep->flags & DWC3_EP_END_TRANSFER_PENDING) ||
1666 	    (dep->flags & DWC3_EP_WEDGE) ||
1667 	    (dep->flags & DWC3_EP_STALL)) {
1668 		dep->flags |= DWC3_EP_DELAY_START;
1669 		return 0;
1670 	}
1671 
1672 	/*
1673 	 * NOTICE: Isochronous endpoints should NEVER be prestarted. We must
1674 	 * wait for a XferNotReady event so we will know what's the current
1675 	 * (micro-)frame number.
1676 	 *
1677 	 * Without this trick, we are very, very likely gonna get Bus Expiry
1678 	 * errors which will force us issue EndTransfer command.
1679 	 */
1680 	if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1681 		if (!(dep->flags & DWC3_EP_PENDING_REQUEST) &&
1682 				!(dep->flags & DWC3_EP_TRANSFER_STARTED))
1683 			return 0;
1684 
1685 		if ((dep->flags & DWC3_EP_PENDING_REQUEST)) {
1686 			if (!(dep->flags & DWC3_EP_TRANSFER_STARTED))
1687 				return __dwc3_gadget_start_isoc(dep);
1688 		}
1689 	}
1690 
1691 	__dwc3_gadget_kick_transfer(dep);
1692 
1693 	return 0;
1694 }
1695 
dwc3_gadget_ep_queue(struct usb_ep * ep,struct usb_request * request,gfp_t gfp_flags)1696 static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
1697 	gfp_t gfp_flags)
1698 {
1699 	struct dwc3_request		*req = to_dwc3_request(request);
1700 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1701 	struct dwc3			*dwc = dep->dwc;
1702 
1703 	unsigned long			flags;
1704 
1705 	int				ret;
1706 
1707 	spin_lock_irqsave(&dwc->lock, flags);
1708 	ret = __dwc3_gadget_ep_queue(dep, req);
1709 	spin_unlock_irqrestore(&dwc->lock, flags);
1710 
1711 	return ret;
1712 }
1713 
dwc3_gadget_ep_skip_trbs(struct dwc3_ep * dep,struct dwc3_request * req)1714 static void dwc3_gadget_ep_skip_trbs(struct dwc3_ep *dep, struct dwc3_request *req)
1715 {
1716 	int i;
1717 
1718 	/* If req->trb is not set, then the request has not started */
1719 	if (!req->trb)
1720 		return;
1721 
1722 	/*
1723 	 * If request was already started, this means we had to
1724 	 * stop the transfer. With that we also need to ignore
1725 	 * all TRBs used by the request, however TRBs can only
1726 	 * be modified after completion of END_TRANSFER
1727 	 * command. So what we do here is that we wait for
1728 	 * END_TRANSFER completion and only after that, we jump
1729 	 * over TRBs by clearing HWO and incrementing dequeue
1730 	 * pointer.
1731 	 */
1732 	for (i = 0; i < req->num_trbs; i++) {
1733 		struct dwc3_trb *trb;
1734 
1735 		trb = &dep->trb_pool[dep->trb_dequeue];
1736 		trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1737 		dwc3_ep_inc_deq(dep);
1738 	}
1739 
1740 	req->num_trbs = 0;
1741 }
1742 
dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep * dep)1743 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep)
1744 {
1745 	struct dwc3_request		*req;
1746 	struct dwc3_request		*tmp;
1747 
1748 	list_for_each_entry_safe(req, tmp, &dep->cancelled_list, list) {
1749 		dwc3_gadget_ep_skip_trbs(dep, req);
1750 		dwc3_gadget_giveback(dep, req, -ECONNRESET);
1751 	}
1752 }
1753 
dwc3_gadget_ep_dequeue(struct usb_ep * ep,struct usb_request * request)1754 static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
1755 		struct usb_request *request)
1756 {
1757 	struct dwc3_request		*req = to_dwc3_request(request);
1758 	struct dwc3_request		*r = NULL;
1759 
1760 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1761 	struct dwc3			*dwc = dep->dwc;
1762 
1763 	unsigned long			flags;
1764 	int				ret = 0;
1765 
1766 	trace_dwc3_ep_dequeue(req);
1767 
1768 	spin_lock_irqsave(&dwc->lock, flags);
1769 
1770 	list_for_each_entry(r, &dep->cancelled_list, list) {
1771 		if (r == req)
1772 			goto out;
1773 	}
1774 
1775 	list_for_each_entry(r, &dep->pending_list, list) {
1776 		if (r == req) {
1777 			dwc3_gadget_giveback(dep, req, -ECONNRESET);
1778 			goto out;
1779 		}
1780 	}
1781 
1782 	list_for_each_entry(r, &dep->started_list, list) {
1783 		if (r == req) {
1784 			struct dwc3_request *t;
1785 
1786 			/* wait until it is processed */
1787 			dwc3_stop_active_transfer(dep, true, true);
1788 
1789 			/*
1790 			 * Remove any started request if the transfer is
1791 			 * cancelled.
1792 			 */
1793 			list_for_each_entry_safe(r, t, &dep->started_list, list)
1794 				dwc3_gadget_move_cancelled_request(r);
1795 
1796 			dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
1797 
1798 			goto out;
1799 		}
1800 	}
1801 
1802 	dev_err(dwc->dev, "request %pK was not queued to %s\n",
1803 		request, ep->name);
1804 	ret = -EINVAL;
1805 out:
1806 	spin_unlock_irqrestore(&dwc->lock, flags);
1807 
1808 	return ret;
1809 }
1810 
__dwc3_gadget_ep_set_halt(struct dwc3_ep * dep,int value,int protocol)1811 int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
1812 {
1813 	struct dwc3_gadget_ep_cmd_params	params;
1814 	struct dwc3				*dwc = dep->dwc;
1815 	struct dwc3_request			*req;
1816 	struct dwc3_request			*tmp;
1817 	int					ret;
1818 
1819 	if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1820 		dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
1821 		return -EINVAL;
1822 	}
1823 
1824 	memset(&params, 0x00, sizeof(params));
1825 
1826 	if (value) {
1827 		struct dwc3_trb *trb;
1828 
1829 		unsigned int transfer_in_flight;
1830 		unsigned int started;
1831 
1832 		if (dep->number > 1)
1833 			trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
1834 		else
1835 			trb = &dwc->ep0_trb[dep->trb_enqueue];
1836 
1837 		transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO;
1838 		started = !list_empty(&dep->started_list);
1839 
1840 		if (!protocol && ((dep->direction && transfer_in_flight) ||
1841 				(!dep->direction && started))) {
1842 			return -EAGAIN;
1843 		}
1844 
1845 		ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL,
1846 				&params);
1847 		if (ret)
1848 			dev_err(dwc->dev, "failed to set STALL on %s\n",
1849 					dep->name);
1850 		else
1851 			dep->flags |= DWC3_EP_STALL;
1852 	} else {
1853 		/*
1854 		 * Don't issue CLEAR_STALL command to control endpoints. The
1855 		 * controller automatically clears the STALL when it receives
1856 		 * the SETUP token.
1857 		 */
1858 		if (dep->number <= 1) {
1859 			dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
1860 			return 0;
1861 		}
1862 
1863 		dwc3_stop_active_transfer(dep, true, true);
1864 
1865 		list_for_each_entry_safe(req, tmp, &dep->started_list, list)
1866 			dwc3_gadget_move_cancelled_request(req);
1867 
1868 		if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) {
1869 			dep->flags |= DWC3_EP_PENDING_CLEAR_STALL;
1870 			return 0;
1871 		}
1872 
1873 		dwc3_gadget_ep_cleanup_cancelled_requests(dep);
1874 
1875 		ret = dwc3_send_clear_stall_ep_cmd(dep);
1876 		if (ret) {
1877 			dev_err(dwc->dev, "failed to clear STALL on %s\n",
1878 					dep->name);
1879 			return ret;
1880 		}
1881 
1882 		dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
1883 
1884 		if ((dep->flags & DWC3_EP_DELAY_START) &&
1885 		    !usb_endpoint_xfer_isoc(dep->endpoint.desc))
1886 			__dwc3_gadget_kick_transfer(dep);
1887 
1888 		dep->flags &= ~DWC3_EP_DELAY_START;
1889 	}
1890 
1891 	return ret;
1892 }
1893 
dwc3_gadget_ep_set_halt(struct usb_ep * ep,int value)1894 static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
1895 {
1896 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1897 	struct dwc3			*dwc = dep->dwc;
1898 
1899 	unsigned long			flags;
1900 
1901 	int				ret;
1902 
1903 	spin_lock_irqsave(&dwc->lock, flags);
1904 	ret = __dwc3_gadget_ep_set_halt(dep, value, false);
1905 	spin_unlock_irqrestore(&dwc->lock, flags);
1906 
1907 	return ret;
1908 }
1909 
dwc3_gadget_ep_set_wedge(struct usb_ep * ep)1910 static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
1911 {
1912 	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1913 	struct dwc3			*dwc = dep->dwc;
1914 	unsigned long			flags;
1915 	int				ret;
1916 
1917 	spin_lock_irqsave(&dwc->lock, flags);
1918 	dep->flags |= DWC3_EP_WEDGE;
1919 
1920 	if (dep->number == 0 || dep->number == 1)
1921 		ret = __dwc3_gadget_ep0_set_halt(ep, 1);
1922 	else
1923 		ret = __dwc3_gadget_ep_set_halt(dep, 1, false);
1924 	spin_unlock_irqrestore(&dwc->lock, flags);
1925 
1926 	return ret;
1927 }
1928 
1929 /* -------------------------------------------------------------------------- */
1930 
1931 static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
1932 	.bLength	= USB_DT_ENDPOINT_SIZE,
1933 	.bDescriptorType = USB_DT_ENDPOINT,
1934 	.bmAttributes	= USB_ENDPOINT_XFER_CONTROL,
1935 };
1936 
1937 static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
1938 	.enable		= dwc3_gadget_ep0_enable,
1939 	.disable	= dwc3_gadget_ep0_disable,
1940 	.alloc_request	= dwc3_gadget_ep_alloc_request,
1941 	.free_request	= dwc3_gadget_ep_free_request,
1942 	.queue		= dwc3_gadget_ep0_queue,
1943 	.dequeue	= dwc3_gadget_ep_dequeue,
1944 	.set_halt	= dwc3_gadget_ep0_set_halt,
1945 	.set_wedge	= dwc3_gadget_ep_set_wedge,
1946 };
1947 
1948 static const struct usb_ep_ops dwc3_gadget_ep_ops = {
1949 	.enable		= dwc3_gadget_ep_enable,
1950 	.disable	= dwc3_gadget_ep_disable,
1951 	.alloc_request	= dwc3_gadget_ep_alloc_request,
1952 	.free_request	= dwc3_gadget_ep_free_request,
1953 	.queue		= dwc3_gadget_ep_queue,
1954 	.dequeue	= dwc3_gadget_ep_dequeue,
1955 	.set_halt	= dwc3_gadget_ep_set_halt,
1956 	.set_wedge	= dwc3_gadget_ep_set_wedge,
1957 };
1958 
1959 /* -------------------------------------------------------------------------- */
1960 
dwc3_gadget_get_frame(struct usb_gadget * g)1961 static int dwc3_gadget_get_frame(struct usb_gadget *g)
1962 {
1963 	struct dwc3		*dwc = gadget_to_dwc(g);
1964 
1965 	return __dwc3_gadget_get_frame(dwc);
1966 }
1967 
__dwc3_gadget_wakeup(struct dwc3 * dwc)1968 static int __dwc3_gadget_wakeup(struct dwc3 *dwc)
1969 {
1970 	int			retries;
1971 
1972 	int			ret;
1973 	u32			reg;
1974 
1975 	u8			link_state;
1976 
1977 	/*
1978 	 * According to the Databook Remote wakeup request should
1979 	 * be issued only when the device is in early suspend state.
1980 	 *
1981 	 * We can check that via USB Link State bits in DSTS register.
1982 	 */
1983 	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1984 
1985 	link_state = DWC3_DSTS_USBLNKST(reg);
1986 
1987 	switch (link_state) {
1988 	case DWC3_LINK_STATE_RESET:
1989 	case DWC3_LINK_STATE_RX_DET:	/* in HS, means Early Suspend */
1990 	case DWC3_LINK_STATE_U3:	/* in HS, means SUSPEND */
1991 	case DWC3_LINK_STATE_U2:	/* in HS, means Sleep (L1) */
1992 	case DWC3_LINK_STATE_U1:
1993 	case DWC3_LINK_STATE_RESUME:
1994 		break;
1995 	default:
1996 		return -EINVAL;
1997 	}
1998 
1999 	ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
2000 	if (ret < 0) {
2001 		dev_err(dwc->dev, "failed to put link in Recovery\n");
2002 		return ret;
2003 	}
2004 
2005 	/* Recent versions do this automatically */
2006 	if (DWC3_VER_IS_PRIOR(DWC3, 194A)) {
2007 		/* write zeroes to Link Change Request */
2008 		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2009 		reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
2010 		dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2011 	}
2012 
2013 	/* poll until Link State changes to ON */
2014 	retries = 20000;
2015 
2016 	while (retries--) {
2017 		reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2018 
2019 		/* in HS, means ON */
2020 		if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
2021 			break;
2022 	}
2023 
2024 	if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
2025 		dev_err(dwc->dev, "failed to send remote wakeup\n");
2026 		return -EINVAL;
2027 	}
2028 
2029 	return 0;
2030 }
2031 
dwc3_gadget_wakeup(struct usb_gadget * g)2032 static int dwc3_gadget_wakeup(struct usb_gadget *g)
2033 {
2034 	struct dwc3		*dwc = gadget_to_dwc(g);
2035 	unsigned long		flags;
2036 	int			ret;
2037 
2038 	spin_lock_irqsave(&dwc->lock, flags);
2039 	ret = __dwc3_gadget_wakeup(dwc);
2040 	spin_unlock_irqrestore(&dwc->lock, flags);
2041 
2042 	return ret;
2043 }
2044 
dwc3_gadget_set_selfpowered(struct usb_gadget * g,int is_selfpowered)2045 static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
2046 		int is_selfpowered)
2047 {
2048 	struct dwc3		*dwc = gadget_to_dwc(g);
2049 	unsigned long		flags;
2050 
2051 	spin_lock_irqsave(&dwc->lock, flags);
2052 	g->is_selfpowered = !!is_selfpowered;
2053 	spin_unlock_irqrestore(&dwc->lock, flags);
2054 
2055 	return 0;
2056 }
2057 
dwc3_stop_active_transfers(struct dwc3 * dwc)2058 static void dwc3_stop_active_transfers(struct dwc3 *dwc)
2059 {
2060 	u32 epnum;
2061 
2062 	for (epnum = 2; epnum < dwc->num_eps; epnum++) {
2063 		struct dwc3_ep *dep;
2064 
2065 		dep = dwc->eps[epnum];
2066 		if (!dep)
2067 			continue;
2068 
2069 		dwc3_remove_requests(dwc, dep);
2070 	}
2071 }
2072 
dwc3_gadget_run_stop(struct dwc3 * dwc,int is_on,int suspend)2073 static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on, int suspend)
2074 {
2075 	u32			reg;
2076 	u32			timeout = 500;
2077 
2078 	if (pm_runtime_suspended(dwc->dev))
2079 		return 0;
2080 
2081 	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2082 	if (is_on) {
2083 		if (DWC3_VER_IS_WITHIN(DWC3, ANY, 187A)) {
2084 			reg &= ~DWC3_DCTL_TRGTULST_MASK;
2085 			reg |= DWC3_DCTL_TRGTULST_RX_DET;
2086 		}
2087 
2088 		if (!DWC3_VER_IS_PRIOR(DWC3, 194A))
2089 			reg &= ~DWC3_DCTL_KEEP_CONNECT;
2090 		reg |= DWC3_DCTL_RUN_STOP;
2091 
2092 		if (dwc->has_hibernation)
2093 			reg |= DWC3_DCTL_KEEP_CONNECT;
2094 
2095 		dwc->pullups_connected = true;
2096 	} else {
2097 		reg &= ~DWC3_DCTL_RUN_STOP;
2098 
2099 		if (dwc->has_hibernation && !suspend)
2100 			reg &= ~DWC3_DCTL_KEEP_CONNECT;
2101 
2102 		dwc->pullups_connected = false;
2103 	}
2104 
2105 	dwc3_gadget_dctl_write_safe(dwc, reg);
2106 
2107 	do {
2108 		reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2109 		reg &= DWC3_DSTS_DEVCTRLHLT;
2110 	} while (--timeout && !(!is_on ^ !reg));
2111 
2112 	if (!timeout)
2113 		return -ETIMEDOUT;
2114 
2115 	return 0;
2116 }
2117 
2118 static void dwc3_gadget_disable_irq(struct dwc3 *dwc);
2119 static void __dwc3_gadget_stop(struct dwc3 *dwc);
2120 static int __dwc3_gadget_start(struct dwc3 *dwc);
2121 
dwc3_gadget_pullup(struct usb_gadget * g,int is_on)2122 static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
2123 {
2124 	struct dwc3		*dwc = gadget_to_dwc(g);
2125 	unsigned long		flags;
2126 	int			ret;
2127 
2128 	is_on = !!is_on;
2129 
2130 	/*
2131 	 * Per databook, when we want to stop the gadget, if a control transfer
2132 	 * is still in process, complete it and get the core into setup phase.
2133 	 */
2134 	if (!is_on && dwc->ep0state != EP0_SETUP_PHASE) {
2135 		reinit_completion(&dwc->ep0_in_setup);
2136 
2137 		ret = wait_for_completion_timeout(&dwc->ep0_in_setup,
2138 				msecs_to_jiffies(DWC3_PULL_UP_TIMEOUT));
2139 		if (ret == 0)
2140 			dev_warn(dwc->dev, "timed out waiting for SETUP phase\n");
2141 	}
2142 
2143 	/*
2144 	 * Avoid issuing a runtime resume if the device is already in the
2145 	 * suspended state during gadget disconnect.  DWC3 gadget was already
2146 	 * halted/stopped during runtime suspend.
2147 	 */
2148 	if (!is_on) {
2149 		pm_runtime_barrier(dwc->dev);
2150 		if (pm_runtime_suspended(dwc->dev))
2151 			return 0;
2152 	}
2153 
2154 	/*
2155 	 * Check the return value for successful resume, or error.  For a
2156 	 * successful resume, the DWC3 runtime PM resume routine will handle
2157 	 * the run stop sequence, so avoid duplicate operations here.
2158 	 */
2159 	ret = pm_runtime_get_sync(dwc->dev);
2160 	if (!ret || ret < 0) {
2161 		pm_runtime_put(dwc->dev);
2162 		return 0;
2163 	}
2164 
2165 	/*
2166 	 * Synchronize and disable any further event handling while controller
2167 	 * is being enabled/disabled.
2168 	 */
2169 	disable_irq(dwc->irq_gadget);
2170 
2171 	spin_lock_irqsave(&dwc->lock, flags);
2172 
2173 	if (!is_on) {
2174 		u32 count;
2175 
2176 		dwc->connected = false;
2177 		/*
2178 		 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
2179 		 * Section 4.1.8 Table 4-7, it states that for a device-initiated
2180 		 * disconnect, the SW needs to ensure that it sends "a DEPENDXFER
2181 		 * command for any active transfers" before clearing the RunStop
2182 		 * bit.
2183 		 */
2184 		dwc3_stop_active_transfers(dwc);
2185 		__dwc3_gadget_stop(dwc);
2186 
2187 		/*
2188 		 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
2189 		 * Section 1.3.4, it mentions that for the DEVCTRLHLT bit, the
2190 		 * "software needs to acknowledge the events that are generated
2191 		 * (by writing to GEVNTCOUNTn) while it is waiting for this bit
2192 		 * to be set to '1'."
2193 		 */
2194 		count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
2195 		count &= DWC3_GEVNTCOUNT_MASK;
2196 		if (count > 0) {
2197 			dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
2198 			dwc->ev_buf->lpos = (dwc->ev_buf->lpos + count) %
2199 						dwc->ev_buf->length;
2200 		}
2201 	} else {
2202 		__dwc3_gadget_start(dwc);
2203 	}
2204 
2205 	ret = dwc3_gadget_run_stop(dwc, is_on, false);
2206 	spin_unlock_irqrestore(&dwc->lock, flags);
2207 	enable_irq(dwc->irq_gadget);
2208 
2209 	pm_runtime_put(dwc->dev);
2210 
2211 	return ret;
2212 }
2213 
dwc3_gadget_enable_irq(struct dwc3 * dwc)2214 static void dwc3_gadget_enable_irq(struct dwc3 *dwc)
2215 {
2216 	u32			reg;
2217 
2218 	/* Enable all but Start and End of Frame IRQs */
2219 	reg = (DWC3_DEVTEN_VNDRDEVTSTRCVEDEN |
2220 			DWC3_DEVTEN_EVNTOVERFLOWEN |
2221 			DWC3_DEVTEN_CMDCMPLTEN |
2222 			DWC3_DEVTEN_ERRTICERREN |
2223 			DWC3_DEVTEN_WKUPEVTEN |
2224 			DWC3_DEVTEN_CONNECTDONEEN |
2225 			DWC3_DEVTEN_USBRSTEN |
2226 			DWC3_DEVTEN_DISCONNEVTEN);
2227 
2228 	if (DWC3_VER_IS_PRIOR(DWC3, 250A))
2229 		reg |= DWC3_DEVTEN_ULSTCNGEN;
2230 
2231 	/* On 2.30a and above this bit enables U3/L2-L1 Suspend Events */
2232 	if (!DWC3_VER_IS_PRIOR(DWC3, 230A))
2233 		reg |= DWC3_DEVTEN_EOPFEN;
2234 
2235 	dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
2236 }
2237 
dwc3_gadget_disable_irq(struct dwc3 * dwc)2238 static void dwc3_gadget_disable_irq(struct dwc3 *dwc)
2239 {
2240 	/* mask all interrupts */
2241 	dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
2242 }
2243 
2244 static irqreturn_t dwc3_interrupt(int irq, void *_dwc);
2245 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc);
2246 
2247 /**
2248  * dwc3_gadget_setup_nump - calculate and initialize NUMP field of %DWC3_DCFG
2249  * @dwc: pointer to our context structure
2250  *
2251  * The following looks like complex but it's actually very simple. In order to
2252  * calculate the number of packets we can burst at once on OUT transfers, we're
2253  * gonna use RxFIFO size.
2254  *
2255  * To calculate RxFIFO size we need two numbers:
2256  * MDWIDTH = size, in bits, of the internal memory bus
2257  * RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)
2258  *
2259  * Given these two numbers, the formula is simple:
2260  *
2261  * RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;
2262  *
2263  * 24 bytes is for 3x SETUP packets
2264  * 16 bytes is a clock domain crossing tolerance
2265  *
2266  * Given RxFIFO Size, NUMP = RxFIFOSize / 1024;
2267  */
dwc3_gadget_setup_nump(struct dwc3 * dwc)2268 static void dwc3_gadget_setup_nump(struct dwc3 *dwc)
2269 {
2270 	u32 ram2_depth;
2271 	u32 mdwidth;
2272 	u32 nump;
2273 	u32 reg;
2274 
2275 	ram2_depth = DWC3_GHWPARAMS7_RAM2_DEPTH(dwc->hwparams.hwparams7);
2276 	mdwidth = DWC3_GHWPARAMS0_MDWIDTH(dwc->hwparams.hwparams0);
2277 	if (DWC3_IP_IS(DWC32))
2278 		mdwidth += DWC3_GHWPARAMS6_MDWIDTH(dwc->hwparams.hwparams6);
2279 
2280 	nump = ((ram2_depth * mdwidth / 8) - 24 - 16) / 1024;
2281 	nump = min_t(u32, nump, 16);
2282 
2283 	/* update NumP */
2284 	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2285 	reg &= ~DWC3_DCFG_NUMP_MASK;
2286 	reg |= nump << DWC3_DCFG_NUMP_SHIFT;
2287 	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2288 }
2289 
__dwc3_gadget_start(struct dwc3 * dwc)2290 static int __dwc3_gadget_start(struct dwc3 *dwc)
2291 {
2292 	struct dwc3_ep		*dep;
2293 	int			ret = 0;
2294 	u32			reg;
2295 
2296 	/*
2297 	 * Use IMOD if enabled via dwc->imod_interval. Otherwise, if
2298 	 * the core supports IMOD, disable it.
2299 	 */
2300 	if (dwc->imod_interval) {
2301 		dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
2302 		dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
2303 	} else if (dwc3_has_imod(dwc)) {
2304 		dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), 0);
2305 	}
2306 
2307 	/*
2308 	 * We are telling dwc3 that we want to use DCFG.NUMP as ACK TP's NUMP
2309 	 * field instead of letting dwc3 itself calculate that automatically.
2310 	 *
2311 	 * This way, we maximize the chances that we'll be able to get several
2312 	 * bursts of data without going through any sort of endpoint throttling.
2313 	 */
2314 	reg = dwc3_readl(dwc->regs, DWC3_GRXTHRCFG);
2315 	if (DWC3_IP_IS(DWC3))
2316 		reg &= ~DWC3_GRXTHRCFG_PKTCNTSEL;
2317 	else
2318 		reg &= ~DWC31_GRXTHRCFG_PKTCNTSEL;
2319 
2320 	dwc3_writel(dwc->regs, DWC3_GRXTHRCFG, reg);
2321 
2322 	dwc3_gadget_setup_nump(dwc);
2323 
2324 	/* Start with SuperSpeed Default */
2325 	dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2326 
2327 	dep = dwc->eps[0];
2328 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2329 	if (ret) {
2330 		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2331 		goto err0;
2332 	}
2333 
2334 	dep = dwc->eps[1];
2335 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2336 	if (ret) {
2337 		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2338 		goto err1;
2339 	}
2340 
2341 	/* begin to receive SETUP packets */
2342 	dwc->ep0state = EP0_SETUP_PHASE;
2343 	dwc->link_state = DWC3_LINK_STATE_SS_DIS;
2344 	dwc->delayed_status = false;
2345 	dwc3_ep0_out_start(dwc);
2346 
2347 	dwc3_gadget_enable_irq(dwc);
2348 
2349 	return 0;
2350 
2351 err1:
2352 	__dwc3_gadget_ep_disable(dwc->eps[0]);
2353 
2354 err0:
2355 	return ret;
2356 }
2357 
dwc3_gadget_start(struct usb_gadget * g,struct usb_gadget_driver * driver)2358 static int dwc3_gadget_start(struct usb_gadget *g,
2359 		struct usb_gadget_driver *driver)
2360 {
2361 	struct dwc3		*dwc = gadget_to_dwc(g);
2362 	unsigned long		flags;
2363 	int			ret = 0;
2364 	int			irq;
2365 
2366 	irq = dwc->irq_gadget;
2367 	ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt,
2368 			IRQF_SHARED, "dwc3", dwc->ev_buf);
2369 	if (ret) {
2370 		dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
2371 				irq, ret);
2372 		goto err0;
2373 	}
2374 
2375 	spin_lock_irqsave(&dwc->lock, flags);
2376 	if (dwc->gadget_driver) {
2377 		dev_err(dwc->dev, "%s is already bound to %s\n",
2378 				dwc->gadget->name,
2379 				dwc->gadget_driver->driver.name);
2380 		ret = -EBUSY;
2381 		goto err1;
2382 	}
2383 
2384 	dwc->gadget_driver	= driver;
2385 	spin_unlock_irqrestore(&dwc->lock, flags);
2386 
2387 	return 0;
2388 
2389 err1:
2390 	spin_unlock_irqrestore(&dwc->lock, flags);
2391 	free_irq(irq, dwc);
2392 
2393 err0:
2394 	return ret;
2395 }
2396 
__dwc3_gadget_stop(struct dwc3 * dwc)2397 static void __dwc3_gadget_stop(struct dwc3 *dwc)
2398 {
2399 	dwc3_gadget_disable_irq(dwc);
2400 	__dwc3_gadget_ep_disable(dwc->eps[0]);
2401 	__dwc3_gadget_ep_disable(dwc->eps[1]);
2402 }
2403 
dwc3_gadget_stop(struct usb_gadget * g)2404 static int dwc3_gadget_stop(struct usb_gadget *g)
2405 {
2406 	struct dwc3		*dwc = gadget_to_dwc(g);
2407 	unsigned long		flags;
2408 
2409 	spin_lock_irqsave(&dwc->lock, flags);
2410 	dwc->gadget_driver	= NULL;
2411 	spin_unlock_irqrestore(&dwc->lock, flags);
2412 
2413 	free_irq(dwc->irq_gadget, dwc->ev_buf);
2414 
2415 	return 0;
2416 }
2417 
dwc3_gadget_config_params(struct usb_gadget * g,struct usb_dcd_config_params * params)2418 static void dwc3_gadget_config_params(struct usb_gadget *g,
2419 				      struct usb_dcd_config_params *params)
2420 {
2421 	struct dwc3		*dwc = gadget_to_dwc(g);
2422 
2423 	params->besl_baseline = USB_DEFAULT_BESL_UNSPECIFIED;
2424 	params->besl_deep = USB_DEFAULT_BESL_UNSPECIFIED;
2425 
2426 	/* Recommended BESL */
2427 	if (!dwc->dis_enblslpm_quirk) {
2428 		/*
2429 		 * If the recommended BESL baseline is 0 or if the BESL deep is
2430 		 * less than 2, Microsoft's Windows 10 host usb stack will issue
2431 		 * a usb reset immediately after it receives the extended BOS
2432 		 * descriptor and the enumeration will fail. To maintain
2433 		 * compatibility with the Windows' usb stack, let's set the
2434 		 * recommended BESL baseline to 1 and clamp the BESL deep to be
2435 		 * within 2 to 15.
2436 		 */
2437 		params->besl_baseline = 1;
2438 		if (dwc->is_utmi_l1_suspend)
2439 			params->besl_deep =
2440 				clamp_t(u8, dwc->hird_threshold, 2, 15);
2441 	}
2442 
2443 	/* U1 Device exit Latency */
2444 	if (dwc->dis_u1_entry_quirk)
2445 		params->bU1devExitLat = 0;
2446 	else
2447 		params->bU1devExitLat = DWC3_DEFAULT_U1_DEV_EXIT_LAT;
2448 
2449 	/* U2 Device exit Latency */
2450 	if (dwc->dis_u2_entry_quirk)
2451 		params->bU2DevExitLat = 0;
2452 	else
2453 		params->bU2DevExitLat =
2454 				cpu_to_le16(DWC3_DEFAULT_U2_DEV_EXIT_LAT);
2455 }
2456 
dwc3_gadget_set_speed(struct usb_gadget * g,enum usb_device_speed speed)2457 static void dwc3_gadget_set_speed(struct usb_gadget *g,
2458 				  enum usb_device_speed speed)
2459 {
2460 	struct dwc3		*dwc = gadget_to_dwc(g);
2461 	unsigned long		flags;
2462 	u32			reg;
2463 
2464 	spin_lock_irqsave(&dwc->lock, flags);
2465 	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2466 	reg &= ~(DWC3_DCFG_SPEED_MASK);
2467 
2468 	/*
2469 	 * WORKAROUND: DWC3 revision < 2.20a have an issue
2470 	 * which would cause metastability state on Run/Stop
2471 	 * bit if we try to force the IP to USB2-only mode.
2472 	 *
2473 	 * Because of that, we cannot configure the IP to any
2474 	 * speed other than the SuperSpeed
2475 	 *
2476 	 * Refers to:
2477 	 *
2478 	 * STAR#9000525659: Clock Domain Crossing on DCTL in
2479 	 * USB 2.0 Mode
2480 	 */
2481 	if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
2482 	    !dwc->dis_metastability_quirk) {
2483 		reg |= DWC3_DCFG_SUPERSPEED;
2484 	} else {
2485 		switch (speed) {
2486 		case USB_SPEED_LOW:
2487 			reg |= DWC3_DCFG_LOWSPEED;
2488 			break;
2489 		case USB_SPEED_FULL:
2490 			reg |= DWC3_DCFG_FULLSPEED;
2491 			break;
2492 		case USB_SPEED_HIGH:
2493 			reg |= DWC3_DCFG_HIGHSPEED;
2494 			break;
2495 		case USB_SPEED_SUPER:
2496 			reg |= DWC3_DCFG_SUPERSPEED;
2497 			break;
2498 		case USB_SPEED_SUPER_PLUS:
2499 			if (DWC3_IP_IS(DWC3))
2500 				reg |= DWC3_DCFG_SUPERSPEED;
2501 			else
2502 				reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2503 			break;
2504 		default:
2505 			dev_err(dwc->dev, "invalid speed (%d)\n", speed);
2506 
2507 			if (DWC3_IP_IS(DWC3))
2508 				reg |= DWC3_DCFG_SUPERSPEED;
2509 			else
2510 				reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2511 		}
2512 	}
2513 	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2514 
2515 	spin_unlock_irqrestore(&dwc->lock, flags);
2516 }
2517 
2518 static const struct usb_gadget_ops dwc3_gadget_ops = {
2519 	.get_frame		= dwc3_gadget_get_frame,
2520 	.wakeup			= dwc3_gadget_wakeup,
2521 	.set_selfpowered	= dwc3_gadget_set_selfpowered,
2522 	.pullup			= dwc3_gadget_pullup,
2523 	.udc_start		= dwc3_gadget_start,
2524 	.udc_stop		= dwc3_gadget_stop,
2525 	.udc_set_speed		= dwc3_gadget_set_speed,
2526 	.get_config_params	= dwc3_gadget_config_params,
2527 };
2528 
2529 /* -------------------------------------------------------------------------- */
2530 
dwc3_gadget_init_control_endpoint(struct dwc3_ep * dep)2531 static int dwc3_gadget_init_control_endpoint(struct dwc3_ep *dep)
2532 {
2533 	struct dwc3 *dwc = dep->dwc;
2534 
2535 	usb_ep_set_maxpacket_limit(&dep->endpoint, 512);
2536 	dep->endpoint.maxburst = 1;
2537 	dep->endpoint.ops = &dwc3_gadget_ep0_ops;
2538 	if (!dep->direction)
2539 		dwc->gadget->ep0 = &dep->endpoint;
2540 
2541 	dep->endpoint.caps.type_control = true;
2542 
2543 	return 0;
2544 }
2545 
dwc3_gadget_init_in_endpoint(struct dwc3_ep * dep)2546 static int dwc3_gadget_init_in_endpoint(struct dwc3_ep *dep)
2547 {
2548 	struct dwc3 *dwc = dep->dwc;
2549 	int mdwidth;
2550 	int size;
2551 
2552 	mdwidth = DWC3_MDWIDTH(dwc->hwparams.hwparams0);
2553 	if (DWC3_IP_IS(DWC32))
2554 		mdwidth += DWC3_GHWPARAMS6_MDWIDTH(dwc->hwparams.hwparams6);
2555 
2556 	/* MDWIDTH is represented in bits, we need it in bytes */
2557 	mdwidth /= 8;
2558 
2559 	size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1));
2560 	if (DWC3_IP_IS(DWC3))
2561 		size = DWC3_GTXFIFOSIZ_TXFDEP(size);
2562 	else
2563 		size = DWC31_GTXFIFOSIZ_TXFDEP(size);
2564 
2565 	/* FIFO Depth is in MDWDITH bytes. Multiply */
2566 	size *= mdwidth;
2567 
2568 	/*
2569 	 * To meet performance requirement, a minimum TxFIFO size of 3x
2570 	 * MaxPacketSize is recommended for endpoints that support burst and a
2571 	 * minimum TxFIFO size of 2x MaxPacketSize for endpoints that don't
2572 	 * support burst. Use those numbers and we can calculate the max packet
2573 	 * limit as below.
2574 	 */
2575 	if (dwc->maximum_speed >= USB_SPEED_SUPER)
2576 		size /= 3;
2577 	else
2578 		size /= 2;
2579 
2580 	usb_ep_set_maxpacket_limit(&dep->endpoint, size);
2581 
2582 	dep->endpoint.max_streams = 16;
2583 	dep->endpoint.ops = &dwc3_gadget_ep_ops;
2584 	list_add_tail(&dep->endpoint.ep_list,
2585 			&dwc->gadget->ep_list);
2586 	dep->endpoint.caps.type_iso = true;
2587 	dep->endpoint.caps.type_bulk = true;
2588 	dep->endpoint.caps.type_int = true;
2589 
2590 	return dwc3_alloc_trb_pool(dep);
2591 }
2592 
dwc3_gadget_init_out_endpoint(struct dwc3_ep * dep)2593 static int dwc3_gadget_init_out_endpoint(struct dwc3_ep *dep)
2594 {
2595 	struct dwc3 *dwc = dep->dwc;
2596 	int mdwidth;
2597 	int size;
2598 
2599 	mdwidth = DWC3_MDWIDTH(dwc->hwparams.hwparams0);
2600 	if (DWC3_IP_IS(DWC32))
2601 		mdwidth += DWC3_GHWPARAMS6_MDWIDTH(dwc->hwparams.hwparams6);
2602 
2603 	/* MDWIDTH is represented in bits, convert to bytes */
2604 	mdwidth /= 8;
2605 
2606 	/* All OUT endpoints share a single RxFIFO space */
2607 	size = dwc3_readl(dwc->regs, DWC3_GRXFIFOSIZ(0));
2608 	if (DWC3_IP_IS(DWC3))
2609 		size = DWC3_GRXFIFOSIZ_RXFDEP(size);
2610 	else
2611 		size = DWC31_GRXFIFOSIZ_RXFDEP(size);
2612 
2613 	/* FIFO depth is in MDWDITH bytes */
2614 	size *= mdwidth;
2615 
2616 	/*
2617 	 * To meet performance requirement, a minimum recommended RxFIFO size
2618 	 * is defined as follow:
2619 	 * RxFIFO size >= (3 x MaxPacketSize) +
2620 	 * (3 x 8 bytes setup packets size) + (16 bytes clock crossing margin)
2621 	 *
2622 	 * Then calculate the max packet limit as below.
2623 	 */
2624 	size -= (3 * 8) + 16;
2625 	if (size < 0)
2626 		size = 0;
2627 	else
2628 		size /= 3;
2629 
2630 	usb_ep_set_maxpacket_limit(&dep->endpoint, size);
2631 	dep->endpoint.max_streams = 16;
2632 	dep->endpoint.ops = &dwc3_gadget_ep_ops;
2633 	list_add_tail(&dep->endpoint.ep_list,
2634 			&dwc->gadget->ep_list);
2635 	dep->endpoint.caps.type_iso = true;
2636 	dep->endpoint.caps.type_bulk = true;
2637 	dep->endpoint.caps.type_int = true;
2638 
2639 	return dwc3_alloc_trb_pool(dep);
2640 }
2641 
dwc3_gadget_init_endpoint(struct dwc3 * dwc,u8 epnum)2642 static int dwc3_gadget_init_endpoint(struct dwc3 *dwc, u8 epnum)
2643 {
2644 	struct dwc3_ep			*dep;
2645 	bool				direction = epnum & 1;
2646 	int				ret;
2647 	u8				num = epnum >> 1;
2648 
2649 	dep = kzalloc(sizeof(*dep), GFP_KERNEL);
2650 	if (!dep)
2651 		return -ENOMEM;
2652 
2653 	dep->dwc = dwc;
2654 	dep->number = epnum;
2655 	dep->direction = direction;
2656 	dep->regs = dwc->regs + DWC3_DEP_BASE(epnum);
2657 	dwc->eps[epnum] = dep;
2658 	dep->combo_num = 0;
2659 	dep->start_cmd_status = 0;
2660 
2661 	snprintf(dep->name, sizeof(dep->name), "ep%u%s", num,
2662 			direction ? "in" : "out");
2663 
2664 	dep->endpoint.name = dep->name;
2665 
2666 	if (!(dep->number > 1)) {
2667 		dep->endpoint.desc = &dwc3_gadget_ep0_desc;
2668 		dep->endpoint.comp_desc = NULL;
2669 	}
2670 
2671 	if (num == 0)
2672 		ret = dwc3_gadget_init_control_endpoint(dep);
2673 	else if (direction)
2674 		ret = dwc3_gadget_init_in_endpoint(dep);
2675 	else
2676 		ret = dwc3_gadget_init_out_endpoint(dep);
2677 
2678 	if (ret)
2679 		return ret;
2680 
2681 	dep->endpoint.caps.dir_in = direction;
2682 	dep->endpoint.caps.dir_out = !direction;
2683 
2684 	INIT_LIST_HEAD(&dep->pending_list);
2685 	INIT_LIST_HEAD(&dep->started_list);
2686 	INIT_LIST_HEAD(&dep->cancelled_list);
2687 
2688 	dwc3_debugfs_create_endpoint_dir(dep);
2689 
2690 	return 0;
2691 }
2692 
dwc3_gadget_init_endpoints(struct dwc3 * dwc,u8 total)2693 static int dwc3_gadget_init_endpoints(struct dwc3 *dwc, u8 total)
2694 {
2695 	u8				epnum;
2696 
2697 	INIT_LIST_HEAD(&dwc->gadget->ep_list);
2698 
2699 	for (epnum = 0; epnum < total; epnum++) {
2700 		int			ret;
2701 
2702 		ret = dwc3_gadget_init_endpoint(dwc, epnum);
2703 		if (ret)
2704 			return ret;
2705 	}
2706 
2707 	return 0;
2708 }
2709 
dwc3_gadget_free_endpoints(struct dwc3 * dwc)2710 static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
2711 {
2712 	struct dwc3_ep			*dep;
2713 	u8				epnum;
2714 
2715 	for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2716 		dep = dwc->eps[epnum];
2717 		if (!dep)
2718 			continue;
2719 		/*
2720 		 * Physical endpoints 0 and 1 are special; they form the
2721 		 * bi-directional USB endpoint 0.
2722 		 *
2723 		 * For those two physical endpoints, we don't allocate a TRB
2724 		 * pool nor do we add them the endpoints list. Due to that, we
2725 		 * shouldn't do these two operations otherwise we would end up
2726 		 * with all sorts of bugs when removing dwc3.ko.
2727 		 */
2728 		if (epnum != 0 && epnum != 1) {
2729 			dwc3_free_trb_pool(dep);
2730 			list_del(&dep->endpoint.ep_list);
2731 		}
2732 
2733 		debugfs_remove_recursive(debugfs_lookup(dep->name, dwc->root));
2734 		kfree(dep);
2735 	}
2736 }
2737 
2738 /* -------------------------------------------------------------------------- */
2739 
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)2740 static int dwc3_gadget_ep_reclaim_completed_trb(struct dwc3_ep *dep,
2741 		struct dwc3_request *req, struct dwc3_trb *trb,
2742 		const struct dwc3_event_depevt *event, int status, int chain)
2743 {
2744 	unsigned int		count;
2745 
2746 	dwc3_ep_inc_deq(dep);
2747 
2748 	trace_dwc3_complete_trb(dep, trb);
2749 	req->num_trbs--;
2750 
2751 	/*
2752 	 * If we're in the middle of series of chained TRBs and we
2753 	 * receive a short transfer along the way, DWC3 will skip
2754 	 * through all TRBs including the last TRB in the chain (the
2755 	 * where CHN bit is zero. DWC3 will also avoid clearing HWO
2756 	 * bit and SW has to do it manually.
2757 	 *
2758 	 * We're going to do that here to avoid problems of HW trying
2759 	 * to use bogus TRBs for transfers.
2760 	 */
2761 	if (chain && (trb->ctrl & DWC3_TRB_CTRL_HWO))
2762 		trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2763 
2764 	/*
2765 	 * For isochronous transfers, the first TRB in a service interval must
2766 	 * have the Isoc-First type. Track and report its interval frame number.
2767 	 */
2768 	if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
2769 	    (trb->ctrl & DWC3_TRBCTL_ISOCHRONOUS_FIRST)) {
2770 		unsigned int frame_number;
2771 
2772 		frame_number = DWC3_TRB_CTRL_GET_SID_SOFN(trb->ctrl);
2773 		frame_number &= ~(dep->interval - 1);
2774 		req->request.frame_number = frame_number;
2775 	}
2776 
2777 	/*
2778 	 * We use bounce buffer for requests that needs extra TRB or OUT ZLP. If
2779 	 * this TRB points to the bounce buffer address, it's a MPS alignment
2780 	 * TRB. Don't add it to req->remaining calculation.
2781 	 */
2782 	if (trb->bpl == lower_32_bits(dep->dwc->bounce_addr) &&
2783 	    trb->bph == upper_32_bits(dep->dwc->bounce_addr)) {
2784 		trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2785 		return 1;
2786 	}
2787 
2788 	count = trb->size & DWC3_TRB_SIZE_MASK;
2789 	req->remaining += count;
2790 
2791 	if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
2792 		return 1;
2793 
2794 	if (event->status & DEPEVT_STATUS_SHORT && !chain)
2795 		return 1;
2796 
2797 	if ((trb->ctrl & DWC3_TRB_CTRL_IOC) ||
2798 	    (trb->ctrl & DWC3_TRB_CTRL_LST))
2799 		return 1;
2800 
2801 	return 0;
2802 }
2803 
dwc3_gadget_ep_reclaim_trb_sg(struct dwc3_ep * dep,struct dwc3_request * req,const struct dwc3_event_depevt * event,int status)2804 static int dwc3_gadget_ep_reclaim_trb_sg(struct dwc3_ep *dep,
2805 		struct dwc3_request *req, const struct dwc3_event_depevt *event,
2806 		int status)
2807 {
2808 	struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
2809 	struct scatterlist *sg = req->sg;
2810 	struct scatterlist *s;
2811 	unsigned int num_queued = req->num_queued_sgs;
2812 	unsigned int i;
2813 	int ret = 0;
2814 
2815 	for_each_sg(sg, s, num_queued, i) {
2816 		trb = &dep->trb_pool[dep->trb_dequeue];
2817 
2818 		req->sg = sg_next(s);
2819 		req->num_queued_sgs--;
2820 
2821 		ret = dwc3_gadget_ep_reclaim_completed_trb(dep, req,
2822 				trb, event, status, true);
2823 		if (ret)
2824 			break;
2825 	}
2826 
2827 	return ret;
2828 }
2829 
dwc3_gadget_ep_reclaim_trb_linear(struct dwc3_ep * dep,struct dwc3_request * req,const struct dwc3_event_depevt * event,int status)2830 static int dwc3_gadget_ep_reclaim_trb_linear(struct dwc3_ep *dep,
2831 		struct dwc3_request *req, const struct dwc3_event_depevt *event,
2832 		int status)
2833 {
2834 	struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
2835 
2836 	return dwc3_gadget_ep_reclaim_completed_trb(dep, req, trb,
2837 			event, status, false);
2838 }
2839 
dwc3_gadget_ep_request_completed(struct dwc3_request * req)2840 static bool dwc3_gadget_ep_request_completed(struct dwc3_request *req)
2841 {
2842 	return req->num_pending_sgs == 0 && req->num_queued_sgs == 0;
2843 }
2844 
dwc3_gadget_ep_cleanup_completed_request(struct dwc3_ep * dep,const struct dwc3_event_depevt * event,struct dwc3_request * req,int status)2845 static int dwc3_gadget_ep_cleanup_completed_request(struct dwc3_ep *dep,
2846 		const struct dwc3_event_depevt *event,
2847 		struct dwc3_request *req, int status)
2848 {
2849 	int ret;
2850 
2851 	if (req->request.num_mapped_sgs)
2852 		ret = dwc3_gadget_ep_reclaim_trb_sg(dep, req, event,
2853 				status);
2854 	else
2855 		ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
2856 				status);
2857 
2858 	req->request.actual = req->request.length - req->remaining;
2859 
2860 	if (!dwc3_gadget_ep_request_completed(req))
2861 		goto out;
2862 
2863 	if (req->needs_extra_trb) {
2864 		ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
2865 				status);
2866 		req->needs_extra_trb = false;
2867 	}
2868 
2869 	dwc3_gadget_giveback(dep, req, status);
2870 
2871 out:
2872 	return ret;
2873 }
2874 
dwc3_gadget_ep_cleanup_completed_requests(struct dwc3_ep * dep,const struct dwc3_event_depevt * event,int status)2875 static void dwc3_gadget_ep_cleanup_completed_requests(struct dwc3_ep *dep,
2876 		const struct dwc3_event_depevt *event, int status)
2877 {
2878 	struct dwc3_request	*req;
2879 	struct dwc3_request	*tmp;
2880 
2881 	list_for_each_entry_safe(req, tmp, &dep->started_list, list) {
2882 		int ret;
2883 
2884 		ret = dwc3_gadget_ep_cleanup_completed_request(dep, event,
2885 				req, status);
2886 		if (ret)
2887 			break;
2888 	}
2889 }
2890 
dwc3_gadget_ep_should_continue(struct dwc3_ep * dep)2891 static bool dwc3_gadget_ep_should_continue(struct dwc3_ep *dep)
2892 {
2893 	struct dwc3_request	*req;
2894 
2895 	if (!list_empty(&dep->pending_list))
2896 		return true;
2897 
2898 	/*
2899 	 * We only need to check the first entry of the started list. We can
2900 	 * assume the completed requests are removed from the started list.
2901 	 */
2902 	req = next_request(&dep->started_list);
2903 	if (!req)
2904 		return false;
2905 
2906 	return !dwc3_gadget_ep_request_completed(req);
2907 }
2908 
dwc3_gadget_endpoint_frame_from_event(struct dwc3_ep * dep,const struct dwc3_event_depevt * event)2909 static void dwc3_gadget_endpoint_frame_from_event(struct dwc3_ep *dep,
2910 		const struct dwc3_event_depevt *event)
2911 {
2912 	dep->frame_number = event->parameters;
2913 }
2914 
dwc3_gadget_endpoint_trbs_complete(struct dwc3_ep * dep,const struct dwc3_event_depevt * event,int status)2915 static bool dwc3_gadget_endpoint_trbs_complete(struct dwc3_ep *dep,
2916 		const struct dwc3_event_depevt *event, int status)
2917 {
2918 	struct dwc3		*dwc = dep->dwc;
2919 	bool			no_started_trb = true;
2920 
2921 	if (!dep->endpoint.desc)
2922 		return no_started_trb;
2923 
2924 	dwc3_gadget_ep_cleanup_completed_requests(dep, event, status);
2925 
2926 	if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
2927 		goto out;
2928 
2929 	if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
2930 		list_empty(&dep->started_list) &&
2931 		(list_empty(&dep->pending_list) || status == -EXDEV))
2932 		dwc3_stop_active_transfer(dep, true, true);
2933 	else if (dwc3_gadget_ep_should_continue(dep))
2934 		if (__dwc3_gadget_kick_transfer(dep) == 0)
2935 			no_started_trb = false;
2936 
2937 out:
2938 	/*
2939 	 * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
2940 	 * See dwc3_gadget_linksts_change_interrupt() for 1st half.
2941 	 */
2942 	if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
2943 		u32		reg;
2944 		int		i;
2945 
2946 		for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
2947 			dep = dwc->eps[i];
2948 
2949 			if (!(dep->flags & DWC3_EP_ENABLED))
2950 				continue;
2951 
2952 			if (!list_empty(&dep->started_list))
2953 				return no_started_trb;
2954 		}
2955 
2956 		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2957 		reg |= dwc->u1u2;
2958 		dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2959 
2960 		dwc->u1u2 = 0;
2961 	}
2962 
2963 	return no_started_trb;
2964 }
2965 
dwc3_gadget_endpoint_transfer_in_progress(struct dwc3_ep * dep,const struct dwc3_event_depevt * event)2966 static void dwc3_gadget_endpoint_transfer_in_progress(struct dwc3_ep *dep,
2967 		const struct dwc3_event_depevt *event)
2968 {
2969 	int status = 0;
2970 
2971 	if (!dep->endpoint.desc)
2972 		return;
2973 
2974 	if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
2975 		dwc3_gadget_endpoint_frame_from_event(dep, event);
2976 
2977 	if (event->status & DEPEVT_STATUS_BUSERR)
2978 		status = -ECONNRESET;
2979 
2980 	if (event->status & DEPEVT_STATUS_MISSED_ISOC)
2981 		status = -EXDEV;
2982 
2983 	dwc3_gadget_endpoint_trbs_complete(dep, event, status);
2984 }
2985 
dwc3_gadget_endpoint_transfer_complete(struct dwc3_ep * dep,const struct dwc3_event_depevt * event)2986 static void dwc3_gadget_endpoint_transfer_complete(struct dwc3_ep *dep,
2987 		const struct dwc3_event_depevt *event)
2988 {
2989 	int status = 0;
2990 
2991 	dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
2992 
2993 	if (event->status & DEPEVT_STATUS_BUSERR)
2994 		status = -ECONNRESET;
2995 
2996 	if (dwc3_gadget_endpoint_trbs_complete(dep, event, status))
2997 		dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
2998 }
2999 
dwc3_gadget_endpoint_transfer_not_ready(struct dwc3_ep * dep,const struct dwc3_event_depevt * event)3000 static void dwc3_gadget_endpoint_transfer_not_ready(struct dwc3_ep *dep,
3001 		const struct dwc3_event_depevt *event)
3002 {
3003 	dwc3_gadget_endpoint_frame_from_event(dep, event);
3004 
3005 	/*
3006 	 * The XferNotReady event is generated only once before the endpoint
3007 	 * starts. It will be generated again when END_TRANSFER command is
3008 	 * issued. For some controller versions, the XferNotReady event may be
3009 	 * generated while the END_TRANSFER command is still in process. Ignore
3010 	 * it and wait for the next XferNotReady event after the command is
3011 	 * completed.
3012 	 */
3013 	if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
3014 		return;
3015 
3016 	(void) __dwc3_gadget_start_isoc(dep);
3017 }
3018 
dwc3_gadget_endpoint_command_complete(struct dwc3_ep * dep,const struct dwc3_event_depevt * event)3019 static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep,
3020 		const struct dwc3_event_depevt *event)
3021 {
3022 	u8 cmd = DEPEVT_PARAMETER_CMD(event->parameters);
3023 
3024 	if (cmd != DWC3_DEPCMD_ENDTRANSFER)
3025 		return;
3026 
3027 	/*
3028 	 * The END_TRANSFER command will cause the controller to generate a
3029 	 * NoStream Event, and it's not due to the host DP NoStream rejection.
3030 	 * Ignore the next NoStream event.
3031 	 */
3032 	if (dep->stream_capable)
3033 		dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM;
3034 
3035 	dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
3036 	dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3037 	dwc3_gadget_ep_cleanup_cancelled_requests(dep);
3038 
3039 	if (dep->flags & DWC3_EP_PENDING_CLEAR_STALL) {
3040 		struct dwc3 *dwc = dep->dwc;
3041 
3042 		dep->flags &= ~DWC3_EP_PENDING_CLEAR_STALL;
3043 		if (dwc3_send_clear_stall_ep_cmd(dep)) {
3044 			struct usb_ep *ep0 = &dwc->eps[0]->endpoint;
3045 
3046 			dev_err(dwc->dev, "failed to clear STALL on %s\n", dep->name);
3047 			if (dwc->delayed_status)
3048 				__dwc3_gadget_ep0_set_halt(ep0, 1);
3049 			return;
3050 		}
3051 
3052 		dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
3053 		if (dwc->delayed_status)
3054 			dwc3_ep0_send_delayed_status(dwc);
3055 	}
3056 
3057 	if ((dep->flags & DWC3_EP_DELAY_START) &&
3058 	    !usb_endpoint_xfer_isoc(dep->endpoint.desc))
3059 		__dwc3_gadget_kick_transfer(dep);
3060 
3061 	dep->flags &= ~DWC3_EP_DELAY_START;
3062 }
3063 
dwc3_gadget_endpoint_stream_event(struct dwc3_ep * dep,const struct dwc3_event_depevt * event)3064 static void dwc3_gadget_endpoint_stream_event(struct dwc3_ep *dep,
3065 		const struct dwc3_event_depevt *event)
3066 {
3067 	struct dwc3 *dwc = dep->dwc;
3068 
3069 	if (event->status == DEPEVT_STREAMEVT_FOUND) {
3070 		dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3071 		goto out;
3072 	}
3073 
3074 	/* Note: NoStream rejection event param value is 0 and not 0xFFFF */
3075 	switch (event->parameters) {
3076 	case DEPEVT_STREAM_PRIME:
3077 		/*
3078 		 * If the host can properly transition the endpoint state from
3079 		 * idle to prime after a NoStream rejection, there's no need to
3080 		 * force restarting the endpoint to reinitiate the stream. To
3081 		 * simplify the check, assume the host follows the USB spec if
3082 		 * it primed the endpoint more than once.
3083 		 */
3084 		if (dep->flags & DWC3_EP_FORCE_RESTART_STREAM) {
3085 			if (dep->flags & DWC3_EP_FIRST_STREAM_PRIMED)
3086 				dep->flags &= ~DWC3_EP_FORCE_RESTART_STREAM;
3087 			else
3088 				dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3089 		}
3090 
3091 		break;
3092 	case DEPEVT_STREAM_NOSTREAM:
3093 		if ((dep->flags & DWC3_EP_IGNORE_NEXT_NOSTREAM) ||
3094 		    !(dep->flags & DWC3_EP_FORCE_RESTART_STREAM) ||
3095 		    !(dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE))
3096 			break;
3097 
3098 		/*
3099 		 * If the host rejects a stream due to no active stream, by the
3100 		 * USB and xHCI spec, the endpoint will be put back to idle
3101 		 * state. When the host is ready (buffer added/updated), it will
3102 		 * prime the endpoint to inform the usb device controller. This
3103 		 * triggers the device controller to issue ERDY to restart the
3104 		 * stream. However, some hosts don't follow this and keep the
3105 		 * endpoint in the idle state. No prime will come despite host
3106 		 * streams are updated, and the device controller will not be
3107 		 * triggered to generate ERDY to move the next stream data. To
3108 		 * workaround this and maintain compatibility with various
3109 		 * hosts, force to reinitate the stream until the host is ready
3110 		 * instead of waiting for the host to prime the endpoint.
3111 		 */
3112 		if (DWC3_VER_IS_WITHIN(DWC32, 100A, ANY)) {
3113 			unsigned int cmd = DWC3_DGCMD_SET_ENDPOINT_PRIME;
3114 
3115 			dwc3_send_gadget_generic_command(dwc, cmd, dep->number);
3116 		} else {
3117 			dep->flags |= DWC3_EP_DELAY_START;
3118 			dwc3_stop_active_transfer(dep, true, true);
3119 			return;
3120 		}
3121 		break;
3122 	}
3123 
3124 out:
3125 	dep->flags &= ~DWC3_EP_IGNORE_NEXT_NOSTREAM;
3126 }
3127 
dwc3_endpoint_interrupt(struct dwc3 * dwc,const struct dwc3_event_depevt * event)3128 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
3129 		const struct dwc3_event_depevt *event)
3130 {
3131 	struct dwc3_ep		*dep;
3132 	u8			epnum = event->endpoint_number;
3133 
3134 	dep = dwc->eps[epnum];
3135 
3136 	if (!(dep->flags & DWC3_EP_ENABLED)) {
3137 		if (!(dep->flags & DWC3_EP_TRANSFER_STARTED))
3138 			return;
3139 
3140 		/* Handle only EPCMDCMPLT when EP disabled */
3141 		if (event->endpoint_event != DWC3_DEPEVT_EPCMDCMPLT)
3142 			return;
3143 	}
3144 
3145 	if (epnum == 0 || epnum == 1) {
3146 		dwc3_ep0_interrupt(dwc, event);
3147 		return;
3148 	}
3149 
3150 	switch (event->endpoint_event) {
3151 	case DWC3_DEPEVT_XFERINPROGRESS:
3152 		dwc3_gadget_endpoint_transfer_in_progress(dep, event);
3153 		break;
3154 	case DWC3_DEPEVT_XFERNOTREADY:
3155 		dwc3_gadget_endpoint_transfer_not_ready(dep, event);
3156 		break;
3157 	case DWC3_DEPEVT_EPCMDCMPLT:
3158 		dwc3_gadget_endpoint_command_complete(dep, event);
3159 		break;
3160 	case DWC3_DEPEVT_XFERCOMPLETE:
3161 		dwc3_gadget_endpoint_transfer_complete(dep, event);
3162 		break;
3163 	case DWC3_DEPEVT_STREAMEVT:
3164 		dwc3_gadget_endpoint_stream_event(dep, event);
3165 		break;
3166 	case DWC3_DEPEVT_RXTXFIFOEVT:
3167 		break;
3168 	}
3169 }
3170 
dwc3_disconnect_gadget(struct dwc3 * dwc)3171 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
3172 {
3173 	if (dwc->gadget_driver && dwc->gadget_driver->disconnect) {
3174 		spin_unlock(&dwc->lock);
3175 		dwc->gadget_driver->disconnect(dwc->gadget);
3176 		spin_lock(&dwc->lock);
3177 	}
3178 }
3179 
dwc3_suspend_gadget(struct dwc3 * dwc)3180 static void dwc3_suspend_gadget(struct dwc3 *dwc)
3181 {
3182 	if (dwc->gadget_driver && dwc->gadget_driver->suspend) {
3183 		spin_unlock(&dwc->lock);
3184 		dwc->gadget_driver->suspend(dwc->gadget);
3185 		spin_lock(&dwc->lock);
3186 	}
3187 }
3188 
dwc3_resume_gadget(struct dwc3 * dwc)3189 static void dwc3_resume_gadget(struct dwc3 *dwc)
3190 {
3191 	if (dwc->gadget_driver && dwc->gadget_driver->resume) {
3192 		spin_unlock(&dwc->lock);
3193 		dwc->gadget_driver->resume(dwc->gadget);
3194 		spin_lock(&dwc->lock);
3195 	}
3196 }
3197 
dwc3_reset_gadget(struct dwc3 * dwc)3198 static void dwc3_reset_gadget(struct dwc3 *dwc)
3199 {
3200 	if (!dwc->gadget_driver)
3201 		return;
3202 
3203 	if (dwc->gadget->speed != USB_SPEED_UNKNOWN) {
3204 		spin_unlock(&dwc->lock);
3205 		usb_gadget_udc_reset(dwc->gadget, dwc->gadget_driver);
3206 		spin_lock(&dwc->lock);
3207 	}
3208 }
3209 
dwc3_stop_active_transfer(struct dwc3_ep * dep,bool force,bool interrupt)3210 static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force,
3211 	bool interrupt)
3212 {
3213 	struct dwc3_gadget_ep_cmd_params params;
3214 	u32 cmd;
3215 	int ret;
3216 
3217 	if (!(dep->flags & DWC3_EP_TRANSFER_STARTED) ||
3218 	    (dep->flags & DWC3_EP_END_TRANSFER_PENDING))
3219 		return;
3220 
3221 	/*
3222 	 * NOTICE: We are violating what the Databook says about the
3223 	 * EndTransfer command. Ideally we would _always_ wait for the
3224 	 * EndTransfer Command Completion IRQ, but that's causing too
3225 	 * much trouble synchronizing between us and gadget driver.
3226 	 *
3227 	 * We have discussed this with the IP Provider and it was
3228 	 * suggested to giveback all requests here.
3229 	 *
3230 	 * Note also that a similar handling was tested by Synopsys
3231 	 * (thanks a lot Paul) and nothing bad has come out of it.
3232 	 * In short, what we're doing is issuing EndTransfer with
3233 	 * CMDIOC bit set and delay kicking transfer until the
3234 	 * EndTransfer command had completed.
3235 	 *
3236 	 * As of IP version 3.10a of the DWC_usb3 IP, the controller
3237 	 * supports a mode to work around the above limitation. The
3238 	 * software can poll the CMDACT bit in the DEPCMD register
3239 	 * after issuing a EndTransfer command. This mode is enabled
3240 	 * by writing GUCTL2[14]. This polling is already done in the
3241 	 * dwc3_send_gadget_ep_cmd() function so if the mode is
3242 	 * enabled, the EndTransfer command will have completed upon
3243 	 * returning from this function.
3244 	 *
3245 	 * This mode is NOT available on the DWC_usb31 IP.
3246 	 */
3247 
3248 	cmd = DWC3_DEPCMD_ENDTRANSFER;
3249 	cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
3250 	cmd |= interrupt ? DWC3_DEPCMD_CMDIOC : 0;
3251 	cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
3252 	memset(&params, 0, sizeof(params));
3253 	ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
3254 	WARN_ON_ONCE(ret);
3255 	dep->resource_index = 0;
3256 
3257 	if (!interrupt)
3258 		dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3259 	else
3260 		dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
3261 }
3262 
dwc3_clear_stall_all_ep(struct dwc3 * dwc)3263 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
3264 {
3265 	u32 epnum;
3266 
3267 	for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
3268 		struct dwc3_ep *dep;
3269 		int ret;
3270 
3271 		dep = dwc->eps[epnum];
3272 		if (!dep)
3273 			continue;
3274 
3275 		if (!(dep->flags & DWC3_EP_STALL))
3276 			continue;
3277 
3278 		dep->flags &= ~DWC3_EP_STALL;
3279 
3280 		ret = dwc3_send_clear_stall_ep_cmd(dep);
3281 		WARN_ON_ONCE(ret);
3282 	}
3283 }
3284 
dwc3_gadget_disconnect_interrupt(struct dwc3 * dwc)3285 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
3286 {
3287 	int			reg;
3288 
3289 	dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RX_DET);
3290 
3291 	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3292 	reg &= ~DWC3_DCTL_INITU1ENA;
3293 	reg &= ~DWC3_DCTL_INITU2ENA;
3294 	dwc3_gadget_dctl_write_safe(dwc, reg);
3295 
3296 	dwc3_disconnect_gadget(dwc);
3297 
3298 	dwc->gadget->speed = USB_SPEED_UNKNOWN;
3299 	dwc->setup_packet_pending = false;
3300 	usb_gadget_set_state(dwc->gadget, USB_STATE_NOTATTACHED);
3301 
3302 	dwc->connected = false;
3303 }
3304 
dwc3_gadget_reset_interrupt(struct dwc3 * dwc)3305 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
3306 {
3307 	u32			reg;
3308 
3309 	/*
3310 	 * Ideally, dwc3_reset_gadget() would trigger the function
3311 	 * drivers to stop any active transfers through ep disable.
3312 	 * However, for functions which defer ep disable, such as mass
3313 	 * storage, we will need to rely on the call to stop active
3314 	 * transfers here, and avoid allowing of request queuing.
3315 	 */
3316 	dwc->connected = false;
3317 
3318 	/*
3319 	 * WORKAROUND: DWC3 revisions <1.88a have an issue which
3320 	 * would cause a missing Disconnect Event if there's a
3321 	 * pending Setup Packet in the FIFO.
3322 	 *
3323 	 * There's no suggested workaround on the official Bug
3324 	 * report, which states that "unless the driver/application
3325 	 * is doing any special handling of a disconnect event,
3326 	 * there is no functional issue".
3327 	 *
3328 	 * Unfortunately, it turns out that we _do_ some special
3329 	 * handling of a disconnect event, namely complete all
3330 	 * pending transfers, notify gadget driver of the
3331 	 * disconnection, and so on.
3332 	 *
3333 	 * Our suggested workaround is to follow the Disconnect
3334 	 * Event steps here, instead, based on a setup_packet_pending
3335 	 * flag. Such flag gets set whenever we have a SETUP_PENDING
3336 	 * status for EP0 TRBs and gets cleared on XferComplete for the
3337 	 * same endpoint.
3338 	 *
3339 	 * Refers to:
3340 	 *
3341 	 * STAR#9000466709: RTL: Device : Disconnect event not
3342 	 * generated if setup packet pending in FIFO
3343 	 */
3344 	if (DWC3_VER_IS_PRIOR(DWC3, 188A)) {
3345 		if (dwc->setup_packet_pending)
3346 			dwc3_gadget_disconnect_interrupt(dwc);
3347 	}
3348 
3349 	dwc3_reset_gadget(dwc);
3350 	/*
3351 	 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
3352 	 * Section 4.1.2 Table 4-2, it states that during a USB reset, the SW
3353 	 * needs to ensure that it sends "a DEPENDXFER command for any active
3354 	 * transfers."
3355 	 */
3356 	dwc3_stop_active_transfers(dwc);
3357 	dwc->connected = true;
3358 
3359 	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3360 	reg &= ~DWC3_DCTL_TSTCTRL_MASK;
3361 	dwc3_gadget_dctl_write_safe(dwc, reg);
3362 	dwc->test_mode = false;
3363 	dwc3_clear_stall_all_ep(dwc);
3364 
3365 	/* Reset device address to zero */
3366 	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3367 	reg &= ~(DWC3_DCFG_DEVADDR_MASK);
3368 	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3369 }
3370 
dwc3_gadget_conndone_interrupt(struct dwc3 * dwc)3371 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
3372 {
3373 	struct dwc3_ep		*dep;
3374 	int			ret;
3375 	u32			reg;
3376 	u8			speed;
3377 
3378 	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
3379 	speed = reg & DWC3_DSTS_CONNECTSPD;
3380 	dwc->speed = speed;
3381 
3382 	/*
3383 	 * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
3384 	 * each time on Connect Done.
3385 	 *
3386 	 * Currently we always use the reset value. If any platform
3387 	 * wants to set this to a different value, we need to add a
3388 	 * setting and update GCTL.RAMCLKSEL here.
3389 	 */
3390 
3391 	switch (speed) {
3392 	case DWC3_DSTS_SUPERSPEED_PLUS:
3393 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
3394 		dwc->gadget->ep0->maxpacket = 512;
3395 		dwc->gadget->speed = USB_SPEED_SUPER_PLUS;
3396 		break;
3397 	case DWC3_DSTS_SUPERSPEED:
3398 		/*
3399 		 * WORKAROUND: DWC3 revisions <1.90a have an issue which
3400 		 * would cause a missing USB3 Reset event.
3401 		 *
3402 		 * In such situations, we should force a USB3 Reset
3403 		 * event by calling our dwc3_gadget_reset_interrupt()
3404 		 * routine.
3405 		 *
3406 		 * Refers to:
3407 		 *
3408 		 * STAR#9000483510: RTL: SS : USB3 reset event may
3409 		 * not be generated always when the link enters poll
3410 		 */
3411 		if (DWC3_VER_IS_PRIOR(DWC3, 190A))
3412 			dwc3_gadget_reset_interrupt(dwc);
3413 
3414 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
3415 		dwc->gadget->ep0->maxpacket = 512;
3416 		dwc->gadget->speed = USB_SPEED_SUPER;
3417 		break;
3418 	case DWC3_DSTS_HIGHSPEED:
3419 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
3420 		dwc->gadget->ep0->maxpacket = 64;
3421 		dwc->gadget->speed = USB_SPEED_HIGH;
3422 		break;
3423 	case DWC3_DSTS_FULLSPEED:
3424 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
3425 		dwc->gadget->ep0->maxpacket = 64;
3426 		dwc->gadget->speed = USB_SPEED_FULL;
3427 		break;
3428 	case DWC3_DSTS_LOWSPEED:
3429 		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(8);
3430 		dwc->gadget->ep0->maxpacket = 8;
3431 		dwc->gadget->speed = USB_SPEED_LOW;
3432 		break;
3433 	}
3434 
3435 	dwc->eps[1]->endpoint.maxpacket = dwc->gadget->ep0->maxpacket;
3436 
3437 	/* Enable USB2 LPM Capability */
3438 
3439 	if (!DWC3_VER_IS_WITHIN(DWC3, ANY, 194A) &&
3440 	    !dwc->usb2_gadget_lpm_disable &&
3441 	    (speed != DWC3_DSTS_SUPERSPEED) &&
3442 	    (speed != DWC3_DSTS_SUPERSPEED_PLUS)) {
3443 		reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3444 		reg |= DWC3_DCFG_LPM_CAP;
3445 		dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3446 
3447 		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3448 		reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
3449 
3450 		reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold |
3451 					    (dwc->is_utmi_l1_suspend << 4));
3452 
3453 		/*
3454 		 * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
3455 		 * DCFG.LPMCap is set, core responses with an ACK and the
3456 		 * BESL value in the LPM token is less than or equal to LPM
3457 		 * NYET threshold.
3458 		 */
3459 		WARN_ONCE(DWC3_VER_IS_PRIOR(DWC3, 240A) && dwc->has_lpm_erratum,
3460 				"LPM Erratum not available on dwc3 revisions < 2.40a\n");
3461 
3462 		if (dwc->has_lpm_erratum && !DWC3_VER_IS_PRIOR(DWC3, 240A))
3463 			reg |= DWC3_DCTL_NYET_THRES(dwc->lpm_nyet_threshold);
3464 
3465 		dwc3_gadget_dctl_write_safe(dwc, reg);
3466 	} else {
3467 		if (dwc->usb2_gadget_lpm_disable) {
3468 			reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3469 			reg &= ~DWC3_DCFG_LPM_CAP;
3470 			dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3471 		}
3472 
3473 		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3474 		reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
3475 		dwc3_gadget_dctl_write_safe(dwc, reg);
3476 	}
3477 
3478 	dep = dwc->eps[0];
3479 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
3480 	if (ret) {
3481 		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
3482 		return;
3483 	}
3484 
3485 	dep = dwc->eps[1];
3486 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
3487 	if (ret) {
3488 		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
3489 		return;
3490 	}
3491 
3492 	/*
3493 	 * Configure PHY via GUSB3PIPECTLn if required.
3494 	 *
3495 	 * Update GTXFIFOSIZn
3496 	 *
3497 	 * In both cases reset values should be sufficient.
3498 	 */
3499 }
3500 
dwc3_gadget_wakeup_interrupt(struct dwc3 * dwc)3501 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
3502 {
3503 	/*
3504 	 * TODO take core out of low power mode when that's
3505 	 * implemented.
3506 	 */
3507 
3508 	if (dwc->gadget_driver && dwc->gadget_driver->resume) {
3509 		spin_unlock(&dwc->lock);
3510 		dwc->gadget_driver->resume(dwc->gadget);
3511 		spin_lock(&dwc->lock);
3512 	}
3513 }
3514 
dwc3_gadget_linksts_change_interrupt(struct dwc3 * dwc,unsigned int evtinfo)3515 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
3516 		unsigned int evtinfo)
3517 {
3518 	enum dwc3_link_state	next = evtinfo & DWC3_LINK_STATE_MASK;
3519 	unsigned int		pwropt;
3520 
3521 	/*
3522 	 * WORKAROUND: DWC3 < 2.50a have an issue when configured without
3523 	 * Hibernation mode enabled which would show up when device detects
3524 	 * host-initiated U3 exit.
3525 	 *
3526 	 * In that case, device will generate a Link State Change Interrupt
3527 	 * from U3 to RESUME which is only necessary if Hibernation is
3528 	 * configured in.
3529 	 *
3530 	 * There are no functional changes due to such spurious event and we
3531 	 * just need to ignore it.
3532 	 *
3533 	 * Refers to:
3534 	 *
3535 	 * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
3536 	 * operational mode
3537 	 */
3538 	pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
3539 	if (DWC3_VER_IS_PRIOR(DWC3, 250A) &&
3540 			(pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
3541 		if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
3542 				(next == DWC3_LINK_STATE_RESUME)) {
3543 			return;
3544 		}
3545 	}
3546 
3547 	/*
3548 	 * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
3549 	 * on the link partner, the USB session might do multiple entry/exit
3550 	 * of low power states before a transfer takes place.
3551 	 *
3552 	 * Due to this problem, we might experience lower throughput. The
3553 	 * suggested workaround is to disable DCTL[12:9] bits if we're
3554 	 * transitioning from U1/U2 to U0 and enable those bits again
3555 	 * after a transfer completes and there are no pending transfers
3556 	 * on any of the enabled endpoints.
3557 	 *
3558 	 * This is the first half of that workaround.
3559 	 *
3560 	 * Refers to:
3561 	 *
3562 	 * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
3563 	 * core send LGO_Ux entering U0
3564 	 */
3565 	if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
3566 		if (next == DWC3_LINK_STATE_U0) {
3567 			u32	u1u2;
3568 			u32	reg;
3569 
3570 			switch (dwc->link_state) {
3571 			case DWC3_LINK_STATE_U1:
3572 			case DWC3_LINK_STATE_U2:
3573 				reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3574 				u1u2 = reg & (DWC3_DCTL_INITU2ENA
3575 						| DWC3_DCTL_ACCEPTU2ENA
3576 						| DWC3_DCTL_INITU1ENA
3577 						| DWC3_DCTL_ACCEPTU1ENA);
3578 
3579 				if (!dwc->u1u2)
3580 					dwc->u1u2 = reg & u1u2;
3581 
3582 				reg &= ~u1u2;
3583 
3584 				dwc3_gadget_dctl_write_safe(dwc, reg);
3585 				break;
3586 			default:
3587 				/* do nothing */
3588 				break;
3589 			}
3590 		}
3591 	}
3592 
3593 	switch (next) {
3594 	case DWC3_LINK_STATE_U1:
3595 		if (dwc->speed == USB_SPEED_SUPER)
3596 			dwc3_suspend_gadget(dwc);
3597 		break;
3598 	case DWC3_LINK_STATE_U2:
3599 	case DWC3_LINK_STATE_U3:
3600 		dwc3_suspend_gadget(dwc);
3601 		break;
3602 	case DWC3_LINK_STATE_RESUME:
3603 		dwc3_resume_gadget(dwc);
3604 		break;
3605 	default:
3606 		/* do nothing */
3607 		break;
3608 	}
3609 
3610 	dwc->link_state = next;
3611 }
3612 
dwc3_gadget_suspend_interrupt(struct dwc3 * dwc,unsigned int evtinfo)3613 static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc,
3614 					  unsigned int evtinfo)
3615 {
3616 	enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
3617 
3618 	if (dwc->link_state != next && next == DWC3_LINK_STATE_U3)
3619 		dwc3_suspend_gadget(dwc);
3620 
3621 	dwc->link_state = next;
3622 }
3623 
dwc3_gadget_hibernation_interrupt(struct dwc3 * dwc,unsigned int evtinfo)3624 static void dwc3_gadget_hibernation_interrupt(struct dwc3 *dwc,
3625 		unsigned int evtinfo)
3626 {
3627 	unsigned int is_ss = evtinfo & BIT(4);
3628 
3629 	/*
3630 	 * WORKAROUND: DWC3 revison 2.20a with hibernation support
3631 	 * have a known issue which can cause USB CV TD.9.23 to fail
3632 	 * randomly.
3633 	 *
3634 	 * Because of this issue, core could generate bogus hibernation
3635 	 * events which SW needs to ignore.
3636 	 *
3637 	 * Refers to:
3638 	 *
3639 	 * STAR#9000546576: Device Mode Hibernation: Issue in USB 2.0
3640 	 * Device Fallback from SuperSpeed
3641 	 */
3642 	if (is_ss ^ (dwc->speed == USB_SPEED_SUPER))
3643 		return;
3644 
3645 	/* enter hibernation here */
3646 }
3647 
dwc3_gadget_interrupt(struct dwc3 * dwc,const struct dwc3_event_devt * event)3648 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
3649 		const struct dwc3_event_devt *event)
3650 {
3651 	switch (event->type) {
3652 	case DWC3_DEVICE_EVENT_DISCONNECT:
3653 		dwc3_gadget_disconnect_interrupt(dwc);
3654 		break;
3655 	case DWC3_DEVICE_EVENT_RESET:
3656 		dwc3_gadget_reset_interrupt(dwc);
3657 		break;
3658 	case DWC3_DEVICE_EVENT_CONNECT_DONE:
3659 		dwc3_gadget_conndone_interrupt(dwc);
3660 		break;
3661 	case DWC3_DEVICE_EVENT_WAKEUP:
3662 		dwc3_gadget_wakeup_interrupt(dwc);
3663 		break;
3664 	case DWC3_DEVICE_EVENT_HIBER_REQ:
3665 		if (dev_WARN_ONCE(dwc->dev, !dwc->has_hibernation,
3666 					"unexpected hibernation event\n"))
3667 			break;
3668 
3669 		dwc3_gadget_hibernation_interrupt(dwc, event->event_info);
3670 		break;
3671 	case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
3672 		dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
3673 		break;
3674 	case DWC3_DEVICE_EVENT_EOPF:
3675 		/* It changed to be suspend event for version 2.30a and above */
3676 		if (!DWC3_VER_IS_PRIOR(DWC3, 230A)) {
3677 			/*
3678 			 * Ignore suspend event until the gadget enters into
3679 			 * USB_STATE_CONFIGURED state.
3680 			 */
3681 			if (dwc->gadget->state >= USB_STATE_CONFIGURED)
3682 				dwc3_gadget_suspend_interrupt(dwc,
3683 						event->event_info);
3684 		}
3685 		break;
3686 	case DWC3_DEVICE_EVENT_SOF:
3687 	case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
3688 	case DWC3_DEVICE_EVENT_CMD_CMPL:
3689 	case DWC3_DEVICE_EVENT_OVERFLOW:
3690 		break;
3691 	default:
3692 		dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
3693 	}
3694 }
3695 
dwc3_process_event_entry(struct dwc3 * dwc,const union dwc3_event * event)3696 static void dwc3_process_event_entry(struct dwc3 *dwc,
3697 		const union dwc3_event *event)
3698 {
3699 	trace_dwc3_event(event->raw, dwc);
3700 
3701 	if (!event->type.is_devspec)
3702 		dwc3_endpoint_interrupt(dwc, &event->depevt);
3703 	else if (event->type.type == DWC3_EVENT_TYPE_DEV)
3704 		dwc3_gadget_interrupt(dwc, &event->devt);
3705 	else
3706 		dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
3707 }
3708 
dwc3_process_event_buf(struct dwc3_event_buffer * evt)3709 static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt)
3710 {
3711 	struct dwc3 *dwc = evt->dwc;
3712 	irqreturn_t ret = IRQ_NONE;
3713 	int left;
3714 	u32 reg;
3715 
3716 	left = evt->count;
3717 
3718 	if (!(evt->flags & DWC3_EVENT_PENDING))
3719 		return IRQ_NONE;
3720 
3721 	while (left > 0) {
3722 		union dwc3_event event;
3723 
3724 		event.raw = *(u32 *) (evt->cache + evt->lpos);
3725 
3726 		dwc3_process_event_entry(dwc, &event);
3727 
3728 		/*
3729 		 * FIXME we wrap around correctly to the next entry as
3730 		 * almost all entries are 4 bytes in size. There is one
3731 		 * entry which has 12 bytes which is a regular entry
3732 		 * followed by 8 bytes data. ATM I don't know how
3733 		 * things are organized if we get next to the a
3734 		 * boundary so I worry about that once we try to handle
3735 		 * that.
3736 		 */
3737 		evt->lpos = (evt->lpos + 4) % evt->length;
3738 		left -= 4;
3739 	}
3740 
3741 	evt->count = 0;
3742 	evt->flags &= ~DWC3_EVENT_PENDING;
3743 	ret = IRQ_HANDLED;
3744 
3745 	/* Unmask interrupt */
3746 	reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
3747 	reg &= ~DWC3_GEVNTSIZ_INTMASK;
3748 	dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
3749 
3750 	if (dwc->imod_interval) {
3751 		dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
3752 		dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
3753 	}
3754 
3755 	return ret;
3756 }
3757 
dwc3_thread_interrupt(int irq,void * _evt)3758 static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt)
3759 {
3760 	struct dwc3_event_buffer *evt = _evt;
3761 	struct dwc3 *dwc = evt->dwc;
3762 	unsigned long flags;
3763 	irqreturn_t ret = IRQ_NONE;
3764 
3765 	spin_lock_irqsave(&dwc->lock, flags);
3766 	ret = dwc3_process_event_buf(evt);
3767 	spin_unlock_irqrestore(&dwc->lock, flags);
3768 
3769 	return ret;
3770 }
3771 
dwc3_check_event_buf(struct dwc3_event_buffer * evt)3772 static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt)
3773 {
3774 	struct dwc3 *dwc = evt->dwc;
3775 	u32 amount;
3776 	u32 count;
3777 	u32 reg;
3778 
3779 	if (pm_runtime_suspended(dwc->dev)) {
3780 		pm_runtime_get(dwc->dev);
3781 		disable_irq_nosync(dwc->irq_gadget);
3782 		dwc->pending_events = true;
3783 		return IRQ_HANDLED;
3784 	}
3785 
3786 	/*
3787 	 * With PCIe legacy interrupt, test shows that top-half irq handler can
3788 	 * be called again after HW interrupt deassertion. Check if bottom-half
3789 	 * irq event handler completes before caching new event to prevent
3790 	 * losing events.
3791 	 */
3792 	if (evt->flags & DWC3_EVENT_PENDING)
3793 		return IRQ_HANDLED;
3794 
3795 	count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
3796 	count &= DWC3_GEVNTCOUNT_MASK;
3797 	if (!count)
3798 		return IRQ_NONE;
3799 
3800 	evt->count = count;
3801 	evt->flags |= DWC3_EVENT_PENDING;
3802 
3803 	/* Mask interrupt */
3804 	reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
3805 	reg |= DWC3_GEVNTSIZ_INTMASK;
3806 	dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
3807 
3808 	amount = min(count, evt->length - evt->lpos);
3809 	memcpy(evt->cache + evt->lpos, evt->buf + evt->lpos, amount);
3810 
3811 	if (amount < count)
3812 		memcpy(evt->cache, evt->buf, count - amount);
3813 
3814 	dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
3815 
3816 	return IRQ_WAKE_THREAD;
3817 }
3818 
dwc3_interrupt(int irq,void * _evt)3819 static irqreturn_t dwc3_interrupt(int irq, void *_evt)
3820 {
3821 	struct dwc3_event_buffer	*evt = _evt;
3822 
3823 	return dwc3_check_event_buf(evt);
3824 }
3825 
dwc3_gadget_get_irq(struct dwc3 * dwc)3826 static int dwc3_gadget_get_irq(struct dwc3 *dwc)
3827 {
3828 	struct platform_device *dwc3_pdev = to_platform_device(dwc->dev);
3829 	int irq;
3830 
3831 	irq = platform_get_irq_byname_optional(dwc3_pdev, "peripheral");
3832 	if (irq > 0)
3833 		goto out;
3834 
3835 	if (irq == -EPROBE_DEFER)
3836 		goto out;
3837 
3838 	irq = platform_get_irq_byname_optional(dwc3_pdev, "dwc_usb3");
3839 	if (irq > 0)
3840 		goto out;
3841 
3842 	if (irq == -EPROBE_DEFER)
3843 		goto out;
3844 
3845 	irq = platform_get_irq(dwc3_pdev, 0);
3846 	if (irq > 0)
3847 		goto out;
3848 
3849 	if (!irq)
3850 		irq = -EINVAL;
3851 
3852 out:
3853 	return irq;
3854 }
3855 
dwc_gadget_release(struct device * dev)3856 static void dwc_gadget_release(struct device *dev)
3857 {
3858 	struct usb_gadget *gadget = container_of(dev, struct usb_gadget, dev);
3859 
3860 	kfree(gadget);
3861 }
3862 
3863 /**
3864  * dwc3_gadget_init - initializes gadget related registers
3865  * @dwc: pointer to our controller context structure
3866  *
3867  * Returns 0 on success otherwise negative errno.
3868  */
dwc3_gadget_init(struct dwc3 * dwc)3869 int dwc3_gadget_init(struct dwc3 *dwc)
3870 {
3871 	int ret;
3872 	int irq;
3873 	struct device *dev;
3874 
3875 	irq = dwc3_gadget_get_irq(dwc);
3876 	if (irq < 0) {
3877 		ret = irq;
3878 		goto err0;
3879 	}
3880 
3881 	dwc->irq_gadget = irq;
3882 
3883 	dwc->ep0_trb = dma_alloc_coherent(dwc->sysdev,
3884 					  sizeof(*dwc->ep0_trb) * 2,
3885 					  &dwc->ep0_trb_addr, GFP_KERNEL);
3886 	if (!dwc->ep0_trb) {
3887 		dev_err(dwc->dev, "failed to allocate ep0 trb\n");
3888 		ret = -ENOMEM;
3889 		goto err0;
3890 	}
3891 
3892 	dwc->setup_buf = kzalloc(DWC3_EP0_SETUP_SIZE, GFP_KERNEL);
3893 	if (!dwc->setup_buf) {
3894 		ret = -ENOMEM;
3895 		goto err1;
3896 	}
3897 
3898 	dwc->bounce = dma_alloc_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE,
3899 			&dwc->bounce_addr, GFP_KERNEL);
3900 	if (!dwc->bounce) {
3901 		ret = -ENOMEM;
3902 		goto err2;
3903 	}
3904 
3905 	init_completion(&dwc->ep0_in_setup);
3906 	dwc->gadget = kzalloc(sizeof(struct usb_gadget), GFP_KERNEL);
3907 	if (!dwc->gadget) {
3908 		ret = -ENOMEM;
3909 		goto err3;
3910 	}
3911 
3912 
3913 	usb_initialize_gadget(dwc->dev, dwc->gadget, dwc_gadget_release);
3914 	dev				= &dwc->gadget->dev;
3915 	dev->platform_data		= dwc;
3916 	dwc->gadget->ops		= &dwc3_gadget_ops;
3917 	dwc->gadget->speed		= USB_SPEED_UNKNOWN;
3918 	dwc->gadget->sg_supported	= true;
3919 	dwc->gadget->name		= "dwc3-gadget";
3920 	dwc->gadget->lpm_capable	= !dwc->usb2_gadget_lpm_disable;
3921 
3922 	/*
3923 	 * FIXME We might be setting max_speed to <SUPER, however versions
3924 	 * <2.20a of dwc3 have an issue with metastability (documented
3925 	 * elsewhere in this driver) which tells us we can't set max speed to
3926 	 * anything lower than SUPER.
3927 	 *
3928 	 * Because gadget.max_speed is only used by composite.c and function
3929 	 * drivers (i.e. it won't go into dwc3's registers) we are allowing this
3930 	 * to happen so we avoid sending SuperSpeed Capability descriptor
3931 	 * together with our BOS descriptor as that could confuse host into
3932 	 * thinking we can handle super speed.
3933 	 *
3934 	 * Note that, in fact, we won't even support GetBOS requests when speed
3935 	 * is less than super speed because we don't have means, yet, to tell
3936 	 * composite.c that we are USB 2.0 + LPM ECN.
3937 	 */
3938 	if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
3939 	    !dwc->dis_metastability_quirk)
3940 		dev_info(dwc->dev, "changing max_speed on rev %08x\n",
3941 				dwc->revision);
3942 
3943 	dwc->gadget->max_speed		= dwc->maximum_speed;
3944 
3945 	/*
3946 	 * REVISIT: Here we should clear all pending IRQs to be
3947 	 * sure we're starting from a well known location.
3948 	 */
3949 
3950 	ret = dwc3_gadget_init_endpoints(dwc, dwc->num_eps);
3951 	if (ret)
3952 		goto err4;
3953 
3954 	ret = usb_add_gadget(dwc->gadget);
3955 	if (ret) {
3956 		dev_err(dwc->dev, "failed to add gadget\n");
3957 		goto err5;
3958 	}
3959 
3960 	dwc3_gadget_set_speed(dwc->gadget, dwc->maximum_speed);
3961 
3962 	return 0;
3963 
3964 err5:
3965 	dwc3_gadget_free_endpoints(dwc);
3966 err4:
3967 	usb_put_gadget(dwc->gadget);
3968 	dwc->gadget = NULL;
3969 err3:
3970 	dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
3971 			dwc->bounce_addr);
3972 
3973 err2:
3974 	kfree(dwc->setup_buf);
3975 
3976 err1:
3977 	dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
3978 			dwc->ep0_trb, dwc->ep0_trb_addr);
3979 
3980 err0:
3981 	return ret;
3982 }
3983 
3984 /* -------------------------------------------------------------------------- */
3985 
dwc3_gadget_exit(struct dwc3 * dwc)3986 void dwc3_gadget_exit(struct dwc3 *dwc)
3987 {
3988 	if (!dwc->gadget)
3989 		return;
3990 
3991 	usb_del_gadget(dwc->gadget);
3992 	dwc3_gadget_free_endpoints(dwc);
3993 	usb_put_gadget(dwc->gadget);
3994 	dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
3995 			  dwc->bounce_addr);
3996 	kfree(dwc->setup_buf);
3997 	dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
3998 			  dwc->ep0_trb, dwc->ep0_trb_addr);
3999 }
4000 
dwc3_gadget_suspend(struct dwc3 * dwc)4001 int dwc3_gadget_suspend(struct dwc3 *dwc)
4002 {
4003 	if (!dwc->gadget_driver)
4004 		return 0;
4005 
4006 	dwc3_gadget_run_stop(dwc, false, false);
4007 	dwc3_disconnect_gadget(dwc);
4008 	__dwc3_gadget_stop(dwc);
4009 
4010 	return 0;
4011 }
4012 
dwc3_gadget_resume(struct dwc3 * dwc)4013 int dwc3_gadget_resume(struct dwc3 *dwc)
4014 {
4015 	int			ret;
4016 
4017 	if (!dwc->gadget_driver)
4018 		return 0;
4019 
4020 	ret = __dwc3_gadget_start(dwc);
4021 	if (ret < 0)
4022 		goto err0;
4023 
4024 	ret = dwc3_gadget_run_stop(dwc, true, false);
4025 	if (ret < 0)
4026 		goto err1;
4027 
4028 	return 0;
4029 
4030 err1:
4031 	__dwc3_gadget_stop(dwc);
4032 
4033 err0:
4034 	return ret;
4035 }
4036 
dwc3_gadget_process_pending_events(struct dwc3 * dwc)4037 void dwc3_gadget_process_pending_events(struct dwc3 *dwc)
4038 {
4039 	if (dwc->pending_events) {
4040 		dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf);
4041 		dwc->pending_events = false;
4042 		enable_irq(dwc->irq_gadget);
4043 	}
4044 }
4045