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