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