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