]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/usb/dwc3/gadget.c
b0b72e72bbac86b39162c838a15e9d6885387e47
[linux.git] / drivers / usb / dwc3 / gadget.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * gadget.c - DesignWare USB3 DRD Controller Gadget Framework Link
4  *
5  * Copyright (C) 2010-2011 Texas Instruments Incorporated - http://www.ti.com
6  *
7  * Authors: Felipe Balbi <balbi@ti.com>,
8  *          Sebastian Andrzej Siewior <bigeasy@linutronix.de>
9  */
10
11 #include <linux/kernel.h>
12 #include <linux/delay.h>
13 #include <linux/slab.h>
14 #include <linux/spinlock.h>
15 #include <linux/platform_device.h>
16 #include <linux/pm_runtime.h>
17 #include <linux/interrupt.h>
18 #include <linux/io.h>
19 #include <linux/list.h>
20 #include <linux/dma-mapping.h>
21
22 #include <linux/usb/ch9.h>
23 #include <linux/usb/gadget.h>
24
25 #include "debug.h"
26 #include "core.h"
27 #include "gadget.h"
28 #include "io.h"
29
30 /**
31  * dwc3_gadget_set_test_mode - enables usb2 test modes
32  * @dwc: pointer to our context structure
33  * @mode: the mode to set (J, K SE0 NAK, Force Enable)
34  *
35  * Caller should take care of locking. This function will return 0 on
36  * success or -EINVAL if wrong Test Selector is passed.
37  */
38 int dwc3_gadget_set_test_mode(struct dwc3 *dwc, int mode)
39 {
40         u32             reg;
41
42         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
43         reg &= ~DWC3_DCTL_TSTCTRL_MASK;
44
45         switch (mode) {
46         case TEST_J:
47         case TEST_K:
48         case TEST_SE0_NAK:
49         case TEST_PACKET:
50         case TEST_FORCE_EN:
51                 reg |= mode << 1;
52                 break;
53         default:
54                 return -EINVAL;
55         }
56
57         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
58
59         return 0;
60 }
61
62 /**
63  * dwc3_gadget_get_link_state - gets current state of usb link
64  * @dwc: pointer to our context structure
65  *
66  * Caller should take care of locking. This function will
67  * return the link state on success (>= 0) or -ETIMEDOUT.
68  */
69 int dwc3_gadget_get_link_state(struct dwc3 *dwc)
70 {
71         u32             reg;
72
73         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
74
75         return DWC3_DSTS_USBLNKST(reg);
76 }
77
78 /**
79  * dwc3_gadget_set_link_state - sets usb link to a particular state
80  * @dwc: pointer to our context structure
81  * @state: the state to put link into
82  *
83  * Caller should take care of locking. This function will
84  * return 0 on success or -ETIMEDOUT.
85  */
86 int dwc3_gadget_set_link_state(struct dwc3 *dwc, enum dwc3_link_state state)
87 {
88         int             retries = 10000;
89         u32             reg;
90
91         /*
92          * Wait until device controller is ready. Only applies to 1.94a and
93          * later RTL.
94          */
95         if (dwc->revision >= DWC3_REVISION_194A) {
96                 while (--retries) {
97                         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
98                         if (reg & DWC3_DSTS_DCNRD)
99                                 udelay(5);
100                         else
101                                 break;
102                 }
103
104                 if (retries <= 0)
105                         return -ETIMEDOUT;
106         }
107
108         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
109         reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
110
111         /* set requested state */
112         reg |= DWC3_DCTL_ULSTCHNGREQ(state);
113         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
114
115         /*
116          * The following code is racy when called from dwc3_gadget_wakeup,
117          * and is not needed, at least on newer versions
118          */
119         if (dwc->revision >= DWC3_REVISION_194A)
120                 return 0;
121
122         /* wait for a change in DSTS */
123         retries = 10000;
124         while (--retries) {
125                 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
126
127                 if (DWC3_DSTS_USBLNKST(reg) == state)
128                         return 0;
129
130                 udelay(5);
131         }
132
133         return -ETIMEDOUT;
134 }
135
136 /**
137  * dwc3_ep_inc_trb - increment a trb index.
138  * @index: Pointer to the TRB index to increment.
139  *
140  * The index should never point to the link TRB. After incrementing,
141  * if it is point to the link TRB, wrap around to the beginning. The
142  * link TRB is always at the last TRB entry.
143  */
144 static void dwc3_ep_inc_trb(u8 *index)
145 {
146         (*index)++;
147         if (*index == (DWC3_TRB_NUM - 1))
148                 *index = 0;
149 }
150
151 /**
152  * dwc3_ep_inc_enq - increment endpoint's enqueue pointer
153  * @dep: The endpoint whose enqueue pointer we're incrementing
154  */
155 static void dwc3_ep_inc_enq(struct dwc3_ep *dep)
156 {
157         dwc3_ep_inc_trb(&dep->trb_enqueue);
158 }
159
160 /**
161  * dwc3_ep_inc_deq - increment endpoint's dequeue pointer
162  * @dep: The endpoint whose enqueue pointer we're incrementing
163  */
164 static void dwc3_ep_inc_deq(struct dwc3_ep *dep)
165 {
166         dwc3_ep_inc_trb(&dep->trb_dequeue);
167 }
168
169 void dwc3_gadget_del_and_unmap_request(struct dwc3_ep *dep,
170                 struct dwc3_request *req, int status)
171 {
172         struct dwc3                     *dwc = dep->dwc;
173
174         req->started = false;
175         list_del(&req->list);
176         req->remaining = 0;
177
178         if (req->request.status == -EINPROGRESS)
179                 req->request.status = status;
180
181         if (req->trb)
182                 usb_gadget_unmap_request_by_dev(dwc->sysdev,
183                                 &req->request, req->direction);
184
185         req->trb = NULL;
186         trace_dwc3_gadget_giveback(req);
187
188         if (dep->number > 1)
189                 pm_runtime_put(dwc->dev);
190 }
191
192 /**
193  * dwc3_gadget_giveback - call struct usb_request's ->complete callback
194  * @dep: The endpoint to whom the request belongs to
195  * @req: The request we're giving back
196  * @status: completion code for the request
197  *
198  * Must be called with controller's lock held and interrupts disabled. This
199  * function will unmap @req and call its ->complete() callback to notify upper
200  * layers that it has completed.
201  */
202 void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
203                 int status)
204 {
205         struct dwc3                     *dwc = dep->dwc;
206
207         dwc3_gadget_del_and_unmap_request(dep, req, status);
208
209         spin_unlock(&dwc->lock);
210         usb_gadget_giveback_request(&dep->endpoint, &req->request);
211         spin_lock(&dwc->lock);
212 }
213
214 /**
215  * dwc3_send_gadget_generic_command - issue a generic command for the controller
216  * @dwc: pointer to the controller context
217  * @cmd: the command to be issued
218  * @param: command parameter
219  *
220  * Caller should take care of locking. Issue @cmd with a given @param to @dwc
221  * and wait for its completion.
222  */
223 int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned cmd, u32 param)
224 {
225         u32             timeout = 500;
226         int             status = 0;
227         int             ret = 0;
228         u32             reg;
229
230         dwc3_writel(dwc->regs, DWC3_DGCMDPAR, param);
231         dwc3_writel(dwc->regs, DWC3_DGCMD, cmd | DWC3_DGCMD_CMDACT);
232
233         do {
234                 reg = dwc3_readl(dwc->regs, DWC3_DGCMD);
235                 if (!(reg & DWC3_DGCMD_CMDACT)) {
236                         status = DWC3_DGCMD_STATUS(reg);
237                         if (status)
238                                 ret = -EINVAL;
239                         break;
240                 }
241         } while (--timeout);
242
243         if (!timeout) {
244                 ret = -ETIMEDOUT;
245                 status = -ETIMEDOUT;
246         }
247
248         trace_dwc3_gadget_generic_cmd(cmd, param, status);
249
250         return ret;
251 }
252
253 static int __dwc3_gadget_wakeup(struct dwc3 *dwc);
254
255 /**
256  * dwc3_send_gadget_ep_cmd - issue an endpoint command
257  * @dep: the endpoint to which the command is going to be issued
258  * @cmd: the command to be issued
259  * @params: parameters to the command
260  *
261  * Caller should handle locking. This function will issue @cmd with given
262  * @params to @dep and wait for its completion.
263  */
264 int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned cmd,
265                 struct dwc3_gadget_ep_cmd_params *params)
266 {
267         const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
268         struct dwc3             *dwc = dep->dwc;
269         u32                     timeout = 1000;
270         u32                     reg;
271
272         int                     cmd_status = 0;
273         int                     susphy = false;
274         int                     ret = -EINVAL;
275
276         /*
277          * Synopsys Databook 2.60a states, on section 6.3.2.5.[1-8], that if
278          * we're issuing an endpoint command, we must check if
279          * GUSB2PHYCFG.SUSPHY bit is set. If it is, then we need to clear it.
280          *
281          * We will also set SUSPHY bit to what it was before returning as stated
282          * by the same section on Synopsys databook.
283          */
284         if (dwc->gadget.speed <= USB_SPEED_HIGH) {
285                 reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
286                 if (unlikely(reg & DWC3_GUSB2PHYCFG_SUSPHY)) {
287                         susphy = true;
288                         reg &= ~DWC3_GUSB2PHYCFG_SUSPHY;
289                         dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
290                 }
291         }
292
293         if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
294                 int             needs_wakeup;
295
296                 needs_wakeup = (dwc->link_state == DWC3_LINK_STATE_U1 ||
297                                 dwc->link_state == DWC3_LINK_STATE_U2 ||
298                                 dwc->link_state == DWC3_LINK_STATE_U3);
299
300                 if (unlikely(needs_wakeup)) {
301                         ret = __dwc3_gadget_wakeup(dwc);
302                         dev_WARN_ONCE(dwc->dev, ret, "wakeup failed --> %d\n",
303                                         ret);
304                 }
305         }
306
307         dwc3_writel(dep->regs, DWC3_DEPCMDPAR0, params->param0);
308         dwc3_writel(dep->regs, DWC3_DEPCMDPAR1, params->param1);
309         dwc3_writel(dep->regs, DWC3_DEPCMDPAR2, params->param2);
310
311         /*
312          * Synopsys Databook 2.60a states in section 6.3.2.5.6 of that if we're
313          * not relying on XferNotReady, we can make use of a special "No
314          * Response Update Transfer" command where we should clear both CmdAct
315          * and CmdIOC bits.
316          *
317          * With this, we don't need to wait for command completion and can
318          * straight away issue further commands to the endpoint.
319          *
320          * NOTICE: We're making an assumption that control endpoints will never
321          * make use of Update Transfer command. This is a safe assumption
322          * because we can never have more than one request at a time with
323          * Control Endpoints. If anybody changes that assumption, this chunk
324          * needs to be updated accordingly.
325          */
326         if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_UPDATETRANSFER &&
327                         !usb_endpoint_xfer_isoc(desc))
328                 cmd &= ~(DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_CMDACT);
329         else
330                 cmd |= DWC3_DEPCMD_CMDACT;
331
332         dwc3_writel(dep->regs, DWC3_DEPCMD, cmd);
333         do {
334                 reg = dwc3_readl(dep->regs, DWC3_DEPCMD);
335                 if (!(reg & DWC3_DEPCMD_CMDACT)) {
336                         cmd_status = DWC3_DEPCMD_STATUS(reg);
337
338                         switch (cmd_status) {
339                         case 0:
340                                 ret = 0;
341                                 break;
342                         case DEPEVT_TRANSFER_NO_RESOURCE:
343                                 ret = -EINVAL;
344                                 break;
345                         case DEPEVT_TRANSFER_BUS_EXPIRY:
346                                 /*
347                                  * SW issues START TRANSFER command to
348                                  * isochronous ep with future frame interval. If
349                                  * future interval time has already passed when
350                                  * core receives the command, it will respond
351                                  * with an error status of 'Bus Expiry'.
352                                  *
353                                  * Instead of always returning -EINVAL, let's
354                                  * give a hint to the gadget driver that this is
355                                  * the case by returning -EAGAIN.
356                                  */
357                                 ret = -EAGAIN;
358                                 break;
359                         default:
360                                 dev_WARN(dwc->dev, "UNKNOWN cmd status\n");
361                         }
362
363                         break;
364                 }
365         } while (--timeout);
366
367         if (timeout == 0) {
368                 ret = -ETIMEDOUT;
369                 cmd_status = -ETIMEDOUT;
370         }
371
372         trace_dwc3_gadget_ep_cmd(dep, cmd, params, cmd_status);
373
374         if (ret == 0) {
375                 switch (DWC3_DEPCMD_CMD(cmd)) {
376                 case DWC3_DEPCMD_STARTTRANSFER:
377                         dep->flags |= DWC3_EP_TRANSFER_STARTED;
378                         break;
379                 case DWC3_DEPCMD_ENDTRANSFER:
380                         dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
381                         break;
382                 default:
383                         /* nothing */
384                         break;
385                 }
386         }
387
388         if (unlikely(susphy)) {
389                 reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
390                 reg |= DWC3_GUSB2PHYCFG_SUSPHY;
391                 dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
392         }
393
394         return ret;
395 }
396
397 static int dwc3_send_clear_stall_ep_cmd(struct dwc3_ep *dep)
398 {
399         struct dwc3 *dwc = dep->dwc;
400         struct dwc3_gadget_ep_cmd_params params;
401         u32 cmd = DWC3_DEPCMD_CLEARSTALL;
402
403         /*
404          * As of core revision 2.60a the recommended programming model
405          * is to set the ClearPendIN bit when issuing a Clear Stall EP
406          * command for IN endpoints. This is to prevent an issue where
407          * some (non-compliant) hosts may not send ACK TPs for pending
408          * IN transfers due to a mishandled error condition. Synopsys
409          * STAR 9000614252.
410          */
411         if (dep->direction && (dwc->revision >= DWC3_REVISION_260A) &&
412             (dwc->gadget.speed >= USB_SPEED_SUPER))
413                 cmd |= DWC3_DEPCMD_CLEARPENDIN;
414
415         memset(&params, 0, sizeof(params));
416
417         return dwc3_send_gadget_ep_cmd(dep, cmd, &params);
418 }
419
420 static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep,
421                 struct dwc3_trb *trb)
422 {
423         u32             offset = (char *) trb - (char *) dep->trb_pool;
424
425         return dep->trb_pool_dma + offset;
426 }
427
428 static int dwc3_alloc_trb_pool(struct dwc3_ep *dep)
429 {
430         struct dwc3             *dwc = dep->dwc;
431
432         if (dep->trb_pool)
433                 return 0;
434
435         dep->trb_pool = dma_alloc_coherent(dwc->sysdev,
436                         sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
437                         &dep->trb_pool_dma, GFP_KERNEL);
438         if (!dep->trb_pool) {
439                 dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n",
440                                 dep->name);
441                 return -ENOMEM;
442         }
443
444         return 0;
445 }
446
447 static void dwc3_free_trb_pool(struct dwc3_ep *dep)
448 {
449         struct dwc3             *dwc = dep->dwc;
450
451         dma_free_coherent(dwc->sysdev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
452                         dep->trb_pool, dep->trb_pool_dma);
453
454         dep->trb_pool = NULL;
455         dep->trb_pool_dma = 0;
456 }
457
458 static int dwc3_gadget_set_xfer_resource(struct dwc3 *dwc, struct dwc3_ep *dep);
459
460 /**
461  * dwc3_gadget_start_config - configure ep resources
462  * @dwc: pointer to our controller context structure
463  * @dep: endpoint that is being enabled
464  *
465  * Issue a %DWC3_DEPCMD_DEPSTARTCFG command to @dep. After the command's
466  * completion, it will set Transfer Resource for all available endpoints.
467  *
468  * The assignment of transfer resources cannot perfectly follow the data book
469  * due to the fact that the controller driver does not have all knowledge of the
470  * configuration in advance. It is given this information piecemeal by the
471  * composite gadget framework after every SET_CONFIGURATION and
472  * SET_INTERFACE. Trying to follow the databook programming model in this
473  * scenario can cause errors. For two reasons:
474  *
475  * 1) The databook says to do %DWC3_DEPCMD_DEPSTARTCFG for every
476  * %USB_REQ_SET_CONFIGURATION and %USB_REQ_SET_INTERFACE (8.1.5). This is
477  * incorrect in the scenario of multiple interfaces.
478  *
479  * 2) The databook does not mention doing more %DWC3_DEPCMD_DEPXFERCFG for new
480  * endpoint on alt setting (8.1.6).
481  *
482  * The following simplified method is used instead:
483  *
484  * All hardware endpoints can be assigned a transfer resource and this setting
485  * will stay persistent until either a core reset or hibernation. So whenever we
486  * do a %DWC3_DEPCMD_DEPSTARTCFG(0) we can go ahead and do
487  * %DWC3_DEPCMD_DEPXFERCFG for every hardware endpoint as well. We are
488  * guaranteed that there are as many transfer resources as endpoints.
489  *
490  * This function is called for each endpoint when it is being enabled but is
491  * triggered only when called for EP0-out, which always happens first, and which
492  * should only happen in one of the above conditions.
493  */
494 static int dwc3_gadget_start_config(struct dwc3 *dwc, struct dwc3_ep *dep)
495 {
496         struct dwc3_gadget_ep_cmd_params params;
497         u32                     cmd;
498         int                     i;
499         int                     ret;
500
501         if (dep->number)
502                 return 0;
503
504         memset(&params, 0x00, sizeof(params));
505         cmd = DWC3_DEPCMD_DEPSTARTCFG;
506
507         ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
508         if (ret)
509                 return ret;
510
511         for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
512                 struct dwc3_ep *dep = dwc->eps[i];
513
514                 if (!dep)
515                         continue;
516
517                 ret = dwc3_gadget_set_xfer_resource(dwc, dep);
518                 if (ret)
519                         return ret;
520         }
521
522         return 0;
523 }
524
525 static int dwc3_gadget_set_ep_config(struct dwc3 *dwc, struct dwc3_ep *dep,
526                 bool modify, bool restore)
527 {
528         const struct usb_ss_ep_comp_descriptor *comp_desc;
529         const struct usb_endpoint_descriptor *desc;
530         struct dwc3_gadget_ep_cmd_params params;
531
532         if (dev_WARN_ONCE(dwc->dev, modify && restore,
533                                         "Can't modify and restore\n"))
534                 return -EINVAL;
535
536         comp_desc = dep->endpoint.comp_desc;
537         desc = dep->endpoint.desc;
538
539         memset(&params, 0x00, sizeof(params));
540
541         params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc))
542                 | DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc));
543
544         /* Burst size is only needed in SuperSpeed mode */
545         if (dwc->gadget.speed >= USB_SPEED_SUPER) {
546                 u32 burst = dep->endpoint.maxburst;
547                 params.param0 |= DWC3_DEPCFG_BURST_SIZE(burst - 1);
548         }
549
550         if (modify) {
551                 params.param0 |= DWC3_DEPCFG_ACTION_MODIFY;
552         } else if (restore) {
553                 params.param0 |= DWC3_DEPCFG_ACTION_RESTORE;
554                 params.param2 |= dep->saved_state;
555         } else {
556                 params.param0 |= DWC3_DEPCFG_ACTION_INIT;
557         }
558
559         if (usb_endpoint_xfer_control(desc))
560                 params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN;
561
562         if (dep->number <= 1 || usb_endpoint_xfer_isoc(desc))
563                 params.param1 |= DWC3_DEPCFG_XFER_NOT_READY_EN;
564
565         if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) {
566                 params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE
567                         | DWC3_DEPCFG_STREAM_EVENT_EN;
568                 dep->stream_capable = true;
569         }
570
571         if (!usb_endpoint_xfer_control(desc))
572                 params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN;
573
574         /*
575          * We are doing 1:1 mapping for endpoints, meaning
576          * Physical Endpoints 2 maps to Logical Endpoint 2 and
577          * so on. We consider the direction bit as part of the physical
578          * endpoint number. So USB endpoint 0x81 is 0x03.
579          */
580         params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number);
581
582         /*
583          * We must use the lower 16 TX FIFOs even though
584          * HW might have more
585          */
586         if (dep->direction)
587                 params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1);
588
589         if (desc->bInterval) {
590                 params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(desc->bInterval - 1);
591                 dep->interval = 1 << (desc->bInterval - 1);
592         }
593
594         return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETEPCONFIG, &params);
595 }
596
597 static int dwc3_gadget_set_xfer_resource(struct dwc3 *dwc, struct dwc3_ep *dep)
598 {
599         struct dwc3_gadget_ep_cmd_params params;
600
601         memset(&params, 0x00, sizeof(params));
602
603         params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1);
604
605         return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETTRANSFRESOURCE,
606                         &params);
607 }
608
609 /**
610  * __dwc3_gadget_ep_enable - initializes a hw endpoint
611  * @dep: endpoint to be initialized
612  * @modify: if true, modify existing endpoint configuration
613  * @restore: if true, restore endpoint configuration from scratch buffer
614  *
615  * Caller should take care of locking. Execute all necessary commands to
616  * initialize a HW endpoint so it can be used by a gadget driver.
617  */
618 static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep,
619                 bool modify, bool restore)
620 {
621         const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
622         struct dwc3             *dwc = dep->dwc;
623
624         u32                     reg;
625         int                     ret;
626
627         if (!(dep->flags & DWC3_EP_ENABLED)) {
628                 ret = dwc3_gadget_start_config(dwc, dep);
629                 if (ret)
630                         return ret;
631         }
632
633         ret = dwc3_gadget_set_ep_config(dwc, dep, modify, restore);
634         if (ret)
635                 return ret;
636
637         if (!(dep->flags & DWC3_EP_ENABLED)) {
638                 struct dwc3_trb *trb_st_hw;
639                 struct dwc3_trb *trb_link;
640
641                 dep->type = usb_endpoint_type(desc);
642                 dep->flags |= DWC3_EP_ENABLED;
643                 dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
644
645                 reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
646                 reg |= DWC3_DALEPENA_EP(dep->number);
647                 dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
648
649                 init_waitqueue_head(&dep->wait_end_transfer);
650
651                 if (usb_endpoint_xfer_control(desc))
652                         goto out;
653
654                 /* Initialize the TRB ring */
655                 dep->trb_dequeue = 0;
656                 dep->trb_enqueue = 0;
657                 memset(dep->trb_pool, 0,
658                        sizeof(struct dwc3_trb) * DWC3_TRB_NUM);
659
660                 /* Link TRB. The HWO bit is never reset */
661                 trb_st_hw = &dep->trb_pool[0];
662
663                 trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
664                 trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
665                 trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
666                 trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
667                 trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
668         }
669
670         /*
671          * Issue StartTransfer here with no-op TRB so we can always rely on No
672          * Response Update Transfer command.
673          */
674         if (usb_endpoint_xfer_bulk(desc) ||
675                         usb_endpoint_xfer_int(desc)) {
676                 struct dwc3_gadget_ep_cmd_params params;
677                 struct dwc3_trb *trb;
678                 dma_addr_t trb_dma;
679                 u32 cmd;
680
681                 memset(&params, 0, sizeof(params));
682                 trb = &dep->trb_pool[0];
683                 trb_dma = dwc3_trb_dma_offset(dep, trb);
684
685                 params.param0 = upper_32_bits(trb_dma);
686                 params.param1 = lower_32_bits(trb_dma);
687
688                 cmd = DWC3_DEPCMD_STARTTRANSFER;
689
690                 ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
691                 if (ret < 0)
692                         return ret;
693
694                 dep->resource_index = dwc3_gadget_ep_get_transfer_index(dep);
695                 WARN_ON_ONCE(!dep->resource_index);
696         }
697
698 out:
699         trace_dwc3_gadget_ep_enable(dep);
700
701         return 0;
702 }
703
704 static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force);
705 static void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep)
706 {
707         struct dwc3_request             *req;
708
709         dwc3_stop_active_transfer(dep, true);
710
711         /* - giveback all requests to gadget driver */
712         while (!list_empty(&dep->started_list)) {
713                 req = next_request(&dep->started_list);
714
715                 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
716         }
717
718         while (!list_empty(&dep->pending_list)) {
719                 req = next_request(&dep->pending_list);
720
721                 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
722         }
723 }
724
725 /**
726  * __dwc3_gadget_ep_disable - disables a hw endpoint
727  * @dep: the endpoint to disable
728  *
729  * This function undoes what __dwc3_gadget_ep_enable did and also removes
730  * requests which are currently being processed by the hardware and those which
731  * are not yet scheduled.
732  *
733  * Caller should take care of locking.
734  */
735 static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
736 {
737         struct dwc3             *dwc = dep->dwc;
738         u32                     reg;
739
740         trace_dwc3_gadget_ep_disable(dep);
741
742         dwc3_remove_requests(dwc, dep);
743
744         /* make sure HW endpoint isn't stalled */
745         if (dep->flags & DWC3_EP_STALL)
746                 __dwc3_gadget_ep_set_halt(dep, 0, false);
747
748         reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
749         reg &= ~DWC3_DALEPENA_EP(dep->number);
750         dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
751
752         dep->stream_capable = false;
753         dep->type = 0;
754         dep->flags &= DWC3_EP_END_TRANSFER_PENDING;
755
756         /* Clear out the ep descriptors for non-ep0 */
757         if (dep->number > 1) {
758                 dep->endpoint.comp_desc = NULL;
759                 dep->endpoint.desc = NULL;
760         }
761
762         return 0;
763 }
764
765 /* -------------------------------------------------------------------------- */
766
767 static int dwc3_gadget_ep0_enable(struct usb_ep *ep,
768                 const struct usb_endpoint_descriptor *desc)
769 {
770         return -EINVAL;
771 }
772
773 static int dwc3_gadget_ep0_disable(struct usb_ep *ep)
774 {
775         return -EINVAL;
776 }
777
778 /* -------------------------------------------------------------------------- */
779
780 static int dwc3_gadget_ep_enable(struct usb_ep *ep,
781                 const struct usb_endpoint_descriptor *desc)
782 {
783         struct dwc3_ep                  *dep;
784         struct dwc3                     *dwc;
785         unsigned long                   flags;
786         int                             ret;
787
788         if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
789                 pr_debug("dwc3: invalid parameters\n");
790                 return -EINVAL;
791         }
792
793         if (!desc->wMaxPacketSize) {
794                 pr_debug("dwc3: missing wMaxPacketSize\n");
795                 return -EINVAL;
796         }
797
798         dep = to_dwc3_ep(ep);
799         dwc = dep->dwc;
800
801         if (dev_WARN_ONCE(dwc->dev, dep->flags & DWC3_EP_ENABLED,
802                                         "%s is already enabled\n",
803                                         dep->name))
804                 return 0;
805
806         spin_lock_irqsave(&dwc->lock, flags);
807         ret = __dwc3_gadget_ep_enable(dep, false, false);
808         spin_unlock_irqrestore(&dwc->lock, flags);
809
810         return ret;
811 }
812
813 static int dwc3_gadget_ep_disable(struct usb_ep *ep)
814 {
815         struct dwc3_ep                  *dep;
816         struct dwc3                     *dwc;
817         unsigned long                   flags;
818         int                             ret;
819
820         if (!ep) {
821                 pr_debug("dwc3: invalid parameters\n");
822                 return -EINVAL;
823         }
824
825         dep = to_dwc3_ep(ep);
826         dwc = dep->dwc;
827
828         if (dev_WARN_ONCE(dwc->dev, !(dep->flags & DWC3_EP_ENABLED),
829                                         "%s is already disabled\n",
830                                         dep->name))
831                 return 0;
832
833         spin_lock_irqsave(&dwc->lock, flags);
834         ret = __dwc3_gadget_ep_disable(dep);
835         spin_unlock_irqrestore(&dwc->lock, flags);
836
837         return ret;
838 }
839
840 static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep,
841                 gfp_t gfp_flags)
842 {
843         struct dwc3_request             *req;
844         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
845
846         req = kzalloc(sizeof(*req), gfp_flags);
847         if (!req)
848                 return NULL;
849
850         req->epnum      = dep->number;
851         req->dep        = dep;
852
853         trace_dwc3_alloc_request(req);
854
855         return &req->request;
856 }
857
858 static void dwc3_gadget_ep_free_request(struct usb_ep *ep,
859                 struct usb_request *request)
860 {
861         struct dwc3_request             *req = to_dwc3_request(request);
862
863         trace_dwc3_free_request(req);
864         kfree(req);
865 }
866
867 static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep);
868
869 static void __dwc3_prepare_one_trb(struct dwc3_ep *dep, struct dwc3_trb *trb,
870                 dma_addr_t dma, unsigned length, unsigned chain, unsigned node,
871                 unsigned stream_id, unsigned short_not_ok, unsigned no_interrupt)
872 {
873         struct dwc3             *dwc = dep->dwc;
874         struct usb_gadget       *gadget = &dwc->gadget;
875         enum usb_device_speed   speed = gadget->speed;
876
877         dwc3_ep_inc_enq(dep);
878
879         trb->size = DWC3_TRB_SIZE_LENGTH(length);
880         trb->bpl = lower_32_bits(dma);
881         trb->bph = upper_32_bits(dma);
882
883         switch (usb_endpoint_type(dep->endpoint.desc)) {
884         case USB_ENDPOINT_XFER_CONTROL:
885                 trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP;
886                 break;
887
888         case USB_ENDPOINT_XFER_ISOC:
889                 if (!node) {
890                         trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST;
891
892                         /*
893                          * USB Specification 2.0 Section 5.9.2 states that: "If
894                          * there is only a single transaction in the microframe,
895                          * only a DATA0 data packet PID is used.  If there are
896                          * two transactions per microframe, DATA1 is used for
897                          * the first transaction data packet and DATA0 is used
898                          * for the second transaction data packet.  If there are
899                          * three transactions per microframe, DATA2 is used for
900                          * the first transaction data packet, DATA1 is used for
901                          * the second, and DATA0 is used for the third."
902                          *
903                          * IOW, we should satisfy the following cases:
904                          *
905                          * 1) length <= maxpacket
906                          *      - DATA0
907                          *
908                          * 2) maxpacket < length <= (2 * maxpacket)
909                          *      - DATA1, DATA0
910                          *
911                          * 3) (2 * maxpacket) < length <= (3 * maxpacket)
912                          *      - DATA2, DATA1, DATA0
913                          */
914                         if (speed == USB_SPEED_HIGH) {
915                                 struct usb_ep *ep = &dep->endpoint;
916                                 unsigned int mult = 2;
917                                 unsigned int maxp = usb_endpoint_maxp(ep->desc);
918
919                                 if (length <= (2 * maxp))
920                                         mult--;
921
922                                 if (length <= maxp)
923                                         mult--;
924
925                                 trb->size |= DWC3_TRB_SIZE_PCM1(mult);
926                         }
927                 } else {
928                         trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS;
929                 }
930
931                 /* always enable Interrupt on Missed ISOC */
932                 trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
933                 break;
934
935         case USB_ENDPOINT_XFER_BULK:
936         case USB_ENDPOINT_XFER_INT:
937                 trb->ctrl = DWC3_TRBCTL_NORMAL;
938                 break;
939         default:
940                 /*
941                  * This is only possible with faulty memory because we
942                  * checked it already :)
943                  */
944                 dev_WARN(dwc->dev, "Unknown endpoint type %d\n",
945                                 usb_endpoint_type(dep->endpoint.desc));
946         }
947
948         /* always enable Continue on Short Packet */
949         if (usb_endpoint_dir_out(dep->endpoint.desc)) {
950                 trb->ctrl |= DWC3_TRB_CTRL_CSP;
951
952                 if (short_not_ok)
953                         trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
954         }
955
956         if ((!no_interrupt && !chain) ||
957                         (dwc3_calc_trbs_left(dep) == 0))
958                 trb->ctrl |= DWC3_TRB_CTRL_IOC;
959
960         if (chain)
961                 trb->ctrl |= DWC3_TRB_CTRL_CHN;
962
963         if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable)
964                 trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(stream_id);
965
966         trb->ctrl |= DWC3_TRB_CTRL_HWO;
967
968         trace_dwc3_prepare_trb(dep, trb);
969 }
970
971 /**
972  * dwc3_prepare_one_trb - setup one TRB from one request
973  * @dep: endpoint for which this request is prepared
974  * @req: dwc3_request pointer
975  * @chain: should this TRB be chained to the next?
976  * @node: only for isochronous endpoints. First TRB needs different type.
977  */
978 static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
979                 struct dwc3_request *req, unsigned chain, unsigned node)
980 {
981         struct dwc3_trb         *trb;
982         unsigned int            length;
983         dma_addr_t              dma;
984         unsigned                stream_id = req->request.stream_id;
985         unsigned                short_not_ok = req->request.short_not_ok;
986         unsigned                no_interrupt = req->request.no_interrupt;
987
988         if (req->request.num_sgs > 0) {
989                 length = sg_dma_len(req->start_sg);
990                 dma = sg_dma_address(req->start_sg);
991         } else {
992                 length = req->request.length;
993                 dma = req->request.dma;
994         }
995
996         trb = &dep->trb_pool[dep->trb_enqueue];
997
998         if (!req->trb) {
999                 dwc3_gadget_move_started_request(req);
1000                 req->trb = trb;
1001                 req->trb_dma = dwc3_trb_dma_offset(dep, trb);
1002         }
1003
1004         __dwc3_prepare_one_trb(dep, trb, dma, length, chain, node,
1005                         stream_id, short_not_ok, no_interrupt);
1006 }
1007
1008 /**
1009  * dwc3_ep_prev_trb - returns the previous TRB in the ring
1010  * @dep: The endpoint with the TRB ring
1011  * @index: The index of the current TRB in the ring
1012  *
1013  * Returns the TRB prior to the one pointed to by the index. If the
1014  * index is 0, we will wrap backwards, skip the link TRB, and return
1015  * the one just before that.
1016  */
1017 static struct dwc3_trb *dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index)
1018 {
1019         u8 tmp = index;
1020
1021         if (!tmp)
1022                 tmp = DWC3_TRB_NUM - 1;
1023
1024         return &dep->trb_pool[tmp - 1];
1025 }
1026
1027 static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep)
1028 {
1029         struct dwc3_trb         *tmp;
1030         u8                      trbs_left;
1031
1032         /*
1033          * If enqueue & dequeue are equal than it is either full or empty.
1034          *
1035          * One way to know for sure is if the TRB right before us has HWO bit
1036          * set or not. If it has, then we're definitely full and can't fit any
1037          * more transfers in our ring.
1038          */
1039         if (dep->trb_enqueue == dep->trb_dequeue) {
1040                 tmp = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
1041                 if (tmp->ctrl & DWC3_TRB_CTRL_HWO)
1042                         return 0;
1043
1044                 return DWC3_TRB_NUM - 1;
1045         }
1046
1047         trbs_left = dep->trb_dequeue - dep->trb_enqueue;
1048         trbs_left &= (DWC3_TRB_NUM - 1);
1049
1050         if (dep->trb_dequeue < dep->trb_enqueue)
1051                 trbs_left--;
1052
1053         return trbs_left;
1054 }
1055
1056 static void dwc3_prepare_one_trb_sg(struct dwc3_ep *dep,
1057                 struct dwc3_request *req)
1058 {
1059         struct scatterlist *sg = req->start_sg;
1060         struct scatterlist *s;
1061         int             i;
1062
1063         unsigned int remaining = req->request.num_mapped_sgs
1064                 - req->num_queued_sgs;
1065
1066         for_each_sg(sg, s, remaining, i) {
1067                 unsigned int length = req->request.length;
1068                 unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1069                 unsigned int rem = length % maxp;
1070                 unsigned chain = true;
1071
1072                 if (sg_is_last(s))
1073                         chain = false;
1074
1075                 if (rem && usb_endpoint_dir_out(dep->endpoint.desc) && !chain) {
1076                         struct dwc3     *dwc = dep->dwc;
1077                         struct dwc3_trb *trb;
1078
1079                         req->unaligned = true;
1080
1081                         /* prepare normal TRB */
1082                         dwc3_prepare_one_trb(dep, req, true, i);
1083
1084                         /* Now prepare one extra TRB to align transfer size */
1085                         trb = &dep->trb_pool[dep->trb_enqueue];
1086                         __dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr,
1087                                         maxp - rem, false, 0,
1088                                         req->request.stream_id,
1089                                         req->request.short_not_ok,
1090                                         req->request.no_interrupt);
1091                 } else {
1092                         dwc3_prepare_one_trb(dep, req, chain, i);
1093                 }
1094
1095                 /*
1096                  * There can be a situation where all sgs in sglist are not
1097                  * queued because of insufficient trb number. To handle this
1098                  * case, update start_sg to next sg to be queued, so that
1099                  * we have free trbs we can continue queuing from where we
1100                  * previously stopped
1101                  */
1102                 if (chain)
1103                         req->start_sg = sg_next(s);
1104
1105                 req->num_queued_sgs++;
1106
1107                 if (!dwc3_calc_trbs_left(dep))
1108                         break;
1109         }
1110 }
1111
1112 static void dwc3_prepare_one_trb_linear(struct dwc3_ep *dep,
1113                 struct dwc3_request *req)
1114 {
1115         unsigned int length = req->request.length;
1116         unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1117         unsigned int rem = length % maxp;
1118
1119         if (rem && usb_endpoint_dir_out(dep->endpoint.desc)) {
1120                 struct dwc3     *dwc = dep->dwc;
1121                 struct dwc3_trb *trb;
1122
1123                 req->unaligned = true;
1124
1125                 /* prepare normal TRB */
1126                 dwc3_prepare_one_trb(dep, req, true, 0);
1127
1128                 /* Now prepare one extra TRB to align transfer size */
1129                 trb = &dep->trb_pool[dep->trb_enqueue];
1130                 __dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr, maxp - rem,
1131                                 false, 0, req->request.stream_id,
1132                                 req->request.short_not_ok,
1133                                 req->request.no_interrupt);
1134         } else if (req->request.zero && req->request.length &&
1135                    (IS_ALIGNED(req->request.length,dep->endpoint.maxpacket))) {
1136                 struct dwc3     *dwc = dep->dwc;
1137                 struct dwc3_trb *trb;
1138
1139                 req->zero = true;
1140
1141                 /* prepare normal TRB */
1142                 dwc3_prepare_one_trb(dep, req, true, 0);
1143
1144                 /* Now prepare one extra TRB to handle ZLP */
1145                 trb = &dep->trb_pool[dep->trb_enqueue];
1146                 __dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr, 0,
1147                                 false, 0, req->request.stream_id,
1148                                 req->request.short_not_ok,
1149                                 req->request.no_interrupt);
1150         } else {
1151                 dwc3_prepare_one_trb(dep, req, false, 0);
1152         }
1153 }
1154
1155 /*
1156  * dwc3_prepare_trbs - setup TRBs from requests
1157  * @dep: endpoint for which requests are being prepared
1158  *
1159  * The function goes through the requests list and sets up TRBs for the
1160  * transfers. The function returns once there are no more TRBs available or
1161  * it runs out of requests.
1162  */
1163 static void dwc3_prepare_trbs(struct dwc3_ep *dep)
1164 {
1165         struct dwc3_request     *req, *n;
1166
1167         BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
1168
1169         /*
1170          * We can get in a situation where there's a request in the started list
1171          * but there weren't enough TRBs to fully kick it in the first time
1172          * around, so it has been waiting for more TRBs to be freed up.
1173          *
1174          * In that case, we should check if we have a request with pending_sgs
1175          * in the started list and prepare TRBs for that request first,
1176          * otherwise we will prepare TRBs completely out of order and that will
1177          * break things.
1178          */
1179         list_for_each_entry(req, &dep->started_list, list) {
1180                 if (req->num_pending_sgs > 0)
1181                         dwc3_prepare_one_trb_sg(dep, req);
1182
1183                 if (!dwc3_calc_trbs_left(dep))
1184                         return;
1185         }
1186
1187         list_for_each_entry_safe(req, n, &dep->pending_list, list) {
1188                 struct dwc3     *dwc = dep->dwc;
1189                 int             ret;
1190
1191                 ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request,
1192                                                     dep->direction);
1193                 if (ret)
1194                         return;
1195
1196                 req->sg                 = req->request.sg;
1197                 req->start_sg           = req->sg;
1198                 req->num_queued_sgs     = 0;
1199                 req->num_pending_sgs    = req->request.num_mapped_sgs;
1200
1201                 if (req->num_pending_sgs > 0)
1202                         dwc3_prepare_one_trb_sg(dep, req);
1203                 else
1204                         dwc3_prepare_one_trb_linear(dep, req);
1205
1206                 if (!dwc3_calc_trbs_left(dep))
1207                         return;
1208         }
1209 }
1210
1211 static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep)
1212 {
1213         struct dwc3_gadget_ep_cmd_params params;
1214         struct dwc3_request             *req;
1215         int                             starting;
1216         int                             ret;
1217         u32                             cmd;
1218
1219         if (!dwc3_calc_trbs_left(dep))
1220                 return 0;
1221
1222         starting = !(dep->flags & DWC3_EP_TRANSFER_STARTED);
1223
1224         dwc3_prepare_trbs(dep);
1225         req = next_request(&dep->started_list);
1226         if (!req) {
1227                 dep->flags |= DWC3_EP_PENDING_REQUEST;
1228                 return 0;
1229         }
1230
1231         memset(&params, 0, sizeof(params));
1232
1233         if (starting) {
1234                 params.param0 = upper_32_bits(req->trb_dma);
1235                 params.param1 = lower_32_bits(req->trb_dma);
1236                 cmd = DWC3_DEPCMD_STARTTRANSFER;
1237
1238                 if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
1239                         cmd |= DWC3_DEPCMD_PARAM(dep->frame_number);
1240         } else {
1241                 cmd = DWC3_DEPCMD_UPDATETRANSFER |
1242                         DWC3_DEPCMD_PARAM(dep->resource_index);
1243         }
1244
1245         ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1246         if (ret < 0) {
1247                 /*
1248                  * FIXME we need to iterate over the list of requests
1249                  * here and stop, unmap, free and del each of the linked
1250                  * requests instead of what we do now.
1251                  */
1252                 if (req->trb)
1253                         memset(req->trb, 0, sizeof(struct dwc3_trb));
1254                 dwc3_gadget_del_and_unmap_request(dep, req, ret);
1255                 return ret;
1256         }
1257
1258         if (starting) {
1259                 dep->resource_index = dwc3_gadget_ep_get_transfer_index(dep);
1260                 WARN_ON_ONCE(!dep->resource_index);
1261         }
1262
1263         return 0;
1264 }
1265
1266 static int __dwc3_gadget_get_frame(struct dwc3 *dwc)
1267 {
1268         u32                     reg;
1269
1270         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1271         return DWC3_DSTS_SOFFN(reg);
1272 }
1273
1274 static void __dwc3_gadget_start_isoc(struct dwc3_ep *dep)
1275 {
1276         if (list_empty(&dep->pending_list)) {
1277                 dev_info(dep->dwc->dev, "%s: ran out of requests\n",
1278                                 dep->name);
1279                 dep->flags |= DWC3_EP_PENDING_REQUEST;
1280                 return;
1281         }
1282
1283         /*
1284          * Schedule the first trb for one interval in the future or at
1285          * least 4 microframes.
1286          */
1287         dep->frame_number += max_t(u32, 4, dep->interval);
1288         __dwc3_gadget_kick_transfer(dep);
1289 }
1290
1291 static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
1292 {
1293         struct dwc3             *dwc = dep->dwc;
1294
1295         if (!dep->endpoint.desc) {
1296                 dev_err(dwc->dev, "%s: can't queue to disabled endpoint\n",
1297                                 dep->name);
1298                 return -ESHUTDOWN;
1299         }
1300
1301         if (WARN(req->dep != dep, "request %pK belongs to '%s'\n",
1302                                 &req->request, req->dep->name))
1303                 return -EINVAL;
1304
1305         pm_runtime_get(dwc->dev);
1306
1307         req->request.actual     = 0;
1308         req->request.status     = -EINPROGRESS;
1309         req->direction          = dep->direction;
1310         req->epnum              = dep->number;
1311
1312         trace_dwc3_ep_queue(req);
1313
1314         list_add_tail(&req->list, &dep->pending_list);
1315
1316         /*
1317          * NOTICE: Isochronous endpoints should NEVER be prestarted. We must
1318          * wait for a XferNotReady event so we will know what's the current
1319          * (micro-)frame number.
1320          *
1321          * Without this trick, we are very, very likely gonna get Bus Expiry
1322          * errors which will force us issue EndTransfer command.
1323          */
1324         if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1325                 if (!(dep->flags & DWC3_EP_PENDING_REQUEST) &&
1326                                 !(dep->flags & DWC3_EP_TRANSFER_STARTED))
1327                         return 0;
1328
1329                 if ((dep->flags & DWC3_EP_PENDING_REQUEST)) {
1330                         if (!(dep->flags & DWC3_EP_TRANSFER_STARTED)) {
1331                                 __dwc3_gadget_start_isoc(dep);
1332                                 return 0;
1333                         }
1334                 }
1335         }
1336
1337         return __dwc3_gadget_kick_transfer(dep);
1338 }
1339
1340 static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
1341         gfp_t gfp_flags)
1342 {
1343         struct dwc3_request             *req = to_dwc3_request(request);
1344         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1345         struct dwc3                     *dwc = dep->dwc;
1346
1347         unsigned long                   flags;
1348
1349         int                             ret;
1350
1351         spin_lock_irqsave(&dwc->lock, flags);
1352         ret = __dwc3_gadget_ep_queue(dep, req);
1353         spin_unlock_irqrestore(&dwc->lock, flags);
1354
1355         return ret;
1356 }
1357
1358 static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
1359                 struct usb_request *request)
1360 {
1361         struct dwc3_request             *req = to_dwc3_request(request);
1362         struct dwc3_request             *r = NULL;
1363
1364         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1365         struct dwc3                     *dwc = dep->dwc;
1366
1367         unsigned long                   flags;
1368         int                             ret = 0;
1369
1370         trace_dwc3_ep_dequeue(req);
1371
1372         spin_lock_irqsave(&dwc->lock, flags);
1373
1374         list_for_each_entry(r, &dep->pending_list, list) {
1375                 if (r == req)
1376                         break;
1377         }
1378
1379         if (r != req) {
1380                 list_for_each_entry(r, &dep->started_list, list) {
1381                         if (r == req)
1382                                 break;
1383                 }
1384                 if (r == req) {
1385                         /* wait until it is processed */
1386                         dwc3_stop_active_transfer(dep, true);
1387
1388                         /*
1389                          * If request was already started, this means we had to
1390                          * stop the transfer. With that we also need to ignore
1391                          * all TRBs used by the request, however TRBs can only
1392                          * be modified after completion of END_TRANSFER
1393                          * command. So what we do here is that we wait for
1394                          * END_TRANSFER completion and only after that, we jump
1395                          * over TRBs by clearing HWO and incrementing dequeue
1396                          * pointer.
1397                          *
1398                          * Note that we have 2 possible types of transfers here:
1399                          *
1400                          * i) Linear buffer request
1401                          * ii) SG-list based request
1402                          *
1403                          * SG-list based requests will have r->num_pending_sgs
1404                          * set to a valid number (> 0). Linear requests,
1405                          * normally use a single TRB.
1406                          *
1407                          * For each of these two cases, if r->unaligned flag is
1408                          * set, one extra TRB has been used to align transfer
1409                          * size to wMaxPacketSize.
1410                          *
1411                          * All of these cases need to be taken into
1412                          * consideration so we don't mess up our TRB ring
1413                          * pointers.
1414                          */
1415                         wait_event_lock_irq(dep->wait_end_transfer,
1416                                         !(dep->flags & DWC3_EP_END_TRANSFER_PENDING),
1417                                         dwc->lock);
1418
1419                         if (!r->trb)
1420                                 goto out1;
1421
1422                         if (r->num_pending_sgs) {
1423                                 struct dwc3_trb *trb;
1424                                 int i = 0;
1425
1426                                 for (i = 0; i < r->num_pending_sgs; i++) {
1427                                         trb = r->trb + i;
1428                                         trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1429                                         dwc3_ep_inc_deq(dep);
1430                                 }
1431
1432                                 if (r->unaligned || r->zero) {
1433                                         trb = r->trb + r->num_pending_sgs + 1;
1434                                         trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1435                                         dwc3_ep_inc_deq(dep);
1436                                 }
1437                         } else {
1438                                 struct dwc3_trb *trb = r->trb;
1439
1440                                 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1441                                 dwc3_ep_inc_deq(dep);
1442
1443                                 if (r->unaligned || r->zero) {
1444                                         trb = r->trb + 1;
1445                                         trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1446                                         dwc3_ep_inc_deq(dep);
1447                                 }
1448                         }
1449                         goto out1;
1450                 }
1451                 dev_err(dwc->dev, "request %pK was not queued to %s\n",
1452                                 request, ep->name);
1453                 ret = -EINVAL;
1454                 goto out0;
1455         }
1456
1457 out1:
1458         /* giveback the request */
1459
1460         dwc3_gadget_giveback(dep, req, -ECONNRESET);
1461
1462 out0:
1463         spin_unlock_irqrestore(&dwc->lock, flags);
1464
1465         return ret;
1466 }
1467
1468 int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
1469 {
1470         struct dwc3_gadget_ep_cmd_params        params;
1471         struct dwc3                             *dwc = dep->dwc;
1472         int                                     ret;
1473
1474         if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1475                 dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
1476                 return -EINVAL;
1477         }
1478
1479         memset(&params, 0x00, sizeof(params));
1480
1481         if (value) {
1482                 struct dwc3_trb *trb;
1483
1484                 unsigned transfer_in_flight;
1485                 unsigned started;
1486
1487                 if (dep->flags & DWC3_EP_STALL)
1488                         return 0;
1489
1490                 if (dep->number > 1)
1491                         trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
1492                 else
1493                         trb = &dwc->ep0_trb[dep->trb_enqueue];
1494
1495                 transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO;
1496                 started = !list_empty(&dep->started_list);
1497
1498                 if (!protocol && ((dep->direction && transfer_in_flight) ||
1499                                 (!dep->direction && started))) {
1500                         return -EAGAIN;
1501                 }
1502
1503                 ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL,
1504                                 &params);
1505                 if (ret)
1506                         dev_err(dwc->dev, "failed to set STALL on %s\n",
1507                                         dep->name);
1508                 else
1509                         dep->flags |= DWC3_EP_STALL;
1510         } else {
1511                 if (!(dep->flags & DWC3_EP_STALL))
1512                         return 0;
1513
1514                 ret = dwc3_send_clear_stall_ep_cmd(dep);
1515                 if (ret)
1516                         dev_err(dwc->dev, "failed to clear STALL on %s\n",
1517                                         dep->name);
1518                 else
1519                         dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
1520         }
1521
1522         return ret;
1523 }
1524
1525 static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
1526 {
1527         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1528         struct dwc3                     *dwc = dep->dwc;
1529
1530         unsigned long                   flags;
1531
1532         int                             ret;
1533
1534         spin_lock_irqsave(&dwc->lock, flags);
1535         ret = __dwc3_gadget_ep_set_halt(dep, value, false);
1536         spin_unlock_irqrestore(&dwc->lock, flags);
1537
1538         return ret;
1539 }
1540
1541 static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
1542 {
1543         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1544         struct dwc3                     *dwc = dep->dwc;
1545         unsigned long                   flags;
1546         int                             ret;
1547
1548         spin_lock_irqsave(&dwc->lock, flags);
1549         dep->flags |= DWC3_EP_WEDGE;
1550
1551         if (dep->number == 0 || dep->number == 1)
1552                 ret = __dwc3_gadget_ep0_set_halt(ep, 1);
1553         else
1554                 ret = __dwc3_gadget_ep_set_halt(dep, 1, false);
1555         spin_unlock_irqrestore(&dwc->lock, flags);
1556
1557         return ret;
1558 }
1559
1560 /* -------------------------------------------------------------------------- */
1561
1562 static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
1563         .bLength        = USB_DT_ENDPOINT_SIZE,
1564         .bDescriptorType = USB_DT_ENDPOINT,
1565         .bmAttributes   = USB_ENDPOINT_XFER_CONTROL,
1566 };
1567
1568 static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
1569         .enable         = dwc3_gadget_ep0_enable,
1570         .disable        = dwc3_gadget_ep0_disable,
1571         .alloc_request  = dwc3_gadget_ep_alloc_request,
1572         .free_request   = dwc3_gadget_ep_free_request,
1573         .queue          = dwc3_gadget_ep0_queue,
1574         .dequeue        = dwc3_gadget_ep_dequeue,
1575         .set_halt       = dwc3_gadget_ep0_set_halt,
1576         .set_wedge      = dwc3_gadget_ep_set_wedge,
1577 };
1578
1579 static const struct usb_ep_ops dwc3_gadget_ep_ops = {
1580         .enable         = dwc3_gadget_ep_enable,
1581         .disable        = dwc3_gadget_ep_disable,
1582         .alloc_request  = dwc3_gadget_ep_alloc_request,
1583         .free_request   = dwc3_gadget_ep_free_request,
1584         .queue          = dwc3_gadget_ep_queue,
1585         .dequeue        = dwc3_gadget_ep_dequeue,
1586         .set_halt       = dwc3_gadget_ep_set_halt,
1587         .set_wedge      = dwc3_gadget_ep_set_wedge,
1588 };
1589
1590 /* -------------------------------------------------------------------------- */
1591
1592 static int dwc3_gadget_get_frame(struct usb_gadget *g)
1593 {
1594         struct dwc3             *dwc = gadget_to_dwc(g);
1595
1596         return __dwc3_gadget_get_frame(dwc);
1597 }
1598
1599 static int __dwc3_gadget_wakeup(struct dwc3 *dwc)
1600 {
1601         int                     retries;
1602
1603         int                     ret;
1604         u32                     reg;
1605
1606         u8                      link_state;
1607         u8                      speed;
1608
1609         /*
1610          * According to the Databook Remote wakeup request should
1611          * be issued only when the device is in early suspend state.
1612          *
1613          * We can check that via USB Link State bits in DSTS register.
1614          */
1615         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1616
1617         speed = reg & DWC3_DSTS_CONNECTSPD;
1618         if ((speed == DWC3_DSTS_SUPERSPEED) ||
1619             (speed == DWC3_DSTS_SUPERSPEED_PLUS))
1620                 return 0;
1621
1622         link_state = DWC3_DSTS_USBLNKST(reg);
1623
1624         switch (link_state) {
1625         case DWC3_LINK_STATE_RX_DET:    /* in HS, means Early Suspend */
1626         case DWC3_LINK_STATE_U3:        /* in HS, means SUSPEND */
1627                 break;
1628         default:
1629                 return -EINVAL;
1630         }
1631
1632         ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
1633         if (ret < 0) {
1634                 dev_err(dwc->dev, "failed to put link in Recovery\n");
1635                 return ret;
1636         }
1637
1638         /* Recent versions do this automatically */
1639         if (dwc->revision < DWC3_REVISION_194A) {
1640                 /* write zeroes to Link Change Request */
1641                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1642                 reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
1643                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1644         }
1645
1646         /* poll until Link State changes to ON */
1647         retries = 20000;
1648
1649         while (retries--) {
1650                 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1651
1652                 /* in HS, means ON */
1653                 if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
1654                         break;
1655         }
1656
1657         if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
1658                 dev_err(dwc->dev, "failed to send remote wakeup\n");
1659                 return -EINVAL;
1660         }
1661
1662         return 0;
1663 }
1664
1665 static int dwc3_gadget_wakeup(struct usb_gadget *g)
1666 {
1667         struct dwc3             *dwc = gadget_to_dwc(g);
1668         unsigned long           flags;
1669         int                     ret;
1670
1671         spin_lock_irqsave(&dwc->lock, flags);
1672         ret = __dwc3_gadget_wakeup(dwc);
1673         spin_unlock_irqrestore(&dwc->lock, flags);
1674
1675         return ret;
1676 }
1677
1678 static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
1679                 int is_selfpowered)
1680 {
1681         struct dwc3             *dwc = gadget_to_dwc(g);
1682         unsigned long           flags;
1683
1684         spin_lock_irqsave(&dwc->lock, flags);
1685         g->is_selfpowered = !!is_selfpowered;
1686         spin_unlock_irqrestore(&dwc->lock, flags);
1687
1688         return 0;
1689 }
1690
1691 static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on, int suspend)
1692 {
1693         u32                     reg;
1694         u32                     timeout = 500;
1695
1696         if (pm_runtime_suspended(dwc->dev))
1697                 return 0;
1698
1699         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1700         if (is_on) {
1701                 if (dwc->revision <= DWC3_REVISION_187A) {
1702                         reg &= ~DWC3_DCTL_TRGTULST_MASK;
1703                         reg |= DWC3_DCTL_TRGTULST_RX_DET;
1704                 }
1705
1706                 if (dwc->revision >= DWC3_REVISION_194A)
1707                         reg &= ~DWC3_DCTL_KEEP_CONNECT;
1708                 reg |= DWC3_DCTL_RUN_STOP;
1709
1710                 if (dwc->has_hibernation)
1711                         reg |= DWC3_DCTL_KEEP_CONNECT;
1712
1713                 dwc->pullups_connected = true;
1714         } else {
1715                 reg &= ~DWC3_DCTL_RUN_STOP;
1716
1717                 if (dwc->has_hibernation && !suspend)
1718                         reg &= ~DWC3_DCTL_KEEP_CONNECT;
1719
1720                 dwc->pullups_connected = false;
1721         }
1722
1723         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1724
1725         do {
1726                 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1727                 reg &= DWC3_DSTS_DEVCTRLHLT;
1728         } while (--timeout && !(!is_on ^ !reg));
1729
1730         if (!timeout)
1731                 return -ETIMEDOUT;
1732
1733         return 0;
1734 }
1735
1736 static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
1737 {
1738         struct dwc3             *dwc = gadget_to_dwc(g);
1739         unsigned long           flags;
1740         int                     ret;
1741
1742         is_on = !!is_on;
1743
1744         /*
1745          * Per databook, when we want to stop the gadget, if a control transfer
1746          * is still in process, complete it and get the core into setup phase.
1747          */
1748         if (!is_on && dwc->ep0state != EP0_SETUP_PHASE) {
1749                 reinit_completion(&dwc->ep0_in_setup);
1750
1751                 ret = wait_for_completion_timeout(&dwc->ep0_in_setup,
1752                                 msecs_to_jiffies(DWC3_PULL_UP_TIMEOUT));
1753                 if (ret == 0) {
1754                         dev_err(dwc->dev, "timed out waiting for SETUP phase\n");
1755                         return -ETIMEDOUT;
1756                 }
1757         }
1758
1759         spin_lock_irqsave(&dwc->lock, flags);
1760         ret = dwc3_gadget_run_stop(dwc, is_on, false);
1761         spin_unlock_irqrestore(&dwc->lock, flags);
1762
1763         return ret;
1764 }
1765
1766 static void dwc3_gadget_enable_irq(struct dwc3 *dwc)
1767 {
1768         u32                     reg;
1769
1770         /* Enable all but Start and End of Frame IRQs */
1771         reg = (DWC3_DEVTEN_VNDRDEVTSTRCVEDEN |
1772                         DWC3_DEVTEN_EVNTOVERFLOWEN |
1773                         DWC3_DEVTEN_CMDCMPLTEN |
1774                         DWC3_DEVTEN_ERRTICERREN |
1775                         DWC3_DEVTEN_WKUPEVTEN |
1776                         DWC3_DEVTEN_CONNECTDONEEN |
1777                         DWC3_DEVTEN_USBRSTEN |
1778                         DWC3_DEVTEN_DISCONNEVTEN);
1779
1780         if (dwc->revision < DWC3_REVISION_250A)
1781                 reg |= DWC3_DEVTEN_ULSTCNGEN;
1782
1783         dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
1784 }
1785
1786 static void dwc3_gadget_disable_irq(struct dwc3 *dwc)
1787 {
1788         /* mask all interrupts */
1789         dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
1790 }
1791
1792 static irqreturn_t dwc3_interrupt(int irq, void *_dwc);
1793 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc);
1794
1795 /**
1796  * dwc3_gadget_setup_nump - calculate and initialize NUMP field of %DWC3_DCFG
1797  * @dwc: pointer to our context structure
1798  *
1799  * The following looks like complex but it's actually very simple. In order to
1800  * calculate the number of packets we can burst at once on OUT transfers, we're
1801  * gonna use RxFIFO size.
1802  *
1803  * To calculate RxFIFO size we need two numbers:
1804  * MDWIDTH = size, in bits, of the internal memory bus
1805  * RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)
1806  *
1807  * Given these two numbers, the formula is simple:
1808  *
1809  * RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;
1810  *
1811  * 24 bytes is for 3x SETUP packets
1812  * 16 bytes is a clock domain crossing tolerance
1813  *
1814  * Given RxFIFO Size, NUMP = RxFIFOSize / 1024;
1815  */
1816 static void dwc3_gadget_setup_nump(struct dwc3 *dwc)
1817 {
1818         u32 ram2_depth;
1819         u32 mdwidth;
1820         u32 nump;
1821         u32 reg;
1822
1823         ram2_depth = DWC3_GHWPARAMS7_RAM2_DEPTH(dwc->hwparams.hwparams7);
1824         mdwidth = DWC3_GHWPARAMS0_MDWIDTH(dwc->hwparams.hwparams0);
1825
1826         nump = ((ram2_depth * mdwidth / 8) - 24 - 16) / 1024;
1827         nump = min_t(u32, nump, 16);
1828
1829         /* update NumP */
1830         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
1831         reg &= ~DWC3_DCFG_NUMP_MASK;
1832         reg |= nump << DWC3_DCFG_NUMP_SHIFT;
1833         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
1834 }
1835
1836 static int __dwc3_gadget_start(struct dwc3 *dwc)
1837 {
1838         struct dwc3_ep          *dep;
1839         int                     ret = 0;
1840         u32                     reg;
1841
1842         /*
1843          * Use IMOD if enabled via dwc->imod_interval. Otherwise, if
1844          * the core supports IMOD, disable it.
1845          */
1846         if (dwc->imod_interval) {
1847                 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
1848                 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
1849         } else if (dwc3_has_imod(dwc)) {
1850                 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), 0);
1851         }
1852
1853         /*
1854          * We are telling dwc3 that we want to use DCFG.NUMP as ACK TP's NUMP
1855          * field instead of letting dwc3 itself calculate that automatically.
1856          *
1857          * This way, we maximize the chances that we'll be able to get several
1858          * bursts of data without going through any sort of endpoint throttling.
1859          */
1860         reg = dwc3_readl(dwc->regs, DWC3_GRXTHRCFG);
1861         if (dwc3_is_usb31(dwc))
1862                 reg &= ~DWC31_GRXTHRCFG_PKTCNTSEL;
1863         else
1864                 reg &= ~DWC3_GRXTHRCFG_PKTCNTSEL;
1865
1866         dwc3_writel(dwc->regs, DWC3_GRXTHRCFG, reg);
1867
1868         dwc3_gadget_setup_nump(dwc);
1869
1870         /* Start with SuperSpeed Default */
1871         dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
1872
1873         dep = dwc->eps[0];
1874         ret = __dwc3_gadget_ep_enable(dep, false, false);
1875         if (ret) {
1876                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
1877                 goto err0;
1878         }
1879
1880         dep = dwc->eps[1];
1881         ret = __dwc3_gadget_ep_enable(dep, false, false);
1882         if (ret) {
1883                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
1884                 goto err1;
1885         }
1886
1887         /* begin to receive SETUP packets */
1888         dwc->ep0state = EP0_SETUP_PHASE;
1889         dwc3_ep0_out_start(dwc);
1890
1891         dwc3_gadget_enable_irq(dwc);
1892
1893         return 0;
1894
1895 err1:
1896         __dwc3_gadget_ep_disable(dwc->eps[0]);
1897
1898 err0:
1899         return ret;
1900 }
1901
1902 static int dwc3_gadget_start(struct usb_gadget *g,
1903                 struct usb_gadget_driver *driver)
1904 {
1905         struct dwc3             *dwc = gadget_to_dwc(g);
1906         unsigned long           flags;
1907         int                     ret = 0;
1908         int                     irq;
1909
1910         irq = dwc->irq_gadget;
1911         ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt,
1912                         IRQF_SHARED, "dwc3", dwc->ev_buf);
1913         if (ret) {
1914                 dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
1915                                 irq, ret);
1916                 goto err0;
1917         }
1918
1919         spin_lock_irqsave(&dwc->lock, flags);
1920         if (dwc->gadget_driver) {
1921                 dev_err(dwc->dev, "%s is already bound to %s\n",
1922                                 dwc->gadget.name,
1923                                 dwc->gadget_driver->driver.name);
1924                 ret = -EBUSY;
1925                 goto err1;
1926         }
1927
1928         dwc->gadget_driver      = driver;
1929
1930         if (pm_runtime_active(dwc->dev))
1931                 __dwc3_gadget_start(dwc);
1932
1933         spin_unlock_irqrestore(&dwc->lock, flags);
1934
1935         return 0;
1936
1937 err1:
1938         spin_unlock_irqrestore(&dwc->lock, flags);
1939         free_irq(irq, dwc);
1940
1941 err0:
1942         return ret;
1943 }
1944
1945 static void __dwc3_gadget_stop(struct dwc3 *dwc)
1946 {
1947         dwc3_gadget_disable_irq(dwc);
1948         __dwc3_gadget_ep_disable(dwc->eps[0]);
1949         __dwc3_gadget_ep_disable(dwc->eps[1]);
1950 }
1951
1952 static int dwc3_gadget_stop(struct usb_gadget *g)
1953 {
1954         struct dwc3             *dwc = gadget_to_dwc(g);
1955         unsigned long           flags;
1956         int                     epnum;
1957         u32                     tmo_eps = 0;
1958
1959         spin_lock_irqsave(&dwc->lock, flags);
1960
1961         if (pm_runtime_suspended(dwc->dev))
1962                 goto out;
1963
1964         __dwc3_gadget_stop(dwc);
1965
1966         for (epnum = 2; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
1967                 struct dwc3_ep  *dep = dwc->eps[epnum];
1968                 int ret;
1969
1970                 if (!dep)
1971                         continue;
1972
1973                 if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
1974                         continue;
1975
1976                 ret = wait_event_interruptible_lock_irq_timeout(dep->wait_end_transfer,
1977                             !(dep->flags & DWC3_EP_END_TRANSFER_PENDING),
1978                             dwc->lock, msecs_to_jiffies(5));
1979
1980                 if (ret <= 0) {
1981                         /* Timed out or interrupted! There's nothing much
1982                          * we can do so we just log here and print which
1983                          * endpoints timed out at the end.
1984                          */
1985                         tmo_eps |= 1 << epnum;
1986                         dep->flags &= DWC3_EP_END_TRANSFER_PENDING;
1987                 }
1988         }
1989
1990         if (tmo_eps) {
1991                 dev_err(dwc->dev,
1992                         "end transfer timed out on endpoints 0x%x [bitmap]\n",
1993                         tmo_eps);
1994         }
1995
1996 out:
1997         dwc->gadget_driver      = NULL;
1998         spin_unlock_irqrestore(&dwc->lock, flags);
1999
2000         free_irq(dwc->irq_gadget, dwc->ev_buf);
2001
2002         return 0;
2003 }
2004
2005 static void dwc3_gadget_set_speed(struct usb_gadget *g,
2006                                   enum usb_device_speed speed)
2007 {
2008         struct dwc3             *dwc = gadget_to_dwc(g);
2009         unsigned long           flags;
2010         u32                     reg;
2011
2012         spin_lock_irqsave(&dwc->lock, flags);
2013         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2014         reg &= ~(DWC3_DCFG_SPEED_MASK);
2015
2016         /*
2017          * WORKAROUND: DWC3 revision < 2.20a have an issue
2018          * which would cause metastability state on Run/Stop
2019          * bit if we try to force the IP to USB2-only mode.
2020          *
2021          * Because of that, we cannot configure the IP to any
2022          * speed other than the SuperSpeed
2023          *
2024          * Refers to:
2025          *
2026          * STAR#9000525659: Clock Domain Crossing on DCTL in
2027          * USB 2.0 Mode
2028          */
2029         if (dwc->revision < DWC3_REVISION_220A &&
2030             !dwc->dis_metastability_quirk) {
2031                 reg |= DWC3_DCFG_SUPERSPEED;
2032         } else {
2033                 switch (speed) {
2034                 case USB_SPEED_LOW:
2035                         reg |= DWC3_DCFG_LOWSPEED;
2036                         break;
2037                 case USB_SPEED_FULL:
2038                         reg |= DWC3_DCFG_FULLSPEED;
2039                         break;
2040                 case USB_SPEED_HIGH:
2041                         reg |= DWC3_DCFG_HIGHSPEED;
2042                         break;
2043                 case USB_SPEED_SUPER:
2044                         reg |= DWC3_DCFG_SUPERSPEED;
2045                         break;
2046                 case USB_SPEED_SUPER_PLUS:
2047                         if (dwc3_is_usb31(dwc))
2048                                 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2049                         else
2050                                 reg |= DWC3_DCFG_SUPERSPEED;
2051                         break;
2052                 default:
2053                         dev_err(dwc->dev, "invalid speed (%d)\n", speed);
2054
2055                         if (dwc->revision & DWC3_REVISION_IS_DWC31)
2056                                 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2057                         else
2058                                 reg |= DWC3_DCFG_SUPERSPEED;
2059                 }
2060         }
2061         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2062
2063         spin_unlock_irqrestore(&dwc->lock, flags);
2064 }
2065
2066 static const struct usb_gadget_ops dwc3_gadget_ops = {
2067         .get_frame              = dwc3_gadget_get_frame,
2068         .wakeup                 = dwc3_gadget_wakeup,
2069         .set_selfpowered        = dwc3_gadget_set_selfpowered,
2070         .pullup                 = dwc3_gadget_pullup,
2071         .udc_start              = dwc3_gadget_start,
2072         .udc_stop               = dwc3_gadget_stop,
2073         .udc_set_speed          = dwc3_gadget_set_speed,
2074 };
2075
2076 /* -------------------------------------------------------------------------- */
2077
2078 static int dwc3_gadget_init_endpoints(struct dwc3 *dwc, u8 total)
2079 {
2080         struct dwc3_ep                  *dep;
2081         u8                              epnum;
2082
2083         INIT_LIST_HEAD(&dwc->gadget.ep_list);
2084
2085         for (epnum = 0; epnum < total; epnum++) {
2086                 bool                    direction = epnum & 1;
2087                 u8                      num = epnum >> 1;
2088
2089                 dep = kzalloc(sizeof(*dep), GFP_KERNEL);
2090                 if (!dep)
2091                         return -ENOMEM;
2092
2093                 dep->dwc = dwc;
2094                 dep->number = epnum;
2095                 dep->direction = direction;
2096                 dep->regs = dwc->regs + DWC3_DEP_BASE(epnum);
2097                 dwc->eps[epnum] = dep;
2098
2099                 snprintf(dep->name, sizeof(dep->name), "ep%u%s", num,
2100                                 direction ? "in" : "out");
2101
2102                 dep->endpoint.name = dep->name;
2103
2104                 if (!(dep->number > 1)) {
2105                         dep->endpoint.desc = &dwc3_gadget_ep0_desc;
2106                         dep->endpoint.comp_desc = NULL;
2107                 }
2108
2109                 spin_lock_init(&dep->lock);
2110
2111                 if (num == 0) {
2112                         usb_ep_set_maxpacket_limit(&dep->endpoint, 512);
2113                         dep->endpoint.maxburst = 1;
2114                         dep->endpoint.ops = &dwc3_gadget_ep0_ops;
2115                         if (!direction)
2116                                 dwc->gadget.ep0 = &dep->endpoint;
2117                 } else if (direction) {
2118                         int mdwidth;
2119                         int kbytes;
2120                         int size;
2121                         int ret;
2122
2123                         mdwidth = DWC3_MDWIDTH(dwc->hwparams.hwparams0);
2124                         /* MDWIDTH is represented in bits, we need it in bytes */
2125                         mdwidth /= 8;
2126
2127                         size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(num));
2128                         if (dwc3_is_usb31(dwc))
2129                                 size = DWC31_GTXFIFOSIZ_TXFDEF(size);
2130                         else
2131                                 size = DWC3_GTXFIFOSIZ_TXFDEF(size);
2132
2133                         /* FIFO Depth is in MDWDITH bytes. Multiply */
2134                         size *= mdwidth;
2135
2136                         kbytes = size / 1024;
2137                         if (kbytes == 0)
2138                                 kbytes = 1;
2139
2140                         /*
2141                          * FIFO sizes account an extra MDWIDTH * (kbytes + 1) bytes for
2142                          * internal overhead. We don't really know how these are used,
2143                          * but documentation say it exists.
2144                          */
2145                         size -= mdwidth * (kbytes + 1);
2146                         size /= kbytes;
2147
2148                         usb_ep_set_maxpacket_limit(&dep->endpoint, size);
2149
2150                         dep->endpoint.max_streams = 15;
2151                         dep->endpoint.ops = &dwc3_gadget_ep_ops;
2152                         list_add_tail(&dep->endpoint.ep_list,
2153                                         &dwc->gadget.ep_list);
2154
2155                         ret = dwc3_alloc_trb_pool(dep);
2156                         if (ret)
2157                                 return ret;
2158                 } else {
2159                         int             ret;
2160
2161                         usb_ep_set_maxpacket_limit(&dep->endpoint, 1024);
2162                         dep->endpoint.max_streams = 15;
2163                         dep->endpoint.ops = &dwc3_gadget_ep_ops;
2164                         list_add_tail(&dep->endpoint.ep_list,
2165                                         &dwc->gadget.ep_list);
2166
2167                         ret = dwc3_alloc_trb_pool(dep);
2168                         if (ret)
2169                                 return ret;
2170                 }
2171
2172                 if (num == 0) {
2173                         dep->endpoint.caps.type_control = true;
2174                 } else {
2175                         dep->endpoint.caps.type_iso = true;
2176                         dep->endpoint.caps.type_bulk = true;
2177                         dep->endpoint.caps.type_int = true;
2178                 }
2179
2180                 dep->endpoint.caps.dir_in = direction;
2181                 dep->endpoint.caps.dir_out = !direction;
2182
2183                 INIT_LIST_HEAD(&dep->pending_list);
2184                 INIT_LIST_HEAD(&dep->started_list);
2185         }
2186
2187         return 0;
2188 }
2189
2190 static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
2191 {
2192         struct dwc3_ep                  *dep;
2193         u8                              epnum;
2194
2195         for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2196                 dep = dwc->eps[epnum];
2197                 if (!dep)
2198                         continue;
2199                 /*
2200                  * Physical endpoints 0 and 1 are special; they form the
2201                  * bi-directional USB endpoint 0.
2202                  *
2203                  * For those two physical endpoints, we don't allocate a TRB
2204                  * pool nor do we add them the endpoints list. Due to that, we
2205                  * shouldn't do these two operations otherwise we would end up
2206                  * with all sorts of bugs when removing dwc3.ko.
2207                  */
2208                 if (epnum != 0 && epnum != 1) {
2209                         dwc3_free_trb_pool(dep);
2210                         list_del(&dep->endpoint.ep_list);
2211                 }
2212
2213                 kfree(dep);
2214         }
2215 }
2216
2217 /* -------------------------------------------------------------------------- */
2218
2219 static int dwc3_gadget_ep_reclaim_completed_trb(struct dwc3_ep *dep,
2220                 struct dwc3_request *req, struct dwc3_trb *trb,
2221                 const struct dwc3_event_depevt *event, int status, int chain)
2222 {
2223         unsigned int            count;
2224         unsigned int            s_pkt = 0;
2225
2226         dwc3_ep_inc_deq(dep);
2227
2228         trace_dwc3_complete_trb(dep, trb);
2229
2230         /*
2231          * If we're in the middle of series of chained TRBs and we
2232          * receive a short transfer along the way, DWC3 will skip
2233          * through all TRBs including the last TRB in the chain (the
2234          * where CHN bit is zero. DWC3 will also avoid clearing HWO
2235          * bit and SW has to do it manually.
2236          *
2237          * We're going to do that here to avoid problems of HW trying
2238          * to use bogus TRBs for transfers.
2239          */
2240         if (chain && (trb->ctrl & DWC3_TRB_CTRL_HWO))
2241                 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2242
2243         /*
2244          * If we're dealing with unaligned size OUT transfer, we will be left
2245          * with one TRB pending in the ring. We need to manually clear HWO bit
2246          * from that TRB.
2247          */
2248         if ((req->zero || req->unaligned) && (trb->ctrl & DWC3_TRB_CTRL_HWO)) {
2249                 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2250                 return 1;
2251         }
2252
2253         count = trb->size & DWC3_TRB_SIZE_MASK;
2254         req->remaining += count;
2255
2256         if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
2257                 return 1;
2258
2259         if (!dep->direction) {
2260                 if (count && (event->status & DEPEVT_STATUS_SHORT))
2261                         s_pkt = 1;
2262         }
2263
2264         if (s_pkt && !chain)
2265                 return 1;
2266
2267         if ((event->status & DEPEVT_STATUS_IOC) &&
2268                         (trb->ctrl & DWC3_TRB_CTRL_IOC))
2269                 return 1;
2270
2271         return 0;
2272 }
2273
2274 static int dwc3_gadget_ep_reclaim_trb_sg(struct dwc3_ep *dep,
2275                 struct dwc3_request *req, const struct dwc3_event_depevt *event,
2276                 int status)
2277 {
2278         struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
2279         struct scatterlist *sg = req->sg;
2280         struct scatterlist *s;
2281         unsigned int pending = req->num_pending_sgs;
2282         unsigned int i;
2283         int ret = 0;
2284
2285         for_each_sg(sg, s, pending, i) {
2286                 trb = &dep->trb_pool[dep->trb_dequeue];
2287
2288                 if (trb->ctrl & DWC3_TRB_CTRL_HWO)
2289                         break;
2290
2291                 req->sg = sg_next(s);
2292                 req->num_pending_sgs--;
2293
2294                 ret = dwc3_gadget_ep_reclaim_completed_trb(dep, req,
2295                                 trb, event, status, true);
2296                 if (ret)
2297                         break;
2298         }
2299
2300         return ret;
2301 }
2302
2303 static int dwc3_gadget_ep_reclaim_trb_linear(struct dwc3_ep *dep,
2304                 struct dwc3_request *req, const struct dwc3_event_depevt *event,
2305                 int status)
2306 {
2307         struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
2308
2309         return dwc3_gadget_ep_reclaim_completed_trb(dep, req, trb,
2310                         event, status, false);
2311 }
2312
2313 static void dwc3_gadget_ep_cleanup_completed_requests(struct dwc3_ep *dep,
2314                 const struct dwc3_event_depevt *event, int status)
2315 {
2316         struct dwc3_request     *req, *n;
2317         struct dwc3_trb         *trb;
2318         int                     ret = 0;
2319
2320         list_for_each_entry_safe(req, n, &dep->started_list, list) {
2321                 unsigned length;
2322                 int chain;
2323
2324                 length = req->request.length;
2325                 chain = req->num_pending_sgs > 0;
2326                 if (chain)
2327                         ret = dwc3_gadget_ep_reclaim_trb_sg(dep, req, event,
2328                                         status);
2329                 else
2330                         ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
2331                                         status);
2332
2333                 if (req->unaligned || req->zero) {
2334                         trb = &dep->trb_pool[dep->trb_dequeue];
2335                         ret = dwc3_gadget_ep_reclaim_completed_trb(dep, req,
2336                                         trb, event, status, false);
2337                         req->unaligned = false;
2338                         req->zero = false;
2339                 }
2340
2341                 req->request.actual = length - req->remaining;
2342
2343                 if (req->request.actual < length || req->num_pending_sgs) {
2344                         /*
2345                          * There could be a scenario where the whole req can't
2346                          * be mapped into available TRB's. In that case, we need
2347                          * to kick transfer again if (req->num_pending_sgs > 0)
2348                          */
2349                         if (req->num_pending_sgs) {
2350                                 dev_WARN_ONCE(dep->dwc->dev,
2351                                               (req->request.actual == length),
2352                                               "There are some pending sg's that needs to be queued again\n");
2353                                 __dwc3_gadget_kick_transfer(dep);
2354                                 return;
2355                         }
2356                 }
2357
2358                 dwc3_gadget_giveback(dep, req, status);
2359
2360                 if (ret)
2361                         break;
2362         }
2363
2364         /*
2365          * Our endpoint might get disabled by another thread during
2366          * dwc3_gadget_giveback(). If that happens, we're just gonna return 1
2367          * early.
2368          */
2369         if (!dep->endpoint.desc)
2370                 return;
2371
2372         if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
2373                         list_empty(&dep->started_list) &&
2374                         list_empty(&dep->pending_list)) {
2375                 dep->flags = DWC3_EP_PENDING_REQUEST;
2376         }
2377 }
2378
2379 static void dwc3_gadget_endpoint_frame_from_event(struct dwc3_ep *dep,
2380                 const struct dwc3_event_depevt *event)
2381 {
2382         u32 cur_uf, mask;
2383
2384         mask = ~(dep->interval - 1);
2385         cur_uf = event->parameters & mask;
2386         dep->frame_number = cur_uf;
2387 }
2388
2389 static void dwc3_gadget_endpoint_transfer_in_progress(struct dwc3_ep *dep,
2390                 const struct dwc3_event_depevt *event)
2391 {
2392         struct dwc3             *dwc = dep->dwc;
2393         unsigned                status = 0;
2394         bool                    stop = false;
2395
2396         dwc3_gadget_endpoint_frame_from_event(dep, event);
2397
2398         if (event->status & DEPEVT_STATUS_BUSERR)
2399                 status = -ECONNRESET;
2400
2401         if (event->status & DEPEVT_STATUS_MISSED_ISOC) {
2402                 status = -EXDEV;
2403                 stop = true;
2404         }
2405
2406         dwc3_gadget_ep_cleanup_completed_requests(dep, event, status);
2407
2408         if (stop) {
2409                 dwc3_stop_active_transfer(dep, true);
2410                 dep->flags = DWC3_EP_ENABLED;
2411         }
2412
2413         /*
2414          * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
2415          * See dwc3_gadget_linksts_change_interrupt() for 1st half.
2416          */
2417         if (dwc->revision < DWC3_REVISION_183A) {
2418                 u32             reg;
2419                 int             i;
2420
2421                 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
2422                         dep = dwc->eps[i];
2423
2424                         if (!(dep->flags & DWC3_EP_ENABLED))
2425                                 continue;
2426
2427                         if (!list_empty(&dep->started_list))
2428                                 return;
2429                 }
2430
2431                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2432                 reg |= dwc->u1u2;
2433                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2434
2435                 dwc->u1u2 = 0;
2436         }
2437 }
2438
2439 static void dwc3_gadget_endpoint_transfer_not_ready(struct dwc3_ep *dep,
2440                 const struct dwc3_event_depevt *event)
2441 {
2442         dwc3_gadget_endpoint_frame_from_event(dep, event);
2443         __dwc3_gadget_start_isoc(dep);
2444 }
2445
2446 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
2447                 const struct dwc3_event_depevt *event)
2448 {
2449         struct dwc3_ep          *dep;
2450         u8                      epnum = event->endpoint_number;
2451         u8                      cmd;
2452
2453         dep = dwc->eps[epnum];
2454
2455         if (!(dep->flags & DWC3_EP_ENABLED)) {
2456                 if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
2457                         return;
2458
2459                 /* Handle only EPCMDCMPLT when EP disabled */
2460                 if (event->endpoint_event != DWC3_DEPEVT_EPCMDCMPLT)
2461                         return;
2462         }
2463
2464         if (epnum == 0 || epnum == 1) {
2465                 dwc3_ep0_interrupt(dwc, event);
2466                 return;
2467         }
2468
2469         switch (event->endpoint_event) {
2470         case DWC3_DEPEVT_XFERINPROGRESS:
2471                 dwc3_gadget_endpoint_transfer_in_progress(dep, event);
2472                 break;
2473         case DWC3_DEPEVT_XFERNOTREADY:
2474                 dwc3_gadget_endpoint_transfer_not_ready(dep, event);
2475                 break;
2476         case DWC3_DEPEVT_EPCMDCMPLT:
2477                 cmd = DEPEVT_PARAMETER_CMD(event->parameters);
2478
2479                 if (cmd == DWC3_DEPCMD_ENDTRANSFER) {
2480                         dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
2481                         wake_up(&dep->wait_end_transfer);
2482                 }
2483                 break;
2484         case DWC3_DEPEVT_STREAMEVT:
2485         case DWC3_DEPEVT_XFERCOMPLETE:
2486         case DWC3_DEPEVT_RXTXFIFOEVT:
2487                 break;
2488         }
2489 }
2490
2491 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
2492 {
2493         if (dwc->gadget_driver && dwc->gadget_driver->disconnect) {
2494                 spin_unlock(&dwc->lock);
2495                 dwc->gadget_driver->disconnect(&dwc->gadget);
2496                 spin_lock(&dwc->lock);
2497         }
2498 }
2499
2500 static void dwc3_suspend_gadget(struct dwc3 *dwc)
2501 {
2502         if (dwc->gadget_driver && dwc->gadget_driver->suspend) {
2503                 spin_unlock(&dwc->lock);
2504                 dwc->gadget_driver->suspend(&dwc->gadget);
2505                 spin_lock(&dwc->lock);
2506         }
2507 }
2508
2509 static void dwc3_resume_gadget(struct dwc3 *dwc)
2510 {
2511         if (dwc->gadget_driver && dwc->gadget_driver->resume) {
2512                 spin_unlock(&dwc->lock);
2513                 dwc->gadget_driver->resume(&dwc->gadget);
2514                 spin_lock(&dwc->lock);
2515         }
2516 }
2517
2518 static void dwc3_reset_gadget(struct dwc3 *dwc)
2519 {
2520         if (!dwc->gadget_driver)
2521                 return;
2522
2523         if (dwc->gadget.speed != USB_SPEED_UNKNOWN) {
2524                 spin_unlock(&dwc->lock);
2525                 usb_gadget_udc_reset(&dwc->gadget, dwc->gadget_driver);
2526                 spin_lock(&dwc->lock);
2527         }
2528 }
2529
2530 static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force)
2531 {
2532         struct dwc3 *dwc = dep->dwc;
2533         struct dwc3_gadget_ep_cmd_params params;
2534         u32 cmd;
2535         int ret;
2536
2537         if ((dep->flags & DWC3_EP_END_TRANSFER_PENDING) ||
2538             !dep->resource_index)
2539                 return;
2540
2541         /*
2542          * NOTICE: We are violating what the Databook says about the
2543          * EndTransfer command. Ideally we would _always_ wait for the
2544          * EndTransfer Command Completion IRQ, but that's causing too
2545          * much trouble synchronizing between us and gadget driver.
2546          *
2547          * We have discussed this with the IP Provider and it was
2548          * suggested to giveback all requests here, but give HW some
2549          * extra time to synchronize with the interconnect. We're using
2550          * an arbitrary 100us delay for that.
2551          *
2552          * Note also that a similar handling was tested by Synopsys
2553          * (thanks a lot Paul) and nothing bad has come out of it.
2554          * In short, what we're doing is:
2555          *
2556          * - Issue EndTransfer WITH CMDIOC bit set
2557          * - Wait 100us
2558          *
2559          * As of IP version 3.10a of the DWC_usb3 IP, the controller
2560          * supports a mode to work around the above limitation. The
2561          * software can poll the CMDACT bit in the DEPCMD register
2562          * after issuing a EndTransfer command. This mode is enabled
2563          * by writing GUCTL2[14]. This polling is already done in the
2564          * dwc3_send_gadget_ep_cmd() function so if the mode is
2565          * enabled, the EndTransfer command will have completed upon
2566          * returning from this function and we don't need to delay for
2567          * 100us.
2568          *
2569          * This mode is NOT available on the DWC_usb31 IP.
2570          */
2571
2572         cmd = DWC3_DEPCMD_ENDTRANSFER;
2573         cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
2574         cmd |= DWC3_DEPCMD_CMDIOC;
2575         cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
2576         memset(&params, 0, sizeof(params));
2577         ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
2578         WARN_ON_ONCE(ret);
2579         dep->resource_index = 0;
2580
2581         if (dwc3_is_usb31(dwc) || dwc->revision < DWC3_REVISION_310A) {
2582                 dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
2583                 udelay(100);
2584         }
2585 }
2586
2587 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
2588 {
2589         u32 epnum;
2590
2591         for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2592                 struct dwc3_ep *dep;
2593                 int ret;
2594
2595                 dep = dwc->eps[epnum];
2596                 if (!dep)
2597                         continue;
2598
2599                 if (!(dep->flags & DWC3_EP_STALL))
2600                         continue;
2601
2602                 dep->flags &= ~DWC3_EP_STALL;
2603
2604                 ret = dwc3_send_clear_stall_ep_cmd(dep);
2605                 WARN_ON_ONCE(ret);
2606         }
2607 }
2608
2609 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
2610 {
2611         int                     reg;
2612
2613         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2614         reg &= ~DWC3_DCTL_INITU1ENA;
2615         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2616
2617         reg &= ~DWC3_DCTL_INITU2ENA;
2618         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2619
2620         dwc3_disconnect_gadget(dwc);
2621
2622         dwc->gadget.speed = USB_SPEED_UNKNOWN;
2623         dwc->setup_packet_pending = false;
2624         usb_gadget_set_state(&dwc->gadget, USB_STATE_NOTATTACHED);
2625
2626         dwc->connected = false;
2627 }
2628
2629 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
2630 {
2631         u32                     reg;
2632
2633         dwc->connected = true;
2634
2635         /*
2636          * WORKAROUND: DWC3 revisions <1.88a have an issue which
2637          * would cause a missing Disconnect Event if there's a
2638          * pending Setup Packet in the FIFO.
2639          *
2640          * There's no suggested workaround on the official Bug
2641          * report, which states that "unless the driver/application
2642          * is doing any special handling of a disconnect event,
2643          * there is no functional issue".
2644          *
2645          * Unfortunately, it turns out that we _do_ some special
2646          * handling of a disconnect event, namely complete all
2647          * pending transfers, notify gadget driver of the
2648          * disconnection, and so on.
2649          *
2650          * Our suggested workaround is to follow the Disconnect
2651          * Event steps here, instead, based on a setup_packet_pending
2652          * flag. Such flag gets set whenever we have a SETUP_PENDING
2653          * status for EP0 TRBs and gets cleared on XferComplete for the
2654          * same endpoint.
2655          *
2656          * Refers to:
2657          *
2658          * STAR#9000466709: RTL: Device : Disconnect event not
2659          * generated if setup packet pending in FIFO
2660          */
2661         if (dwc->revision < DWC3_REVISION_188A) {
2662                 if (dwc->setup_packet_pending)
2663                         dwc3_gadget_disconnect_interrupt(dwc);
2664         }
2665
2666         dwc3_reset_gadget(dwc);
2667
2668         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2669         reg &= ~DWC3_DCTL_TSTCTRL_MASK;
2670         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2671         dwc->test_mode = false;
2672         dwc3_clear_stall_all_ep(dwc);
2673
2674         /* Reset device address to zero */
2675         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2676         reg &= ~(DWC3_DCFG_DEVADDR_MASK);
2677         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2678 }
2679
2680 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
2681 {
2682         struct dwc3_ep          *dep;
2683         int                     ret;
2684         u32                     reg;
2685         u8                      speed;
2686
2687         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2688         speed = reg & DWC3_DSTS_CONNECTSPD;
2689         dwc->speed = speed;
2690
2691         /*
2692          * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
2693          * each time on Connect Done.
2694          *
2695          * Currently we always use the reset value. If any platform
2696          * wants to set this to a different value, we need to add a
2697          * setting and update GCTL.RAMCLKSEL here.
2698          */
2699
2700         switch (speed) {
2701         case DWC3_DSTS_SUPERSPEED_PLUS:
2702                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2703                 dwc->gadget.ep0->maxpacket = 512;
2704                 dwc->gadget.speed = USB_SPEED_SUPER_PLUS;
2705                 break;
2706         case DWC3_DSTS_SUPERSPEED:
2707                 /*
2708                  * WORKAROUND: DWC3 revisions <1.90a have an issue which
2709                  * would cause a missing USB3 Reset event.
2710                  *
2711                  * In such situations, we should force a USB3 Reset
2712                  * event by calling our dwc3_gadget_reset_interrupt()
2713                  * routine.
2714                  *
2715                  * Refers to:
2716                  *
2717                  * STAR#9000483510: RTL: SS : USB3 reset event may
2718                  * not be generated always when the link enters poll
2719                  */
2720                 if (dwc->revision < DWC3_REVISION_190A)
2721                         dwc3_gadget_reset_interrupt(dwc);
2722
2723                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2724                 dwc->gadget.ep0->maxpacket = 512;
2725                 dwc->gadget.speed = USB_SPEED_SUPER;
2726                 break;
2727         case DWC3_DSTS_HIGHSPEED:
2728                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
2729                 dwc->gadget.ep0->maxpacket = 64;
2730                 dwc->gadget.speed = USB_SPEED_HIGH;
2731                 break;
2732         case DWC3_DSTS_FULLSPEED:
2733                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
2734                 dwc->gadget.ep0->maxpacket = 64;
2735                 dwc->gadget.speed = USB_SPEED_FULL;
2736                 break;
2737         case DWC3_DSTS_LOWSPEED:
2738                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(8);
2739                 dwc->gadget.ep0->maxpacket = 8;
2740                 dwc->gadget.speed = USB_SPEED_LOW;
2741                 break;
2742         }
2743
2744         dwc->eps[1]->endpoint.maxpacket = dwc->gadget.ep0->maxpacket;
2745
2746         /* Enable USB2 LPM Capability */
2747
2748         if ((dwc->revision > DWC3_REVISION_194A) &&
2749             (speed != DWC3_DSTS_SUPERSPEED) &&
2750             (speed != DWC3_DSTS_SUPERSPEED_PLUS)) {
2751                 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2752                 reg |= DWC3_DCFG_LPM_CAP;
2753                 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2754
2755                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2756                 reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
2757
2758                 reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold);
2759
2760                 /*
2761                  * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
2762                  * DCFG.LPMCap is set, core responses with an ACK and the
2763                  * BESL value in the LPM token is less than or equal to LPM
2764                  * NYET threshold.
2765                  */
2766                 WARN_ONCE(dwc->revision < DWC3_REVISION_240A
2767                                 && dwc->has_lpm_erratum,
2768                                 "LPM Erratum not available on dwc3 revisions < 2.40a\n");
2769
2770                 if (dwc->has_lpm_erratum && dwc->revision >= DWC3_REVISION_240A)
2771                         reg |= DWC3_DCTL_LPM_ERRATA(dwc->lpm_nyet_threshold);
2772
2773                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2774         } else {
2775                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2776                 reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
2777                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2778         }
2779
2780         dep = dwc->eps[0];
2781         ret = __dwc3_gadget_ep_enable(dep, true, false);
2782         if (ret) {
2783                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2784                 return;
2785         }
2786
2787         dep = dwc->eps[1];
2788         ret = __dwc3_gadget_ep_enable(dep, true, false);
2789         if (ret) {
2790                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2791                 return;
2792         }
2793
2794         /*
2795          * Configure PHY via GUSB3PIPECTLn if required.
2796          *
2797          * Update GTXFIFOSIZn
2798          *
2799          * In both cases reset values should be sufficient.
2800          */
2801 }
2802
2803 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
2804 {
2805         /*
2806          * TODO take core out of low power mode when that's
2807          * implemented.
2808          */
2809
2810         if (dwc->gadget_driver && dwc->gadget_driver->resume) {
2811                 spin_unlock(&dwc->lock);
2812                 dwc->gadget_driver->resume(&dwc->gadget);
2813                 spin_lock(&dwc->lock);
2814         }
2815 }
2816
2817 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
2818                 unsigned int evtinfo)
2819 {
2820         enum dwc3_link_state    next = evtinfo & DWC3_LINK_STATE_MASK;
2821         unsigned int            pwropt;
2822
2823         /*
2824          * WORKAROUND: DWC3 < 2.50a have an issue when configured without
2825          * Hibernation mode enabled which would show up when device detects
2826          * host-initiated U3 exit.
2827          *
2828          * In that case, device will generate a Link State Change Interrupt
2829          * from U3 to RESUME which is only necessary if Hibernation is
2830          * configured in.
2831          *
2832          * There are no functional changes due to such spurious event and we
2833          * just need to ignore it.
2834          *
2835          * Refers to:
2836          *
2837          * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
2838          * operational mode
2839          */
2840         pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
2841         if ((dwc->revision < DWC3_REVISION_250A) &&
2842                         (pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
2843                 if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
2844                                 (next == DWC3_LINK_STATE_RESUME)) {
2845                         return;
2846                 }
2847         }
2848
2849         /*
2850          * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
2851          * on the link partner, the USB session might do multiple entry/exit
2852          * of low power states before a transfer takes place.
2853          *
2854          * Due to this problem, we might experience lower throughput. The
2855          * suggested workaround is to disable DCTL[12:9] bits if we're
2856          * transitioning from U1/U2 to U0 and enable those bits again
2857          * after a transfer completes and there are no pending transfers
2858          * on any of the enabled endpoints.
2859          *
2860          * This is the first half of that workaround.
2861          *
2862          * Refers to:
2863          *
2864          * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
2865          * core send LGO_Ux entering U0
2866          */
2867         if (dwc->revision < DWC3_REVISION_183A) {
2868                 if (next == DWC3_LINK_STATE_U0) {
2869                         u32     u1u2;
2870                         u32     reg;
2871
2872                         switch (dwc->link_state) {
2873                         case DWC3_LINK_STATE_U1:
2874                         case DWC3_LINK_STATE_U2:
2875                                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2876                                 u1u2 = reg & (DWC3_DCTL_INITU2ENA
2877                                                 | DWC3_DCTL_ACCEPTU2ENA
2878                                                 | DWC3_DCTL_INITU1ENA
2879                                                 | DWC3_DCTL_ACCEPTU1ENA);
2880
2881                                 if (!dwc->u1u2)
2882                                         dwc->u1u2 = reg & u1u2;
2883
2884                                 reg &= ~u1u2;
2885
2886                                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2887                                 break;
2888                         default:
2889                                 /* do nothing */
2890                                 break;
2891                         }
2892                 }
2893         }
2894
2895         switch (next) {
2896         case DWC3_LINK_STATE_U1:
2897                 if (dwc->speed == USB_SPEED_SUPER)
2898                         dwc3_suspend_gadget(dwc);
2899                 break;
2900         case DWC3_LINK_STATE_U2:
2901         case DWC3_LINK_STATE_U3:
2902                 dwc3_suspend_gadget(dwc);
2903                 break;
2904         case DWC3_LINK_STATE_RESUME:
2905                 dwc3_resume_gadget(dwc);
2906                 break;
2907         default:
2908                 /* do nothing */
2909                 break;
2910         }
2911
2912         dwc->link_state = next;
2913 }
2914
2915 static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc,
2916                                           unsigned int evtinfo)
2917 {
2918         enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
2919
2920         if (dwc->link_state != next && next == DWC3_LINK_STATE_U3)
2921                 dwc3_suspend_gadget(dwc);
2922
2923         dwc->link_state = next;
2924 }
2925
2926 static void dwc3_gadget_hibernation_interrupt(struct dwc3 *dwc,
2927                 unsigned int evtinfo)
2928 {
2929         unsigned int is_ss = evtinfo & BIT(4);
2930
2931         /*
2932          * WORKAROUND: DWC3 revison 2.20a with hibernation support
2933          * have a known issue which can cause USB CV TD.9.23 to fail
2934          * randomly.
2935          *
2936          * Because of this issue, core could generate bogus hibernation
2937          * events which SW needs to ignore.
2938          *
2939          * Refers to:
2940          *
2941          * STAR#9000546576: Device Mode Hibernation: Issue in USB 2.0
2942          * Device Fallback from SuperSpeed
2943          */
2944         if (is_ss ^ (dwc->speed == USB_SPEED_SUPER))
2945                 return;
2946
2947         /* enter hibernation here */
2948 }
2949
2950 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
2951                 const struct dwc3_event_devt *event)
2952 {
2953         switch (event->type) {
2954         case DWC3_DEVICE_EVENT_DISCONNECT:
2955                 dwc3_gadget_disconnect_interrupt(dwc);
2956                 break;
2957         case DWC3_DEVICE_EVENT_RESET:
2958                 dwc3_gadget_reset_interrupt(dwc);
2959                 break;
2960         case DWC3_DEVICE_EVENT_CONNECT_DONE:
2961                 dwc3_gadget_conndone_interrupt(dwc);
2962                 break;
2963         case DWC3_DEVICE_EVENT_WAKEUP:
2964                 dwc3_gadget_wakeup_interrupt(dwc);
2965                 break;
2966         case DWC3_DEVICE_EVENT_HIBER_REQ:
2967                 if (dev_WARN_ONCE(dwc->dev, !dwc->has_hibernation,
2968                                         "unexpected hibernation event\n"))
2969                         break;
2970
2971                 dwc3_gadget_hibernation_interrupt(dwc, event->event_info);
2972                 break;
2973         case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
2974                 dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
2975                 break;
2976         case DWC3_DEVICE_EVENT_EOPF:
2977                 /* It changed to be suspend event for version 2.30a and above */
2978                 if (dwc->revision >= DWC3_REVISION_230A) {
2979                         /*
2980                          * Ignore suspend event until the gadget enters into
2981                          * USB_STATE_CONFIGURED state.
2982                          */
2983                         if (dwc->gadget.state >= USB_STATE_CONFIGURED)
2984                                 dwc3_gadget_suspend_interrupt(dwc,
2985                                                 event->event_info);
2986                 }
2987                 break;
2988         case DWC3_DEVICE_EVENT_SOF:
2989         case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
2990         case DWC3_DEVICE_EVENT_CMD_CMPL:
2991         case DWC3_DEVICE_EVENT_OVERFLOW:
2992                 break;
2993         default:
2994                 dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
2995         }
2996 }
2997
2998 static void dwc3_process_event_entry(struct dwc3 *dwc,
2999                 const union dwc3_event *event)
3000 {
3001         trace_dwc3_event(event->raw, dwc);
3002
3003         if (!event->type.is_devspec)
3004                 dwc3_endpoint_interrupt(dwc, &event->depevt);
3005         else if (event->type.type == DWC3_EVENT_TYPE_DEV)
3006                 dwc3_gadget_interrupt(dwc, &event->devt);
3007         else
3008                 dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
3009 }
3010
3011 static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt)
3012 {
3013         struct dwc3 *dwc = evt->dwc;
3014         irqreturn_t ret = IRQ_NONE;
3015         int left;
3016         u32 reg;
3017
3018         left = evt->count;
3019
3020         if (!(evt->flags & DWC3_EVENT_PENDING))
3021                 return IRQ_NONE;
3022
3023         while (left > 0) {
3024                 union dwc3_event event;
3025
3026                 event.raw = *(u32 *) (evt->cache + evt->lpos);
3027
3028                 dwc3_process_event_entry(dwc, &event);
3029
3030                 /*
3031                  * FIXME we wrap around correctly to the next entry as
3032                  * almost all entries are 4 bytes in size. There is one
3033                  * entry which has 12 bytes which is a regular entry
3034                  * followed by 8 bytes data. ATM I don't know how
3035                  * things are organized if we get next to the a
3036                  * boundary so I worry about that once we try to handle
3037                  * that.
3038                  */
3039                 evt->lpos = (evt->lpos + 4) % evt->length;
3040                 left -= 4;
3041         }
3042
3043         evt->count = 0;
3044         evt->flags &= ~DWC3_EVENT_PENDING;
3045         ret = IRQ_HANDLED;
3046
3047         /* Unmask interrupt */
3048         reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
3049         reg &= ~DWC3_GEVNTSIZ_INTMASK;
3050         dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
3051
3052         if (dwc->imod_interval) {
3053                 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
3054                 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
3055         }
3056
3057         return ret;
3058 }
3059
3060 static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt)
3061 {
3062         struct dwc3_event_buffer *evt = _evt;
3063         struct dwc3 *dwc = evt->dwc;
3064         unsigned long flags;
3065         irqreturn_t ret = IRQ_NONE;
3066
3067         spin_lock_irqsave(&dwc->lock, flags);
3068         ret = dwc3_process_event_buf(evt);
3069         spin_unlock_irqrestore(&dwc->lock, flags);
3070
3071         return ret;
3072 }
3073
3074 static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt)
3075 {
3076         struct dwc3 *dwc = evt->dwc;
3077         u32 amount;
3078         u32 count;
3079         u32 reg;
3080
3081         if (pm_runtime_suspended(dwc->dev)) {
3082                 pm_runtime_get(dwc->dev);
3083                 disable_irq_nosync(dwc->irq_gadget);
3084                 dwc->pending_events = true;
3085                 return IRQ_HANDLED;
3086         }
3087
3088         /*
3089          * With PCIe legacy interrupt, test shows that top-half irq handler can
3090          * be called again after HW interrupt deassertion. Check if bottom-half
3091          * irq event handler completes before caching new event to prevent
3092          * losing events.
3093          */
3094         if (evt->flags & DWC3_EVENT_PENDING)
3095                 return IRQ_HANDLED;
3096
3097         count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
3098         count &= DWC3_GEVNTCOUNT_MASK;
3099         if (!count)
3100                 return IRQ_NONE;
3101
3102         evt->count = count;
3103         evt->flags |= DWC3_EVENT_PENDING;
3104
3105         /* Mask interrupt */
3106         reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
3107         reg |= DWC3_GEVNTSIZ_INTMASK;
3108         dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
3109
3110         amount = min(count, evt->length - evt->lpos);
3111         memcpy(evt->cache + evt->lpos, evt->buf + evt->lpos, amount);
3112
3113         if (amount < count)
3114                 memcpy(evt->cache, evt->buf, count - amount);
3115
3116         dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
3117
3118         return IRQ_WAKE_THREAD;
3119 }
3120
3121 static irqreturn_t dwc3_interrupt(int irq, void *_evt)
3122 {
3123         struct dwc3_event_buffer        *evt = _evt;
3124
3125         return dwc3_check_event_buf(evt);
3126 }
3127
3128 static int dwc3_gadget_get_irq(struct dwc3 *dwc)
3129 {
3130         struct platform_device *dwc3_pdev = to_platform_device(dwc->dev);
3131         int irq;
3132
3133         irq = platform_get_irq_byname(dwc3_pdev, "peripheral");
3134         if (irq > 0)
3135                 goto out;
3136
3137         if (irq == -EPROBE_DEFER)
3138                 goto out;
3139
3140         irq = platform_get_irq_byname(dwc3_pdev, "dwc_usb3");
3141         if (irq > 0)
3142                 goto out;
3143
3144         if (irq == -EPROBE_DEFER)
3145                 goto out;
3146
3147         irq = platform_get_irq(dwc3_pdev, 0);
3148         if (irq > 0)
3149                 goto out;
3150
3151         if (irq != -EPROBE_DEFER)
3152                 dev_err(dwc->dev, "missing peripheral IRQ\n");
3153
3154         if (!irq)
3155                 irq = -EINVAL;
3156
3157 out:
3158         return irq;
3159 }
3160
3161 /**
3162  * dwc3_gadget_init - initializes gadget related registers
3163  * @dwc: pointer to our controller context structure
3164  *
3165  * Returns 0 on success otherwise negative errno.
3166  */
3167 int dwc3_gadget_init(struct dwc3 *dwc)
3168 {
3169         int ret;
3170         int irq;
3171
3172         irq = dwc3_gadget_get_irq(dwc);
3173         if (irq < 0) {
3174                 ret = irq;
3175                 goto err0;
3176         }
3177
3178         dwc->irq_gadget = irq;
3179
3180         dwc->ep0_trb = dma_alloc_coherent(dwc->sysdev,
3181                                           sizeof(*dwc->ep0_trb) * 2,
3182                                           &dwc->ep0_trb_addr, GFP_KERNEL);
3183         if (!dwc->ep0_trb) {
3184                 dev_err(dwc->dev, "failed to allocate ep0 trb\n");
3185                 ret = -ENOMEM;
3186                 goto err0;
3187         }
3188
3189         dwc->setup_buf = kzalloc(DWC3_EP0_SETUP_SIZE, GFP_KERNEL);
3190         if (!dwc->setup_buf) {
3191                 ret = -ENOMEM;
3192                 goto err1;
3193         }
3194
3195         dwc->bounce = dma_alloc_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE,
3196                         &dwc->bounce_addr, GFP_KERNEL);
3197         if (!dwc->bounce) {
3198                 ret = -ENOMEM;
3199                 goto err2;
3200         }
3201
3202         init_completion(&dwc->ep0_in_setup);
3203
3204         dwc->gadget.ops                 = &dwc3_gadget_ops;
3205         dwc->gadget.speed               = USB_SPEED_UNKNOWN;
3206         dwc->gadget.sg_supported        = true;
3207         dwc->gadget.name                = "dwc3-gadget";
3208         dwc->gadget.is_otg              = dwc->dr_mode == USB_DR_MODE_OTG;
3209
3210         /*
3211          * FIXME We might be setting max_speed to <SUPER, however versions
3212          * <2.20a of dwc3 have an issue with metastability (documented
3213          * elsewhere in this driver) which tells us we can't set max speed to
3214          * anything lower than SUPER.
3215          *
3216          * Because gadget.max_speed is only used by composite.c and function
3217          * drivers (i.e. it won't go into dwc3's registers) we are allowing this
3218          * to happen so we avoid sending SuperSpeed Capability descriptor
3219          * together with our BOS descriptor as that could confuse host into
3220          * thinking we can handle super speed.
3221          *
3222          * Note that, in fact, we won't even support GetBOS requests when speed
3223          * is less than super speed because we don't have means, yet, to tell
3224          * composite.c that we are USB 2.0 + LPM ECN.
3225          */
3226         if (dwc->revision < DWC3_REVISION_220A &&
3227             !dwc->dis_metastability_quirk)
3228                 dev_info(dwc->dev, "changing max_speed on rev %08x\n",
3229                                 dwc->revision);
3230
3231         dwc->gadget.max_speed           = dwc->maximum_speed;
3232
3233         /*
3234          * REVISIT: Here we should clear all pending IRQs to be
3235          * sure we're starting from a well known location.
3236          */
3237
3238         ret = dwc3_gadget_init_endpoints(dwc, dwc->num_eps);
3239         if (ret)
3240                 goto err3;
3241
3242         ret = usb_add_gadget_udc(dwc->dev, &dwc->gadget);
3243         if (ret) {
3244                 dev_err(dwc->dev, "failed to register udc\n");
3245                 goto err4;
3246         }
3247
3248         return 0;
3249
3250 err4:
3251         dwc3_gadget_free_endpoints(dwc);
3252
3253 err3:
3254         dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
3255                         dwc->bounce_addr);
3256
3257 err2:
3258         kfree(dwc->setup_buf);
3259
3260 err1:
3261         dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
3262                         dwc->ep0_trb, dwc->ep0_trb_addr);
3263
3264 err0:
3265         return ret;
3266 }
3267
3268 /* -------------------------------------------------------------------------- */
3269
3270 void dwc3_gadget_exit(struct dwc3 *dwc)
3271 {
3272         usb_del_gadget_udc(&dwc->gadget);
3273         dwc3_gadget_free_endpoints(dwc);
3274         dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
3275                           dwc->bounce_addr);
3276         kfree(dwc->setup_buf);
3277         dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
3278                           dwc->ep0_trb, dwc->ep0_trb_addr);
3279 }
3280
3281 int dwc3_gadget_suspend(struct dwc3 *dwc)
3282 {
3283         if (!dwc->gadget_driver)
3284                 return 0;
3285
3286         dwc3_gadget_run_stop(dwc, false, false);
3287         dwc3_disconnect_gadget(dwc);
3288         __dwc3_gadget_stop(dwc);
3289
3290         return 0;
3291 }
3292
3293 int dwc3_gadget_resume(struct dwc3 *dwc)
3294 {
3295         int                     ret;
3296
3297         if (!dwc->gadget_driver)
3298                 return 0;
3299
3300         ret = __dwc3_gadget_start(dwc);
3301         if (ret < 0)
3302                 goto err0;
3303
3304         ret = dwc3_gadget_run_stop(dwc, true, false);
3305         if (ret < 0)
3306                 goto err1;
3307
3308         return 0;
3309
3310 err1:
3311         __dwc3_gadget_stop(dwc);
3312
3313 err0:
3314         return ret;
3315 }
3316
3317 void dwc3_gadget_process_pending_events(struct dwc3 *dwc)
3318 {
3319         if (dwc->pending_events) {
3320                 dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf);
3321                 dwc->pending_events = false;
3322                 enable_irq(dwc->irq_gadget);
3323         }
3324 }