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