GNU Linux-libre 4.14.254-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         trb->ctrl |= DWC3_TRB_CTRL_HWO;
1008
1009         dwc3_ep_inc_enq(dep);
1010
1011         trace_dwc3_prepare_trb(dep, trb);
1012 }
1013
1014 /**
1015  * dwc3_prepare_one_trb - setup one TRB from one request
1016  * @dep: endpoint for which this request is prepared
1017  * @req: dwc3_request pointer
1018  * @chain: should this TRB be chained to the next?
1019  * @node: only for isochronous endpoints. First TRB needs different type.
1020  */
1021 static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
1022                 struct dwc3_request *req, unsigned chain, unsigned node)
1023 {
1024         struct dwc3_trb         *trb;
1025         unsigned                length = req->request.length;
1026         unsigned                stream_id = req->request.stream_id;
1027         unsigned                short_not_ok = req->request.short_not_ok;
1028         unsigned                no_interrupt = req->request.no_interrupt;
1029         dma_addr_t              dma = req->request.dma;
1030
1031         trb = &dep->trb_pool[dep->trb_enqueue];
1032
1033         if (!req->trb) {
1034                 dwc3_gadget_move_started_request(req);
1035                 req->trb = trb;
1036                 req->trb_dma = dwc3_trb_dma_offset(dep, trb);
1037                 dep->queued_requests++;
1038         }
1039
1040         __dwc3_prepare_one_trb(dep, trb, dma, length, chain, node,
1041                         stream_id, short_not_ok, no_interrupt);
1042 }
1043
1044 /**
1045  * dwc3_ep_prev_trb - returns the previous TRB in the ring
1046  * @dep: The endpoint with the TRB ring
1047  * @index: The index of the current TRB in the ring
1048  *
1049  * Returns the TRB prior to the one pointed to by the index. If the
1050  * index is 0, we will wrap backwards, skip the link TRB, and return
1051  * the one just before that.
1052  */
1053 static struct dwc3_trb *dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index)
1054 {
1055         u8 tmp = index;
1056
1057         if (!tmp)
1058                 tmp = DWC3_TRB_NUM - 1;
1059
1060         return &dep->trb_pool[tmp - 1];
1061 }
1062
1063 static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep)
1064 {
1065         u8                      trbs_left;
1066
1067         /*
1068          * If the enqueue & dequeue are equal then the TRB ring is either full
1069          * or empty. It's considered full when there are DWC3_TRB_NUM-1 of TRBs
1070          * pending to be processed by the driver.
1071          */
1072         if (dep->trb_enqueue == dep->trb_dequeue) {
1073                 /*
1074                  * If there is any request remained in the started_list at
1075                  * this point, that means there is no TRB available.
1076                  */
1077                 if (!list_empty(&dep->started_list))
1078                         return 0;
1079
1080                 return DWC3_TRB_NUM - 1;
1081         }
1082
1083         trbs_left = dep->trb_dequeue - dep->trb_enqueue;
1084         trbs_left &= (DWC3_TRB_NUM - 1);
1085
1086         if (dep->trb_dequeue < dep->trb_enqueue)
1087                 trbs_left--;
1088
1089         return trbs_left;
1090 }
1091
1092 static void dwc3_prepare_one_trb_sg(struct dwc3_ep *dep,
1093                 struct dwc3_request *req)
1094 {
1095         struct scatterlist *sg = req->sg;
1096         struct scatterlist *s;
1097         int             i;
1098
1099         for_each_sg(sg, s, req->num_pending_sgs, i) {
1100                 unsigned int length = req->request.length;
1101                 unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1102                 unsigned int rem = length % maxp;
1103                 unsigned chain = true;
1104
1105                 if (sg_is_last(s))
1106                         chain = false;
1107
1108                 if (rem && usb_endpoint_dir_out(dep->endpoint.desc) && !chain) {
1109                         struct dwc3     *dwc = dep->dwc;
1110                         struct dwc3_trb *trb;
1111
1112                         req->unaligned = true;
1113
1114                         /* prepare normal TRB */
1115                         dwc3_prepare_one_trb(dep, req, true, i);
1116
1117                         /* Now prepare one extra TRB to align transfer size */
1118                         trb = &dep->trb_pool[dep->trb_enqueue];
1119                         __dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr,
1120                                         maxp - rem, false, 1,
1121                                         req->request.stream_id,
1122                                         req->request.short_not_ok,
1123                                         req->request.no_interrupt);
1124                 } else {
1125                         dwc3_prepare_one_trb(dep, req, chain, i);
1126                 }
1127
1128                 if (!dwc3_calc_trbs_left(dep))
1129                         break;
1130         }
1131 }
1132
1133 static void dwc3_prepare_one_trb_linear(struct dwc3_ep *dep,
1134                 struct dwc3_request *req)
1135 {
1136         unsigned int length = req->request.length;
1137         unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1138         unsigned int rem = length % maxp;
1139
1140         if ((!length || rem) && usb_endpoint_dir_out(dep->endpoint.desc)) {
1141                 struct dwc3     *dwc = dep->dwc;
1142                 struct dwc3_trb *trb;
1143
1144                 req->unaligned = true;
1145
1146                 /* prepare normal TRB */
1147                 dwc3_prepare_one_trb(dep, req, true, 0);
1148
1149                 /* Now prepare one extra TRB to align transfer size */
1150                 trb = &dep->trb_pool[dep->trb_enqueue];
1151                 __dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr, maxp - rem,
1152                                 false, 1, req->request.stream_id,
1153                                 req->request.short_not_ok,
1154                                 req->request.no_interrupt);
1155         } else if (req->request.zero && req->request.length &&
1156                    (IS_ALIGNED(req->request.length,dep->endpoint.maxpacket))) {
1157                 struct dwc3     *dwc = dep->dwc;
1158                 struct dwc3_trb *trb;
1159
1160                 req->zero = true;
1161
1162                 /* prepare normal TRB */
1163                 dwc3_prepare_one_trb(dep, req, true, 0);
1164
1165                 /* Now prepare one extra TRB to handle ZLP */
1166                 trb = &dep->trb_pool[dep->trb_enqueue];
1167                 __dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr, 0,
1168                                 false, 1, req->request.stream_id,
1169                                 req->request.short_not_ok,
1170                                 req->request.no_interrupt);
1171         } else {
1172                 dwc3_prepare_one_trb(dep, req, false, 0);
1173         }
1174 }
1175
1176 /*
1177  * dwc3_prepare_trbs - setup TRBs from requests
1178  * @dep: endpoint for which requests are being prepared
1179  *
1180  * The function goes through the requests list and sets up TRBs for the
1181  * transfers. The function returns once there are no more TRBs available or
1182  * it runs out of requests.
1183  */
1184 static void dwc3_prepare_trbs(struct dwc3_ep *dep)
1185 {
1186         struct dwc3_request     *req, *n;
1187
1188         BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
1189
1190         if (!dwc3_calc_trbs_left(dep))
1191                 return;
1192
1193         /*
1194          * We can get in a situation where there's a request in the started list
1195          * but there weren't enough TRBs to fully kick it in the first time
1196          * around, so it has been waiting for more TRBs to be freed up.
1197          *
1198          * In that case, we should check if we have a request with pending_sgs
1199          * in the started list and prepare TRBs for that request first,
1200          * otherwise we will prepare TRBs completely out of order and that will
1201          * break things.
1202          */
1203         list_for_each_entry(req, &dep->started_list, list) {
1204                 if (req->num_pending_sgs > 0)
1205                         dwc3_prepare_one_trb_sg(dep, req);
1206
1207                 if (!dwc3_calc_trbs_left(dep))
1208                         return;
1209         }
1210
1211         list_for_each_entry_safe(req, n, &dep->pending_list, list) {
1212                 struct dwc3     *dwc = dep->dwc;
1213                 int             ret;
1214
1215                 ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request,
1216                                                     dep->direction);
1217                 if (ret)
1218                         return;
1219
1220                 req->sg                 = req->request.sg;
1221                 req->num_pending_sgs    = req->request.num_mapped_sgs;
1222
1223                 if (req->num_pending_sgs > 0)
1224                         dwc3_prepare_one_trb_sg(dep, req);
1225                 else
1226                         dwc3_prepare_one_trb_linear(dep, req);
1227
1228                 if (!dwc3_calc_trbs_left(dep))
1229                         return;
1230         }
1231 }
1232
1233 static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep, u16 cmd_param)
1234 {
1235         struct dwc3_gadget_ep_cmd_params params;
1236         struct dwc3_request             *req;
1237         int                             starting;
1238         int                             ret;
1239         u32                             cmd;
1240
1241         starting = !(dep->flags & DWC3_EP_BUSY);
1242
1243         dwc3_prepare_trbs(dep);
1244         req = next_request(&dep->started_list);
1245         if (!req) {
1246                 dep->flags |= DWC3_EP_PENDING_REQUEST;
1247                 return 0;
1248         }
1249
1250         memset(&params, 0, sizeof(params));
1251
1252         if (starting) {
1253                 params.param0 = upper_32_bits(req->trb_dma);
1254                 params.param1 = lower_32_bits(req->trb_dma);
1255                 cmd = DWC3_DEPCMD_STARTTRANSFER |
1256                         DWC3_DEPCMD_PARAM(cmd_param);
1257         } else {
1258                 cmd = DWC3_DEPCMD_UPDATETRANSFER |
1259                         DWC3_DEPCMD_PARAM(dep->resource_index);
1260         }
1261
1262         ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1263         if (ret < 0) {
1264                 /*
1265                  * FIXME we need to iterate over the list of requests
1266                  * here and stop, unmap, free and del each of the linked
1267                  * requests instead of what we do now.
1268                  */
1269                 if (req->trb)
1270                         memset(req->trb, 0, sizeof(struct dwc3_trb));
1271                 dep->queued_requests--;
1272                 dwc3_gadget_del_and_unmap_request(dep, req, ret);
1273                 return ret;
1274         }
1275
1276         dep->flags |= DWC3_EP_BUSY;
1277
1278         if (starting) {
1279                 dep->resource_index = dwc3_gadget_ep_get_transfer_index(dep);
1280                 WARN_ON_ONCE(!dep->resource_index);
1281         }
1282
1283         return 0;
1284 }
1285
1286 static int __dwc3_gadget_get_frame(struct dwc3 *dwc)
1287 {
1288         u32                     reg;
1289
1290         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1291         return DWC3_DSTS_SOFFN(reg);
1292 }
1293
1294 static void __dwc3_gadget_start_isoc(struct dwc3 *dwc,
1295                 struct dwc3_ep *dep, u32 cur_uf)
1296 {
1297         u32 uf;
1298
1299         if (list_empty(&dep->pending_list)) {
1300                 dev_info(dwc->dev, "%s: ran out of requests\n",
1301                                 dep->name);
1302                 dep->flags |= DWC3_EP_PENDING_REQUEST;
1303                 return;
1304         }
1305
1306         /*
1307          * Schedule the first trb for one interval in the future or at
1308          * least 4 microframes.
1309          */
1310         uf = cur_uf + max_t(u32, 4, dep->interval);
1311
1312         __dwc3_gadget_kick_transfer(dep, uf);
1313 }
1314
1315 static void dwc3_gadget_start_isoc(struct dwc3 *dwc,
1316                 struct dwc3_ep *dep, const struct dwc3_event_depevt *event)
1317 {
1318         u32 cur_uf, mask;
1319
1320         mask = ~(dep->interval - 1);
1321         cur_uf = event->parameters & mask;
1322
1323         __dwc3_gadget_start_isoc(dwc, dep, cur_uf);
1324 }
1325
1326 static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
1327 {
1328         struct dwc3             *dwc = dep->dwc;
1329         int                     ret = 0;
1330
1331         if (!dep->endpoint.desc) {
1332                 dev_err(dwc->dev, "%s: can't queue to disabled endpoint\n",
1333                                 dep->name);
1334                 return -ESHUTDOWN;
1335         }
1336
1337         if (WARN(req->dep != dep, "request %pK belongs to '%s'\n",
1338                                 &req->request, req->dep->name))
1339                 return -EINVAL;
1340
1341         pm_runtime_get(dwc->dev);
1342
1343         req->request.actual     = 0;
1344         req->request.status     = -EINPROGRESS;
1345         req->direction          = dep->direction;
1346         req->epnum              = dep->number;
1347
1348         trace_dwc3_ep_queue(req);
1349
1350         list_add_tail(&req->list, &dep->pending_list);
1351
1352         /*
1353          * NOTICE: Isochronous endpoints should NEVER be prestarted. We must
1354          * wait for a XferNotReady event so we will know what's the current
1355          * (micro-)frame number.
1356          *
1357          * Without this trick, we are very, very likely gonna get Bus Expiry
1358          * errors which will force us issue EndTransfer command.
1359          */
1360         if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1361                 if ((dep->flags & DWC3_EP_PENDING_REQUEST)) {
1362                         if (dep->flags & DWC3_EP_TRANSFER_STARTED) {
1363                                 dwc3_stop_active_transfer(dwc, dep->number, true);
1364                                 dep->flags = DWC3_EP_ENABLED;
1365                         } else {
1366                                 u32 cur_uf;
1367
1368                                 cur_uf = __dwc3_gadget_get_frame(dwc);
1369                                 __dwc3_gadget_start_isoc(dwc, dep, cur_uf);
1370                                 dep->flags &= ~DWC3_EP_PENDING_REQUEST;
1371                         }
1372                         return 0;
1373                 }
1374
1375                 if ((dep->flags & DWC3_EP_BUSY) &&
1376                     !(dep->flags & DWC3_EP_MISSED_ISOC)) {
1377                         WARN_ON_ONCE(!dep->resource_index);
1378                         ret = __dwc3_gadget_kick_transfer(dep,
1379                                                           dep->resource_index);
1380                 }
1381
1382                 goto out;
1383         }
1384
1385         if (!dwc3_calc_trbs_left(dep))
1386                 return 0;
1387
1388         ret = __dwc3_gadget_kick_transfer(dep, 0);
1389 out:
1390         if (ret == -EBUSY)
1391                 ret = 0;
1392
1393         return ret;
1394 }
1395
1396 static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
1397         gfp_t gfp_flags)
1398 {
1399         struct dwc3_request             *req = to_dwc3_request(request);
1400         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1401         struct dwc3                     *dwc = dep->dwc;
1402
1403         unsigned long                   flags;
1404
1405         int                             ret;
1406
1407         spin_lock_irqsave(&dwc->lock, flags);
1408         ret = __dwc3_gadget_ep_queue(dep, req);
1409         spin_unlock_irqrestore(&dwc->lock, flags);
1410
1411         return ret;
1412 }
1413
1414 static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
1415                 struct usb_request *request)
1416 {
1417         struct dwc3_request             *req = to_dwc3_request(request);
1418         struct dwc3_request             *r = NULL;
1419
1420         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1421         struct dwc3                     *dwc = dep->dwc;
1422
1423         unsigned long                   flags;
1424         int                             ret = 0;
1425
1426         trace_dwc3_ep_dequeue(req);
1427
1428         spin_lock_irqsave(&dwc->lock, flags);
1429
1430         list_for_each_entry(r, &dep->pending_list, list) {
1431                 if (r == req)
1432                         break;
1433         }
1434
1435         if (r != req) {
1436                 list_for_each_entry(r, &dep->started_list, list) {
1437                         if (r == req)
1438                                 break;
1439                 }
1440                 if (r == req) {
1441                         /* wait until it is processed */
1442                         dwc3_stop_active_transfer(dwc, dep->number, true);
1443
1444                         /*
1445                          * If request was already started, this means we had to
1446                          * stop the transfer. With that we also need to ignore
1447                          * all TRBs used by the request, however TRBs can only
1448                          * be modified after completion of END_TRANSFER
1449                          * command. So what we do here is that we wait for
1450                          * END_TRANSFER completion and only after that, we jump
1451                          * over TRBs by clearing HWO and incrementing dequeue
1452                          * pointer.
1453                          *
1454                          * Note that we have 2 possible types of transfers here:
1455                          *
1456                          * i) Linear buffer request
1457                          * ii) SG-list based request
1458                          *
1459                          * SG-list based requests will have r->num_pending_sgs
1460                          * set to a valid number (> 0). Linear requests,
1461                          * normally use a single TRB.
1462                          *
1463                          * For each of these two cases, if r->unaligned flag is
1464                          * set, one extra TRB has been used to align transfer
1465                          * size to wMaxPacketSize.
1466                          *
1467                          * All of these cases need to be taken into
1468                          * consideration so we don't mess up our TRB ring
1469                          * pointers.
1470                          */
1471                         wait_event_lock_irq(dep->wait_end_transfer,
1472                                         !(dep->flags & DWC3_EP_END_TRANSFER_PENDING),
1473                                         dwc->lock);
1474
1475                         if (!r->trb)
1476                                 goto out0;
1477
1478                         if (r->num_pending_sgs) {
1479                                 struct dwc3_trb *trb;
1480                                 int i = 0;
1481
1482                                 for (i = 0; i < r->num_pending_sgs; i++) {
1483                                         trb = r->trb + i;
1484                                         trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1485                                         dwc3_ep_inc_deq(dep);
1486                                 }
1487
1488                                 if (r->unaligned || r->zero) {
1489                                         trb = r->trb + r->num_pending_sgs + 1;
1490                                         trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1491                                         dwc3_ep_inc_deq(dep);
1492                                 }
1493                         } else {
1494                                 struct dwc3_trb *trb = r->trb;
1495
1496                                 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1497                                 dwc3_ep_inc_deq(dep);
1498
1499                                 if (r->unaligned || r->zero) {
1500                                         trb = r->trb + 1;
1501                                         trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1502                                         dwc3_ep_inc_deq(dep);
1503                                 }
1504                         }
1505                         goto out1;
1506                 }
1507                 dev_err(dwc->dev, "request %pK was not queued to %s\n",
1508                                 request, ep->name);
1509                 ret = -EINVAL;
1510                 goto out0;
1511         }
1512
1513 out1:
1514         /* giveback the request */
1515         dep->queued_requests--;
1516         dwc3_gadget_giveback(dep, req, -ECONNRESET);
1517
1518 out0:
1519         spin_unlock_irqrestore(&dwc->lock, flags);
1520
1521         return ret;
1522 }
1523
1524 int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
1525 {
1526         struct dwc3_gadget_ep_cmd_params        params;
1527         struct dwc3                             *dwc = dep->dwc;
1528         int                                     ret;
1529
1530         if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1531                 dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
1532                 return -EINVAL;
1533         }
1534
1535         memset(&params, 0x00, sizeof(params));
1536
1537         if (value) {
1538                 struct dwc3_trb *trb;
1539
1540                 unsigned transfer_in_flight;
1541                 unsigned started;
1542
1543                 if (dep->number > 1)
1544                         trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
1545                 else
1546                         trb = &dwc->ep0_trb[dep->trb_enqueue];
1547
1548                 transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO;
1549                 started = !list_empty(&dep->started_list);
1550
1551                 if (!protocol && ((dep->direction && transfer_in_flight) ||
1552                                 (!dep->direction && started))) {
1553                         return -EAGAIN;
1554                 }
1555
1556                 ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL,
1557                                 &params);
1558                 if (ret)
1559                         dev_err(dwc->dev, "failed to set STALL on %s\n",
1560                                         dep->name);
1561                 else
1562                         dep->flags |= DWC3_EP_STALL;
1563         } else {
1564
1565                 ret = dwc3_send_clear_stall_ep_cmd(dep);
1566                 if (ret)
1567                         dev_err(dwc->dev, "failed to clear STALL on %s\n",
1568                                         dep->name);
1569                 else
1570                         dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
1571         }
1572
1573         return ret;
1574 }
1575
1576 static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
1577 {
1578         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1579         struct dwc3                     *dwc = dep->dwc;
1580
1581         unsigned long                   flags;
1582
1583         int                             ret;
1584
1585         spin_lock_irqsave(&dwc->lock, flags);
1586         ret = __dwc3_gadget_ep_set_halt(dep, value, false);
1587         spin_unlock_irqrestore(&dwc->lock, flags);
1588
1589         return ret;
1590 }
1591
1592 static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
1593 {
1594         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1595         struct dwc3                     *dwc = dep->dwc;
1596         unsigned long                   flags;
1597         int                             ret;
1598
1599         spin_lock_irqsave(&dwc->lock, flags);
1600         dep->flags |= DWC3_EP_WEDGE;
1601
1602         if (dep->number == 0 || dep->number == 1)
1603                 ret = __dwc3_gadget_ep0_set_halt(ep, 1);
1604         else
1605                 ret = __dwc3_gadget_ep_set_halt(dep, 1, false);
1606         spin_unlock_irqrestore(&dwc->lock, flags);
1607
1608         return ret;
1609 }
1610
1611 /* -------------------------------------------------------------------------- */
1612
1613 static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
1614         .bLength        = USB_DT_ENDPOINT_SIZE,
1615         .bDescriptorType = USB_DT_ENDPOINT,
1616         .bmAttributes   = USB_ENDPOINT_XFER_CONTROL,
1617 };
1618
1619 static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
1620         .enable         = dwc3_gadget_ep0_enable,
1621         .disable        = dwc3_gadget_ep0_disable,
1622         .alloc_request  = dwc3_gadget_ep_alloc_request,
1623         .free_request   = dwc3_gadget_ep_free_request,
1624         .queue          = dwc3_gadget_ep0_queue,
1625         .dequeue        = dwc3_gadget_ep_dequeue,
1626         .set_halt       = dwc3_gadget_ep0_set_halt,
1627         .set_wedge      = dwc3_gadget_ep_set_wedge,
1628 };
1629
1630 static const struct usb_ep_ops dwc3_gadget_ep_ops = {
1631         .enable         = dwc3_gadget_ep_enable,
1632         .disable        = dwc3_gadget_ep_disable,
1633         .alloc_request  = dwc3_gadget_ep_alloc_request,
1634         .free_request   = dwc3_gadget_ep_free_request,
1635         .queue          = dwc3_gadget_ep_queue,
1636         .dequeue        = dwc3_gadget_ep_dequeue,
1637         .set_halt       = dwc3_gadget_ep_set_halt,
1638         .set_wedge      = dwc3_gadget_ep_set_wedge,
1639 };
1640
1641 /* -------------------------------------------------------------------------- */
1642
1643 static int dwc3_gadget_get_frame(struct usb_gadget *g)
1644 {
1645         struct dwc3             *dwc = gadget_to_dwc(g);
1646
1647         return __dwc3_gadget_get_frame(dwc);
1648 }
1649
1650 static int __dwc3_gadget_wakeup(struct dwc3 *dwc)
1651 {
1652         int                     retries;
1653
1654         int                     ret;
1655         u32                     reg;
1656
1657         u8                      link_state;
1658
1659         /*
1660          * According to the Databook Remote wakeup request should
1661          * be issued only when the device is in early suspend state.
1662          *
1663          * We can check that via USB Link State bits in DSTS register.
1664          */
1665         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1666
1667         link_state = DWC3_DSTS_USBLNKST(reg);
1668
1669         switch (link_state) {
1670         case DWC3_LINK_STATE_RESET:
1671         case DWC3_LINK_STATE_RX_DET:    /* in HS, means Early Suspend */
1672         case DWC3_LINK_STATE_U3:        /* in HS, means SUSPEND */
1673         case DWC3_LINK_STATE_U2:        /* in HS, means Sleep (L1) */
1674         case DWC3_LINK_STATE_U1:
1675         case DWC3_LINK_STATE_RESUME:
1676                 break;
1677         default:
1678                 return -EINVAL;
1679         }
1680
1681         ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
1682         if (ret < 0) {
1683                 dev_err(dwc->dev, "failed to put link in Recovery\n");
1684                 return ret;
1685         }
1686
1687         /* Recent versions do this automatically */
1688         if (dwc->revision < DWC3_REVISION_194A) {
1689                 /* write zeroes to Link Change Request */
1690                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1691                 reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
1692                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1693         }
1694
1695         /* poll until Link State changes to ON */
1696         retries = 20000;
1697
1698         while (retries--) {
1699                 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1700
1701                 /* in HS, means ON */
1702                 if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
1703                         break;
1704         }
1705
1706         if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
1707                 dev_err(dwc->dev, "failed to send remote wakeup\n");
1708                 return -EINVAL;
1709         }
1710
1711         return 0;
1712 }
1713
1714 static int dwc3_gadget_wakeup(struct usb_gadget *g)
1715 {
1716         struct dwc3             *dwc = gadget_to_dwc(g);
1717         unsigned long           flags;
1718         int                     ret;
1719
1720         spin_lock_irqsave(&dwc->lock, flags);
1721         ret = __dwc3_gadget_wakeup(dwc);
1722         spin_unlock_irqrestore(&dwc->lock, flags);
1723
1724         return ret;
1725 }
1726
1727 static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
1728                 int is_selfpowered)
1729 {
1730         struct dwc3             *dwc = gadget_to_dwc(g);
1731         unsigned long           flags;
1732
1733         spin_lock_irqsave(&dwc->lock, flags);
1734         g->is_selfpowered = !!is_selfpowered;
1735         spin_unlock_irqrestore(&dwc->lock, flags);
1736
1737         return 0;
1738 }
1739
1740 static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on, int suspend)
1741 {
1742         u32                     reg;
1743         u32                     timeout = 500;
1744
1745         if (pm_runtime_suspended(dwc->dev))
1746                 return 0;
1747
1748         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1749         if (is_on) {
1750                 if (dwc->revision <= DWC3_REVISION_187A) {
1751                         reg &= ~DWC3_DCTL_TRGTULST_MASK;
1752                         reg |= DWC3_DCTL_TRGTULST_RX_DET;
1753                 }
1754
1755                 if (dwc->revision >= DWC3_REVISION_194A)
1756                         reg &= ~DWC3_DCTL_KEEP_CONNECT;
1757                 reg |= DWC3_DCTL_RUN_STOP;
1758
1759                 if (dwc->has_hibernation)
1760                         reg |= DWC3_DCTL_KEEP_CONNECT;
1761
1762                 dwc->pullups_connected = true;
1763         } else {
1764                 reg &= ~DWC3_DCTL_RUN_STOP;
1765
1766                 if (dwc->has_hibernation && !suspend)
1767                         reg &= ~DWC3_DCTL_KEEP_CONNECT;
1768
1769                 dwc->pullups_connected = false;
1770         }
1771
1772         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1773
1774         do {
1775                 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1776                 reg &= DWC3_DSTS_DEVCTRLHLT;
1777         } while (--timeout && !(!is_on ^ !reg));
1778
1779         if (!timeout)
1780                 return -ETIMEDOUT;
1781
1782         return 0;
1783 }
1784
1785 static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
1786 {
1787         struct dwc3             *dwc = gadget_to_dwc(g);
1788         unsigned long           flags;
1789         int                     ret;
1790
1791         is_on = !!is_on;
1792
1793         /*
1794          * Per databook, when we want to stop the gadget, if a control transfer
1795          * is still in process, complete it and get the core into setup phase.
1796          */
1797         if (!is_on && dwc->ep0state != EP0_SETUP_PHASE) {
1798                 reinit_completion(&dwc->ep0_in_setup);
1799
1800                 ret = wait_for_completion_timeout(&dwc->ep0_in_setup,
1801                                 msecs_to_jiffies(DWC3_PULL_UP_TIMEOUT));
1802                 if (ret == 0)
1803                         dev_warn(dwc->dev, "timed out waiting for SETUP phase\n");
1804         }
1805
1806         spin_lock_irqsave(&dwc->lock, flags);
1807         ret = dwc3_gadget_run_stop(dwc, is_on, false);
1808         spin_unlock_irqrestore(&dwc->lock, flags);
1809
1810         return ret;
1811 }
1812
1813 static void dwc3_gadget_enable_irq(struct dwc3 *dwc)
1814 {
1815         u32                     reg;
1816
1817         /* Enable all but Start and End of Frame IRQs */
1818         reg = (DWC3_DEVTEN_VNDRDEVTSTRCVEDEN |
1819                         DWC3_DEVTEN_EVNTOVERFLOWEN |
1820                         DWC3_DEVTEN_CMDCMPLTEN |
1821                         DWC3_DEVTEN_ERRTICERREN |
1822                         DWC3_DEVTEN_WKUPEVTEN |
1823                         DWC3_DEVTEN_CONNECTDONEEN |
1824                         DWC3_DEVTEN_USBRSTEN |
1825                         DWC3_DEVTEN_DISCONNEVTEN);
1826
1827         if (dwc->revision < DWC3_REVISION_250A)
1828                 reg |= DWC3_DEVTEN_ULSTCNGEN;
1829
1830         /* On 2.30a and above this bit enables U3/L2-L1 Suspend Events */
1831         if (dwc->revision >= DWC3_REVISION_230A)
1832                 reg |= DWC3_DEVTEN_EOPFEN;
1833
1834         dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
1835 }
1836
1837 static void dwc3_gadget_disable_irq(struct dwc3 *dwc)
1838 {
1839         /* mask all interrupts */
1840         dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
1841 }
1842
1843 static irqreturn_t dwc3_interrupt(int irq, void *_dwc);
1844 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc);
1845
1846 /**
1847  * dwc3_gadget_setup_nump - calculate and initialize NUMP field of %DWC3_DCFG
1848  * @dwc: pointer to our context structure
1849  *
1850  * The following looks like complex but it's actually very simple. In order to
1851  * calculate the number of packets we can burst at once on OUT transfers, we're
1852  * gonna use RxFIFO size.
1853  *
1854  * To calculate RxFIFO size we need two numbers:
1855  * MDWIDTH = size, in bits, of the internal memory bus
1856  * RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)
1857  *
1858  * Given these two numbers, the formula is simple:
1859  *
1860  * RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;
1861  *
1862  * 24 bytes is for 3x SETUP packets
1863  * 16 bytes is a clock domain crossing tolerance
1864  *
1865  * Given RxFIFO Size, NUMP = RxFIFOSize / 1024;
1866  */
1867 static void dwc3_gadget_setup_nump(struct dwc3 *dwc)
1868 {
1869         u32 ram2_depth;
1870         u32 mdwidth;
1871         u32 nump;
1872         u32 reg;
1873
1874         ram2_depth = DWC3_GHWPARAMS7_RAM2_DEPTH(dwc->hwparams.hwparams7);
1875         mdwidth = DWC3_GHWPARAMS0_MDWIDTH(dwc->hwparams.hwparams0);
1876
1877         nump = ((ram2_depth * mdwidth / 8) - 24 - 16) / 1024;
1878         nump = min_t(u32, nump, 16);
1879
1880         /* update NumP */
1881         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
1882         reg &= ~DWC3_DCFG_NUMP_MASK;
1883         reg |= nump << DWC3_DCFG_NUMP_SHIFT;
1884         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
1885 }
1886
1887 static int __dwc3_gadget_start(struct dwc3 *dwc)
1888 {
1889         struct dwc3_ep          *dep;
1890         int                     ret = 0;
1891         u32                     reg;
1892
1893         /*
1894          * Use IMOD if enabled via dwc->imod_interval. Otherwise, if
1895          * the core supports IMOD, disable it.
1896          */
1897         if (dwc->imod_interval) {
1898                 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
1899                 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
1900         } else if (dwc3_has_imod(dwc)) {
1901                 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), 0);
1902         }
1903
1904         /*
1905          * We are telling dwc3 that we want to use DCFG.NUMP as ACK TP's NUMP
1906          * field instead of letting dwc3 itself calculate that automatically.
1907          *
1908          * This way, we maximize the chances that we'll be able to get several
1909          * bursts of data without going through any sort of endpoint throttling.
1910          */
1911         reg = dwc3_readl(dwc->regs, DWC3_GRXTHRCFG);
1912         reg &= ~DWC3_GRXTHRCFG_PKTCNTSEL;
1913         dwc3_writel(dwc->regs, DWC3_GRXTHRCFG, reg);
1914
1915         dwc3_gadget_setup_nump(dwc);
1916
1917         /* Start with SuperSpeed Default */
1918         dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
1919
1920         dep = dwc->eps[0];
1921         ret = __dwc3_gadget_ep_enable(dep, false, false);
1922         if (ret) {
1923                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
1924                 goto err0;
1925         }
1926
1927         dep = dwc->eps[1];
1928         ret = __dwc3_gadget_ep_enable(dep, false, false);
1929         if (ret) {
1930                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
1931                 goto err1;
1932         }
1933
1934         /* begin to receive SETUP packets */
1935         dwc->ep0state = EP0_SETUP_PHASE;
1936         dwc->link_state = DWC3_LINK_STATE_SS_DIS;
1937         dwc->delayed_status = false;
1938         dwc3_ep0_out_start(dwc);
1939
1940         dwc3_gadget_enable_irq(dwc);
1941
1942         return 0;
1943
1944 err1:
1945         __dwc3_gadget_ep_disable(dwc->eps[0]);
1946
1947 err0:
1948         return ret;
1949 }
1950
1951 static int dwc3_gadget_start(struct usb_gadget *g,
1952                 struct usb_gadget_driver *driver)
1953 {
1954         struct dwc3             *dwc = gadget_to_dwc(g);
1955         unsigned long           flags;
1956         int                     ret = 0;
1957         int                     irq;
1958
1959         irq = dwc->irq_gadget;
1960         ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt,
1961                         IRQF_SHARED, "dwc3", dwc->ev_buf);
1962         if (ret) {
1963                 dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
1964                                 irq, ret);
1965                 goto err0;
1966         }
1967
1968         spin_lock_irqsave(&dwc->lock, flags);
1969         if (dwc->gadget_driver) {
1970                 dev_err(dwc->dev, "%s is already bound to %s\n",
1971                                 dwc->gadget.name,
1972                                 dwc->gadget_driver->driver.name);
1973                 ret = -EBUSY;
1974                 goto err1;
1975         }
1976
1977         dwc->gadget_driver      = driver;
1978
1979         if (pm_runtime_active(dwc->dev))
1980                 __dwc3_gadget_start(dwc);
1981
1982         spin_unlock_irqrestore(&dwc->lock, flags);
1983
1984         return 0;
1985
1986 err1:
1987         spin_unlock_irqrestore(&dwc->lock, flags);
1988         free_irq(irq, dwc);
1989
1990 err0:
1991         return ret;
1992 }
1993
1994 static void __dwc3_gadget_stop(struct dwc3 *dwc)
1995 {
1996         dwc3_gadget_disable_irq(dwc);
1997         __dwc3_gadget_ep_disable(dwc->eps[0]);
1998         __dwc3_gadget_ep_disable(dwc->eps[1]);
1999 }
2000
2001 static int dwc3_gadget_stop(struct usb_gadget *g)
2002 {
2003         struct dwc3             *dwc = gadget_to_dwc(g);
2004         unsigned long           flags;
2005         int                     epnum;
2006
2007         spin_lock_irqsave(&dwc->lock, flags);
2008
2009         if (pm_runtime_suspended(dwc->dev))
2010                 goto out;
2011
2012         __dwc3_gadget_stop(dwc);
2013
2014         for (epnum = 2; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2015                 struct dwc3_ep  *dep = dwc->eps[epnum];
2016
2017                 if (!dep)
2018                         continue;
2019
2020                 if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
2021                         continue;
2022
2023                 wait_event_lock_irq(dep->wait_end_transfer,
2024                                     !(dep->flags & DWC3_EP_END_TRANSFER_PENDING),
2025                                     dwc->lock);
2026         }
2027
2028 out:
2029         dwc->gadget_driver      = NULL;
2030         spin_unlock_irqrestore(&dwc->lock, flags);
2031
2032         free_irq(dwc->irq_gadget, dwc->ev_buf);
2033
2034         return 0;
2035 }
2036
2037 static void dwc3_gadget_set_speed(struct usb_gadget *g,
2038                                   enum usb_device_speed speed)
2039 {
2040         struct dwc3             *dwc = gadget_to_dwc(g);
2041         unsigned long           flags;
2042         u32                     reg;
2043
2044         spin_lock_irqsave(&dwc->lock, flags);
2045         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2046         reg &= ~(DWC3_DCFG_SPEED_MASK);
2047
2048         /*
2049          * WORKAROUND: DWC3 revision < 2.20a have an issue
2050          * which would cause metastability state on Run/Stop
2051          * bit if we try to force the IP to USB2-only mode.
2052          *
2053          * Because of that, we cannot configure the IP to any
2054          * speed other than the SuperSpeed
2055          *
2056          * Refers to:
2057          *
2058          * STAR#9000525659: Clock Domain Crossing on DCTL in
2059          * USB 2.0 Mode
2060          */
2061         if (dwc->revision < DWC3_REVISION_220A &&
2062             !dwc->dis_metastability_quirk) {
2063                 reg |= DWC3_DCFG_SUPERSPEED;
2064         } else {
2065                 switch (speed) {
2066                 case USB_SPEED_LOW:
2067                         reg |= DWC3_DCFG_LOWSPEED;
2068                         break;
2069                 case USB_SPEED_FULL:
2070                         reg |= DWC3_DCFG_FULLSPEED;
2071                         break;
2072                 case USB_SPEED_HIGH:
2073                         reg |= DWC3_DCFG_HIGHSPEED;
2074                         break;
2075                 case USB_SPEED_SUPER:
2076                         reg |= DWC3_DCFG_SUPERSPEED;
2077                         break;
2078                 case USB_SPEED_SUPER_PLUS:
2079                         reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2080                         break;
2081                 default:
2082                         dev_err(dwc->dev, "invalid speed (%d)\n", speed);
2083
2084                         if (dwc->revision & DWC3_REVISION_IS_DWC31)
2085                                 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2086                         else
2087                                 reg |= DWC3_DCFG_SUPERSPEED;
2088                 }
2089         }
2090         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2091
2092         spin_unlock_irqrestore(&dwc->lock, flags);
2093 }
2094
2095 static const struct usb_gadget_ops dwc3_gadget_ops = {
2096         .get_frame              = dwc3_gadget_get_frame,
2097         .wakeup                 = dwc3_gadget_wakeup,
2098         .set_selfpowered        = dwc3_gadget_set_selfpowered,
2099         .pullup                 = dwc3_gadget_pullup,
2100         .udc_start              = dwc3_gadget_start,
2101         .udc_stop               = dwc3_gadget_stop,
2102         .udc_set_speed          = dwc3_gadget_set_speed,
2103 };
2104
2105 /* -------------------------------------------------------------------------- */
2106
2107 static int dwc3_gadget_init_endpoints(struct dwc3 *dwc, u8 total)
2108 {
2109         struct dwc3_ep                  *dep;
2110         u8                              epnum;
2111
2112         INIT_LIST_HEAD(&dwc->gadget.ep_list);
2113
2114         for (epnum = 0; epnum < total; epnum++) {
2115                 bool                    direction = epnum & 1;
2116                 u8                      num = epnum >> 1;
2117
2118                 dep = kzalloc(sizeof(*dep), GFP_KERNEL);
2119                 if (!dep)
2120                         return -ENOMEM;
2121
2122                 dep->dwc = dwc;
2123                 dep->number = epnum;
2124                 dep->direction = direction;
2125                 dep->regs = dwc->regs + DWC3_DEP_BASE(epnum);
2126                 dwc->eps[epnum] = dep;
2127
2128                 snprintf(dep->name, sizeof(dep->name), "ep%u%s", num,
2129                                 direction ? "in" : "out");
2130
2131                 dep->endpoint.name = dep->name;
2132
2133                 if (!(dep->number > 1)) {
2134                         dep->endpoint.desc = &dwc3_gadget_ep0_desc;
2135                         dep->endpoint.comp_desc = NULL;
2136                 }
2137
2138                 spin_lock_init(&dep->lock);
2139
2140                 if (num == 0) {
2141                         usb_ep_set_maxpacket_limit(&dep->endpoint, 512);
2142                         dep->endpoint.maxburst = 1;
2143                         dep->endpoint.ops = &dwc3_gadget_ep0_ops;
2144                         if (!direction)
2145                                 dwc->gadget.ep0 = &dep->endpoint;
2146                 } else if (direction) {
2147                         int mdwidth;
2148                         int kbytes;
2149                         int size;
2150                         int ret;
2151
2152                         mdwidth = DWC3_MDWIDTH(dwc->hwparams.hwparams0);
2153                         /* MDWIDTH is represented in bits, we need it in bytes */
2154                         mdwidth /= 8;
2155
2156                         size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(num));
2157                         size = DWC3_GTXFIFOSIZ_TXFDEF(size);
2158
2159                         /* FIFO Depth is in MDWDITH bytes. Multiply */
2160                         size *= mdwidth;
2161
2162                         kbytes = size / 1024;
2163                         if (kbytes == 0)
2164                                 kbytes = 1;
2165
2166                         /*
2167                          * FIFO sizes account an extra MDWIDTH * (kbytes + 1) bytes for
2168                          * internal overhead. We don't really know how these are used,
2169                          * but documentation say it exists.
2170                          */
2171                         size -= mdwidth * (kbytes + 1);
2172                         size /= kbytes;
2173
2174                         usb_ep_set_maxpacket_limit(&dep->endpoint, size);
2175
2176                         dep->endpoint.max_streams = 15;
2177                         dep->endpoint.ops = &dwc3_gadget_ep_ops;
2178                         list_add_tail(&dep->endpoint.ep_list,
2179                                         &dwc->gadget.ep_list);
2180
2181                         ret = dwc3_alloc_trb_pool(dep);
2182                         if (ret)
2183                                 return ret;
2184                 } else {
2185                         int             ret;
2186
2187                         usb_ep_set_maxpacket_limit(&dep->endpoint, 1024);
2188                         dep->endpoint.max_streams = 15;
2189                         dep->endpoint.ops = &dwc3_gadget_ep_ops;
2190                         list_add_tail(&dep->endpoint.ep_list,
2191                                         &dwc->gadget.ep_list);
2192
2193                         ret = dwc3_alloc_trb_pool(dep);
2194                         if (ret)
2195                                 return ret;
2196                 }
2197
2198                 if (num == 0) {
2199                         dep->endpoint.caps.type_control = true;
2200                 } else {
2201                         dep->endpoint.caps.type_iso = true;
2202                         dep->endpoint.caps.type_bulk = true;
2203                         dep->endpoint.caps.type_int = true;
2204                 }
2205
2206                 dep->endpoint.caps.dir_in = direction;
2207                 dep->endpoint.caps.dir_out = !direction;
2208
2209                 INIT_LIST_HEAD(&dep->pending_list);
2210                 INIT_LIST_HEAD(&dep->started_list);
2211         }
2212
2213         return 0;
2214 }
2215
2216 static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
2217 {
2218         struct dwc3_ep                  *dep;
2219         u8                              epnum;
2220
2221         for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2222                 dep = dwc->eps[epnum];
2223                 if (!dep)
2224                         continue;
2225                 /*
2226                  * Physical endpoints 0 and 1 are special; they form the
2227                  * bi-directional USB endpoint 0.
2228                  *
2229                  * For those two physical endpoints, we don't allocate a TRB
2230                  * pool nor do we add them the endpoints list. Due to that, we
2231                  * shouldn't do these two operations otherwise we would end up
2232                  * with all sorts of bugs when removing dwc3.ko.
2233                  */
2234                 if (epnum != 0 && epnum != 1) {
2235                         dwc3_free_trb_pool(dep);
2236                         list_del(&dep->endpoint.ep_list);
2237                 }
2238
2239                 kfree(dep);
2240         }
2241 }
2242
2243 /* -------------------------------------------------------------------------- */
2244
2245 static int __dwc3_cleanup_done_trbs(struct dwc3 *dwc, struct dwc3_ep *dep,
2246                 struct dwc3_request *req, struct dwc3_trb *trb,
2247                 const struct dwc3_event_depevt *event, int status,
2248                 int chain)
2249 {
2250         unsigned int            count;
2251         unsigned int            s_pkt = 0;
2252         unsigned int            trb_status;
2253
2254         dwc3_ep_inc_deq(dep);
2255
2256         if (req->trb == trb)
2257                 dep->queued_requests--;
2258
2259         trace_dwc3_complete_trb(dep, trb);
2260
2261         /*
2262          * If we're in the middle of series of chained TRBs and we
2263          * receive a short transfer along the way, DWC3 will skip
2264          * through all TRBs including the last TRB in the chain (the
2265          * where CHN bit is zero. DWC3 will also avoid clearing HWO
2266          * bit and SW has to do it manually.
2267          *
2268          * We're going to do that here to avoid problems of HW trying
2269          * to use bogus TRBs for transfers.
2270          */
2271         if (chain && (trb->ctrl & DWC3_TRB_CTRL_HWO))
2272                 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2273
2274         /*
2275          * If we're dealing with unaligned size OUT transfer, we will be left
2276          * with one TRB pending in the ring. We need to manually clear HWO bit
2277          * from that TRB.
2278          */
2279         if ((req->zero || req->unaligned) && !(trb->ctrl & DWC3_TRB_CTRL_CHN)) {
2280                 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2281                 return 1;
2282         }
2283
2284         count = trb->size & DWC3_TRB_SIZE_MASK;
2285         req->remaining += count;
2286
2287         if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
2288                 return 1;
2289
2290         if (dep->direction) {
2291                 if (count) {
2292                         trb_status = DWC3_TRB_SIZE_TRBSTS(trb->size);
2293                         if (trb_status == DWC3_TRBSTS_MISSED_ISOC) {
2294                                 /*
2295                                  * If missed isoc occurred and there is
2296                                  * no request queued then issue END
2297                                  * TRANSFER, so that core generates
2298                                  * next xfernotready and we will issue
2299                                  * a fresh START TRANSFER.
2300                                  * If there are still queued request
2301                                  * then wait, do not issue either END
2302                                  * or UPDATE TRANSFER, just attach next
2303                                  * request in pending_list during
2304                                  * giveback.If any future queued request
2305                                  * is successfully transferred then we
2306                                  * will issue UPDATE TRANSFER for all
2307                                  * request in the pending_list.
2308                                  */
2309                                 dep->flags |= DWC3_EP_MISSED_ISOC;
2310                         } else {
2311                                 dev_err(dwc->dev, "incomplete IN transfer %s\n",
2312                                                 dep->name);
2313                                 status = -ECONNRESET;
2314                         }
2315                 } else {
2316                         dep->flags &= ~DWC3_EP_MISSED_ISOC;
2317                 }
2318         } else {
2319                 if (count && (event->status & DEPEVT_STATUS_SHORT))
2320                         s_pkt = 1;
2321         }
2322
2323         if (s_pkt && !chain)
2324                 return 1;
2325
2326         if ((event->status & DEPEVT_STATUS_IOC) &&
2327                         (trb->ctrl & DWC3_TRB_CTRL_IOC))
2328                 return 1;
2329
2330         return 0;
2331 }
2332
2333 static int dwc3_cleanup_done_reqs(struct dwc3 *dwc, struct dwc3_ep *dep,
2334                 const struct dwc3_event_depevt *event, int status)
2335 {
2336         struct dwc3_request     *req, *n;
2337         struct dwc3_trb         *trb;
2338         bool                    ioc = false;
2339         int                     ret = 0;
2340
2341         list_for_each_entry_safe(req, n, &dep->started_list, list) {
2342                 unsigned length;
2343                 int chain;
2344
2345                 length = req->request.length;
2346                 chain = req->num_pending_sgs > 0;
2347                 if (chain) {
2348                         struct scatterlist *sg = req->sg;
2349                         struct scatterlist *s;
2350                         unsigned int pending = req->num_pending_sgs;
2351                         unsigned int i;
2352
2353                         for_each_sg(sg, s, pending, i) {
2354                                 trb = &dep->trb_pool[dep->trb_dequeue];
2355
2356                                 if (trb->ctrl & DWC3_TRB_CTRL_HWO)
2357                                         break;
2358
2359                                 req->sg = sg_next(s);
2360                                 req->num_pending_sgs--;
2361
2362                                 ret = __dwc3_cleanup_done_trbs(dwc, dep, req, trb,
2363                                                 event, status, chain);
2364                                 if (ret)
2365                                         break;
2366                         }
2367                 } else {
2368                         trb = &dep->trb_pool[dep->trb_dequeue];
2369                         ret = __dwc3_cleanup_done_trbs(dwc, dep, req, trb,
2370                                         event, status, chain);
2371                 }
2372
2373                 if (req->unaligned || req->zero) {
2374                         trb = &dep->trb_pool[dep->trb_dequeue];
2375                         ret = __dwc3_cleanup_done_trbs(dwc, dep, req, trb,
2376                                         event, status, false);
2377                         req->unaligned = false;
2378                         req->zero = false;
2379                 }
2380
2381                 req->request.actual = length - req->remaining;
2382
2383                 if ((req->request.actual < length) && req->num_pending_sgs)
2384                         return __dwc3_gadget_kick_transfer(dep, 0);
2385
2386                 dwc3_gadget_giveback(dep, req, status);
2387
2388                 if (ret) {
2389                         if ((event->status & DEPEVT_STATUS_IOC) &&
2390                             (trb->ctrl & DWC3_TRB_CTRL_IOC))
2391                                 ioc = true;
2392                         break;
2393                 }
2394         }
2395
2396         /*
2397          * Our endpoint might get disabled by another thread during
2398          * dwc3_gadget_giveback(). If that happens, we're just gonna return 1
2399          * early on so DWC3_EP_BUSY flag gets cleared
2400          */
2401         if (!dep->endpoint.desc)
2402                 return 1;
2403
2404         if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
2405                         list_empty(&dep->started_list)) {
2406                 if (list_empty(&dep->pending_list)) {
2407                         /*
2408                          * If there is no entry in request list then do
2409                          * not issue END TRANSFER now. Just set PENDING
2410                          * flag, so that END TRANSFER is issued when an
2411                          * entry is added into request list.
2412                          */
2413                         dep->flags = DWC3_EP_PENDING_REQUEST;
2414                 } else {
2415                         dwc3_stop_active_transfer(dwc, dep->number, true);
2416                         dep->flags = DWC3_EP_ENABLED;
2417                 }
2418                 return 1;
2419         }
2420
2421         if (usb_endpoint_xfer_isoc(dep->endpoint.desc) && ioc)
2422                 return 0;
2423
2424         return 1;
2425 }
2426
2427 static void dwc3_endpoint_transfer_complete(struct dwc3 *dwc,
2428                 struct dwc3_ep *dep, const struct dwc3_event_depevt *event)
2429 {
2430         unsigned                status = 0;
2431         int                     clean_busy;
2432         u32                     is_xfer_complete;
2433
2434         is_xfer_complete = (event->endpoint_event == DWC3_DEPEVT_XFERCOMPLETE);
2435
2436         if (event->status & DEPEVT_STATUS_BUSERR)
2437                 status = -ECONNRESET;
2438
2439         clean_busy = dwc3_cleanup_done_reqs(dwc, dep, event, status);
2440         if (clean_busy && (!dep->endpoint.desc || is_xfer_complete ||
2441                                 usb_endpoint_xfer_isoc(dep->endpoint.desc)))
2442                 dep->flags &= ~DWC3_EP_BUSY;
2443
2444         /*
2445          * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
2446          * See dwc3_gadget_linksts_change_interrupt() for 1st half.
2447          */
2448         if (dwc->revision < DWC3_REVISION_183A) {
2449                 u32             reg;
2450                 int             i;
2451
2452                 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
2453                         dep = dwc->eps[i];
2454
2455                         if (!(dep->flags & DWC3_EP_ENABLED))
2456                                 continue;
2457
2458                         if (!list_empty(&dep->started_list))
2459                                 return;
2460                 }
2461
2462                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2463                 reg |= dwc->u1u2;
2464                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2465
2466                 dwc->u1u2 = 0;
2467         }
2468
2469         /*
2470          * Our endpoint might get disabled by another thread during
2471          * dwc3_gadget_giveback(). If that happens, we're just gonna return 1
2472          * early on so DWC3_EP_BUSY flag gets cleared
2473          */
2474         if (!dep->endpoint.desc)
2475                 return;
2476
2477         if (!usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
2478                 int ret;
2479
2480                 ret = __dwc3_gadget_kick_transfer(dep, 0);
2481                 if (!ret || ret == -EBUSY)
2482                         return;
2483         }
2484 }
2485
2486 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
2487                 const struct dwc3_event_depevt *event)
2488 {
2489         struct dwc3_ep          *dep;
2490         u8                      epnum = event->endpoint_number;
2491         u8                      cmd;
2492
2493         dep = dwc->eps[epnum];
2494
2495         if (!(dep->flags & DWC3_EP_ENABLED)) {
2496                 if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
2497                         return;
2498
2499                 /* Handle only EPCMDCMPLT when EP disabled */
2500                 if (event->endpoint_event != DWC3_DEPEVT_EPCMDCMPLT)
2501                         return;
2502         }
2503
2504         if (epnum == 0 || epnum == 1) {
2505                 dwc3_ep0_interrupt(dwc, event);
2506                 return;
2507         }
2508
2509         switch (event->endpoint_event) {
2510         case DWC3_DEPEVT_XFERCOMPLETE:
2511                 dep->resource_index = 0;
2512
2513                 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
2514                         dev_err(dwc->dev, "XferComplete for Isochronous endpoint\n");
2515                         return;
2516                 }
2517
2518                 dwc3_endpoint_transfer_complete(dwc, dep, event);
2519                 break;
2520         case DWC3_DEPEVT_XFERINPROGRESS:
2521                 dwc3_endpoint_transfer_complete(dwc, dep, event);
2522                 break;
2523         case DWC3_DEPEVT_XFERNOTREADY:
2524                 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
2525                         dwc3_gadget_start_isoc(dwc, dep, event);
2526                 } else {
2527                         int ret;
2528
2529                         ret = __dwc3_gadget_kick_transfer(dep, 0);
2530                         if (!ret || ret == -EBUSY)
2531                                 return;
2532                 }
2533
2534                 break;
2535         case DWC3_DEPEVT_STREAMEVT:
2536                 if (!usb_endpoint_xfer_bulk(dep->endpoint.desc)) {
2537                         dev_err(dwc->dev, "Stream event for non-Bulk %s\n",
2538                                         dep->name);
2539                         return;
2540                 }
2541                 break;
2542         case DWC3_DEPEVT_EPCMDCMPLT:
2543                 cmd = DEPEVT_PARAMETER_CMD(event->parameters);
2544
2545                 if (cmd == DWC3_DEPCMD_ENDTRANSFER) {
2546                         dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
2547                         wake_up(&dep->wait_end_transfer);
2548                 }
2549                 break;
2550         case DWC3_DEPEVT_RXTXFIFOEVT:
2551                 break;
2552         }
2553 }
2554
2555 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
2556 {
2557         if (dwc->gadget_driver && dwc->gadget_driver->disconnect) {
2558                 spin_unlock(&dwc->lock);
2559                 dwc->gadget_driver->disconnect(&dwc->gadget);
2560                 spin_lock(&dwc->lock);
2561         }
2562 }
2563
2564 static void dwc3_suspend_gadget(struct dwc3 *dwc)
2565 {
2566         if (dwc->gadget_driver && dwc->gadget_driver->suspend) {
2567                 spin_unlock(&dwc->lock);
2568                 dwc->gadget_driver->suspend(&dwc->gadget);
2569                 spin_lock(&dwc->lock);
2570         }
2571 }
2572
2573 static void dwc3_resume_gadget(struct dwc3 *dwc)
2574 {
2575         if (dwc->gadget_driver && dwc->gadget_driver->resume) {
2576                 spin_unlock(&dwc->lock);
2577                 dwc->gadget_driver->resume(&dwc->gadget);
2578                 spin_lock(&dwc->lock);
2579         }
2580 }
2581
2582 static void dwc3_reset_gadget(struct dwc3 *dwc)
2583 {
2584         if (!dwc->gadget_driver)
2585                 return;
2586
2587         if (dwc->gadget.speed != USB_SPEED_UNKNOWN) {
2588                 spin_unlock(&dwc->lock);
2589                 usb_gadget_udc_reset(&dwc->gadget, dwc->gadget_driver);
2590                 spin_lock(&dwc->lock);
2591         }
2592 }
2593
2594 static void dwc3_stop_active_transfer(struct dwc3 *dwc, u32 epnum, bool force)
2595 {
2596         struct dwc3_ep *dep;
2597         struct dwc3_gadget_ep_cmd_params params;
2598         u32 cmd;
2599         int ret;
2600
2601         dep = dwc->eps[epnum];
2602
2603         if ((dep->flags & DWC3_EP_END_TRANSFER_PENDING) ||
2604             !dep->resource_index)
2605                 return;
2606
2607         /*
2608          * NOTICE: We are violating what the Databook says about the
2609          * EndTransfer command. Ideally we would _always_ wait for the
2610          * EndTransfer Command Completion IRQ, but that's causing too
2611          * much trouble synchronizing between us and gadget driver.
2612          *
2613          * We have discussed this with the IP Provider and it was
2614          * suggested to giveback all requests here, but give HW some
2615          * extra time to synchronize with the interconnect. We're using
2616          * an arbitrary 100us delay for that.
2617          *
2618          * Note also that a similar handling was tested by Synopsys
2619          * (thanks a lot Paul) and nothing bad has come out of it.
2620          * In short, what we're doing is:
2621          *
2622          * - Issue EndTransfer WITH CMDIOC bit set
2623          * - Wait 100us
2624          *
2625          * As of IP version 3.10a of the DWC_usb3 IP, the controller
2626          * supports a mode to work around the above limitation. The
2627          * software can poll the CMDACT bit in the DEPCMD register
2628          * after issuing a EndTransfer command. This mode is enabled
2629          * by writing GUCTL2[14]. This polling is already done in the
2630          * dwc3_send_gadget_ep_cmd() function so if the mode is
2631          * enabled, the EndTransfer command will have completed upon
2632          * returning from this function and we don't need to delay for
2633          * 100us.
2634          *
2635          * This mode is NOT available on the DWC_usb31 IP.
2636          */
2637
2638         cmd = DWC3_DEPCMD_ENDTRANSFER;
2639         cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
2640         cmd |= DWC3_DEPCMD_CMDIOC;
2641         cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
2642         memset(&params, 0, sizeof(params));
2643         ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
2644         WARN_ON_ONCE(ret);
2645         dep->resource_index = 0;
2646         dep->flags &= ~DWC3_EP_BUSY;
2647
2648         if (dwc3_is_usb31(dwc) || dwc->revision < DWC3_REVISION_310A) {
2649                 dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
2650                 udelay(100);
2651         }
2652 }
2653
2654 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
2655 {
2656         u32 epnum;
2657
2658         for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2659                 struct dwc3_ep *dep;
2660                 int ret;
2661
2662                 dep = dwc->eps[epnum];
2663                 if (!dep)
2664                         continue;
2665
2666                 if (!(dep->flags & DWC3_EP_STALL))
2667                         continue;
2668
2669                 dep->flags &= ~DWC3_EP_STALL;
2670
2671                 ret = dwc3_send_clear_stall_ep_cmd(dep);
2672                 WARN_ON_ONCE(ret);
2673         }
2674 }
2675
2676 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
2677 {
2678         int                     reg;
2679
2680         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2681         reg &= ~DWC3_DCTL_INITU1ENA;
2682         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2683
2684         reg &= ~DWC3_DCTL_INITU2ENA;
2685         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2686
2687         dwc3_disconnect_gadget(dwc);
2688
2689         dwc->gadget.speed = USB_SPEED_UNKNOWN;
2690         dwc->setup_packet_pending = false;
2691         usb_gadget_set_state(&dwc->gadget, USB_STATE_NOTATTACHED);
2692
2693         dwc->connected = false;
2694 }
2695
2696 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
2697 {
2698         u32                     reg;
2699
2700         dwc->connected = true;
2701
2702         /*
2703          * Ideally, dwc3_reset_gadget() would trigger the function
2704          * drivers to stop any active transfers through ep disable.
2705          * However, for functions which defer ep disable, such as mass
2706          * storage, we will need to rely on the call to stop active
2707          * transfers here, and avoid allowing of request queuing.
2708          */
2709         dwc->connected = false;
2710
2711         /*
2712          * WORKAROUND: DWC3 revisions <1.88a have an issue which
2713          * would cause a missing Disconnect Event if there's a
2714          * pending Setup Packet in the FIFO.
2715          *
2716          * There's no suggested workaround on the official Bug
2717          * report, which states that "unless the driver/application
2718          * is doing any special handling of a disconnect event,
2719          * there is no functional issue".
2720          *
2721          * Unfortunately, it turns out that we _do_ some special
2722          * handling of a disconnect event, namely complete all
2723          * pending transfers, notify gadget driver of the
2724          * disconnection, and so on.
2725          *
2726          * Our suggested workaround is to follow the Disconnect
2727          * Event steps here, instead, based on a setup_packet_pending
2728          * flag. Such flag gets set whenever we have a SETUP_PENDING
2729          * status for EP0 TRBs and gets cleared on XferComplete for the
2730          * same endpoint.
2731          *
2732          * Refers to:
2733          *
2734          * STAR#9000466709: RTL: Device : Disconnect event not
2735          * generated if setup packet pending in FIFO
2736          */
2737         if (dwc->revision < DWC3_REVISION_188A) {
2738                 if (dwc->setup_packet_pending)
2739                         dwc3_gadget_disconnect_interrupt(dwc);
2740         }
2741
2742         dwc3_reset_gadget(dwc);
2743
2744         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2745         reg &= ~DWC3_DCTL_TSTCTRL_MASK;
2746         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2747         dwc->test_mode = false;
2748         dwc3_clear_stall_all_ep(dwc);
2749
2750         /* Reset device address to zero */
2751         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2752         reg &= ~(DWC3_DCFG_DEVADDR_MASK);
2753         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2754 }
2755
2756 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
2757 {
2758         struct dwc3_ep          *dep;
2759         int                     ret;
2760         u32                     reg;
2761         u8                      speed;
2762
2763         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2764         speed = reg & DWC3_DSTS_CONNECTSPD;
2765         dwc->speed = speed;
2766
2767         /*
2768          * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
2769          * each time on Connect Done.
2770          *
2771          * Currently we always use the reset value. If any platform
2772          * wants to set this to a different value, we need to add a
2773          * setting and update GCTL.RAMCLKSEL here.
2774          */
2775
2776         switch (speed) {
2777         case DWC3_DSTS_SUPERSPEED_PLUS:
2778                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2779                 dwc->gadget.ep0->maxpacket = 512;
2780                 dwc->gadget.speed = USB_SPEED_SUPER_PLUS;
2781                 break;
2782         case DWC3_DSTS_SUPERSPEED:
2783                 /*
2784                  * WORKAROUND: DWC3 revisions <1.90a have an issue which
2785                  * would cause a missing USB3 Reset event.
2786                  *
2787                  * In such situations, we should force a USB3 Reset
2788                  * event by calling our dwc3_gadget_reset_interrupt()
2789                  * routine.
2790                  *
2791                  * Refers to:
2792                  *
2793                  * STAR#9000483510: RTL: SS : USB3 reset event may
2794                  * not be generated always when the link enters poll
2795                  */
2796                 if (dwc->revision < DWC3_REVISION_190A)
2797                         dwc3_gadget_reset_interrupt(dwc);
2798
2799                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2800                 dwc->gadget.ep0->maxpacket = 512;
2801                 dwc->gadget.speed = USB_SPEED_SUPER;
2802                 break;
2803         case DWC3_DSTS_HIGHSPEED:
2804                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
2805                 dwc->gadget.ep0->maxpacket = 64;
2806                 dwc->gadget.speed = USB_SPEED_HIGH;
2807                 break;
2808         case DWC3_DSTS_FULLSPEED:
2809                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
2810                 dwc->gadget.ep0->maxpacket = 64;
2811                 dwc->gadget.speed = USB_SPEED_FULL;
2812                 break;
2813         case DWC3_DSTS_LOWSPEED:
2814                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(8);
2815                 dwc->gadget.ep0->maxpacket = 8;
2816                 dwc->gadget.speed = USB_SPEED_LOW;
2817                 break;
2818         }
2819
2820         dwc->eps[1]->endpoint.maxpacket = dwc->gadget.ep0->maxpacket;
2821
2822         /* Enable USB2 LPM Capability */
2823
2824         if ((dwc->revision > DWC3_REVISION_194A) &&
2825             (speed != DWC3_DSTS_SUPERSPEED) &&
2826             (speed != DWC3_DSTS_SUPERSPEED_PLUS)) {
2827                 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2828                 reg |= DWC3_DCFG_LPM_CAP;
2829                 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2830
2831                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2832                 reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
2833
2834                 reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold);
2835
2836                 /*
2837                  * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
2838                  * DCFG.LPMCap is set, core responses with an ACK and the
2839                  * BESL value in the LPM token is less than or equal to LPM
2840                  * NYET threshold.
2841                  */
2842                 WARN_ONCE(dwc->revision < DWC3_REVISION_240A
2843                                 && dwc->has_lpm_erratum,
2844                                 "LPM Erratum not available on dwc3 revisions < 2.40a\n");
2845
2846                 if (dwc->has_lpm_erratum && dwc->revision >= DWC3_REVISION_240A)
2847                         reg |= DWC3_DCTL_LPM_ERRATA(dwc->lpm_nyet_threshold);
2848
2849                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2850         } else {
2851                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2852                 reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
2853                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2854         }
2855
2856         dep = dwc->eps[0];
2857         ret = __dwc3_gadget_ep_enable(dep, true, false);
2858         if (ret) {
2859                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2860                 return;
2861         }
2862
2863         dep = dwc->eps[1];
2864         ret = __dwc3_gadget_ep_enable(dep, true, false);
2865         if (ret) {
2866                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2867                 return;
2868         }
2869
2870         /*
2871          * Configure PHY via GUSB3PIPECTLn if required.
2872          *
2873          * Update GTXFIFOSIZn
2874          *
2875          * In both cases reset values should be sufficient.
2876          */
2877 }
2878
2879 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
2880 {
2881         /*
2882          * TODO take core out of low power mode when that's
2883          * implemented.
2884          */
2885
2886         if (dwc->gadget_driver && dwc->gadget_driver->resume) {
2887                 spin_unlock(&dwc->lock);
2888                 dwc->gadget_driver->resume(&dwc->gadget);
2889                 spin_lock(&dwc->lock);
2890         }
2891 }
2892
2893 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
2894                 unsigned int evtinfo)
2895 {
2896         enum dwc3_link_state    next = evtinfo & DWC3_LINK_STATE_MASK;
2897         unsigned int            pwropt;
2898
2899         /*
2900          * WORKAROUND: DWC3 < 2.50a have an issue when configured without
2901          * Hibernation mode enabled which would show up when device detects
2902          * host-initiated U3 exit.
2903          *
2904          * In that case, device will generate a Link State Change Interrupt
2905          * from U3 to RESUME which is only necessary if Hibernation is
2906          * configured in.
2907          *
2908          * There are no functional changes due to such spurious event and we
2909          * just need to ignore it.
2910          *
2911          * Refers to:
2912          *
2913          * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
2914          * operational mode
2915          */
2916         pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
2917         if ((dwc->revision < DWC3_REVISION_250A) &&
2918                         (pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
2919                 if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
2920                                 (next == DWC3_LINK_STATE_RESUME)) {
2921                         return;
2922                 }
2923         }
2924
2925         /*
2926          * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
2927          * on the link partner, the USB session might do multiple entry/exit
2928          * of low power states before a transfer takes place.
2929          *
2930          * Due to this problem, we might experience lower throughput. The
2931          * suggested workaround is to disable DCTL[12:9] bits if we're
2932          * transitioning from U1/U2 to U0 and enable those bits again
2933          * after a transfer completes and there are no pending transfers
2934          * on any of the enabled endpoints.
2935          *
2936          * This is the first half of that workaround.
2937          *
2938          * Refers to:
2939          *
2940          * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
2941          * core send LGO_Ux entering U0
2942          */
2943         if (dwc->revision < DWC3_REVISION_183A) {
2944                 if (next == DWC3_LINK_STATE_U0) {
2945                         u32     u1u2;
2946                         u32     reg;
2947
2948                         switch (dwc->link_state) {
2949                         case DWC3_LINK_STATE_U1:
2950                         case DWC3_LINK_STATE_U2:
2951                                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2952                                 u1u2 = reg & (DWC3_DCTL_INITU2ENA
2953                                                 | DWC3_DCTL_ACCEPTU2ENA
2954                                                 | DWC3_DCTL_INITU1ENA
2955                                                 | DWC3_DCTL_ACCEPTU1ENA);
2956
2957                                 if (!dwc->u1u2)
2958                                         dwc->u1u2 = reg & u1u2;
2959
2960                                 reg &= ~u1u2;
2961
2962                                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2963                                 break;
2964                         default:
2965                                 /* do nothing */
2966                                 break;
2967                         }
2968                 }
2969         }
2970
2971         switch (next) {
2972         case DWC3_LINK_STATE_U1:
2973                 if (dwc->speed == USB_SPEED_SUPER)
2974                         dwc3_suspend_gadget(dwc);
2975                 break;
2976         case DWC3_LINK_STATE_U2:
2977         case DWC3_LINK_STATE_U3:
2978                 dwc3_suspend_gadget(dwc);
2979                 break;
2980         case DWC3_LINK_STATE_RESUME:
2981                 dwc3_resume_gadget(dwc);
2982                 break;
2983         default:
2984                 /* do nothing */
2985                 break;
2986         }
2987
2988         dwc->link_state = next;
2989 }
2990
2991 static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc,
2992                                           unsigned int evtinfo)
2993 {
2994         enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
2995
2996         if (dwc->link_state != next && next == DWC3_LINK_STATE_U3)
2997                 dwc3_suspend_gadget(dwc);
2998
2999         dwc->link_state = next;
3000 }
3001
3002 static void dwc3_gadget_hibernation_interrupt(struct dwc3 *dwc,
3003                 unsigned int evtinfo)
3004 {
3005         unsigned int is_ss = evtinfo & BIT(4);
3006
3007         /*
3008          * WORKAROUND: DWC3 revison 2.20a with hibernation support
3009          * have a known issue which can cause USB CV TD.9.23 to fail
3010          * randomly.
3011          *
3012          * Because of this issue, core could generate bogus hibernation
3013          * events which SW needs to ignore.
3014          *
3015          * Refers to:
3016          *
3017          * STAR#9000546576: Device Mode Hibernation: Issue in USB 2.0
3018          * Device Fallback from SuperSpeed
3019          */
3020         if (is_ss ^ (dwc->speed == USB_SPEED_SUPER))
3021                 return;
3022
3023         /* enter hibernation here */
3024 }
3025
3026 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
3027                 const struct dwc3_event_devt *event)
3028 {
3029         switch (event->type) {
3030         case DWC3_DEVICE_EVENT_DISCONNECT:
3031                 dwc3_gadget_disconnect_interrupt(dwc);
3032                 break;
3033         case DWC3_DEVICE_EVENT_RESET:
3034                 dwc3_gadget_reset_interrupt(dwc);
3035                 break;
3036         case DWC3_DEVICE_EVENT_CONNECT_DONE:
3037                 dwc3_gadget_conndone_interrupt(dwc);
3038                 break;
3039         case DWC3_DEVICE_EVENT_WAKEUP:
3040                 dwc3_gadget_wakeup_interrupt(dwc);
3041                 break;
3042         case DWC3_DEVICE_EVENT_HIBER_REQ:
3043                 if (dev_WARN_ONCE(dwc->dev, !dwc->has_hibernation,
3044                                         "unexpected hibernation event\n"))
3045                         break;
3046
3047                 dwc3_gadget_hibernation_interrupt(dwc, event->event_info);
3048                 break;
3049         case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
3050                 dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
3051                 break;
3052         case DWC3_DEVICE_EVENT_EOPF:
3053                 /* It changed to be suspend event for version 2.30a and above */
3054                 if (dwc->revision >= DWC3_REVISION_230A) {
3055                         /*
3056                          * Ignore suspend event until the gadget enters into
3057                          * USB_STATE_CONFIGURED state.
3058                          */
3059                         if (dwc->gadget.state >= USB_STATE_CONFIGURED)
3060                                 dwc3_gadget_suspend_interrupt(dwc,
3061                                                 event->event_info);
3062                 }
3063                 break;
3064         case DWC3_DEVICE_EVENT_SOF:
3065         case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
3066         case DWC3_DEVICE_EVENT_CMD_CMPL:
3067         case DWC3_DEVICE_EVENT_OVERFLOW:
3068                 break;
3069         default:
3070                 dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
3071         }
3072 }
3073
3074 static void dwc3_process_event_entry(struct dwc3 *dwc,
3075                 const union dwc3_event *event)
3076 {
3077         trace_dwc3_event(event->raw, dwc);
3078
3079         if (!event->type.is_devspec)
3080                 dwc3_endpoint_interrupt(dwc, &event->depevt);
3081         else if (event->type.type == DWC3_EVENT_TYPE_DEV)
3082                 dwc3_gadget_interrupt(dwc, &event->devt);
3083         else
3084                 dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
3085 }
3086
3087 static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt)
3088 {
3089         struct dwc3 *dwc = evt->dwc;
3090         irqreturn_t ret = IRQ_NONE;
3091         int left;
3092         u32 reg;
3093
3094         left = evt->count;
3095
3096         if (!(evt->flags & DWC3_EVENT_PENDING))
3097                 return IRQ_NONE;
3098
3099         while (left > 0) {
3100                 union dwc3_event event;
3101
3102                 event.raw = *(u32 *) (evt->cache + evt->lpos);
3103
3104                 dwc3_process_event_entry(dwc, &event);
3105
3106                 /*
3107                  * FIXME we wrap around correctly to the next entry as
3108                  * almost all entries are 4 bytes in size. There is one
3109                  * entry which has 12 bytes which is a regular entry
3110                  * followed by 8 bytes data. ATM I don't know how
3111                  * things are organized if we get next to the a
3112                  * boundary so I worry about that once we try to handle
3113                  * that.
3114                  */
3115                 evt->lpos = (evt->lpos + 4) % evt->length;
3116                 left -= 4;
3117         }
3118
3119         evt->count = 0;
3120         evt->flags &= ~DWC3_EVENT_PENDING;
3121         ret = IRQ_HANDLED;
3122
3123         /* Unmask interrupt */
3124         reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
3125         reg &= ~DWC3_GEVNTSIZ_INTMASK;
3126         dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
3127
3128         if (dwc->imod_interval) {
3129                 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
3130                 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
3131         }
3132
3133         return ret;
3134 }
3135
3136 static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt)
3137 {
3138         struct dwc3_event_buffer *evt = _evt;
3139         struct dwc3 *dwc = evt->dwc;
3140         unsigned long flags;
3141         irqreturn_t ret = IRQ_NONE;
3142
3143         spin_lock_irqsave(&dwc->lock, flags);
3144         ret = dwc3_process_event_buf(evt);
3145         spin_unlock_irqrestore(&dwc->lock, flags);
3146
3147         return ret;
3148 }
3149
3150 static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt)
3151 {
3152         struct dwc3 *dwc = evt->dwc;
3153         u32 amount;
3154         u32 count;
3155         u32 reg;
3156
3157         if (pm_runtime_suspended(dwc->dev)) {
3158                 pm_runtime_get(dwc->dev);
3159                 disable_irq_nosync(dwc->irq_gadget);
3160                 dwc->pending_events = true;
3161                 return IRQ_HANDLED;
3162         }
3163
3164         /*
3165          * With PCIe legacy interrupt, test shows that top-half irq handler can
3166          * be called again after HW interrupt deassertion. Check if bottom-half
3167          * irq event handler completes before caching new event to prevent
3168          * losing events.
3169          */
3170         if (evt->flags & DWC3_EVENT_PENDING)
3171                 return IRQ_HANDLED;
3172
3173         count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
3174         count &= DWC3_GEVNTCOUNT_MASK;
3175         if (!count)
3176                 return IRQ_NONE;
3177
3178         evt->count = count;
3179         evt->flags |= DWC3_EVENT_PENDING;
3180
3181         /* Mask interrupt */
3182         reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
3183         reg |= DWC3_GEVNTSIZ_INTMASK;
3184         dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
3185
3186         amount = min(count, evt->length - evt->lpos);
3187         memcpy(evt->cache + evt->lpos, evt->buf + evt->lpos, amount);
3188
3189         if (amount < count)
3190                 memcpy(evt->cache, evt->buf, count - amount);
3191
3192         dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
3193
3194         return IRQ_WAKE_THREAD;
3195 }
3196
3197 static irqreturn_t dwc3_interrupt(int irq, void *_evt)
3198 {
3199         struct dwc3_event_buffer        *evt = _evt;
3200
3201         return dwc3_check_event_buf(evt);
3202 }
3203
3204 static int dwc3_gadget_get_irq(struct dwc3 *dwc)
3205 {
3206         struct platform_device *dwc3_pdev = to_platform_device(dwc->dev);
3207         int irq;
3208
3209         irq = platform_get_irq_byname(dwc3_pdev, "peripheral");
3210         if (irq > 0)
3211                 goto out;
3212
3213         if (irq == -EPROBE_DEFER)
3214                 goto out;
3215
3216         irq = platform_get_irq_byname(dwc3_pdev, "dwc_usb3");
3217         if (irq > 0)
3218                 goto out;
3219
3220         if (irq == -EPROBE_DEFER)
3221                 goto out;
3222
3223         irq = platform_get_irq(dwc3_pdev, 0);
3224         if (irq > 0)
3225                 goto out;
3226
3227         if (irq != -EPROBE_DEFER)
3228                 dev_err(dwc->dev, "missing peripheral IRQ\n");
3229
3230         if (!irq)
3231                 irq = -EINVAL;
3232
3233 out:
3234         return irq;
3235 }
3236
3237 /**
3238  * dwc3_gadget_init - initializes gadget related registers
3239  * @dwc: pointer to our controller context structure
3240  *
3241  * Returns 0 on success otherwise negative errno.
3242  */
3243 int dwc3_gadget_init(struct dwc3 *dwc)
3244 {
3245         int ret;
3246         int irq;
3247
3248         irq = dwc3_gadget_get_irq(dwc);
3249         if (irq < 0) {
3250                 ret = irq;
3251                 goto err0;
3252         }
3253
3254         dwc->irq_gadget = irq;
3255
3256         dwc->ep0_trb = dma_alloc_coherent(dwc->sysdev,
3257                                           sizeof(*dwc->ep0_trb) * 2,
3258                                           &dwc->ep0_trb_addr, GFP_KERNEL);
3259         if (!dwc->ep0_trb) {
3260                 dev_err(dwc->dev, "failed to allocate ep0 trb\n");
3261                 ret = -ENOMEM;
3262                 goto err0;
3263         }
3264
3265         dwc->setup_buf = kzalloc(DWC3_EP0_SETUP_SIZE, GFP_KERNEL);
3266         if (!dwc->setup_buf) {
3267                 ret = -ENOMEM;
3268                 goto err1;
3269         }
3270
3271         dwc->bounce = dma_alloc_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE,
3272                         &dwc->bounce_addr, GFP_KERNEL);
3273         if (!dwc->bounce) {
3274                 ret = -ENOMEM;
3275                 goto err2;
3276         }
3277
3278         init_completion(&dwc->ep0_in_setup);
3279
3280         dwc->gadget.ops                 = &dwc3_gadget_ops;
3281         dwc->gadget.speed               = USB_SPEED_UNKNOWN;
3282         dwc->gadget.sg_supported        = true;
3283         dwc->gadget.name                = "dwc3-gadget";
3284
3285         /*
3286          * FIXME We might be setting max_speed to <SUPER, however versions
3287          * <2.20a of dwc3 have an issue with metastability (documented
3288          * elsewhere in this driver) which tells us we can't set max speed to
3289          * anything lower than SUPER.
3290          *
3291          * Because gadget.max_speed is only used by composite.c and function
3292          * drivers (i.e. it won't go into dwc3's registers) we are allowing this
3293          * to happen so we avoid sending SuperSpeed Capability descriptor
3294          * together with our BOS descriptor as that could confuse host into
3295          * thinking we can handle super speed.
3296          *
3297          * Note that, in fact, we won't even support GetBOS requests when speed
3298          * is less than super speed because we don't have means, yet, to tell
3299          * composite.c that we are USB 2.0 + LPM ECN.
3300          */
3301         if (dwc->revision < DWC3_REVISION_220A &&
3302             !dwc->dis_metastability_quirk)
3303                 dev_info(dwc->dev, "changing max_speed on rev %08x\n",
3304                                 dwc->revision);
3305
3306         dwc->gadget.max_speed           = dwc->maximum_speed;
3307
3308         /*
3309          * REVISIT: Here we should clear all pending IRQs to be
3310          * sure we're starting from a well known location.
3311          */
3312
3313         ret = dwc3_gadget_init_endpoints(dwc, dwc->num_eps);
3314         if (ret)
3315                 goto err3;
3316
3317         ret = usb_add_gadget_udc(dwc->dev, &dwc->gadget);
3318         if (ret) {
3319                 dev_err(dwc->dev, "failed to register udc\n");
3320                 goto err4;
3321         }
3322
3323         dwc3_gadget_set_speed(&dwc->gadget, dwc->maximum_speed);
3324
3325         return 0;
3326
3327 err4:
3328         dwc3_gadget_free_endpoints(dwc);
3329
3330 err3:
3331         dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
3332                         dwc->bounce_addr);
3333
3334 err2:
3335         kfree(dwc->setup_buf);
3336
3337 err1:
3338         dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
3339                         dwc->ep0_trb, dwc->ep0_trb_addr);
3340
3341 err0:
3342         return ret;
3343 }
3344
3345 /* -------------------------------------------------------------------------- */
3346
3347 void dwc3_gadget_exit(struct dwc3 *dwc)
3348 {
3349         usb_del_gadget_udc(&dwc->gadget);
3350         dwc3_gadget_free_endpoints(dwc);
3351         dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
3352                           dwc->bounce_addr);
3353         kfree(dwc->setup_buf);
3354         dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
3355                           dwc->ep0_trb, dwc->ep0_trb_addr);
3356 }
3357
3358 int dwc3_gadget_suspend(struct dwc3 *dwc)
3359 {
3360         if (!dwc->gadget_driver)
3361                 return 0;
3362
3363         dwc3_gadget_run_stop(dwc, false, false);
3364         dwc3_disconnect_gadget(dwc);
3365         __dwc3_gadget_stop(dwc);
3366
3367         synchronize_irq(dwc->irq_gadget);
3368
3369         return 0;
3370 }
3371
3372 int dwc3_gadget_resume(struct dwc3 *dwc)
3373 {
3374         int                     ret;
3375
3376         if (!dwc->gadget_driver)
3377                 return 0;
3378
3379         ret = __dwc3_gadget_start(dwc);
3380         if (ret < 0)
3381                 goto err0;
3382
3383         ret = dwc3_gadget_run_stop(dwc, true, false);
3384         if (ret < 0)
3385                 goto err1;
3386
3387         return 0;
3388
3389 err1:
3390         __dwc3_gadget_stop(dwc);
3391
3392 err0:
3393         return ret;
3394 }
3395
3396 void dwc3_gadget_process_pending_events(struct dwc3 *dwc)
3397 {
3398         if (dwc->pending_events) {
3399                 dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf);
3400                 dwc->pending_events = false;
3401                 enable_irq(dwc->irq_gadget);
3402         }
3403 }