gadget.c revision 7efea86c2868b8fd9df65e589e33aebe498ce21d
1/**
2 * gadget.c - DesignWare USB3 DRD Controller Gadget Framework Link
3 *
4 * Copyright (C) 2010-2011 Texas Instruments Incorporated - http://www.ti.com
5 *
6 * Authors: Felipe Balbi <balbi@ti.com>,
7 *	    Sebastian Andrzej Siewior <bigeasy@linutronix.de>
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. The names of the above-listed copyright holders may not be used
19 *    to endorse or promote products derived from this software without
20 *    specific prior written permission.
21 *
22 * ALTERNATIVELY, this software may be distributed under the terms of the
23 * GNU General Public License ("GPL") version 2, as published by the Free
24 * Software Foundation.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
27 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
28 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
30 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
31 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
32 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
33 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
34 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
35 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
36 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38
39#include <linux/kernel.h>
40#include <linux/delay.h>
41#include <linux/slab.h>
42#include <linux/spinlock.h>
43#include <linux/platform_device.h>
44#include <linux/pm_runtime.h>
45#include <linux/interrupt.h>
46#include <linux/io.h>
47#include <linux/list.h>
48#include <linux/dma-mapping.h>
49
50#include <linux/usb/ch9.h>
51#include <linux/usb/gadget.h>
52
53#include "core.h"
54#include "gadget.h"
55#include "io.h"
56
57/**
58 * dwc3_gadget_set_test_mode - Enables USB2 Test Modes
59 * @dwc: pointer to our context structure
60 * @mode: the mode to set (J, K SE0 NAK, Force Enable)
61 *
62 * Caller should take care of locking. This function will
63 * return 0 on success or -EINVAL if wrong Test Selector
64 * is passed
65 */
66int dwc3_gadget_set_test_mode(struct dwc3 *dwc, int mode)
67{
68	u32		reg;
69
70	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
71	reg &= ~DWC3_DCTL_TSTCTRL_MASK;
72
73	switch (mode) {
74	case TEST_J:
75	case TEST_K:
76	case TEST_SE0_NAK:
77	case TEST_PACKET:
78	case TEST_FORCE_EN:
79		reg |= mode << 1;
80		break;
81	default:
82		return -EINVAL;
83	}
84
85	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
86
87	return 0;
88}
89
90/**
91 * dwc3_gadget_set_link_state - Sets USB Link to a particular State
92 * @dwc: pointer to our context structure
93 * @state: the state to put link into
94 *
95 * Caller should take care of locking. This function will
96 * return 0 on success or -ETIMEDOUT.
97 */
98int dwc3_gadget_set_link_state(struct dwc3 *dwc, enum dwc3_link_state state)
99{
100	int		retries = 10000;
101	u32		reg;
102
103	/*
104	 * Wait until device controller is ready. Only applies to 1.94a and
105	 * later RTL.
106	 */
107	if (dwc->revision >= DWC3_REVISION_194A) {
108		while (--retries) {
109			reg = dwc3_readl(dwc->regs, DWC3_DSTS);
110			if (reg & DWC3_DSTS_DCNRD)
111				udelay(5);
112			else
113				break;
114		}
115
116		if (retries <= 0)
117			return -ETIMEDOUT;
118	}
119
120	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
121	reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
122
123	/* set requested state */
124	reg |= DWC3_DCTL_ULSTCHNGREQ(state);
125	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
126
127	/*
128	 * The following code is racy when called from dwc3_gadget_wakeup,
129	 * and is not needed, at least on newer versions
130	 */
131	if (dwc->revision >= DWC3_REVISION_194A)
132		return 0;
133
134	/* wait for a change in DSTS */
135	retries = 10000;
136	while (--retries) {
137		reg = dwc3_readl(dwc->regs, DWC3_DSTS);
138
139		if (DWC3_DSTS_USBLNKST(reg) == state)
140			return 0;
141
142		udelay(5);
143	}
144
145	dev_vdbg(dwc->dev, "link state change request timed out\n");
146
147	return -ETIMEDOUT;
148}
149
150/**
151 * dwc3_gadget_resize_tx_fifos - reallocate fifo spaces for current use-case
152 * @dwc: pointer to our context structure
153 *
154 * This function will a best effort FIFO allocation in order
155 * to improve FIFO usage and throughput, while still allowing
156 * us to enable as many endpoints as possible.
157 *
158 * Keep in mind that this operation will be highly dependent
159 * on the configured size for RAM1 - which contains TxFifo -,
160 * the amount of endpoints enabled on coreConsultant tool, and
161 * the width of the Master Bus.
162 *
163 * In the ideal world, we would always be able to satisfy the
164 * following equation:
165 *
166 * ((512 + 2 * MDWIDTH-Bytes) + (Number of IN Endpoints - 1) * \
167 * (3 * (1024 + MDWIDTH-Bytes) + MDWIDTH-Bytes)) / MDWIDTH-Bytes
168 *
169 * Unfortunately, due to many variables that's not always the case.
170 */
171int dwc3_gadget_resize_tx_fifos(struct dwc3 *dwc)
172{
173	int		last_fifo_depth = 0;
174	int		ram1_depth;
175	int		fifo_size;
176	int		mdwidth;
177	int		num;
178
179	if (!dwc->needs_fifo_resize)
180		return 0;
181
182	ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7);
183	mdwidth = DWC3_MDWIDTH(dwc->hwparams.hwparams0);
184
185	/* MDWIDTH is represented in bits, we need it in bytes */
186	mdwidth >>= 3;
187
188	/*
189	 * FIXME For now we will only allocate 1 wMaxPacketSize space
190	 * for each enabled endpoint, later patches will come to
191	 * improve this algorithm so that we better use the internal
192	 * FIFO space
193	 */
194	for (num = 0; num < DWC3_ENDPOINTS_NUM; num++) {
195		struct dwc3_ep	*dep = dwc->eps[num];
196		int		fifo_number = dep->number >> 1;
197		int		mult = 1;
198		int		tmp;
199
200		if (!(dep->number & 1))
201			continue;
202
203		if (!(dep->flags & DWC3_EP_ENABLED))
204			continue;
205
206		if (usb_endpoint_xfer_bulk(dep->endpoint.desc)
207				|| usb_endpoint_xfer_isoc(dep->endpoint.desc))
208			mult = 3;
209
210		/*
211		 * REVISIT: the following assumes we will always have enough
212		 * space available on the FIFO RAM for all possible use cases.
213		 * Make sure that's true somehow and change FIFO allocation
214		 * accordingly.
215		 *
216		 * If we have Bulk or Isochronous endpoints, we want
217		 * them to be able to be very, very fast. So we're giving
218		 * those endpoints a fifo_size which is enough for 3 full
219		 * packets
220		 */
221		tmp = mult * (dep->endpoint.maxpacket + mdwidth);
222		tmp += mdwidth;
223
224		fifo_size = DIV_ROUND_UP(tmp, mdwidth);
225
226		fifo_size |= (last_fifo_depth << 16);
227
228		dev_vdbg(dwc->dev, "%s: Fifo Addr %04x Size %d\n",
229				dep->name, last_fifo_depth, fifo_size & 0xffff);
230
231		dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(fifo_number),
232				fifo_size);
233
234		last_fifo_depth += (fifo_size & 0xffff);
235	}
236
237	return 0;
238}
239
240void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
241		int status)
242{
243	struct dwc3			*dwc = dep->dwc;
244
245	if (req->queued) {
246		if (req->request.num_mapped_sgs)
247			dep->busy_slot += req->request.num_mapped_sgs;
248		else
249			dep->busy_slot++;
250
251		/*
252		 * Skip LINK TRB. We can't use req->trb and check for
253		 * DWC3_TRBCTL_LINK_TRB because it points the TRB we just
254		 * completed (not the LINK TRB).
255		 */
256		if (((dep->busy_slot & DWC3_TRB_MASK) == DWC3_TRB_NUM - 1) &&
257				usb_endpoint_xfer_isoc(dep->endpoint.desc))
258			dep->busy_slot++;
259	}
260	list_del(&req->list);
261	req->trb = NULL;
262
263	if (req->request.status == -EINPROGRESS)
264		req->request.status = status;
265
266	if (dwc->ep0_bounced && dep->number == 0)
267		dwc->ep0_bounced = false;
268	else
269		usb_gadget_unmap_request(&dwc->gadget, &req->request,
270				req->direction);
271
272	dev_dbg(dwc->dev, "request %p from %s completed %d/%d ===> %d\n",
273			req, dep->name, req->request.actual,
274			req->request.length, status);
275
276	spin_unlock(&dwc->lock);
277	req->request.complete(&dep->endpoint, &req->request);
278	spin_lock(&dwc->lock);
279}
280
281static const char *dwc3_gadget_ep_cmd_string(u8 cmd)
282{
283	switch (cmd) {
284	case DWC3_DEPCMD_DEPSTARTCFG:
285		return "Start New Configuration";
286	case DWC3_DEPCMD_ENDTRANSFER:
287		return "End Transfer";
288	case DWC3_DEPCMD_UPDATETRANSFER:
289		return "Update Transfer";
290	case DWC3_DEPCMD_STARTTRANSFER:
291		return "Start Transfer";
292	case DWC3_DEPCMD_CLEARSTALL:
293		return "Clear Stall";
294	case DWC3_DEPCMD_SETSTALL:
295		return "Set Stall";
296	case DWC3_DEPCMD_GETEPSTATE:
297		return "Get Endpoint State";
298	case DWC3_DEPCMD_SETTRANSFRESOURCE:
299		return "Set Endpoint Transfer Resource";
300	case DWC3_DEPCMD_SETEPCONFIG:
301		return "Set Endpoint Configuration";
302	default:
303		return "UNKNOWN command";
304	}
305}
306
307int dwc3_send_gadget_generic_command(struct dwc3 *dwc, int cmd, u32 param)
308{
309	u32		timeout = 500;
310	u32		reg;
311
312	dwc3_writel(dwc->regs, DWC3_DGCMDPAR, param);
313	dwc3_writel(dwc->regs, DWC3_DGCMD, cmd | DWC3_DGCMD_CMDACT);
314
315	do {
316		reg = dwc3_readl(dwc->regs, DWC3_DGCMD);
317		if (!(reg & DWC3_DGCMD_CMDACT)) {
318			dev_vdbg(dwc->dev, "Command Complete --> %d\n",
319					DWC3_DGCMD_STATUS(reg));
320			return 0;
321		}
322
323		/*
324		 * We can't sleep here, because it's also called from
325		 * interrupt context.
326		 */
327		timeout--;
328		if (!timeout)
329			return -ETIMEDOUT;
330		udelay(1);
331	} while (1);
332}
333
334int dwc3_send_gadget_ep_cmd(struct dwc3 *dwc, unsigned ep,
335		unsigned cmd, struct dwc3_gadget_ep_cmd_params *params)
336{
337	struct dwc3_ep		*dep = dwc->eps[ep];
338	u32			timeout = 500;
339	u32			reg;
340
341	dev_vdbg(dwc->dev, "%s: cmd '%s' params %08x %08x %08x\n",
342			dep->name,
343			dwc3_gadget_ep_cmd_string(cmd), params->param0,
344			params->param1, params->param2);
345
346	dwc3_writel(dwc->regs, DWC3_DEPCMDPAR0(ep), params->param0);
347	dwc3_writel(dwc->regs, DWC3_DEPCMDPAR1(ep), params->param1);
348	dwc3_writel(dwc->regs, DWC3_DEPCMDPAR2(ep), params->param2);
349
350	dwc3_writel(dwc->regs, DWC3_DEPCMD(ep), cmd | DWC3_DEPCMD_CMDACT);
351	do {
352		reg = dwc3_readl(dwc->regs, DWC3_DEPCMD(ep));
353		if (!(reg & DWC3_DEPCMD_CMDACT)) {
354			dev_vdbg(dwc->dev, "Command Complete --> %d\n",
355					DWC3_DEPCMD_STATUS(reg));
356			return 0;
357		}
358
359		/*
360		 * We can't sleep here, because it is also called from
361		 * interrupt context.
362		 */
363		timeout--;
364		if (!timeout)
365			return -ETIMEDOUT;
366
367		udelay(1);
368	} while (1);
369}
370
371static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep,
372		struct dwc3_trb *trb)
373{
374	u32		offset = (char *) trb - (char *) dep->trb_pool;
375
376	return dep->trb_pool_dma + offset;
377}
378
379static int dwc3_alloc_trb_pool(struct dwc3_ep *dep)
380{
381	struct dwc3		*dwc = dep->dwc;
382
383	if (dep->trb_pool)
384		return 0;
385
386	if (dep->number == 0 || dep->number == 1)
387		return 0;
388
389	dep->trb_pool = dma_alloc_coherent(dwc->dev,
390			sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
391			&dep->trb_pool_dma, GFP_KERNEL);
392	if (!dep->trb_pool) {
393		dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n",
394				dep->name);
395		return -ENOMEM;
396	}
397
398	return 0;
399}
400
401static void dwc3_free_trb_pool(struct dwc3_ep *dep)
402{
403	struct dwc3		*dwc = dep->dwc;
404
405	dma_free_coherent(dwc->dev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
406			dep->trb_pool, dep->trb_pool_dma);
407
408	dep->trb_pool = NULL;
409	dep->trb_pool_dma = 0;
410}
411
412static int dwc3_gadget_start_config(struct dwc3 *dwc, struct dwc3_ep *dep)
413{
414	struct dwc3_gadget_ep_cmd_params params;
415	u32			cmd;
416
417	memset(&params, 0x00, sizeof(params));
418
419	if (dep->number != 1) {
420		cmd = DWC3_DEPCMD_DEPSTARTCFG;
421		/* XferRscIdx == 0 for ep0 and 2 for the remaining */
422		if (dep->number > 1) {
423			if (dwc->start_config_issued)
424				return 0;
425			dwc->start_config_issued = true;
426			cmd |= DWC3_DEPCMD_PARAM(2);
427		}
428
429		return dwc3_send_gadget_ep_cmd(dwc, 0, cmd, &params);
430	}
431
432	return 0;
433}
434
435static int dwc3_gadget_set_ep_config(struct dwc3 *dwc, struct dwc3_ep *dep,
436		const struct usb_endpoint_descriptor *desc,
437		const struct usb_ss_ep_comp_descriptor *comp_desc,
438		bool ignore)
439{
440	struct dwc3_gadget_ep_cmd_params params;
441
442	memset(&params, 0x00, sizeof(params));
443
444	params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc))
445		| DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc));
446
447	/* Burst size is only needed in SuperSpeed mode */
448	if (dwc->gadget.speed == USB_SPEED_SUPER) {
449		u32 burst = dep->endpoint.maxburst - 1;
450
451		params.param0 |= DWC3_DEPCFG_BURST_SIZE(burst);
452	}
453
454	if (ignore)
455		params.param0 |= DWC3_DEPCFG_IGN_SEQ_NUM;
456
457	params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN
458		| DWC3_DEPCFG_XFER_NOT_READY_EN;
459
460	if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) {
461		params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE
462			| DWC3_DEPCFG_STREAM_EVENT_EN;
463		dep->stream_capable = true;
464	}
465
466	if (usb_endpoint_xfer_isoc(desc))
467		params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN;
468
469	/*
470	 * We are doing 1:1 mapping for endpoints, meaning
471	 * Physical Endpoints 2 maps to Logical Endpoint 2 and
472	 * so on. We consider the direction bit as part of the physical
473	 * endpoint number. So USB endpoint 0x81 is 0x03.
474	 */
475	params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number);
476
477	/*
478	 * We must use the lower 16 TX FIFOs even though
479	 * HW might have more
480	 */
481	if (dep->direction)
482		params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1);
483
484	if (desc->bInterval) {
485		params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(desc->bInterval - 1);
486		dep->interval = 1 << (desc->bInterval - 1);
487	}
488
489	return dwc3_send_gadget_ep_cmd(dwc, dep->number,
490			DWC3_DEPCMD_SETEPCONFIG, &params);
491}
492
493static int dwc3_gadget_set_xfer_resource(struct dwc3 *dwc, struct dwc3_ep *dep)
494{
495	struct dwc3_gadget_ep_cmd_params params;
496
497	memset(&params, 0x00, sizeof(params));
498
499	params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1);
500
501	return dwc3_send_gadget_ep_cmd(dwc, dep->number,
502			DWC3_DEPCMD_SETTRANSFRESOURCE, &params);
503}
504
505/**
506 * __dwc3_gadget_ep_enable - Initializes a HW endpoint
507 * @dep: endpoint to be initialized
508 * @desc: USB Endpoint Descriptor
509 *
510 * Caller should take care of locking
511 */
512static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep,
513		const struct usb_endpoint_descriptor *desc,
514		const struct usb_ss_ep_comp_descriptor *comp_desc,
515		bool ignore)
516{
517	struct dwc3		*dwc = dep->dwc;
518	u32			reg;
519	int			ret = -ENOMEM;
520
521	if (!(dep->flags & DWC3_EP_ENABLED)) {
522		ret = dwc3_gadget_start_config(dwc, dep);
523		if (ret)
524			return ret;
525	}
526
527	ret = dwc3_gadget_set_ep_config(dwc, dep, desc, comp_desc, ignore);
528	if (ret)
529		return ret;
530
531	if (!(dep->flags & DWC3_EP_ENABLED)) {
532		struct dwc3_trb	*trb_st_hw;
533		struct dwc3_trb	*trb_link;
534
535		ret = dwc3_gadget_set_xfer_resource(dwc, dep);
536		if (ret)
537			return ret;
538
539		dep->endpoint.desc = desc;
540		dep->comp_desc = comp_desc;
541		dep->type = usb_endpoint_type(desc);
542		dep->flags |= DWC3_EP_ENABLED;
543
544		reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
545		reg |= DWC3_DALEPENA_EP(dep->number);
546		dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
547
548		if (!usb_endpoint_xfer_isoc(desc))
549			return 0;
550
551		memset(&trb_link, 0, sizeof(trb_link));
552
553		/* Link TRB for ISOC. The HWO bit is never reset */
554		trb_st_hw = &dep->trb_pool[0];
555
556		trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
557
558		trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
559		trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
560		trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
561		trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
562	}
563
564	return 0;
565}
566
567static void dwc3_stop_active_transfer(struct dwc3 *dwc, u32 epnum);
568static void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep)
569{
570	struct dwc3_request		*req;
571
572	if (!list_empty(&dep->req_queued)) {
573		dwc3_stop_active_transfer(dwc, dep->number);
574
575		/* - giveback all requests to gadget driver */
576		while (!list_empty(&dep->req_queued)) {
577			req = next_request(&dep->req_queued);
578
579			dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
580		}
581	}
582
583	while (!list_empty(&dep->request_list)) {
584		req = next_request(&dep->request_list);
585
586		dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
587	}
588}
589
590/**
591 * __dwc3_gadget_ep_disable - Disables a HW endpoint
592 * @dep: the endpoint to disable
593 *
594 * This function also removes requests which are currently processed ny the
595 * hardware and those which are not yet scheduled.
596 * Caller should take care of locking.
597 */
598static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
599{
600	struct dwc3		*dwc = dep->dwc;
601	u32			reg;
602
603	dwc3_remove_requests(dwc, dep);
604
605	reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
606	reg &= ~DWC3_DALEPENA_EP(dep->number);
607	dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
608
609	dep->stream_capable = false;
610	dep->endpoint.desc = NULL;
611	dep->comp_desc = NULL;
612	dep->type = 0;
613	dep->flags = 0;
614
615	return 0;
616}
617
618/* -------------------------------------------------------------------------- */
619
620static int dwc3_gadget_ep0_enable(struct usb_ep *ep,
621		const struct usb_endpoint_descriptor *desc)
622{
623	return -EINVAL;
624}
625
626static int dwc3_gadget_ep0_disable(struct usb_ep *ep)
627{
628	return -EINVAL;
629}
630
631/* -------------------------------------------------------------------------- */
632
633static int dwc3_gadget_ep_enable(struct usb_ep *ep,
634		const struct usb_endpoint_descriptor *desc)
635{
636	struct dwc3_ep			*dep;
637	struct dwc3			*dwc;
638	unsigned long			flags;
639	int				ret;
640
641	if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
642		pr_debug("dwc3: invalid parameters\n");
643		return -EINVAL;
644	}
645
646	if (!desc->wMaxPacketSize) {
647		pr_debug("dwc3: missing wMaxPacketSize\n");
648		return -EINVAL;
649	}
650
651	dep = to_dwc3_ep(ep);
652	dwc = dep->dwc;
653
654	if (dep->flags & DWC3_EP_ENABLED) {
655		dev_WARN_ONCE(dwc->dev, true, "%s is already enabled\n",
656				dep->name);
657		return 0;
658	}
659
660	switch (usb_endpoint_type(desc)) {
661	case USB_ENDPOINT_XFER_CONTROL:
662		strlcat(dep->name, "-control", sizeof(dep->name));
663		break;
664	case USB_ENDPOINT_XFER_ISOC:
665		strlcat(dep->name, "-isoc", sizeof(dep->name));
666		break;
667	case USB_ENDPOINT_XFER_BULK:
668		strlcat(dep->name, "-bulk", sizeof(dep->name));
669		break;
670	case USB_ENDPOINT_XFER_INT:
671		strlcat(dep->name, "-int", sizeof(dep->name));
672		break;
673	default:
674		dev_err(dwc->dev, "invalid endpoint transfer type\n");
675	}
676
677	dev_vdbg(dwc->dev, "Enabling %s\n", dep->name);
678
679	spin_lock_irqsave(&dwc->lock, flags);
680	ret = __dwc3_gadget_ep_enable(dep, desc, ep->comp_desc, false);
681	spin_unlock_irqrestore(&dwc->lock, flags);
682
683	return ret;
684}
685
686static int dwc3_gadget_ep_disable(struct usb_ep *ep)
687{
688	struct dwc3_ep			*dep;
689	struct dwc3			*dwc;
690	unsigned long			flags;
691	int				ret;
692
693	if (!ep) {
694		pr_debug("dwc3: invalid parameters\n");
695		return -EINVAL;
696	}
697
698	dep = to_dwc3_ep(ep);
699	dwc = dep->dwc;
700
701	if (!(dep->flags & DWC3_EP_ENABLED)) {
702		dev_WARN_ONCE(dwc->dev, true, "%s is already disabled\n",
703				dep->name);
704		return 0;
705	}
706
707	snprintf(dep->name, sizeof(dep->name), "ep%d%s",
708			dep->number >> 1,
709			(dep->number & 1) ? "in" : "out");
710
711	spin_lock_irqsave(&dwc->lock, flags);
712	ret = __dwc3_gadget_ep_disable(dep);
713	spin_unlock_irqrestore(&dwc->lock, flags);
714
715	return ret;
716}
717
718static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep,
719	gfp_t gfp_flags)
720{
721	struct dwc3_request		*req;
722	struct dwc3_ep			*dep = to_dwc3_ep(ep);
723	struct dwc3			*dwc = dep->dwc;
724
725	req = kzalloc(sizeof(*req), gfp_flags);
726	if (!req) {
727		dev_err(dwc->dev, "not enough memory\n");
728		return NULL;
729	}
730
731	req->epnum	= dep->number;
732	req->dep	= dep;
733
734	return &req->request;
735}
736
737static void dwc3_gadget_ep_free_request(struct usb_ep *ep,
738		struct usb_request *request)
739{
740	struct dwc3_request		*req = to_dwc3_request(request);
741
742	kfree(req);
743}
744
745/**
746 * dwc3_prepare_one_trb - setup one TRB from one request
747 * @dep: endpoint for which this request is prepared
748 * @req: dwc3_request pointer
749 */
750static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
751		struct dwc3_request *req, dma_addr_t dma,
752		unsigned length, unsigned last, unsigned chain)
753{
754	struct dwc3		*dwc = dep->dwc;
755	struct dwc3_trb		*trb;
756
757	unsigned int		cur_slot;
758
759	dev_vdbg(dwc->dev, "%s: req %p dma %08llx length %d%s%s\n",
760			dep->name, req, (unsigned long long) dma,
761			length, last ? " last" : "",
762			chain ? " chain" : "");
763
764	trb = &dep->trb_pool[dep->free_slot & DWC3_TRB_MASK];
765	cur_slot = dep->free_slot;
766	dep->free_slot++;
767
768	/* Skip the LINK-TRB on ISOC */
769	if (((cur_slot & DWC3_TRB_MASK) == DWC3_TRB_NUM - 1) &&
770			usb_endpoint_xfer_isoc(dep->endpoint.desc))
771		return;
772
773	if (!req->trb) {
774		dwc3_gadget_move_request_queued(req);
775		req->trb = trb;
776		req->trb_dma = dwc3_trb_dma_offset(dep, trb);
777	}
778
779	trb->size = DWC3_TRB_SIZE_LENGTH(length);
780	trb->bpl = lower_32_bits(dma);
781	trb->bph = upper_32_bits(dma);
782
783	switch (usb_endpoint_type(dep->endpoint.desc)) {
784	case USB_ENDPOINT_XFER_CONTROL:
785		trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP;
786		break;
787
788	case USB_ENDPOINT_XFER_ISOC:
789		trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST;
790
791		if (!req->request.no_interrupt)
792			trb->ctrl |= DWC3_TRB_CTRL_IOC;
793		break;
794
795	case USB_ENDPOINT_XFER_BULK:
796	case USB_ENDPOINT_XFER_INT:
797		trb->ctrl = DWC3_TRBCTL_NORMAL;
798		break;
799	default:
800		/*
801		 * This is only possible with faulty memory because we
802		 * checked it already :)
803		 */
804		BUG();
805	}
806
807	if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
808		trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
809		trb->ctrl |= DWC3_TRB_CTRL_CSP;
810	} else {
811		if (chain)
812			trb->ctrl |= DWC3_TRB_CTRL_CHN;
813
814		if (last)
815			trb->ctrl |= DWC3_TRB_CTRL_LST;
816	}
817
818	if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable)
819		trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(req->request.stream_id);
820
821	trb->ctrl |= DWC3_TRB_CTRL_HWO;
822}
823
824/*
825 * dwc3_prepare_trbs - setup TRBs from requests
826 * @dep: endpoint for which requests are being prepared
827 * @starting: true if the endpoint is idle and no requests are queued.
828 *
829 * The function goes through the requests list and sets up TRBs for the
830 * transfers. The function returns once there are no more TRBs available or
831 * it runs out of requests.
832 */
833static void dwc3_prepare_trbs(struct dwc3_ep *dep, bool starting)
834{
835	struct dwc3_request	*req, *n;
836	u32			trbs_left;
837	u32			max;
838	unsigned int		last_one = 0;
839
840	BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
841
842	/* the first request must not be queued */
843	trbs_left = (dep->busy_slot - dep->free_slot) & DWC3_TRB_MASK;
844
845	/* Can't wrap around on a non-isoc EP since there's no link TRB */
846	if (!usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
847		max = DWC3_TRB_NUM - (dep->free_slot & DWC3_TRB_MASK);
848		if (trbs_left > max)
849			trbs_left = max;
850	}
851
852	/*
853	 * If busy & slot are equal than it is either full or empty. If we are
854	 * starting to process requests then we are empty. Otherwise we are
855	 * full and don't do anything
856	 */
857	if (!trbs_left) {
858		if (!starting)
859			return;
860		trbs_left = DWC3_TRB_NUM;
861		/*
862		 * In case we start from scratch, we queue the ISOC requests
863		 * starting from slot 1. This is done because we use ring
864		 * buffer and have no LST bit to stop us. Instead, we place
865		 * IOC bit every TRB_NUM/4. We try to avoid having an interrupt
866		 * after the first request so we start at slot 1 and have
867		 * 7 requests proceed before we hit the first IOC.
868		 * Other transfer types don't use the ring buffer and are
869		 * processed from the first TRB until the last one. Since we
870		 * don't wrap around we have to start at the beginning.
871		 */
872		if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
873			dep->busy_slot = 1;
874			dep->free_slot = 1;
875		} else {
876			dep->busy_slot = 0;
877			dep->free_slot = 0;
878		}
879	}
880
881	/* The last TRB is a link TRB, not used for xfer */
882	if ((trbs_left <= 1) && usb_endpoint_xfer_isoc(dep->endpoint.desc))
883		return;
884
885	list_for_each_entry_safe(req, n, &dep->request_list, list) {
886		unsigned	length;
887		dma_addr_t	dma;
888
889		if (req->request.num_mapped_sgs > 0) {
890			struct usb_request *request = &req->request;
891			struct scatterlist *sg = request->sg;
892			struct scatterlist *s;
893			int		i;
894
895			for_each_sg(sg, s, request->num_mapped_sgs, i) {
896				unsigned chain = true;
897
898				length = sg_dma_len(s);
899				dma = sg_dma_address(s);
900
901				if (i == (request->num_mapped_sgs - 1) ||
902						sg_is_last(s)) {
903					last_one = true;
904					chain = false;
905				}
906
907				trbs_left--;
908				if (!trbs_left)
909					last_one = true;
910
911				if (last_one)
912					chain = false;
913
914				dwc3_prepare_one_trb(dep, req, dma, length,
915						last_one, chain);
916
917				if (last_one)
918					break;
919			}
920		} else {
921			dma = req->request.dma;
922			length = req->request.length;
923			trbs_left--;
924
925			if (!trbs_left)
926				last_one = 1;
927
928			/* Is this the last request? */
929			if (list_is_last(&req->list, &dep->request_list))
930				last_one = 1;
931
932			dwc3_prepare_one_trb(dep, req, dma, length,
933					last_one, false);
934
935			if (last_one)
936				break;
937		}
938	}
939}
940
941static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep, u16 cmd_param,
942		int start_new)
943{
944	struct dwc3_gadget_ep_cmd_params params;
945	struct dwc3_request		*req;
946	struct dwc3			*dwc = dep->dwc;
947	int				ret;
948	u32				cmd;
949
950	if (start_new && (dep->flags & DWC3_EP_BUSY)) {
951		dev_vdbg(dwc->dev, "%s: endpoint busy\n", dep->name);
952		return -EBUSY;
953	}
954	dep->flags &= ~DWC3_EP_PENDING_REQUEST;
955
956	/*
957	 * If we are getting here after a short-out-packet we don't enqueue any
958	 * new requests as we try to set the IOC bit only on the last request.
959	 */
960	if (start_new) {
961		if (list_empty(&dep->req_queued))
962			dwc3_prepare_trbs(dep, start_new);
963
964		/* req points to the first request which will be sent */
965		req = next_request(&dep->req_queued);
966	} else {
967		dwc3_prepare_trbs(dep, start_new);
968
969		/*
970		 * req points to the first request where HWO changed from 0 to 1
971		 */
972		req = next_request(&dep->req_queued);
973	}
974	if (!req) {
975		dep->flags |= DWC3_EP_PENDING_REQUEST;
976		return 0;
977	}
978
979	memset(&params, 0, sizeof(params));
980	params.param0 = upper_32_bits(req->trb_dma);
981	params.param1 = lower_32_bits(req->trb_dma);
982
983	if (start_new)
984		cmd = DWC3_DEPCMD_STARTTRANSFER;
985	else
986		cmd = DWC3_DEPCMD_UPDATETRANSFER;
987
988	cmd |= DWC3_DEPCMD_PARAM(cmd_param);
989	ret = dwc3_send_gadget_ep_cmd(dwc, dep->number, cmd, &params);
990	if (ret < 0) {
991		dev_dbg(dwc->dev, "failed to send STARTTRANSFER command\n");
992
993		/*
994		 * FIXME we need to iterate over the list of requests
995		 * here and stop, unmap, free and del each of the linked
996		 * requests instead of what we do now.
997		 */
998		usb_gadget_unmap_request(&dwc->gadget, &req->request,
999				req->direction);
1000		list_del(&req->list);
1001		return ret;
1002	}
1003
1004	dep->flags |= DWC3_EP_BUSY;
1005
1006	if (start_new) {
1007		dep->resource_index = dwc3_gadget_ep_get_transfer_index(dwc,
1008				dep->number);
1009		WARN_ON_ONCE(!dep->resource_index);
1010	}
1011
1012	return 0;
1013}
1014
1015static void __dwc3_gadget_start_isoc(struct dwc3 *dwc,
1016		struct dwc3_ep *dep, u32 cur_uf)
1017{
1018	u32 uf;
1019
1020	if (list_empty(&dep->request_list)) {
1021		dev_vdbg(dwc->dev, "ISOC ep %s run out for requests.\n",
1022			dep->name);
1023		dep->flags |= DWC3_EP_PENDING_REQUEST;
1024		return;
1025	}
1026
1027	/* 4 micro frames in the future */
1028	uf = cur_uf + dep->interval * 4;
1029
1030	__dwc3_gadget_kick_transfer(dep, uf, 1);
1031}
1032
1033static void dwc3_gadget_start_isoc(struct dwc3 *dwc,
1034		struct dwc3_ep *dep, const struct dwc3_event_depevt *event)
1035{
1036	u32 cur_uf, mask;
1037
1038	mask = ~(dep->interval - 1);
1039	cur_uf = event->parameters & mask;
1040
1041	__dwc3_gadget_start_isoc(dwc, dep, cur_uf);
1042}
1043
1044static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
1045{
1046	struct dwc3		*dwc = dep->dwc;
1047	int			ret;
1048
1049	req->request.actual	= 0;
1050	req->request.status	= -EINPROGRESS;
1051	req->direction		= dep->direction;
1052	req->epnum		= dep->number;
1053
1054	/*
1055	 * We only add to our list of requests now and
1056	 * start consuming the list once we get XferNotReady
1057	 * IRQ.
1058	 *
1059	 * That way, we avoid doing anything that we don't need
1060	 * to do now and defer it until the point we receive a
1061	 * particular token from the Host side.
1062	 *
1063	 * This will also avoid Host cancelling URBs due to too
1064	 * many NAKs.
1065	 */
1066	ret = usb_gadget_map_request(&dwc->gadget, &req->request,
1067			dep->direction);
1068	if (ret)
1069		return ret;
1070
1071	list_add_tail(&req->list, &dep->request_list);
1072
1073	/*
1074	 * There are a few special cases:
1075	 *
1076	 * 1. XferNotReady with empty list of requests. We need to kick the
1077	 *    transfer here in that situation, otherwise we will be NAKing
1078	 *    forever. If we get XferNotReady before gadget driver has a
1079	 *    chance to queue a request, we will ACK the IRQ but won't be
1080	 *    able to receive the data until the next request is queued.
1081	 *    The following code is handling exactly that.
1082	 *
1083	 */
1084	if (dep->flags & DWC3_EP_PENDING_REQUEST) {
1085		/*
1086		 * If xfernotready is already elapsed and it is a case
1087		 * of isoc transfer, then issue END TRANSFER, so that
1088		 * you can receive xfernotready again and can have
1089		 * notion of current microframe.
1090		 */
1091		if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1092			dwc3_stop_active_transfer(dwc, dep->number);
1093			return 0;
1094		}
1095
1096		ret = __dwc3_gadget_kick_transfer(dep, 0, true);
1097		if (ret && ret != -EBUSY)
1098			dev_dbg(dwc->dev, "%s: failed to kick transfers\n",
1099					dep->name);
1100	}
1101
1102	/*
1103	 * 2. XferInProgress on Isoc EP with an active transfer. We need to
1104	 *    kick the transfer here after queuing a request, otherwise the
1105	 *    core may not see the modified TRB(s).
1106	 */
1107	if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
1108			(dep->flags & DWC3_EP_BUSY) &&
1109			!(dep->flags & DWC3_EP_MISSED_ISOC)) {
1110		WARN_ON_ONCE(!dep->resource_index);
1111		ret = __dwc3_gadget_kick_transfer(dep, dep->resource_index,
1112				false);
1113		if (ret && ret != -EBUSY)
1114			dev_dbg(dwc->dev, "%s: failed to kick transfers\n",
1115					dep->name);
1116	}
1117
1118	return 0;
1119}
1120
1121static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
1122	gfp_t gfp_flags)
1123{
1124	struct dwc3_request		*req = to_dwc3_request(request);
1125	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1126	struct dwc3			*dwc = dep->dwc;
1127
1128	unsigned long			flags;
1129
1130	int				ret;
1131
1132	if (!dep->endpoint.desc) {
1133		dev_dbg(dwc->dev, "trying to queue request %p to disabled %s\n",
1134				request, ep->name);
1135		return -ESHUTDOWN;
1136	}
1137
1138	dev_vdbg(dwc->dev, "queing request %p to %s length %d\n",
1139			request, ep->name, request->length);
1140
1141	spin_lock_irqsave(&dwc->lock, flags);
1142	ret = __dwc3_gadget_ep_queue(dep, req);
1143	spin_unlock_irqrestore(&dwc->lock, flags);
1144
1145	return ret;
1146}
1147
1148static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
1149		struct usb_request *request)
1150{
1151	struct dwc3_request		*req = to_dwc3_request(request);
1152	struct dwc3_request		*r = NULL;
1153
1154	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1155	struct dwc3			*dwc = dep->dwc;
1156
1157	unsigned long			flags;
1158	int				ret = 0;
1159
1160	spin_lock_irqsave(&dwc->lock, flags);
1161
1162	list_for_each_entry(r, &dep->request_list, list) {
1163		if (r == req)
1164			break;
1165	}
1166
1167	if (r != req) {
1168		list_for_each_entry(r, &dep->req_queued, list) {
1169			if (r == req)
1170				break;
1171		}
1172		if (r == req) {
1173			/* wait until it is processed */
1174			dwc3_stop_active_transfer(dwc, dep->number);
1175			goto out1;
1176		}
1177		dev_err(dwc->dev, "request %p was not queued to %s\n",
1178				request, ep->name);
1179		ret = -EINVAL;
1180		goto out0;
1181	}
1182
1183out1:
1184	/* giveback the request */
1185	dwc3_gadget_giveback(dep, req, -ECONNRESET);
1186
1187out0:
1188	spin_unlock_irqrestore(&dwc->lock, flags);
1189
1190	return ret;
1191}
1192
1193int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value)
1194{
1195	struct dwc3_gadget_ep_cmd_params	params;
1196	struct dwc3				*dwc = dep->dwc;
1197	int					ret;
1198
1199	memset(&params, 0x00, sizeof(params));
1200
1201	if (value) {
1202		ret = dwc3_send_gadget_ep_cmd(dwc, dep->number,
1203			DWC3_DEPCMD_SETSTALL, &params);
1204		if (ret)
1205			dev_err(dwc->dev, "failed to %s STALL on %s\n",
1206					value ? "set" : "clear",
1207					dep->name);
1208		else
1209			dep->flags |= DWC3_EP_STALL;
1210	} else {
1211		if (dep->flags & DWC3_EP_WEDGE)
1212			return 0;
1213
1214		ret = dwc3_send_gadget_ep_cmd(dwc, dep->number,
1215			DWC3_DEPCMD_CLEARSTALL, &params);
1216		if (ret)
1217			dev_err(dwc->dev, "failed to %s STALL on %s\n",
1218					value ? "set" : "clear",
1219					dep->name);
1220		else
1221			dep->flags &= ~DWC3_EP_STALL;
1222	}
1223
1224	return ret;
1225}
1226
1227static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
1228{
1229	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1230	struct dwc3			*dwc = dep->dwc;
1231
1232	unsigned long			flags;
1233
1234	int				ret;
1235
1236	spin_lock_irqsave(&dwc->lock, flags);
1237
1238	if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1239		dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
1240		ret = -EINVAL;
1241		goto out;
1242	}
1243
1244	ret = __dwc3_gadget_ep_set_halt(dep, value);
1245out:
1246	spin_unlock_irqrestore(&dwc->lock, flags);
1247
1248	return ret;
1249}
1250
1251static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
1252{
1253	struct dwc3_ep			*dep = to_dwc3_ep(ep);
1254	struct dwc3			*dwc = dep->dwc;
1255	unsigned long			flags;
1256
1257	spin_lock_irqsave(&dwc->lock, flags);
1258	dep->flags |= DWC3_EP_WEDGE;
1259	spin_unlock_irqrestore(&dwc->lock, flags);
1260
1261	if (dep->number == 0 || dep->number == 1)
1262		return dwc3_gadget_ep0_set_halt(ep, 1);
1263	else
1264		return dwc3_gadget_ep_set_halt(ep, 1);
1265}
1266
1267/* -------------------------------------------------------------------------- */
1268
1269static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
1270	.bLength	= USB_DT_ENDPOINT_SIZE,
1271	.bDescriptorType = USB_DT_ENDPOINT,
1272	.bmAttributes	= USB_ENDPOINT_XFER_CONTROL,
1273};
1274
1275static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
1276	.enable		= dwc3_gadget_ep0_enable,
1277	.disable	= dwc3_gadget_ep0_disable,
1278	.alloc_request	= dwc3_gadget_ep_alloc_request,
1279	.free_request	= dwc3_gadget_ep_free_request,
1280	.queue		= dwc3_gadget_ep0_queue,
1281	.dequeue	= dwc3_gadget_ep_dequeue,
1282	.set_halt	= dwc3_gadget_ep0_set_halt,
1283	.set_wedge	= dwc3_gadget_ep_set_wedge,
1284};
1285
1286static const struct usb_ep_ops dwc3_gadget_ep_ops = {
1287	.enable		= dwc3_gadget_ep_enable,
1288	.disable	= dwc3_gadget_ep_disable,
1289	.alloc_request	= dwc3_gadget_ep_alloc_request,
1290	.free_request	= dwc3_gadget_ep_free_request,
1291	.queue		= dwc3_gadget_ep_queue,
1292	.dequeue	= dwc3_gadget_ep_dequeue,
1293	.set_halt	= dwc3_gadget_ep_set_halt,
1294	.set_wedge	= dwc3_gadget_ep_set_wedge,
1295};
1296
1297/* -------------------------------------------------------------------------- */
1298
1299static int dwc3_gadget_get_frame(struct usb_gadget *g)
1300{
1301	struct dwc3		*dwc = gadget_to_dwc(g);
1302	u32			reg;
1303
1304	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1305	return DWC3_DSTS_SOFFN(reg);
1306}
1307
1308static int dwc3_gadget_wakeup(struct usb_gadget *g)
1309{
1310	struct dwc3		*dwc = gadget_to_dwc(g);
1311
1312	unsigned long		timeout;
1313	unsigned long		flags;
1314
1315	u32			reg;
1316
1317	int			ret = 0;
1318
1319	u8			link_state;
1320	u8			speed;
1321
1322	spin_lock_irqsave(&dwc->lock, flags);
1323
1324	/*
1325	 * According to the Databook Remote wakeup request should
1326	 * be issued only when the device is in early suspend state.
1327	 *
1328	 * We can check that via USB Link State bits in DSTS register.
1329	 */
1330	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1331
1332	speed = reg & DWC3_DSTS_CONNECTSPD;
1333	if (speed == DWC3_DSTS_SUPERSPEED) {
1334		dev_dbg(dwc->dev, "no wakeup on SuperSpeed\n");
1335		ret = -EINVAL;
1336		goto out;
1337	}
1338
1339	link_state = DWC3_DSTS_USBLNKST(reg);
1340
1341	switch (link_state) {
1342	case DWC3_LINK_STATE_RX_DET:	/* in HS, means Early Suspend */
1343	case DWC3_LINK_STATE_U3:	/* in HS, means SUSPEND */
1344		break;
1345	default:
1346		dev_dbg(dwc->dev, "can't wakeup from link state %d\n",
1347				link_state);
1348		ret = -EINVAL;
1349		goto out;
1350	}
1351
1352	ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
1353	if (ret < 0) {
1354		dev_err(dwc->dev, "failed to put link in Recovery\n");
1355		goto out;
1356	}
1357
1358	/* Recent versions do this automatically */
1359	if (dwc->revision < DWC3_REVISION_194A) {
1360		/* write zeroes to Link Change Request */
1361		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1362		reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
1363		dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1364	}
1365
1366	/* poll until Link State changes to ON */
1367	timeout = jiffies + msecs_to_jiffies(100);
1368
1369	while (!time_after(jiffies, timeout)) {
1370		reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1371
1372		/* in HS, means ON */
1373		if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
1374			break;
1375	}
1376
1377	if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
1378		dev_err(dwc->dev, "failed to send remote wakeup\n");
1379		ret = -EINVAL;
1380	}
1381
1382out:
1383	spin_unlock_irqrestore(&dwc->lock, flags);
1384
1385	return ret;
1386}
1387
1388static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
1389		int is_selfpowered)
1390{
1391	struct dwc3		*dwc = gadget_to_dwc(g);
1392	unsigned long		flags;
1393
1394	spin_lock_irqsave(&dwc->lock, flags);
1395	dwc->is_selfpowered = !!is_selfpowered;
1396	spin_unlock_irqrestore(&dwc->lock, flags);
1397
1398	return 0;
1399}
1400
1401static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on)
1402{
1403	u32			reg;
1404	u32			timeout = 500;
1405
1406	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1407	if (is_on) {
1408		if (dwc->revision <= DWC3_REVISION_187A) {
1409			reg &= ~DWC3_DCTL_TRGTULST_MASK;
1410			reg |= DWC3_DCTL_TRGTULST_RX_DET;
1411		}
1412
1413		if (dwc->revision >= DWC3_REVISION_194A)
1414			reg &= ~DWC3_DCTL_KEEP_CONNECT;
1415		reg |= DWC3_DCTL_RUN_STOP;
1416	} else {
1417		reg &= ~DWC3_DCTL_RUN_STOP;
1418	}
1419
1420	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1421
1422	do {
1423		reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1424		if (is_on) {
1425			if (!(reg & DWC3_DSTS_DEVCTRLHLT))
1426				break;
1427		} else {
1428			if (reg & DWC3_DSTS_DEVCTRLHLT)
1429				break;
1430		}
1431		timeout--;
1432		if (!timeout)
1433			return -ETIMEDOUT;
1434		udelay(1);
1435	} while (1);
1436
1437	dev_vdbg(dwc->dev, "gadget %s data soft-%s\n",
1438			dwc->gadget_driver
1439			? dwc->gadget_driver->function : "no-function",
1440			is_on ? "connect" : "disconnect");
1441
1442	return 0;
1443}
1444
1445static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
1446{
1447	struct dwc3		*dwc = gadget_to_dwc(g);
1448	unsigned long		flags;
1449	int			ret;
1450
1451	is_on = !!is_on;
1452
1453	spin_lock_irqsave(&dwc->lock, flags);
1454	ret = dwc3_gadget_run_stop(dwc, is_on);
1455	spin_unlock_irqrestore(&dwc->lock, flags);
1456
1457	return ret;
1458}
1459
1460static int dwc3_gadget_start(struct usb_gadget *g,
1461		struct usb_gadget_driver *driver)
1462{
1463	struct dwc3		*dwc = gadget_to_dwc(g);
1464	struct dwc3_ep		*dep;
1465	unsigned long		flags;
1466	int			ret = 0;
1467	u32			reg;
1468
1469	spin_lock_irqsave(&dwc->lock, flags);
1470
1471	if (dwc->gadget_driver) {
1472		dev_err(dwc->dev, "%s is already bound to %s\n",
1473				dwc->gadget.name,
1474				dwc->gadget_driver->driver.name);
1475		ret = -EBUSY;
1476		goto err0;
1477	}
1478
1479	dwc->gadget_driver	= driver;
1480	dwc->gadget.dev.driver	= &driver->driver;
1481
1482	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
1483	reg &= ~(DWC3_DCFG_SPEED_MASK);
1484
1485	/**
1486	 * WORKAROUND: DWC3 revision < 2.20a have an issue
1487	 * which would cause metastability state on Run/Stop
1488	 * bit if we try to force the IP to USB2-only mode.
1489	 *
1490	 * Because of that, we cannot configure the IP to any
1491	 * speed other than the SuperSpeed
1492	 *
1493	 * Refers to:
1494	 *
1495	 * STAR#9000525659: Clock Domain Crossing on DCTL in
1496	 * USB 2.0 Mode
1497	 */
1498	if (dwc->revision < DWC3_REVISION_220A)
1499		reg |= DWC3_DCFG_SUPERSPEED;
1500	else
1501		reg |= dwc->maximum_speed;
1502	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
1503
1504	dwc->start_config_issued = false;
1505
1506	/* Start with SuperSpeed Default */
1507	dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
1508
1509	dep = dwc->eps[0];
1510	ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL, false);
1511	if (ret) {
1512		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
1513		goto err0;
1514	}
1515
1516	dep = dwc->eps[1];
1517	ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL, false);
1518	if (ret) {
1519		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
1520		goto err1;
1521	}
1522
1523	/* begin to receive SETUP packets */
1524	dwc->ep0state = EP0_SETUP_PHASE;
1525	dwc3_ep0_out_start(dwc);
1526
1527	spin_unlock_irqrestore(&dwc->lock, flags);
1528
1529	return 0;
1530
1531err1:
1532	__dwc3_gadget_ep_disable(dwc->eps[0]);
1533
1534err0:
1535	spin_unlock_irqrestore(&dwc->lock, flags);
1536
1537	return ret;
1538}
1539
1540static int dwc3_gadget_stop(struct usb_gadget *g,
1541		struct usb_gadget_driver *driver)
1542{
1543	struct dwc3		*dwc = gadget_to_dwc(g);
1544	unsigned long		flags;
1545
1546	spin_lock_irqsave(&dwc->lock, flags);
1547
1548	__dwc3_gadget_ep_disable(dwc->eps[0]);
1549	__dwc3_gadget_ep_disable(dwc->eps[1]);
1550
1551	dwc->gadget_driver	= NULL;
1552	dwc->gadget.dev.driver	= NULL;
1553
1554	spin_unlock_irqrestore(&dwc->lock, flags);
1555
1556	return 0;
1557}
1558
1559static const struct usb_gadget_ops dwc3_gadget_ops = {
1560	.get_frame		= dwc3_gadget_get_frame,
1561	.wakeup			= dwc3_gadget_wakeup,
1562	.set_selfpowered	= dwc3_gadget_set_selfpowered,
1563	.pullup			= dwc3_gadget_pullup,
1564	.udc_start		= dwc3_gadget_start,
1565	.udc_stop		= dwc3_gadget_stop,
1566};
1567
1568/* -------------------------------------------------------------------------- */
1569
1570static int dwc3_gadget_init_endpoints(struct dwc3 *dwc)
1571{
1572	struct dwc3_ep			*dep;
1573	u8				epnum;
1574
1575	INIT_LIST_HEAD(&dwc->gadget.ep_list);
1576
1577	for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
1578		dep = kzalloc(sizeof(*dep), GFP_KERNEL);
1579		if (!dep) {
1580			dev_err(dwc->dev, "can't allocate endpoint %d\n",
1581					epnum);
1582			return -ENOMEM;
1583		}
1584
1585		dep->dwc = dwc;
1586		dep->number = epnum;
1587		dwc->eps[epnum] = dep;
1588
1589		snprintf(dep->name, sizeof(dep->name), "ep%d%s", epnum >> 1,
1590				(epnum & 1) ? "in" : "out");
1591		dep->endpoint.name = dep->name;
1592		dep->direction = (epnum & 1);
1593
1594		if (epnum == 0 || epnum == 1) {
1595			dep->endpoint.maxpacket = 512;
1596			dep->endpoint.ops = &dwc3_gadget_ep0_ops;
1597			if (!epnum)
1598				dwc->gadget.ep0 = &dep->endpoint;
1599		} else {
1600			int		ret;
1601
1602			dep->endpoint.maxpacket = 1024;
1603			dep->endpoint.max_streams = 15;
1604			dep->endpoint.ops = &dwc3_gadget_ep_ops;
1605			list_add_tail(&dep->endpoint.ep_list,
1606					&dwc->gadget.ep_list);
1607
1608			ret = dwc3_alloc_trb_pool(dep);
1609			if (ret)
1610				return ret;
1611		}
1612
1613		INIT_LIST_HEAD(&dep->request_list);
1614		INIT_LIST_HEAD(&dep->req_queued);
1615	}
1616
1617	return 0;
1618}
1619
1620static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
1621{
1622	struct dwc3_ep			*dep;
1623	u8				epnum;
1624
1625	for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
1626		dep = dwc->eps[epnum];
1627		dwc3_free_trb_pool(dep);
1628
1629		if (epnum != 0 && epnum != 1)
1630			list_del(&dep->endpoint.ep_list);
1631
1632		kfree(dep);
1633	}
1634}
1635
1636static void dwc3_gadget_release(struct device *dev)
1637{
1638	dev_dbg(dev, "%s\n", __func__);
1639}
1640
1641/* -------------------------------------------------------------------------- */
1642static int dwc3_cleanup_done_reqs(struct dwc3 *dwc, struct dwc3_ep *dep,
1643		const struct dwc3_event_depevt *event, int status)
1644{
1645	struct dwc3_request	*req;
1646	struct dwc3_trb		*trb;
1647	unsigned int		count;
1648	unsigned int		s_pkt = 0;
1649	unsigned int		trb_status;
1650
1651	do {
1652		req = next_request(&dep->req_queued);
1653		if (!req) {
1654			WARN_ON_ONCE(1);
1655			return 1;
1656		}
1657
1658		trb = req->trb;
1659
1660		if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
1661			/*
1662			 * We continue despite the error. There is not much we
1663			 * can do. If we don't clean it up we loop forever. If
1664			 * we skip the TRB then it gets overwritten after a
1665			 * while since we use them in a ring buffer. A BUG()
1666			 * would help. Lets hope that if this occurs, someone
1667			 * fixes the root cause instead of looking away :)
1668			 */
1669			dev_err(dwc->dev, "%s's TRB (%p) still owned by HW\n",
1670					dep->name, req->trb);
1671		count = trb->size & DWC3_TRB_SIZE_MASK;
1672
1673		if (dep->direction) {
1674			if (count) {
1675				trb_status = DWC3_TRB_SIZE_TRBSTS(trb->size);
1676				if (trb_status == DWC3_TRBSTS_MISSED_ISOC) {
1677					dev_dbg(dwc->dev, "incomplete IN transfer %s\n",
1678							dep->name);
1679					/*
1680					 * If missed isoc occurred and there is
1681					 * no request queued then issue END
1682					 * TRANSFER, so that core generates
1683					 * next xfernotready and we will issue
1684					 * a fresh START TRANSFER.
1685					 * If there are still queued request
1686					 * then wait, do not issue either END
1687					 * or UPDATE TRANSFER, just attach next
1688					 * request in request_list during
1689					 * giveback.If any future queued request
1690					 * is successfully transferred then we
1691					 * will issue UPDATE TRANSFER for all
1692					 * request in the request_list.
1693					 */
1694					dep->flags |= DWC3_EP_MISSED_ISOC;
1695				} else {
1696					dev_err(dwc->dev, "incomplete IN transfer %s\n",
1697							dep->name);
1698					status = -ECONNRESET;
1699				}
1700			} else {
1701				dep->flags &= ~DWC3_EP_MISSED_ISOC;
1702			}
1703		} else {
1704			if (count && (event->status & DEPEVT_STATUS_SHORT))
1705				s_pkt = 1;
1706		}
1707
1708		/*
1709		 * We assume here we will always receive the entire data block
1710		 * which we should receive. Meaning, if we program RX to
1711		 * receive 4K but we receive only 2K, we assume that's all we
1712		 * should receive and we simply bounce the request back to the
1713		 * gadget driver for further processing.
1714		 */
1715		req->request.actual += req->request.length - count;
1716		dwc3_gadget_giveback(dep, req, status);
1717		if (s_pkt)
1718			break;
1719		if ((event->status & DEPEVT_STATUS_LST) &&
1720				(trb->ctrl & (DWC3_TRB_CTRL_LST |
1721						DWC3_TRB_CTRL_HWO)))
1722			break;
1723		if ((event->status & DEPEVT_STATUS_IOC) &&
1724				(trb->ctrl & DWC3_TRB_CTRL_IOC))
1725			break;
1726	} while (1);
1727
1728	if (list_empty(&dep->req_queued) &&
1729			(dep->flags & DWC3_EP_MISSED_ISOC)) {
1730		dwc3_stop_active_transfer(dwc, dep->number);
1731		dep->flags &= ~DWC3_EP_MISSED_ISOC;
1732		return 1;
1733	}
1734
1735	if ((event->status & DEPEVT_STATUS_IOC) &&
1736			(trb->ctrl & DWC3_TRB_CTRL_IOC))
1737		return 0;
1738	return 1;
1739}
1740
1741static void dwc3_endpoint_transfer_complete(struct dwc3 *dwc,
1742		struct dwc3_ep *dep, const struct dwc3_event_depevt *event,
1743		int start_new)
1744{
1745	unsigned		status = 0;
1746	int			clean_busy;
1747
1748	if (event->status & DEPEVT_STATUS_BUSERR)
1749		status = -ECONNRESET;
1750
1751	clean_busy = dwc3_cleanup_done_reqs(dwc, dep, event, status);
1752	if (clean_busy)
1753		dep->flags &= ~DWC3_EP_BUSY;
1754
1755	/*
1756	 * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
1757	 * See dwc3_gadget_linksts_change_interrupt() for 1st half.
1758	 */
1759	if (dwc->revision < DWC3_REVISION_183A) {
1760		u32		reg;
1761		int		i;
1762
1763		for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
1764			dep = dwc->eps[i];
1765
1766			if (!(dep->flags & DWC3_EP_ENABLED))
1767				continue;
1768
1769			if (!list_empty(&dep->req_queued))
1770				return;
1771		}
1772
1773		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1774		reg |= dwc->u1u2;
1775		dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1776
1777		dwc->u1u2 = 0;
1778	}
1779}
1780
1781static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
1782		const struct dwc3_event_depevt *event)
1783{
1784	struct dwc3_ep		*dep;
1785	u8			epnum = event->endpoint_number;
1786
1787	dep = dwc->eps[epnum];
1788
1789	if (!(dep->flags & DWC3_EP_ENABLED))
1790		return;
1791
1792	dev_vdbg(dwc->dev, "%s: %s\n", dep->name,
1793			dwc3_ep_event_string(event->endpoint_event));
1794
1795	if (epnum == 0 || epnum == 1) {
1796		dwc3_ep0_interrupt(dwc, event);
1797		return;
1798	}
1799
1800	switch (event->endpoint_event) {
1801	case DWC3_DEPEVT_XFERCOMPLETE:
1802		dep->resource_index = 0;
1803
1804		if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1805			dev_dbg(dwc->dev, "%s is an Isochronous endpoint\n",
1806					dep->name);
1807			return;
1808		}
1809
1810		dwc3_endpoint_transfer_complete(dwc, dep, event, 1);
1811		break;
1812	case DWC3_DEPEVT_XFERINPROGRESS:
1813		if (!usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1814			dev_dbg(dwc->dev, "%s is not an Isochronous endpoint\n",
1815					dep->name);
1816			return;
1817		}
1818
1819		dwc3_endpoint_transfer_complete(dwc, dep, event, 0);
1820		break;
1821	case DWC3_DEPEVT_XFERNOTREADY:
1822		if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1823			dwc3_gadget_start_isoc(dwc, dep, event);
1824		} else {
1825			int ret;
1826
1827			dev_vdbg(dwc->dev, "%s: reason %s\n",
1828					dep->name, event->status &
1829					DEPEVT_STATUS_TRANSFER_ACTIVE
1830					? "Transfer Active"
1831					: "Transfer Not Active");
1832
1833			ret = __dwc3_gadget_kick_transfer(dep, 0, 1);
1834			if (!ret || ret == -EBUSY)
1835				return;
1836
1837			dev_dbg(dwc->dev, "%s: failed to kick transfers\n",
1838					dep->name);
1839		}
1840
1841		break;
1842	case DWC3_DEPEVT_STREAMEVT:
1843		if (!usb_endpoint_xfer_bulk(dep->endpoint.desc)) {
1844			dev_err(dwc->dev, "Stream event for non-Bulk %s\n",
1845					dep->name);
1846			return;
1847		}
1848
1849		switch (event->status) {
1850		case DEPEVT_STREAMEVT_FOUND:
1851			dev_vdbg(dwc->dev, "Stream %d found and started\n",
1852					event->parameters);
1853
1854			break;
1855		case DEPEVT_STREAMEVT_NOTFOUND:
1856			/* FALLTHROUGH */
1857		default:
1858			dev_dbg(dwc->dev, "Couldn't find suitable stream\n");
1859		}
1860		break;
1861	case DWC3_DEPEVT_RXTXFIFOEVT:
1862		dev_dbg(dwc->dev, "%s FIFO Overrun\n", dep->name);
1863		break;
1864	case DWC3_DEPEVT_EPCMDCMPLT:
1865		dev_vdbg(dwc->dev, "Endpoint Command Complete\n");
1866		break;
1867	}
1868}
1869
1870static void dwc3_disconnect_gadget(struct dwc3 *dwc)
1871{
1872	if (dwc->gadget_driver && dwc->gadget_driver->disconnect) {
1873		spin_unlock(&dwc->lock);
1874		dwc->gadget_driver->disconnect(&dwc->gadget);
1875		spin_lock(&dwc->lock);
1876	}
1877}
1878
1879static void dwc3_stop_active_transfer(struct dwc3 *dwc, u32 epnum)
1880{
1881	struct dwc3_ep *dep;
1882	struct dwc3_gadget_ep_cmd_params params;
1883	u32 cmd;
1884	int ret;
1885
1886	dep = dwc->eps[epnum];
1887
1888	if (!dep->resource_index)
1889		return;
1890
1891	/*
1892	 * NOTICE: We are violating what the Databook says about the
1893	 * EndTransfer command. Ideally we would _always_ wait for the
1894	 * EndTransfer Command Completion IRQ, but that's causing too
1895	 * much trouble synchronizing between us and gadget driver.
1896	 *
1897	 * We have discussed this with the IP Provider and it was
1898	 * suggested to giveback all requests here, but give HW some
1899	 * extra time to synchronize with the interconnect. We're using
1900	 * an arbitraty 100us delay for that.
1901	 *
1902	 * Note also that a similar handling was tested by Synopsys
1903	 * (thanks a lot Paul) and nothing bad has come out of it.
1904	 * In short, what we're doing is:
1905	 *
1906	 * - Issue EndTransfer WITH CMDIOC bit set
1907	 * - Wait 100us
1908	 */
1909
1910	cmd = DWC3_DEPCMD_ENDTRANSFER;
1911	cmd |= DWC3_DEPCMD_HIPRI_FORCERM | DWC3_DEPCMD_CMDIOC;
1912	cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
1913	memset(&params, 0, sizeof(params));
1914	ret = dwc3_send_gadget_ep_cmd(dwc, dep->number, cmd, &params);
1915	WARN_ON_ONCE(ret);
1916	dep->resource_index = 0;
1917	dep->flags &= ~DWC3_EP_BUSY;
1918	udelay(100);
1919}
1920
1921static void dwc3_stop_active_transfers(struct dwc3 *dwc)
1922{
1923	u32 epnum;
1924
1925	for (epnum = 2; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
1926		struct dwc3_ep *dep;
1927
1928		dep = dwc->eps[epnum];
1929		if (!(dep->flags & DWC3_EP_ENABLED))
1930			continue;
1931
1932		dwc3_remove_requests(dwc, dep);
1933	}
1934}
1935
1936static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
1937{
1938	u32 epnum;
1939
1940	for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
1941		struct dwc3_ep *dep;
1942		struct dwc3_gadget_ep_cmd_params params;
1943		int ret;
1944
1945		dep = dwc->eps[epnum];
1946
1947		if (!(dep->flags & DWC3_EP_STALL))
1948			continue;
1949
1950		dep->flags &= ~DWC3_EP_STALL;
1951
1952		memset(&params, 0, sizeof(params));
1953		ret = dwc3_send_gadget_ep_cmd(dwc, dep->number,
1954				DWC3_DEPCMD_CLEARSTALL, &params);
1955		WARN_ON_ONCE(ret);
1956	}
1957}
1958
1959static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
1960{
1961	int			reg;
1962
1963	dev_vdbg(dwc->dev, "%s\n", __func__);
1964
1965	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1966	reg &= ~DWC3_DCTL_INITU1ENA;
1967	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1968
1969	reg &= ~DWC3_DCTL_INITU2ENA;
1970	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1971
1972	dwc3_disconnect_gadget(dwc);
1973	dwc->start_config_issued = false;
1974
1975	dwc->gadget.speed = USB_SPEED_UNKNOWN;
1976	dwc->setup_packet_pending = false;
1977}
1978
1979static void dwc3_gadget_usb3_phy_suspend(struct dwc3 *dwc, int suspend)
1980{
1981	u32			reg;
1982
1983	reg = dwc3_readl(dwc->regs, DWC3_GUSB3PIPECTL(0));
1984
1985	if (suspend)
1986		reg |= DWC3_GUSB3PIPECTL_SUSPHY;
1987	else
1988		reg &= ~DWC3_GUSB3PIPECTL_SUSPHY;
1989
1990	dwc3_writel(dwc->regs, DWC3_GUSB3PIPECTL(0), reg);
1991}
1992
1993static void dwc3_gadget_usb2_phy_suspend(struct dwc3 *dwc, int suspend)
1994{
1995	u32			reg;
1996
1997	reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
1998
1999	if (suspend)
2000		reg |= DWC3_GUSB2PHYCFG_SUSPHY;
2001	else
2002		reg &= ~DWC3_GUSB2PHYCFG_SUSPHY;
2003
2004	dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
2005}
2006
2007static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
2008{
2009	u32			reg;
2010
2011	dev_vdbg(dwc->dev, "%s\n", __func__);
2012
2013	/*
2014	 * WORKAROUND: DWC3 revisions <1.88a have an issue which
2015	 * would cause a missing Disconnect Event if there's a
2016	 * pending Setup Packet in the FIFO.
2017	 *
2018	 * There's no suggested workaround on the official Bug
2019	 * report, which states that "unless the driver/application
2020	 * is doing any special handling of a disconnect event,
2021	 * there is no functional issue".
2022	 *
2023	 * Unfortunately, it turns out that we _do_ some special
2024	 * handling of a disconnect event, namely complete all
2025	 * pending transfers, notify gadget driver of the
2026	 * disconnection, and so on.
2027	 *
2028	 * Our suggested workaround is to follow the Disconnect
2029	 * Event steps here, instead, based on a setup_packet_pending
2030	 * flag. Such flag gets set whenever we have a XferNotReady
2031	 * event on EP0 and gets cleared on XferComplete for the
2032	 * same endpoint.
2033	 *
2034	 * Refers to:
2035	 *
2036	 * STAR#9000466709: RTL: Device : Disconnect event not
2037	 * generated if setup packet pending in FIFO
2038	 */
2039	if (dwc->revision < DWC3_REVISION_188A) {
2040		if (dwc->setup_packet_pending)
2041			dwc3_gadget_disconnect_interrupt(dwc);
2042	}
2043
2044	/* after reset -> Default State */
2045	dwc->dev_state = DWC3_DEFAULT_STATE;
2046
2047	/* Recent versions support automatic phy suspend and don't need this */
2048	if (dwc->revision < DWC3_REVISION_194A) {
2049		/* Resume PHYs */
2050		dwc3_gadget_usb2_phy_suspend(dwc, false);
2051		dwc3_gadget_usb3_phy_suspend(dwc, false);
2052	}
2053
2054	if (dwc->gadget.speed != USB_SPEED_UNKNOWN)
2055		dwc3_disconnect_gadget(dwc);
2056
2057	reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2058	reg &= ~DWC3_DCTL_TSTCTRL_MASK;
2059	dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2060	dwc->test_mode = false;
2061
2062	dwc3_stop_active_transfers(dwc);
2063	dwc3_clear_stall_all_ep(dwc);
2064	dwc->start_config_issued = false;
2065
2066	/* Reset device address to zero */
2067	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2068	reg &= ~(DWC3_DCFG_DEVADDR_MASK);
2069	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2070}
2071
2072static void dwc3_update_ram_clk_sel(struct dwc3 *dwc, u32 speed)
2073{
2074	u32 reg;
2075	u32 usb30_clock = DWC3_GCTL_CLK_BUS;
2076
2077	/*
2078	 * We change the clock only at SS but I dunno why I would want to do
2079	 * this. Maybe it becomes part of the power saving plan.
2080	 */
2081
2082	if (speed != DWC3_DSTS_SUPERSPEED)
2083		return;
2084
2085	/*
2086	 * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
2087	 * each time on Connect Done.
2088	 */
2089	if (!usb30_clock)
2090		return;
2091
2092	reg = dwc3_readl(dwc->regs, DWC3_GCTL);
2093	reg |= DWC3_GCTL_RAMCLKSEL(usb30_clock);
2094	dwc3_writel(dwc->regs, DWC3_GCTL, reg);
2095}
2096
2097static void dwc3_gadget_phy_suspend(struct dwc3 *dwc, u8 speed)
2098{
2099	switch (speed) {
2100	case USB_SPEED_SUPER:
2101		dwc3_gadget_usb2_phy_suspend(dwc, true);
2102		break;
2103	case USB_SPEED_HIGH:
2104	case USB_SPEED_FULL:
2105	case USB_SPEED_LOW:
2106		dwc3_gadget_usb3_phy_suspend(dwc, true);
2107		break;
2108	}
2109}
2110
2111static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
2112{
2113	struct dwc3_gadget_ep_cmd_params params;
2114	struct dwc3_ep		*dep;
2115	int			ret;
2116	u32			reg;
2117	u8			speed;
2118
2119	dev_vdbg(dwc->dev, "%s\n", __func__);
2120
2121	memset(&params, 0x00, sizeof(params));
2122
2123	reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2124	speed = reg & DWC3_DSTS_CONNECTSPD;
2125	dwc->speed = speed;
2126
2127	dwc3_update_ram_clk_sel(dwc, speed);
2128
2129	switch (speed) {
2130	case DWC3_DCFG_SUPERSPEED:
2131		/*
2132		 * WORKAROUND: DWC3 revisions <1.90a have an issue which
2133		 * would cause a missing USB3 Reset event.
2134		 *
2135		 * In such situations, we should force a USB3 Reset
2136		 * event by calling our dwc3_gadget_reset_interrupt()
2137		 * routine.
2138		 *
2139		 * Refers to:
2140		 *
2141		 * STAR#9000483510: RTL: SS : USB3 reset event may
2142		 * not be generated always when the link enters poll
2143		 */
2144		if (dwc->revision < DWC3_REVISION_190A)
2145			dwc3_gadget_reset_interrupt(dwc);
2146
2147		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2148		dwc->gadget.ep0->maxpacket = 512;
2149		dwc->gadget.speed = USB_SPEED_SUPER;
2150		break;
2151	case DWC3_DCFG_HIGHSPEED:
2152		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
2153		dwc->gadget.ep0->maxpacket = 64;
2154		dwc->gadget.speed = USB_SPEED_HIGH;
2155		break;
2156	case DWC3_DCFG_FULLSPEED2:
2157	case DWC3_DCFG_FULLSPEED1:
2158		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
2159		dwc->gadget.ep0->maxpacket = 64;
2160		dwc->gadget.speed = USB_SPEED_FULL;
2161		break;
2162	case DWC3_DCFG_LOWSPEED:
2163		dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(8);
2164		dwc->gadget.ep0->maxpacket = 8;
2165		dwc->gadget.speed = USB_SPEED_LOW;
2166		break;
2167	}
2168
2169	/* Enable USB2 LPM Capability */
2170
2171	if ((dwc->revision > DWC3_REVISION_194A)
2172			&& (speed != DWC3_DCFG_SUPERSPEED)) {
2173		reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2174		reg |= DWC3_DCFG_LPM_CAP;
2175		dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2176
2177		reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2178		reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
2179
2180		/* TODO: This should be configurable */
2181		reg |= DWC3_DCTL_HIRD_THRES(28);
2182
2183		dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2184	}
2185
2186	/* Recent versions support automatic phy suspend and don't need this */
2187	if (dwc->revision < DWC3_REVISION_194A) {
2188		/* Suspend unneeded PHY */
2189		dwc3_gadget_phy_suspend(dwc, dwc->gadget.speed);
2190	}
2191
2192	dep = dwc->eps[0];
2193	ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL, true);
2194	if (ret) {
2195		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2196		return;
2197	}
2198
2199	dep = dwc->eps[1];
2200	ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL, true);
2201	if (ret) {
2202		dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2203		return;
2204	}
2205
2206	/*
2207	 * Configure PHY via GUSB3PIPECTLn if required.
2208	 *
2209	 * Update GTXFIFOSIZn
2210	 *
2211	 * In both cases reset values should be sufficient.
2212	 */
2213}
2214
2215static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
2216{
2217	dev_vdbg(dwc->dev, "%s\n", __func__);
2218
2219	/*
2220	 * TODO take core out of low power mode when that's
2221	 * implemented.
2222	 */
2223
2224	dwc->gadget_driver->resume(&dwc->gadget);
2225}
2226
2227static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
2228		unsigned int evtinfo)
2229{
2230	enum dwc3_link_state	next = evtinfo & DWC3_LINK_STATE_MASK;
2231
2232	/*
2233	 * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
2234	 * on the link partner, the USB session might do multiple entry/exit
2235	 * of low power states before a transfer takes place.
2236	 *
2237	 * Due to this problem, we might experience lower throughput. The
2238	 * suggested workaround is to disable DCTL[12:9] bits if we're
2239	 * transitioning from U1/U2 to U0 and enable those bits again
2240	 * after a transfer completes and there are no pending transfers
2241	 * on any of the enabled endpoints.
2242	 *
2243	 * This is the first half of that workaround.
2244	 *
2245	 * Refers to:
2246	 *
2247	 * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
2248	 * core send LGO_Ux entering U0
2249	 */
2250	if (dwc->revision < DWC3_REVISION_183A) {
2251		if (next == DWC3_LINK_STATE_U0) {
2252			u32	u1u2;
2253			u32	reg;
2254
2255			switch (dwc->link_state) {
2256			case DWC3_LINK_STATE_U1:
2257			case DWC3_LINK_STATE_U2:
2258				reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2259				u1u2 = reg & (DWC3_DCTL_INITU2ENA
2260						| DWC3_DCTL_ACCEPTU2ENA
2261						| DWC3_DCTL_INITU1ENA
2262						| DWC3_DCTL_ACCEPTU1ENA);
2263
2264				if (!dwc->u1u2)
2265					dwc->u1u2 = reg & u1u2;
2266
2267				reg &= ~u1u2;
2268
2269				dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2270				break;
2271			default:
2272				/* do nothing */
2273				break;
2274			}
2275		}
2276	}
2277
2278	dwc->link_state = next;
2279
2280	dev_vdbg(dwc->dev, "%s link %d\n", __func__, dwc->link_state);
2281}
2282
2283static void dwc3_gadget_interrupt(struct dwc3 *dwc,
2284		const struct dwc3_event_devt *event)
2285{
2286	switch (event->type) {
2287	case DWC3_DEVICE_EVENT_DISCONNECT:
2288		dwc3_gadget_disconnect_interrupt(dwc);
2289		break;
2290	case DWC3_DEVICE_EVENT_RESET:
2291		dwc3_gadget_reset_interrupt(dwc);
2292		break;
2293	case DWC3_DEVICE_EVENT_CONNECT_DONE:
2294		dwc3_gadget_conndone_interrupt(dwc);
2295		break;
2296	case DWC3_DEVICE_EVENT_WAKEUP:
2297		dwc3_gadget_wakeup_interrupt(dwc);
2298		break;
2299	case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
2300		dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
2301		break;
2302	case DWC3_DEVICE_EVENT_EOPF:
2303		dev_vdbg(dwc->dev, "End of Periodic Frame\n");
2304		break;
2305	case DWC3_DEVICE_EVENT_SOF:
2306		dev_vdbg(dwc->dev, "Start of Periodic Frame\n");
2307		break;
2308	case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
2309		dev_vdbg(dwc->dev, "Erratic Error\n");
2310		break;
2311	case DWC3_DEVICE_EVENT_CMD_CMPL:
2312		dev_vdbg(dwc->dev, "Command Complete\n");
2313		break;
2314	case DWC3_DEVICE_EVENT_OVERFLOW:
2315		dev_vdbg(dwc->dev, "Overflow\n");
2316		break;
2317	default:
2318		dev_dbg(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
2319	}
2320}
2321
2322static void dwc3_process_event_entry(struct dwc3 *dwc,
2323		const union dwc3_event *event)
2324{
2325	/* Endpoint IRQ, handle it and return early */
2326	if (event->type.is_devspec == 0) {
2327		/* depevt */
2328		return dwc3_endpoint_interrupt(dwc, &event->depevt);
2329	}
2330
2331	switch (event->type.type) {
2332	case DWC3_EVENT_TYPE_DEV:
2333		dwc3_gadget_interrupt(dwc, &event->devt);
2334		break;
2335	/* REVISIT what to do with Carkit and I2C events ? */
2336	default:
2337		dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
2338	}
2339}
2340
2341static irqreturn_t dwc3_process_event_buf(struct dwc3 *dwc, u32 buf)
2342{
2343	struct dwc3_event_buffer *evt;
2344	int left;
2345	u32 count;
2346
2347	count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(buf));
2348	count &= DWC3_GEVNTCOUNT_MASK;
2349	if (!count)
2350		return IRQ_NONE;
2351
2352	evt = dwc->ev_buffs[buf];
2353	left = count;
2354
2355	while (left > 0) {
2356		union dwc3_event event;
2357
2358		event.raw = *(u32 *) (evt->buf + evt->lpos);
2359
2360		dwc3_process_event_entry(dwc, &event);
2361		/*
2362		 * XXX we wrap around correctly to the next entry as almost all
2363		 * entries are 4 bytes in size. There is one entry which has 12
2364		 * bytes which is a regular entry followed by 8 bytes data. ATM
2365		 * I don't know how things are organized if were get next to the
2366		 * a boundary so I worry about that once we try to handle that.
2367		 */
2368		evt->lpos = (evt->lpos + 4) % DWC3_EVENT_BUFFERS_SIZE;
2369		left -= 4;
2370
2371		dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(buf), 4);
2372	}
2373
2374	return IRQ_HANDLED;
2375}
2376
2377static irqreturn_t dwc3_interrupt(int irq, void *_dwc)
2378{
2379	struct dwc3			*dwc = _dwc;
2380	int				i;
2381	irqreturn_t			ret = IRQ_NONE;
2382
2383	spin_lock(&dwc->lock);
2384
2385	for (i = 0; i < dwc->num_event_buffers; i++) {
2386		irqreturn_t status;
2387
2388		status = dwc3_process_event_buf(dwc, i);
2389		if (status == IRQ_HANDLED)
2390			ret = status;
2391	}
2392
2393	spin_unlock(&dwc->lock);
2394
2395	return ret;
2396}
2397
2398/**
2399 * dwc3_gadget_init - Initializes gadget related registers
2400 * @dwc: pointer to our controller context structure
2401 *
2402 * Returns 0 on success otherwise negative errno.
2403 */
2404int dwc3_gadget_init(struct dwc3 *dwc)
2405{
2406	u32					reg;
2407	int					ret;
2408	int					irq;
2409
2410	dwc->ctrl_req = dma_alloc_coherent(dwc->dev, sizeof(*dwc->ctrl_req),
2411			&dwc->ctrl_req_addr, GFP_KERNEL);
2412	if (!dwc->ctrl_req) {
2413		dev_err(dwc->dev, "failed to allocate ctrl request\n");
2414		ret = -ENOMEM;
2415		goto err0;
2416	}
2417
2418	dwc->ep0_trb = dma_alloc_coherent(dwc->dev, sizeof(*dwc->ep0_trb),
2419			&dwc->ep0_trb_addr, GFP_KERNEL);
2420	if (!dwc->ep0_trb) {
2421		dev_err(dwc->dev, "failed to allocate ep0 trb\n");
2422		ret = -ENOMEM;
2423		goto err1;
2424	}
2425
2426	dwc->setup_buf = kzalloc(DWC3_EP0_BOUNCE_SIZE, GFP_KERNEL);
2427	if (!dwc->setup_buf) {
2428		dev_err(dwc->dev, "failed to allocate setup buffer\n");
2429		ret = -ENOMEM;
2430		goto err2;
2431	}
2432
2433	dwc->ep0_bounce = dma_alloc_coherent(dwc->dev,
2434			DWC3_EP0_BOUNCE_SIZE, &dwc->ep0_bounce_addr,
2435			GFP_KERNEL);
2436	if (!dwc->ep0_bounce) {
2437		dev_err(dwc->dev, "failed to allocate ep0 bounce buffer\n");
2438		ret = -ENOMEM;
2439		goto err3;
2440	}
2441
2442	dev_set_name(&dwc->gadget.dev, "gadget");
2443
2444	dwc->gadget.ops			= &dwc3_gadget_ops;
2445	dwc->gadget.max_speed		= USB_SPEED_SUPER;
2446	dwc->gadget.speed		= USB_SPEED_UNKNOWN;
2447	dwc->gadget.dev.parent		= dwc->dev;
2448	dwc->gadget.sg_supported	= true;
2449
2450	dma_set_coherent_mask(&dwc->gadget.dev, dwc->dev->coherent_dma_mask);
2451
2452	dwc->gadget.dev.dma_parms	= dwc->dev->dma_parms;
2453	dwc->gadget.dev.dma_mask	= dwc->dev->dma_mask;
2454	dwc->gadget.dev.release		= dwc3_gadget_release;
2455	dwc->gadget.name		= "dwc3-gadget";
2456
2457	/*
2458	 * REVISIT: Here we should clear all pending IRQs to be
2459	 * sure we're starting from a well known location.
2460	 */
2461
2462	ret = dwc3_gadget_init_endpoints(dwc);
2463	if (ret)
2464		goto err4;
2465
2466	irq = platform_get_irq(to_platform_device(dwc->dev), 0);
2467
2468	ret = request_irq(irq, dwc3_interrupt, IRQF_SHARED,
2469			"dwc3", dwc);
2470	if (ret) {
2471		dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
2472				irq, ret);
2473		goto err5;
2474	}
2475
2476	reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2477	reg |= DWC3_DCFG_LPM_CAP;
2478	dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2479
2480	/* Enable all but Start and End of Frame IRQs */
2481	reg = (DWC3_DEVTEN_VNDRDEVTSTRCVEDEN |
2482			DWC3_DEVTEN_EVNTOVERFLOWEN |
2483			DWC3_DEVTEN_CMDCMPLTEN |
2484			DWC3_DEVTEN_ERRTICERREN |
2485			DWC3_DEVTEN_WKUPEVTEN |
2486			DWC3_DEVTEN_ULSTCNGEN |
2487			DWC3_DEVTEN_CONNECTDONEEN |
2488			DWC3_DEVTEN_USBRSTEN |
2489			DWC3_DEVTEN_DISCONNEVTEN);
2490	dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
2491
2492	/* automatic phy suspend only on recent versions */
2493	if (dwc->revision >= DWC3_REVISION_194A) {
2494		dwc3_gadget_usb2_phy_suspend(dwc, false);
2495		dwc3_gadget_usb3_phy_suspend(dwc, false);
2496	}
2497
2498	ret = device_register(&dwc->gadget.dev);
2499	if (ret) {
2500		dev_err(dwc->dev, "failed to register gadget device\n");
2501		put_device(&dwc->gadget.dev);
2502		goto err6;
2503	}
2504
2505	ret = usb_add_gadget_udc(dwc->dev, &dwc->gadget);
2506	if (ret) {
2507		dev_err(dwc->dev, "failed to register udc\n");
2508		goto err7;
2509	}
2510
2511	return 0;
2512
2513err7:
2514	device_unregister(&dwc->gadget.dev);
2515
2516err6:
2517	dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
2518	free_irq(irq, dwc);
2519
2520err5:
2521	dwc3_gadget_free_endpoints(dwc);
2522
2523err4:
2524	dma_free_coherent(dwc->dev, DWC3_EP0_BOUNCE_SIZE,
2525			dwc->ep0_bounce, dwc->ep0_bounce_addr);
2526
2527err3:
2528	kfree(dwc->setup_buf);
2529
2530err2:
2531	dma_free_coherent(dwc->dev, sizeof(*dwc->ep0_trb),
2532			dwc->ep0_trb, dwc->ep0_trb_addr);
2533
2534err1:
2535	dma_free_coherent(dwc->dev, sizeof(*dwc->ctrl_req),
2536			dwc->ctrl_req, dwc->ctrl_req_addr);
2537
2538err0:
2539	return ret;
2540}
2541
2542void dwc3_gadget_exit(struct dwc3 *dwc)
2543{
2544	int			irq;
2545
2546	usb_del_gadget_udc(&dwc->gadget);
2547	irq = platform_get_irq(to_platform_device(dwc->dev), 0);
2548
2549	dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
2550	free_irq(irq, dwc);
2551
2552	dwc3_gadget_free_endpoints(dwc);
2553
2554	dma_free_coherent(dwc->dev, DWC3_EP0_BOUNCE_SIZE,
2555			dwc->ep0_bounce, dwc->ep0_bounce_addr);
2556
2557	kfree(dwc->setup_buf);
2558
2559	dma_free_coherent(dwc->dev, sizeof(*dwc->ep0_trb),
2560			dwc->ep0_trb, dwc->ep0_trb_addr);
2561
2562	dma_free_coherent(dwc->dev, sizeof(*dwc->ctrl_req),
2563			dwc->ctrl_req, dwc->ctrl_req_addr);
2564
2565	device_unregister(&dwc->gadget.dev);
2566}
2567