3a5c2715a3b5e05e19d9656628705331fb115339
[cascardo/linux.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->queued) {
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->queued = 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->req_queued)) {
526                 dwc3_stop_active_transfer(dwc, dep->number, true);
527
528                 /* - giveback all requests to gadget driver */
529                 while (!list_empty(&dep->req_queued)) {
530                         req = next_request(&dep->req_queued);
531
532                         dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
533                 }
534         }
535
536         while (!list_empty(&dep->request_list)) {
537                 req = next_request(&dep->request_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_request_queued(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                 break;
730
731         case USB_ENDPOINT_XFER_BULK:
732         case USB_ENDPOINT_XFER_INT:
733                 trb->ctrl = DWC3_TRBCTL_NORMAL;
734                 break;
735         default:
736                 /*
737                  * This is only possible with faulty memory because we
738                  * checked it already :)
739                  */
740                 BUG();
741         }
742
743         if (!req->request.no_interrupt && !chain)
744                 trb->ctrl |= DWC3_TRB_CTRL_IOC;
745
746         if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
747                 trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
748                 trb->ctrl |= DWC3_TRB_CTRL_CSP;
749         } else if (last) {
750                 trb->ctrl |= DWC3_TRB_CTRL_LST;
751         }
752
753         if (chain)
754                 trb->ctrl |= DWC3_TRB_CTRL_CHN;
755
756         if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable)
757                 trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(req->request.stream_id);
758
759         trb->ctrl |= DWC3_TRB_CTRL_HWO;
760
761         trace_dwc3_prepare_trb(dep, trb);
762 }
763
764 /*
765  * dwc3_prepare_trbs - setup TRBs from requests
766  * @dep: endpoint for which requests are being prepared
767  * @starting: true if the endpoint is idle and no requests are queued.
768  *
769  * The function goes through the requests list and sets up TRBs for the
770  * transfers. The function returns once there are no more TRBs available or
771  * it runs out of requests.
772  */
773 static void dwc3_prepare_trbs(struct dwc3_ep *dep, bool starting)
774 {
775         struct dwc3_request     *req, *n;
776         u32                     trbs_left;
777         u32                     max;
778         unsigned int            last_one = 0;
779
780         BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
781
782         /* the first request must not be queued */
783         trbs_left = (dep->busy_slot - dep->free_slot) & DWC3_TRB_MASK;
784
785         /* Can't wrap around on a non-isoc EP since there's no link TRB */
786         if (!usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
787                 max = DWC3_TRB_NUM - (dep->free_slot & DWC3_TRB_MASK);
788                 if (trbs_left > max)
789                         trbs_left = max;
790         }
791
792         /*
793          * If busy & slot are equal than it is either full or empty. If we are
794          * starting to process requests then we are empty. Otherwise we are
795          * full and don't do anything
796          */
797         if (!trbs_left) {
798                 if (!starting)
799                         return;
800                 trbs_left = DWC3_TRB_NUM;
801                 /*
802                  * In case we start from scratch, we queue the ISOC requests
803                  * starting from slot 1. This is done because we use ring
804                  * buffer and have no LST bit to stop us. Instead, we place
805                  * IOC bit every TRB_NUM/4. We try to avoid having an interrupt
806                  * after the first request so we start at slot 1 and have
807                  * 7 requests proceed before we hit the first IOC.
808                  * Other transfer types don't use the ring buffer and are
809                  * processed from the first TRB until the last one. Since we
810                  * don't wrap around we have to start at the beginning.
811                  */
812                 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
813                         dep->busy_slot = 1;
814                         dep->free_slot = 1;
815                 } else {
816                         dep->busy_slot = 0;
817                         dep->free_slot = 0;
818                 }
819         }
820
821         /* The last TRB is a link TRB, not used for xfer */
822         if ((trbs_left <= 1) && usb_endpoint_xfer_isoc(dep->endpoint.desc))
823                 return;
824
825         list_for_each_entry_safe(req, n, &dep->request_list, list) {
826                 unsigned        length;
827                 dma_addr_t      dma;
828                 last_one = false;
829
830                 if (req->request.num_mapped_sgs > 0) {
831                         struct usb_request *request = &req->request;
832                         struct scatterlist *sg = request->sg;
833                         struct scatterlist *s;
834                         int             i;
835
836                         for_each_sg(sg, s, request->num_mapped_sgs, i) {
837                                 unsigned chain = true;
838
839                                 length = sg_dma_len(s);
840                                 dma = sg_dma_address(s);
841
842                                 if (i == (request->num_mapped_sgs - 1) ||
843                                                 sg_is_last(s)) {
844                                         if (list_empty(&dep->request_list))
845                                                 last_one = true;
846                                         chain = false;
847                                 }
848
849                                 trbs_left--;
850                                 if (!trbs_left)
851                                         last_one = true;
852
853                                 if (last_one)
854                                         chain = false;
855
856                                 dwc3_prepare_one_trb(dep, req, dma, length,
857                                                 last_one, chain, i);
858
859                                 if (last_one)
860                                         break;
861                         }
862
863                         if (last_one)
864                                 break;
865                 } else {
866                         dma = req->request.dma;
867                         length = req->request.length;
868                         trbs_left--;
869
870                         if (!trbs_left)
871                                 last_one = 1;
872
873                         /* Is this the last request? */
874                         if (list_is_last(&req->list, &dep->request_list))
875                                 last_one = 1;
876
877                         dwc3_prepare_one_trb(dep, req, dma, length,
878                                         last_one, false, 0);
879
880                         if (last_one)
881                                 break;
882                 }
883         }
884 }
885
886 static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep, u16 cmd_param,
887                 int start_new)
888 {
889         struct dwc3_gadget_ep_cmd_params params;
890         struct dwc3_request             *req;
891         struct dwc3                     *dwc = dep->dwc;
892         int                             ret;
893         u32                             cmd;
894
895         if (start_new && (dep->flags & DWC3_EP_BUSY)) {
896                 dwc3_trace(trace_dwc3_gadget, "%s: endpoint busy", dep->name);
897                 return -EBUSY;
898         }
899
900         /*
901          * If we are getting here after a short-out-packet we don't enqueue any
902          * new requests as we try to set the IOC bit only on the last request.
903          */
904         if (start_new) {
905                 if (list_empty(&dep->req_queued))
906                         dwc3_prepare_trbs(dep, start_new);
907
908                 /* req points to the first request which will be sent */
909                 req = next_request(&dep->req_queued);
910         } else {
911                 dwc3_prepare_trbs(dep, start_new);
912
913                 /*
914                  * req points to the first request where HWO changed from 0 to 1
915                  */
916                 req = next_request(&dep->req_queued);
917         }
918         if (!req) {
919                 dep->flags |= DWC3_EP_PENDING_REQUEST;
920                 return 0;
921         }
922
923         memset(&params, 0, sizeof(params));
924
925         if (start_new) {
926                 params.param0 = upper_32_bits(req->trb_dma);
927                 params.param1 = lower_32_bits(req->trb_dma);
928                 cmd = DWC3_DEPCMD_STARTTRANSFER;
929         } else {
930                 cmd = DWC3_DEPCMD_UPDATETRANSFER;
931         }
932
933         cmd |= DWC3_DEPCMD_PARAM(cmd_param);
934         ret = dwc3_send_gadget_ep_cmd(dwc, dep->number, cmd, &params);
935         if (ret < 0) {
936                 /*
937                  * FIXME we need to iterate over the list of requests
938                  * here and stop, unmap, free and del each of the linked
939                  * requests instead of what we do now.
940                  */
941                 usb_gadget_unmap_request(&dwc->gadget, &req->request,
942                                 req->direction);
943                 list_del(&req->list);
944                 return ret;
945         }
946
947         dep->flags |= DWC3_EP_BUSY;
948
949         if (start_new) {
950                 dep->resource_index = dwc3_gadget_ep_get_transfer_index(dwc,
951                                 dep->number);
952                 WARN_ON_ONCE(!dep->resource_index);
953         }
954
955         return 0;
956 }
957
958 static void __dwc3_gadget_start_isoc(struct dwc3 *dwc,
959                 struct dwc3_ep *dep, u32 cur_uf)
960 {
961         u32 uf;
962
963         if (list_empty(&dep->request_list)) {
964                 dwc3_trace(trace_dwc3_gadget,
965                                 "ISOC ep %s run out for requests",
966                                 dep->name);
967                 dep->flags |= DWC3_EP_PENDING_REQUEST;
968                 return;
969         }
970
971         /* 4 micro frames in the future */
972         uf = cur_uf + dep->interval * 4;
973
974         __dwc3_gadget_kick_transfer(dep, uf, 1);
975 }
976
977 static void dwc3_gadget_start_isoc(struct dwc3 *dwc,
978                 struct dwc3_ep *dep, const struct dwc3_event_depevt *event)
979 {
980         u32 cur_uf, mask;
981
982         mask = ~(dep->interval - 1);
983         cur_uf = event->parameters & mask;
984
985         __dwc3_gadget_start_isoc(dwc, dep, cur_uf);
986 }
987
988 static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
989 {
990         struct dwc3             *dwc = dep->dwc;
991         int                     ret;
992
993         if (!dep->endpoint.desc) {
994                 dwc3_trace(trace_dwc3_gadget,
995                                 "trying to queue request %p to disabled %s\n",
996                                 &req->request, dep->endpoint.name);
997                 return -ESHUTDOWN;
998         }
999
1000         if (WARN(req->dep != dep, "request %p belongs to '%s'\n",
1001                                 &req->request, req->dep->name)) {
1002                 dwc3_trace(trace_dwc3_gadget, "request %p belongs to '%s'\n",
1003                                 &req->request, req->dep->name);
1004                 return -EINVAL;
1005         }
1006
1007         req->request.actual     = 0;
1008         req->request.status     = -EINPROGRESS;
1009         req->direction          = dep->direction;
1010         req->epnum              = dep->number;
1011
1012         trace_dwc3_ep_queue(req);
1013
1014         /*
1015          * We only add to our list of requests now and
1016          * start consuming the list once we get XferNotReady
1017          * IRQ.
1018          *
1019          * That way, we avoid doing anything that we don't need
1020          * to do now and defer it until the point we receive a
1021          * particular token from the Host side.
1022          *
1023          * This will also avoid Host cancelling URBs due to too
1024          * many NAKs.
1025          */
1026         ret = usb_gadget_map_request(&dwc->gadget, &req->request,
1027                         dep->direction);
1028         if (ret)
1029                 return ret;
1030
1031         list_add_tail(&req->list, &dep->request_list);
1032
1033         /*
1034          * If there are no pending requests and the endpoint isn't already
1035          * busy, we will just start the request straight away.
1036          *
1037          * This will save one IRQ (XFER_NOT_READY) and possibly make it a
1038          * little bit faster.
1039          */
1040         if (!usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
1041                         !usb_endpoint_xfer_int(dep->endpoint.desc) &&
1042                         !(dep->flags & DWC3_EP_BUSY)) {
1043                 ret = __dwc3_gadget_kick_transfer(dep, 0, true);
1044                 goto out;
1045         }
1046
1047         /*
1048          * There are a few special cases:
1049          *
1050          * 1. XferNotReady with empty list of requests. We need to kick the
1051          *    transfer here in that situation, otherwise we will be NAKing
1052          *    forever. If we get XferNotReady before gadget driver has a
1053          *    chance to queue a request, we will ACK the IRQ but won't be
1054          *    able to receive the data until the next request is queued.
1055          *    The following code is handling exactly that.
1056          *
1057          */
1058         if (dep->flags & DWC3_EP_PENDING_REQUEST) {
1059                 /*
1060                  * If xfernotready is already elapsed and it is a case
1061                  * of isoc transfer, then issue END TRANSFER, so that
1062                  * you can receive xfernotready again and can have
1063                  * notion of current microframe.
1064                  */
1065                 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1066                         if (list_empty(&dep->req_queued)) {
1067                                 dwc3_stop_active_transfer(dwc, dep->number, true);
1068                                 dep->flags = DWC3_EP_ENABLED;
1069                         }
1070                         return 0;
1071                 }
1072
1073                 ret = __dwc3_gadget_kick_transfer(dep, 0, true);
1074                 if (!ret)
1075                         dep->flags &= ~DWC3_EP_PENDING_REQUEST;
1076
1077                 goto out;
1078         }
1079
1080         /*
1081          * 2. XferInProgress on Isoc EP with an active transfer. We need to
1082          *    kick the transfer here after queuing a request, otherwise the
1083          *    core may not see the modified TRB(s).
1084          */
1085         if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
1086                         (dep->flags & DWC3_EP_BUSY) &&
1087                         !(dep->flags & DWC3_EP_MISSED_ISOC)) {
1088                 WARN_ON_ONCE(!dep->resource_index);
1089                 ret = __dwc3_gadget_kick_transfer(dep, dep->resource_index,
1090                                 false);
1091                 goto out;
1092         }
1093
1094         /*
1095          * 4. Stream Capable Bulk Endpoints. We need to start the transfer
1096          * right away, otherwise host will not know we have streams to be
1097          * handled.
1098          */
1099         if (dep->stream_capable)
1100                 ret = __dwc3_gadget_kick_transfer(dep, 0, true);
1101
1102 out:
1103         if (ret && ret != -EBUSY)
1104                 dwc3_trace(trace_dwc3_gadget,
1105                                 "%s: failed to kick transfers\n",
1106                                 dep->name);
1107         if (ret == -EBUSY)
1108                 ret = 0;
1109
1110         return ret;
1111 }
1112
1113 static void __dwc3_gadget_ep_zlp_complete(struct usb_ep *ep,
1114                 struct usb_request *request)
1115 {
1116         dwc3_gadget_ep_free_request(ep, request);
1117 }
1118
1119 static int __dwc3_gadget_ep_queue_zlp(struct dwc3 *dwc, struct dwc3_ep *dep)
1120 {
1121         struct dwc3_request             *req;
1122         struct usb_request              *request;
1123         struct usb_ep                   *ep = &dep->endpoint;
1124
1125         dwc3_trace(trace_dwc3_gadget, "queueing ZLP\n");
1126         request = dwc3_gadget_ep_alloc_request(ep, GFP_ATOMIC);
1127         if (!request)
1128                 return -ENOMEM;
1129
1130         request->length = 0;
1131         request->buf = dwc->zlp_buf;
1132         request->complete = __dwc3_gadget_ep_zlp_complete;
1133
1134         req = to_dwc3_request(request);
1135
1136         return __dwc3_gadget_ep_queue(dep, req);
1137 }
1138
1139 static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
1140         gfp_t gfp_flags)
1141 {
1142         struct dwc3_request             *req = to_dwc3_request(request);
1143         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1144         struct dwc3                     *dwc = dep->dwc;
1145
1146         unsigned long                   flags;
1147
1148         int                             ret;
1149
1150         spin_lock_irqsave(&dwc->lock, flags);
1151         ret = __dwc3_gadget_ep_queue(dep, req);
1152
1153         /*
1154          * Okay, here's the thing, if gadget driver has requested for a ZLP by
1155          * setting request->zero, instead of doing magic, we will just queue an
1156          * extra usb_request ourselves so that it gets handled the same way as
1157          * any other request.
1158          */
1159         if (ret == 0 && request->zero && request->length &&
1160             (request->length % ep->maxpacket == 0))
1161                 ret = __dwc3_gadget_ep_queue_zlp(dwc, dep);
1162
1163         spin_unlock_irqrestore(&dwc->lock, flags);
1164
1165         return ret;
1166 }
1167
1168 static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
1169                 struct usb_request *request)
1170 {
1171         struct dwc3_request             *req = to_dwc3_request(request);
1172         struct dwc3_request             *r = NULL;
1173
1174         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1175         struct dwc3                     *dwc = dep->dwc;
1176
1177         unsigned long                   flags;
1178         int                             ret = 0;
1179
1180         trace_dwc3_ep_dequeue(req);
1181
1182         spin_lock_irqsave(&dwc->lock, flags);
1183
1184         list_for_each_entry(r, &dep->request_list, list) {
1185                 if (r == req)
1186                         break;
1187         }
1188
1189         if (r != req) {
1190                 list_for_each_entry(r, &dep->req_queued, list) {
1191                         if (r == req)
1192                                 break;
1193                 }
1194                 if (r == req) {
1195                         /* wait until it is processed */
1196                         dwc3_stop_active_transfer(dwc, dep->number, true);
1197                         goto out1;
1198                 }
1199                 dev_err(dwc->dev, "request %p was not queued to %s\n",
1200                                 request, ep->name);
1201                 ret = -EINVAL;
1202                 goto out0;
1203         }
1204
1205 out1:
1206         /* giveback the request */
1207         dwc3_gadget_giveback(dep, req, -ECONNRESET);
1208
1209 out0:
1210         spin_unlock_irqrestore(&dwc->lock, flags);
1211
1212         return ret;
1213 }
1214
1215 int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
1216 {
1217         struct dwc3_gadget_ep_cmd_params        params;
1218         struct dwc3                             *dwc = dep->dwc;
1219         int                                     ret;
1220
1221         if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1222                 dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
1223                 return -EINVAL;
1224         }
1225
1226         memset(&params, 0x00, sizeof(params));
1227
1228         if (value) {
1229                 if (!protocol && ((dep->direction && dep->flags & DWC3_EP_BUSY) ||
1230                                 (!list_empty(&dep->req_queued) ||
1231                                  !list_empty(&dep->request_list)))) {
1232                         dwc3_trace(trace_dwc3_gadget,
1233                                         "%s: pending request, cannot halt\n",
1234                                         dep->name);
1235                         return -EAGAIN;
1236                 }
1237
1238                 ret = dwc3_send_gadget_ep_cmd(dwc, dep->number,
1239                         DWC3_DEPCMD_SETSTALL, &params);
1240                 if (ret)
1241                         dev_err(dwc->dev, "failed to set STALL on %s\n",
1242                                         dep->name);
1243                 else
1244                         dep->flags |= DWC3_EP_STALL;
1245         } else {
1246                 ret = dwc3_send_gadget_ep_cmd(dwc, dep->number,
1247                         DWC3_DEPCMD_CLEARSTALL, &params);
1248                 if (ret)
1249                         dev_err(dwc->dev, "failed to clear STALL on %s\n",
1250                                         dep->name);
1251                 else
1252                         dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
1253         }
1254
1255         return ret;
1256 }
1257
1258 static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
1259 {
1260         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1261         struct dwc3                     *dwc = dep->dwc;
1262
1263         unsigned long                   flags;
1264
1265         int                             ret;
1266
1267         spin_lock_irqsave(&dwc->lock, flags);
1268         ret = __dwc3_gadget_ep_set_halt(dep, value, false);
1269         spin_unlock_irqrestore(&dwc->lock, flags);
1270
1271         return ret;
1272 }
1273
1274 static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
1275 {
1276         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1277         struct dwc3                     *dwc = dep->dwc;
1278         unsigned long                   flags;
1279         int                             ret;
1280
1281         spin_lock_irqsave(&dwc->lock, flags);
1282         dep->flags |= DWC3_EP_WEDGE;
1283
1284         if (dep->number == 0 || dep->number == 1)
1285                 ret = __dwc3_gadget_ep0_set_halt(ep, 1);
1286         else
1287                 ret = __dwc3_gadget_ep_set_halt(dep, 1, false);
1288         spin_unlock_irqrestore(&dwc->lock, flags);
1289
1290         return ret;
1291 }
1292
1293 /* -------------------------------------------------------------------------- */
1294
1295 static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
1296         .bLength        = USB_DT_ENDPOINT_SIZE,
1297         .bDescriptorType = USB_DT_ENDPOINT,
1298         .bmAttributes   = USB_ENDPOINT_XFER_CONTROL,
1299 };
1300
1301 static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
1302         .enable         = dwc3_gadget_ep0_enable,
1303         .disable        = dwc3_gadget_ep0_disable,
1304         .alloc_request  = dwc3_gadget_ep_alloc_request,
1305         .free_request   = dwc3_gadget_ep_free_request,
1306         .queue          = dwc3_gadget_ep0_queue,
1307         .dequeue        = dwc3_gadget_ep_dequeue,
1308         .set_halt       = dwc3_gadget_ep0_set_halt,
1309         .set_wedge      = dwc3_gadget_ep_set_wedge,
1310 };
1311
1312 static const struct usb_ep_ops dwc3_gadget_ep_ops = {
1313         .enable         = dwc3_gadget_ep_enable,
1314         .disable        = dwc3_gadget_ep_disable,
1315         .alloc_request  = dwc3_gadget_ep_alloc_request,
1316         .free_request   = dwc3_gadget_ep_free_request,
1317         .queue          = dwc3_gadget_ep_queue,
1318         .dequeue        = dwc3_gadget_ep_dequeue,
1319         .set_halt       = dwc3_gadget_ep_set_halt,
1320         .set_wedge      = dwc3_gadget_ep_set_wedge,
1321 };
1322
1323 /* -------------------------------------------------------------------------- */
1324
1325 static int dwc3_gadget_get_frame(struct usb_gadget *g)
1326 {
1327         struct dwc3             *dwc = gadget_to_dwc(g);
1328         u32                     reg;
1329
1330         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1331         return DWC3_DSTS_SOFFN(reg);
1332 }
1333
1334 static int dwc3_gadget_wakeup(struct usb_gadget *g)
1335 {
1336         struct dwc3             *dwc = gadget_to_dwc(g);
1337
1338         unsigned long           timeout;
1339         unsigned long           flags;
1340
1341         u32                     reg;
1342
1343         int                     ret = 0;
1344
1345         u8                      link_state;
1346         u8                      speed;
1347
1348         spin_lock_irqsave(&dwc->lock, flags);
1349
1350         /*
1351          * According to the Databook Remote wakeup request should
1352          * be issued only when the device is in early suspend state.
1353          *
1354          * We can check that via USB Link State bits in DSTS register.
1355          */
1356         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1357
1358         speed = reg & DWC3_DSTS_CONNECTSPD;
1359         if ((speed == DWC3_DSTS_SUPERSPEED) ||
1360             (speed == DWC3_DSTS_SUPERSPEED_PLUS)) {
1361                 dwc3_trace(trace_dwc3_gadget, "no wakeup on SuperSpeed\n");
1362                 ret = -EINVAL;
1363                 goto out;
1364         }
1365
1366         link_state = DWC3_DSTS_USBLNKST(reg);
1367
1368         switch (link_state) {
1369         case DWC3_LINK_STATE_RX_DET:    /* in HS, means Early Suspend */
1370         case DWC3_LINK_STATE_U3:        /* in HS, means SUSPEND */
1371                 break;
1372         default:
1373                 dwc3_trace(trace_dwc3_gadget,
1374                                 "can't wakeup from '%s'\n",
1375                                 dwc3_gadget_link_string(link_state));
1376                 ret = -EINVAL;
1377                 goto out;
1378         }
1379
1380         ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
1381         if (ret < 0) {
1382                 dev_err(dwc->dev, "failed to put link in Recovery\n");
1383                 goto out;
1384         }
1385
1386         /* Recent versions do this automatically */
1387         if (dwc->revision < DWC3_REVISION_194A) {
1388                 /* write zeroes to Link Change Request */
1389                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1390                 reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
1391                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1392         }
1393
1394         /* poll until Link State changes to ON */
1395         timeout = jiffies + msecs_to_jiffies(100);
1396
1397         while (!time_after(jiffies, timeout)) {
1398                 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1399
1400                 /* in HS, means ON */
1401                 if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
1402                         break;
1403         }
1404
1405         if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
1406                 dev_err(dwc->dev, "failed to send remote wakeup\n");
1407                 ret = -EINVAL;
1408         }
1409
1410 out:
1411         spin_unlock_irqrestore(&dwc->lock, flags);
1412
1413         return ret;
1414 }
1415
1416 static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
1417                 int is_selfpowered)
1418 {
1419         struct dwc3             *dwc = gadget_to_dwc(g);
1420         unsigned long           flags;
1421
1422         spin_lock_irqsave(&dwc->lock, flags);
1423         g->is_selfpowered = !!is_selfpowered;
1424         spin_unlock_irqrestore(&dwc->lock, flags);
1425
1426         return 0;
1427 }
1428
1429 static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on, int suspend)
1430 {
1431         u32                     reg;
1432         u32                     timeout = 500;
1433
1434         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1435         if (is_on) {
1436                 if (dwc->revision <= DWC3_REVISION_187A) {
1437                         reg &= ~DWC3_DCTL_TRGTULST_MASK;
1438                         reg |= DWC3_DCTL_TRGTULST_RX_DET;
1439                 }
1440
1441                 if (dwc->revision >= DWC3_REVISION_194A)
1442                         reg &= ~DWC3_DCTL_KEEP_CONNECT;
1443                 reg |= DWC3_DCTL_RUN_STOP;
1444
1445                 if (dwc->has_hibernation)
1446                         reg |= DWC3_DCTL_KEEP_CONNECT;
1447
1448                 dwc->pullups_connected = true;
1449         } else {
1450                 reg &= ~DWC3_DCTL_RUN_STOP;
1451
1452                 if (dwc->has_hibernation && !suspend)
1453                         reg &= ~DWC3_DCTL_KEEP_CONNECT;
1454
1455                 dwc->pullups_connected = false;
1456         }
1457
1458         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1459
1460         do {
1461                 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1462                 if (is_on) {
1463                         if (!(reg & DWC3_DSTS_DEVCTRLHLT))
1464                                 break;
1465                 } else {
1466                         if (reg & DWC3_DSTS_DEVCTRLHLT)
1467                                 break;
1468                 }
1469                 timeout--;
1470                 if (!timeout)
1471                         return -ETIMEDOUT;
1472                 udelay(1);
1473         } while (1);
1474
1475         dwc3_trace(trace_dwc3_gadget, "gadget %s data soft-%s",
1476                         dwc->gadget_driver
1477                         ? dwc->gadget_driver->function : "no-function",
1478                         is_on ? "connect" : "disconnect");
1479
1480         return 0;
1481 }
1482
1483 static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
1484 {
1485         struct dwc3             *dwc = gadget_to_dwc(g);
1486         unsigned long           flags;
1487         int                     ret;
1488
1489         is_on = !!is_on;
1490
1491         spin_lock_irqsave(&dwc->lock, flags);
1492         ret = dwc3_gadget_run_stop(dwc, is_on, false);
1493         spin_unlock_irqrestore(&dwc->lock, flags);
1494
1495         return ret;
1496 }
1497
1498 static void dwc3_gadget_enable_irq(struct dwc3 *dwc)
1499 {
1500         u32                     reg;
1501
1502         /* Enable all but Start and End of Frame IRQs */
1503         reg = (DWC3_DEVTEN_VNDRDEVTSTRCVEDEN |
1504                         DWC3_DEVTEN_EVNTOVERFLOWEN |
1505                         DWC3_DEVTEN_CMDCMPLTEN |
1506                         DWC3_DEVTEN_ERRTICERREN |
1507                         DWC3_DEVTEN_WKUPEVTEN |
1508                         DWC3_DEVTEN_ULSTCNGEN |
1509                         DWC3_DEVTEN_CONNECTDONEEN |
1510                         DWC3_DEVTEN_USBRSTEN |
1511                         DWC3_DEVTEN_DISCONNEVTEN);
1512
1513         dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
1514 }
1515
1516 static void dwc3_gadget_disable_irq(struct dwc3 *dwc)
1517 {
1518         /* mask all interrupts */
1519         dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
1520 }
1521
1522 static irqreturn_t dwc3_interrupt(int irq, void *_dwc);
1523 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc);
1524
1525 static int dwc3_gadget_start(struct usb_gadget *g,
1526                 struct usb_gadget_driver *driver)
1527 {
1528         struct dwc3             *dwc = gadget_to_dwc(g);
1529         struct dwc3_ep          *dep;
1530         unsigned long           flags;
1531         int                     ret = 0;
1532         int                     irq;
1533         u32                     reg;
1534
1535         irq = platform_get_irq(to_platform_device(dwc->dev), 0);
1536         ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt,
1537                         IRQF_SHARED, "dwc3", dwc);
1538         if (ret) {
1539                 dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
1540                                 irq, ret);
1541                 goto err0;
1542         }
1543
1544         spin_lock_irqsave(&dwc->lock, flags);
1545
1546         if (dwc->gadget_driver) {
1547                 dev_err(dwc->dev, "%s is already bound to %s\n",
1548                                 dwc->gadget.name,
1549                                 dwc->gadget_driver->driver.name);
1550                 ret = -EBUSY;
1551                 goto err1;
1552         }
1553
1554         dwc->gadget_driver      = driver;
1555
1556         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
1557         reg &= ~(DWC3_DCFG_SPEED_MASK);
1558
1559         /**
1560          * WORKAROUND: DWC3 revision < 2.20a have an issue
1561          * which would cause metastability state on Run/Stop
1562          * bit if we try to force the IP to USB2-only mode.
1563          *
1564          * Because of that, we cannot configure the IP to any
1565          * speed other than the SuperSpeed
1566          *
1567          * Refers to:
1568          *
1569          * STAR#9000525659: Clock Domain Crossing on DCTL in
1570          * USB 2.0 Mode
1571          */
1572         if (dwc->revision < DWC3_REVISION_220A) {
1573                 reg |= DWC3_DCFG_SUPERSPEED;
1574         } else {
1575                 switch (dwc->maximum_speed) {
1576                 case USB_SPEED_LOW:
1577                         reg |= DWC3_DSTS_LOWSPEED;
1578                         break;
1579                 case USB_SPEED_FULL:
1580                         reg |= DWC3_DSTS_FULLSPEED1;
1581                         break;
1582                 case USB_SPEED_HIGH:
1583                         reg |= DWC3_DSTS_HIGHSPEED;
1584                         break;
1585                 case USB_SPEED_SUPER_PLUS:
1586                         reg |= DWC3_DSTS_SUPERSPEED_PLUS;
1587                         break;
1588                 default:
1589                         dev_err(dwc->dev, "invalid dwc->maximum_speed (%d)\n",
1590                                 dwc->maximum_speed);
1591                         /* fall through */
1592                 case USB_SPEED_SUPER:
1593                         reg |= DWC3_DCFG_SUPERSPEED;
1594                         break;
1595                 }
1596         }
1597         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
1598
1599         /* Start with SuperSpeed Default */
1600         dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
1601
1602         dep = dwc->eps[0];
1603         ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL, false,
1604                         false);
1605         if (ret) {
1606                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
1607                 goto err2;
1608         }
1609
1610         dep = dwc->eps[1];
1611         ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL, false,
1612                         false);
1613         if (ret) {
1614                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
1615                 goto err3;
1616         }
1617
1618         /* begin to receive SETUP packets */
1619         dwc->ep0state = EP0_SETUP_PHASE;
1620         dwc3_ep0_out_start(dwc);
1621
1622         dwc3_gadget_enable_irq(dwc);
1623
1624         spin_unlock_irqrestore(&dwc->lock, flags);
1625
1626         return 0;
1627
1628 err3:
1629         __dwc3_gadget_ep_disable(dwc->eps[0]);
1630
1631 err2:
1632         dwc->gadget_driver = NULL;
1633
1634 err1:
1635         spin_unlock_irqrestore(&dwc->lock, flags);
1636
1637         free_irq(irq, dwc);
1638
1639 err0:
1640         return ret;
1641 }
1642
1643 static int dwc3_gadget_stop(struct usb_gadget *g)
1644 {
1645         struct dwc3             *dwc = gadget_to_dwc(g);
1646         unsigned long           flags;
1647         int                     irq;
1648
1649         spin_lock_irqsave(&dwc->lock, flags);
1650
1651         dwc3_gadget_disable_irq(dwc);
1652         __dwc3_gadget_ep_disable(dwc->eps[0]);
1653         __dwc3_gadget_ep_disable(dwc->eps[1]);
1654
1655         dwc->gadget_driver      = NULL;
1656
1657         spin_unlock_irqrestore(&dwc->lock, flags);
1658
1659         irq = platform_get_irq(to_platform_device(dwc->dev), 0);
1660         free_irq(irq, dwc);
1661
1662         return 0;
1663 }
1664
1665 static const struct usb_gadget_ops dwc3_gadget_ops = {
1666         .get_frame              = dwc3_gadget_get_frame,
1667         .wakeup                 = dwc3_gadget_wakeup,
1668         .set_selfpowered        = dwc3_gadget_set_selfpowered,
1669         .pullup                 = dwc3_gadget_pullup,
1670         .udc_start              = dwc3_gadget_start,
1671         .udc_stop               = dwc3_gadget_stop,
1672 };
1673
1674 /* -------------------------------------------------------------------------- */
1675
1676 static int dwc3_gadget_init_hw_endpoints(struct dwc3 *dwc,
1677                 u8 num, u32 direction)
1678 {
1679         struct dwc3_ep                  *dep;
1680         u8                              i;
1681
1682         for (i = 0; i < num; i++) {
1683                 u8 epnum = (i << 1) | (!!direction);
1684
1685                 dep = kzalloc(sizeof(*dep), GFP_KERNEL);
1686                 if (!dep)
1687                         return -ENOMEM;
1688
1689                 dep->dwc = dwc;
1690                 dep->number = epnum;
1691                 dep->direction = !!direction;
1692                 dwc->eps[epnum] = dep;
1693
1694                 snprintf(dep->name, sizeof(dep->name), "ep%d%s", epnum >> 1,
1695                                 (epnum & 1) ? "in" : "out");
1696
1697                 dep->endpoint.name = dep->name;
1698
1699                 dwc3_trace(trace_dwc3_gadget, "initializing %s", dep->name);
1700
1701                 if (epnum == 0 || epnum == 1) {
1702                         usb_ep_set_maxpacket_limit(&dep->endpoint, 512);
1703                         dep->endpoint.maxburst = 1;
1704                         dep->endpoint.ops = &dwc3_gadget_ep0_ops;
1705                         if (!epnum)
1706                                 dwc->gadget.ep0 = &dep->endpoint;
1707                 } else {
1708                         int             ret;
1709
1710                         usb_ep_set_maxpacket_limit(&dep->endpoint, 1024);
1711                         dep->endpoint.max_streams = 15;
1712                         dep->endpoint.ops = &dwc3_gadget_ep_ops;
1713                         list_add_tail(&dep->endpoint.ep_list,
1714                                         &dwc->gadget.ep_list);
1715
1716                         ret = dwc3_alloc_trb_pool(dep);
1717                         if (ret)
1718                                 return ret;
1719                 }
1720
1721                 if (epnum == 0 || epnum == 1) {
1722                         dep->endpoint.caps.type_control = true;
1723                 } else {
1724                         dep->endpoint.caps.type_iso = true;
1725                         dep->endpoint.caps.type_bulk = true;
1726                         dep->endpoint.caps.type_int = true;
1727                 }
1728
1729                 dep->endpoint.caps.dir_in = !!direction;
1730                 dep->endpoint.caps.dir_out = !direction;
1731
1732                 INIT_LIST_HEAD(&dep->request_list);
1733                 INIT_LIST_HEAD(&dep->req_queued);
1734         }
1735
1736         return 0;
1737 }
1738
1739 static int dwc3_gadget_init_endpoints(struct dwc3 *dwc)
1740 {
1741         int                             ret;
1742
1743         INIT_LIST_HEAD(&dwc->gadget.ep_list);
1744
1745         ret = dwc3_gadget_init_hw_endpoints(dwc, dwc->num_out_eps, 0);
1746         if (ret < 0) {
1747                 dwc3_trace(trace_dwc3_gadget,
1748                                 "failed to allocate OUT endpoints");
1749                 return ret;
1750         }
1751
1752         ret = dwc3_gadget_init_hw_endpoints(dwc, dwc->num_in_eps, 1);
1753         if (ret < 0) {
1754                 dwc3_trace(trace_dwc3_gadget,
1755                                 "failed to allocate IN endpoints");
1756                 return ret;
1757         }
1758
1759         return 0;
1760 }
1761
1762 static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
1763 {
1764         struct dwc3_ep                  *dep;
1765         u8                              epnum;
1766
1767         for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
1768                 dep = dwc->eps[epnum];
1769                 if (!dep)
1770                         continue;
1771                 /*
1772                  * Physical endpoints 0 and 1 are special; they form the
1773                  * bi-directional USB endpoint 0.
1774                  *
1775                  * For those two physical endpoints, we don't allocate a TRB
1776                  * pool nor do we add them the endpoints list. Due to that, we
1777                  * shouldn't do these two operations otherwise we would end up
1778                  * with all sorts of bugs when removing dwc3.ko.
1779                  */
1780                 if (epnum != 0 && epnum != 1) {
1781                         dwc3_free_trb_pool(dep);
1782                         list_del(&dep->endpoint.ep_list);
1783                 }
1784
1785                 kfree(dep);
1786         }
1787 }
1788
1789 /* -------------------------------------------------------------------------- */
1790
1791 static int __dwc3_cleanup_done_trbs(struct dwc3 *dwc, struct dwc3_ep *dep,
1792                 struct dwc3_request *req, struct dwc3_trb *trb,
1793                 const struct dwc3_event_depevt *event, int status)
1794 {
1795         unsigned int            count;
1796         unsigned int            s_pkt = 0;
1797         unsigned int            trb_status;
1798
1799         trace_dwc3_complete_trb(dep, trb);
1800
1801         if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
1802                 /*
1803                  * We continue despite the error. There is not much we
1804                  * can do. If we don't clean it up we loop forever. If
1805                  * we skip the TRB then it gets overwritten after a
1806                  * while since we use them in a ring buffer. A BUG()
1807                  * would help. Lets hope that if this occurs, someone
1808                  * fixes the root cause instead of looking away :)
1809                  */
1810                 dev_err(dwc->dev, "%s's TRB (%p) still owned by HW\n",
1811                                 dep->name, trb);
1812         count = trb->size & DWC3_TRB_SIZE_MASK;
1813
1814         if (dep->direction) {
1815                 if (count) {
1816                         trb_status = DWC3_TRB_SIZE_TRBSTS(trb->size);
1817                         if (trb_status == DWC3_TRBSTS_MISSED_ISOC) {
1818                                 dwc3_trace(trace_dwc3_gadget,
1819                                                 "%s: incomplete IN transfer\n",
1820                                                 dep->name);
1821                                 /*
1822                                  * If missed isoc occurred and there is
1823                                  * no request queued then issue END
1824                                  * TRANSFER, so that core generates
1825                                  * next xfernotready and we will issue
1826                                  * a fresh START TRANSFER.
1827                                  * If there are still queued request
1828                                  * then wait, do not issue either END
1829                                  * or UPDATE TRANSFER, just attach next
1830                                  * request in request_list during
1831                                  * giveback.If any future queued request
1832                                  * is successfully transferred then we
1833                                  * will issue UPDATE TRANSFER for all
1834                                  * request in the request_list.
1835                                  */
1836                                 dep->flags |= DWC3_EP_MISSED_ISOC;
1837                         } else {
1838                                 dev_err(dwc->dev, "incomplete IN transfer %s\n",
1839                                                 dep->name);
1840                                 status = -ECONNRESET;
1841                         }
1842                 } else {
1843                         dep->flags &= ~DWC3_EP_MISSED_ISOC;
1844                 }
1845         } else {
1846                 if (count && (event->status & DEPEVT_STATUS_SHORT))
1847                         s_pkt = 1;
1848         }
1849
1850         /*
1851          * We assume here we will always receive the entire data block
1852          * which we should receive. Meaning, if we program RX to
1853          * receive 4K but we receive only 2K, we assume that's all we
1854          * should receive and we simply bounce the request back to the
1855          * gadget driver for further processing.
1856          */
1857         req->request.actual += req->request.length - count;
1858         if (s_pkt)
1859                 return 1;
1860         if ((event->status & DEPEVT_STATUS_LST) &&
1861                         (trb->ctrl & (DWC3_TRB_CTRL_LST |
1862                                 DWC3_TRB_CTRL_HWO)))
1863                 return 1;
1864         if ((event->status & DEPEVT_STATUS_IOC) &&
1865                         (trb->ctrl & DWC3_TRB_CTRL_IOC))
1866                 return 1;
1867         return 0;
1868 }
1869
1870 static int dwc3_cleanup_done_reqs(struct dwc3 *dwc, struct dwc3_ep *dep,
1871                 const struct dwc3_event_depevt *event, int status)
1872 {
1873         struct dwc3_request     *req;
1874         struct dwc3_trb         *trb;
1875         unsigned int            slot;
1876         unsigned int            i;
1877         int                     ret;
1878
1879         do {
1880                 req = next_request(&dep->req_queued);
1881                 if (WARN_ON_ONCE(!req))
1882                         return 1;
1883
1884                 i = 0;
1885                 do {
1886                         slot = req->start_slot + i;
1887                         if ((slot == DWC3_TRB_NUM - 1) &&
1888                                 usb_endpoint_xfer_isoc(dep->endpoint.desc))
1889                                 slot++;
1890                         slot %= DWC3_TRB_NUM;
1891                         trb = &dep->trb_pool[slot];
1892
1893                         ret = __dwc3_cleanup_done_trbs(dwc, dep, req, trb,
1894                                         event, status);
1895                         if (ret)
1896                                 break;
1897                 } while (++i < req->request.num_mapped_sgs);
1898
1899                 dwc3_gadget_giveback(dep, req, status);
1900
1901                 if (ret)
1902                         break;
1903         } while (1);
1904
1905         if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
1906                         list_empty(&dep->req_queued)) {
1907                 if (list_empty(&dep->request_list)) {
1908                         /*
1909                          * If there is no entry in request list then do
1910                          * not issue END TRANSFER now. Just set PENDING
1911                          * flag, so that END TRANSFER is issued when an
1912                          * entry is added into request list.
1913                          */
1914                         dep->flags = DWC3_EP_PENDING_REQUEST;
1915                 } else {
1916                         dwc3_stop_active_transfer(dwc, dep->number, true);
1917                         dep->flags = DWC3_EP_ENABLED;
1918                 }
1919                 return 1;
1920         }
1921
1922         return 1;
1923 }
1924
1925 static void dwc3_endpoint_transfer_complete(struct dwc3 *dwc,
1926                 struct dwc3_ep *dep, const struct dwc3_event_depevt *event)
1927 {
1928         unsigned                status = 0;
1929         int                     clean_busy;
1930         u32                     is_xfer_complete;
1931
1932         is_xfer_complete = (event->endpoint_event == DWC3_DEPEVT_XFERCOMPLETE);
1933
1934         if (event->status & DEPEVT_STATUS_BUSERR)
1935                 status = -ECONNRESET;
1936
1937         clean_busy = dwc3_cleanup_done_reqs(dwc, dep, event, status);
1938         if (clean_busy && (is_xfer_complete ||
1939                                 usb_endpoint_xfer_isoc(dep->endpoint.desc)))
1940                 dep->flags &= ~DWC3_EP_BUSY;
1941
1942         /*
1943          * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
1944          * See dwc3_gadget_linksts_change_interrupt() for 1st half.
1945          */
1946         if (dwc->revision < DWC3_REVISION_183A) {
1947                 u32             reg;
1948                 int             i;
1949
1950                 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
1951                         dep = dwc->eps[i];
1952
1953                         if (!(dep->flags & DWC3_EP_ENABLED))
1954                                 continue;
1955
1956                         if (!list_empty(&dep->req_queued))
1957                                 return;
1958                 }
1959
1960                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1961                 reg |= dwc->u1u2;
1962                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1963
1964                 dwc->u1u2 = 0;
1965         }
1966
1967         if (!usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1968                 int ret;
1969
1970                 ret = __dwc3_gadget_kick_transfer(dep, 0, is_xfer_complete);
1971                 if (!ret || ret == -EBUSY)
1972                         return;
1973         }
1974 }
1975
1976 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
1977                 const struct dwc3_event_depevt *event)
1978 {
1979         struct dwc3_ep          *dep;
1980         u8                      epnum = event->endpoint_number;
1981
1982         dep = dwc->eps[epnum];
1983
1984         if (!(dep->flags & DWC3_EP_ENABLED))
1985                 return;
1986
1987         if (epnum == 0 || epnum == 1) {
1988                 dwc3_ep0_interrupt(dwc, event);
1989                 return;
1990         }
1991
1992         switch (event->endpoint_event) {
1993         case DWC3_DEPEVT_XFERCOMPLETE:
1994                 dep->resource_index = 0;
1995
1996                 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1997                         dwc3_trace(trace_dwc3_gadget,
1998                                         "%s is an Isochronous endpoint\n",
1999                                         dep->name);
2000                         return;
2001                 }
2002
2003                 dwc3_endpoint_transfer_complete(dwc, dep, event);
2004                 break;
2005         case DWC3_DEPEVT_XFERINPROGRESS:
2006                 dwc3_endpoint_transfer_complete(dwc, dep, event);
2007                 break;
2008         case DWC3_DEPEVT_XFERNOTREADY:
2009                 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
2010                         dwc3_gadget_start_isoc(dwc, dep, event);
2011                 } else {
2012                         int active;
2013                         int ret;
2014
2015                         active = event->status & DEPEVT_STATUS_TRANSFER_ACTIVE;
2016
2017                         dwc3_trace(trace_dwc3_gadget, "%s: reason %s",
2018                                         dep->name, active ? "Transfer Active"
2019                                         : "Transfer Not Active");
2020
2021                         ret = __dwc3_gadget_kick_transfer(dep, 0, !active);
2022                         if (!ret || ret == -EBUSY)
2023                                 return;
2024
2025                         dwc3_trace(trace_dwc3_gadget,
2026                                         "%s: failed to kick transfers\n",
2027                                         dep->name);
2028                 }
2029
2030                 break;
2031         case DWC3_DEPEVT_STREAMEVT:
2032                 if (!usb_endpoint_xfer_bulk(dep->endpoint.desc)) {
2033                         dev_err(dwc->dev, "Stream event for non-Bulk %s\n",
2034                                         dep->name);
2035                         return;
2036                 }
2037
2038                 switch (event->status) {
2039                 case DEPEVT_STREAMEVT_FOUND:
2040                         dwc3_trace(trace_dwc3_gadget,
2041                                         "Stream %d found and started",
2042                                         event->parameters);
2043
2044                         break;
2045                 case DEPEVT_STREAMEVT_NOTFOUND:
2046                         /* FALLTHROUGH */
2047                 default:
2048                         dwc3_trace(trace_dwc3_gadget,
2049                                         "unable to find suitable stream\n");
2050                 }
2051                 break;
2052         case DWC3_DEPEVT_RXTXFIFOEVT:
2053                 dwc3_trace(trace_dwc3_gadget, "%s FIFO Overrun\n", dep->name);
2054                 break;
2055         case DWC3_DEPEVT_EPCMDCMPLT:
2056                 dwc3_trace(trace_dwc3_gadget, "Endpoint Command Complete");
2057                 break;
2058         }
2059 }
2060
2061 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
2062 {
2063         if (dwc->gadget_driver && dwc->gadget_driver->disconnect) {
2064                 spin_unlock(&dwc->lock);
2065                 dwc->gadget_driver->disconnect(&dwc->gadget);
2066                 spin_lock(&dwc->lock);
2067         }
2068 }
2069
2070 static void dwc3_suspend_gadget(struct dwc3 *dwc)
2071 {
2072         if (dwc->gadget_driver && dwc->gadget_driver->suspend) {
2073                 spin_unlock(&dwc->lock);
2074                 dwc->gadget_driver->suspend(&dwc->gadget);
2075                 spin_lock(&dwc->lock);
2076         }
2077 }
2078
2079 static void dwc3_resume_gadget(struct dwc3 *dwc)
2080 {
2081         if (dwc->gadget_driver && dwc->gadget_driver->resume) {
2082                 spin_unlock(&dwc->lock);
2083                 dwc->gadget_driver->resume(&dwc->gadget);
2084                 spin_lock(&dwc->lock);
2085         }
2086 }
2087
2088 static void dwc3_reset_gadget(struct dwc3 *dwc)
2089 {
2090         if (!dwc->gadget_driver)
2091                 return;
2092
2093         if (dwc->gadget.speed != USB_SPEED_UNKNOWN) {
2094                 spin_unlock(&dwc->lock);
2095                 usb_gadget_udc_reset(&dwc->gadget, dwc->gadget_driver);
2096                 spin_lock(&dwc->lock);
2097         }
2098 }
2099
2100 static void dwc3_stop_active_transfer(struct dwc3 *dwc, u32 epnum, bool force)
2101 {
2102         struct dwc3_ep *dep;
2103         struct dwc3_gadget_ep_cmd_params params;
2104         u32 cmd;
2105         int ret;
2106
2107         dep = dwc->eps[epnum];
2108
2109         if (!dep->resource_index)
2110                 return;
2111
2112         /*
2113          * NOTICE: We are violating what the Databook says about the
2114          * EndTransfer command. Ideally we would _always_ wait for the
2115          * EndTransfer Command Completion IRQ, but that's causing too
2116          * much trouble synchronizing between us and gadget driver.
2117          *
2118          * We have discussed this with the IP Provider and it was
2119          * suggested to giveback all requests here, but give HW some
2120          * extra time to synchronize with the interconnect. We're using
2121          * an arbitrary 100us delay for that.
2122          *
2123          * Note also that a similar handling was tested by Synopsys
2124          * (thanks a lot Paul) and nothing bad has come out of it.
2125          * In short, what we're doing is:
2126          *
2127          * - Issue EndTransfer WITH CMDIOC bit set
2128          * - Wait 100us
2129          */
2130
2131         cmd = DWC3_DEPCMD_ENDTRANSFER;
2132         cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
2133         cmd |= DWC3_DEPCMD_CMDIOC;
2134         cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
2135         memset(&params, 0, sizeof(params));
2136         ret = dwc3_send_gadget_ep_cmd(dwc, dep->number, cmd, &params);
2137         WARN_ON_ONCE(ret);
2138         dep->resource_index = 0;
2139         dep->flags &= ~DWC3_EP_BUSY;
2140         udelay(100);
2141 }
2142
2143 static void dwc3_stop_active_transfers(struct dwc3 *dwc)
2144 {
2145         u32 epnum;
2146
2147         for (epnum = 2; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2148                 struct dwc3_ep *dep;
2149
2150                 dep = dwc->eps[epnum];
2151                 if (!dep)
2152                         continue;
2153
2154                 if (!(dep->flags & DWC3_EP_ENABLED))
2155                         continue;
2156
2157                 dwc3_remove_requests(dwc, dep);
2158         }
2159 }
2160
2161 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
2162 {
2163         u32 epnum;
2164
2165         for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2166                 struct dwc3_ep *dep;
2167                 struct dwc3_gadget_ep_cmd_params params;
2168                 int ret;
2169
2170                 dep = dwc->eps[epnum];
2171                 if (!dep)
2172                         continue;
2173
2174                 if (!(dep->flags & DWC3_EP_STALL))
2175                         continue;
2176
2177                 dep->flags &= ~DWC3_EP_STALL;
2178
2179                 memset(&params, 0, sizeof(params));
2180                 ret = dwc3_send_gadget_ep_cmd(dwc, dep->number,
2181                                 DWC3_DEPCMD_CLEARSTALL, &params);
2182                 WARN_ON_ONCE(ret);
2183         }
2184 }
2185
2186 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
2187 {
2188         int                     reg;
2189
2190         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2191         reg &= ~DWC3_DCTL_INITU1ENA;
2192         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2193
2194         reg &= ~DWC3_DCTL_INITU2ENA;
2195         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2196
2197         dwc3_disconnect_gadget(dwc);
2198
2199         dwc->gadget.speed = USB_SPEED_UNKNOWN;
2200         dwc->setup_packet_pending = false;
2201         usb_gadget_set_state(&dwc->gadget, USB_STATE_NOTATTACHED);
2202 }
2203
2204 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
2205 {
2206         u32                     reg;
2207
2208         /*
2209          * WORKAROUND: DWC3 revisions <1.88a have an issue which
2210          * would cause a missing Disconnect Event if there's a
2211          * pending Setup Packet in the FIFO.
2212          *
2213          * There's no suggested workaround on the official Bug
2214          * report, which states that "unless the driver/application
2215          * is doing any special handling of a disconnect event,
2216          * there is no functional issue".
2217          *
2218          * Unfortunately, it turns out that we _do_ some special
2219          * handling of a disconnect event, namely complete all
2220          * pending transfers, notify gadget driver of the
2221          * disconnection, and so on.
2222          *
2223          * Our suggested workaround is to follow the Disconnect
2224          * Event steps here, instead, based on a setup_packet_pending
2225          * flag. Such flag gets set whenever we have a SETUP_PENDING
2226          * status for EP0 TRBs and gets cleared on XferComplete for the
2227          * same endpoint.
2228          *
2229          * Refers to:
2230          *
2231          * STAR#9000466709: RTL: Device : Disconnect event not
2232          * generated if setup packet pending in FIFO
2233          */
2234         if (dwc->revision < DWC3_REVISION_188A) {
2235                 if (dwc->setup_packet_pending)
2236                         dwc3_gadget_disconnect_interrupt(dwc);
2237         }
2238
2239         dwc3_reset_gadget(dwc);
2240
2241         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2242         reg &= ~DWC3_DCTL_TSTCTRL_MASK;
2243         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2244         dwc->test_mode = false;
2245
2246         dwc3_stop_active_transfers(dwc);
2247         dwc3_clear_stall_all_ep(dwc);
2248
2249         /* Reset device address to zero */
2250         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2251         reg &= ~(DWC3_DCFG_DEVADDR_MASK);
2252         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2253 }
2254
2255 static void dwc3_update_ram_clk_sel(struct dwc3 *dwc, u32 speed)
2256 {
2257         u32 reg;
2258         u32 usb30_clock = DWC3_GCTL_CLK_BUS;
2259
2260         /*
2261          * We change the clock only at SS but I dunno why I would want to do
2262          * this. Maybe it becomes part of the power saving plan.
2263          */
2264
2265         if ((speed != DWC3_DSTS_SUPERSPEED) &&
2266             (speed != DWC3_DSTS_SUPERSPEED_PLUS))
2267                 return;
2268
2269         /*
2270          * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
2271          * each time on Connect Done.
2272          */
2273         if (!usb30_clock)
2274                 return;
2275
2276         reg = dwc3_readl(dwc->regs, DWC3_GCTL);
2277         reg |= DWC3_GCTL_RAMCLKSEL(usb30_clock);
2278         dwc3_writel(dwc->regs, DWC3_GCTL, reg);
2279 }
2280
2281 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
2282 {
2283         struct dwc3_ep          *dep;
2284         int                     ret;
2285         u32                     reg;
2286         u8                      speed;
2287
2288         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2289         speed = reg & DWC3_DSTS_CONNECTSPD;
2290         dwc->speed = speed;
2291
2292         dwc3_update_ram_clk_sel(dwc, speed);
2293
2294         switch (speed) {
2295         case DWC3_DCFG_SUPERSPEED_PLUS:
2296                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2297                 dwc->gadget.ep0->maxpacket = 512;
2298                 dwc->gadget.speed = USB_SPEED_SUPER_PLUS;
2299                 break;
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             (speed != DWC3_DCFG_SUPERSPEED_PLUS)) {
2344                 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2345                 reg |= DWC3_DCFG_LPM_CAP;
2346                 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2347
2348                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2349                 reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
2350
2351                 reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold);
2352
2353                 /*
2354                  * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
2355                  * DCFG.LPMCap is set, core responses with an ACK and the
2356                  * BESL value in the LPM token is less than or equal to LPM
2357                  * NYET threshold.
2358                  */
2359                 WARN_ONCE(dwc->revision < DWC3_REVISION_240A
2360                                 && dwc->has_lpm_erratum,
2361                                 "LPM Erratum not available on dwc3 revisisions < 2.40a\n");
2362
2363                 if (dwc->has_lpm_erratum && dwc->revision >= DWC3_REVISION_240A)
2364                         reg |= DWC3_DCTL_LPM_ERRATA(dwc->lpm_nyet_threshold);
2365
2366                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2367         } else {
2368                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2369                 reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
2370                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2371         }
2372
2373         dep = dwc->eps[0];
2374         ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL, true,
2375                         false);
2376         if (ret) {
2377                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2378                 return;
2379         }
2380
2381         dep = dwc->eps[1];
2382         ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL, true,
2383                         false);
2384         if (ret) {
2385                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2386                 return;
2387         }
2388
2389         /*
2390          * Configure PHY via GUSB3PIPECTLn if required.
2391          *
2392          * Update GTXFIFOSIZn
2393          *
2394          * In both cases reset values should be sufficient.
2395          */
2396 }
2397
2398 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
2399 {
2400         /*
2401          * TODO take core out of low power mode when that's
2402          * implemented.
2403          */
2404
2405         if (dwc->gadget_driver && dwc->gadget_driver->resume) {
2406                 spin_unlock(&dwc->lock);
2407                 dwc->gadget_driver->resume(&dwc->gadget);
2408                 spin_lock(&dwc->lock);
2409         }
2410 }
2411
2412 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
2413                 unsigned int evtinfo)
2414 {
2415         enum dwc3_link_state    next = evtinfo & DWC3_LINK_STATE_MASK;
2416         unsigned int            pwropt;
2417
2418         /*
2419          * WORKAROUND: DWC3 < 2.50a have an issue when configured without
2420          * Hibernation mode enabled which would show up when device detects
2421          * host-initiated U3 exit.
2422          *
2423          * In that case, device will generate a Link State Change Interrupt
2424          * from U3 to RESUME which is only necessary if Hibernation is
2425          * configured in.
2426          *
2427          * There are no functional changes due to such spurious event and we
2428          * just need to ignore it.
2429          *
2430          * Refers to:
2431          *
2432          * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
2433          * operational mode
2434          */
2435         pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
2436         if ((dwc->revision < DWC3_REVISION_250A) &&
2437                         (pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
2438                 if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
2439                                 (next == DWC3_LINK_STATE_RESUME)) {
2440                         dwc3_trace(trace_dwc3_gadget,
2441                                         "ignoring transition U3 -> Resume");
2442                         return;
2443                 }
2444         }
2445
2446         /*
2447          * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
2448          * on the link partner, the USB session might do multiple entry/exit
2449          * of low power states before a transfer takes place.
2450          *
2451          * Due to this problem, we might experience lower throughput. The
2452          * suggested workaround is to disable DCTL[12:9] bits if we're
2453          * transitioning from U1/U2 to U0 and enable those bits again
2454          * after a transfer completes and there are no pending transfers
2455          * on any of the enabled endpoints.
2456          *
2457          * This is the first half of that workaround.
2458          *
2459          * Refers to:
2460          *
2461          * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
2462          * core send LGO_Ux entering U0
2463          */
2464         if (dwc->revision < DWC3_REVISION_183A) {
2465                 if (next == DWC3_LINK_STATE_U0) {
2466                         u32     u1u2;
2467                         u32     reg;
2468
2469                         switch (dwc->link_state) {
2470                         case DWC3_LINK_STATE_U1:
2471                         case DWC3_LINK_STATE_U2:
2472                                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2473                                 u1u2 = reg & (DWC3_DCTL_INITU2ENA
2474                                                 | DWC3_DCTL_ACCEPTU2ENA
2475                                                 | DWC3_DCTL_INITU1ENA
2476                                                 | DWC3_DCTL_ACCEPTU1ENA);
2477
2478                                 if (!dwc->u1u2)
2479                                         dwc->u1u2 = reg & u1u2;
2480
2481                                 reg &= ~u1u2;
2482
2483                                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2484                                 break;
2485                         default:
2486                                 /* do nothing */
2487                                 break;
2488                         }
2489                 }
2490         }
2491
2492         switch (next) {
2493         case DWC3_LINK_STATE_U1:
2494                 if (dwc->speed == USB_SPEED_SUPER)
2495                         dwc3_suspend_gadget(dwc);
2496                 break;
2497         case DWC3_LINK_STATE_U2:
2498         case DWC3_LINK_STATE_U3:
2499                 dwc3_suspend_gadget(dwc);
2500                 break;
2501         case DWC3_LINK_STATE_RESUME:
2502                 dwc3_resume_gadget(dwc);
2503                 break;
2504         default:
2505                 /* do nothing */
2506                 break;
2507         }
2508
2509         dwc->link_state = next;
2510 }
2511
2512 static void dwc3_gadget_hibernation_interrupt(struct dwc3 *dwc,
2513                 unsigned int evtinfo)
2514 {
2515         unsigned int is_ss = evtinfo & BIT(4);
2516
2517         /**
2518          * WORKAROUND: DWC3 revison 2.20a with hibernation support
2519          * have a known issue which can cause USB CV TD.9.23 to fail
2520          * randomly.
2521          *
2522          * Because of this issue, core could generate bogus hibernation
2523          * events which SW needs to ignore.
2524          *
2525          * Refers to:
2526          *
2527          * STAR#9000546576: Device Mode Hibernation: Issue in USB 2.0
2528          * Device Fallback from SuperSpeed
2529          */
2530         if (is_ss ^ (dwc->speed == USB_SPEED_SUPER))
2531                 return;
2532
2533         /* enter hibernation here */
2534 }
2535
2536 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
2537                 const struct dwc3_event_devt *event)
2538 {
2539         switch (event->type) {
2540         case DWC3_DEVICE_EVENT_DISCONNECT:
2541                 dwc3_gadget_disconnect_interrupt(dwc);
2542                 break;
2543         case DWC3_DEVICE_EVENT_RESET:
2544                 dwc3_gadget_reset_interrupt(dwc);
2545                 break;
2546         case DWC3_DEVICE_EVENT_CONNECT_DONE:
2547                 dwc3_gadget_conndone_interrupt(dwc);
2548                 break;
2549         case DWC3_DEVICE_EVENT_WAKEUP:
2550                 dwc3_gadget_wakeup_interrupt(dwc);
2551                 break;
2552         case DWC3_DEVICE_EVENT_HIBER_REQ:
2553                 if (dev_WARN_ONCE(dwc->dev, !dwc->has_hibernation,
2554                                         "unexpected hibernation event\n"))
2555                         break;
2556
2557                 dwc3_gadget_hibernation_interrupt(dwc, event->event_info);
2558                 break;
2559         case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
2560                 dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
2561                 break;
2562         case DWC3_DEVICE_EVENT_EOPF:
2563                 dwc3_trace(trace_dwc3_gadget, "End of Periodic Frame");
2564                 break;
2565         case DWC3_DEVICE_EVENT_SOF:
2566                 dwc3_trace(trace_dwc3_gadget, "Start of Periodic Frame");
2567                 break;
2568         case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
2569                 dwc3_trace(trace_dwc3_gadget, "Erratic Error");
2570                 break;
2571         case DWC3_DEVICE_EVENT_CMD_CMPL:
2572                 dwc3_trace(trace_dwc3_gadget, "Command Complete");
2573                 break;
2574         case DWC3_DEVICE_EVENT_OVERFLOW:
2575                 dwc3_trace(trace_dwc3_gadget, "Overflow");
2576                 break;
2577         default:
2578                 dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
2579         }
2580 }
2581
2582 static void dwc3_process_event_entry(struct dwc3 *dwc,
2583                 const union dwc3_event *event)
2584 {
2585         trace_dwc3_event(event->raw);
2586
2587         /* Endpoint IRQ, handle it and return early */
2588         if (event->type.is_devspec == 0) {
2589                 /* depevt */
2590                 return dwc3_endpoint_interrupt(dwc, &event->depevt);
2591         }
2592
2593         switch (event->type.type) {
2594         case DWC3_EVENT_TYPE_DEV:
2595                 dwc3_gadget_interrupt(dwc, &event->devt);
2596                 break;
2597         /* REVISIT what to do with Carkit and I2C events ? */
2598         default:
2599                 dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
2600         }
2601 }
2602
2603 static irqreturn_t dwc3_process_event_buf(struct dwc3 *dwc, u32 buf)
2604 {
2605         struct dwc3_event_buffer *evt;
2606         irqreturn_t ret = IRQ_NONE;
2607         int left;
2608         u32 reg;
2609
2610         evt = dwc->ev_buffs[buf];
2611         left = evt->count;
2612
2613         if (!(evt->flags & DWC3_EVENT_PENDING))
2614                 return IRQ_NONE;
2615
2616         while (left > 0) {
2617                 union dwc3_event event;
2618
2619                 event.raw = *(u32 *) (evt->buf + evt->lpos);
2620
2621                 dwc3_process_event_entry(dwc, &event);
2622
2623                 /*
2624                  * FIXME we wrap around correctly to the next entry as
2625                  * almost all entries are 4 bytes in size. There is one
2626                  * entry which has 12 bytes which is a regular entry
2627                  * followed by 8 bytes data. ATM I don't know how
2628                  * things are organized if we get next to the a
2629                  * boundary so I worry about that once we try to handle
2630                  * that.
2631                  */
2632                 evt->lpos = (evt->lpos + 4) % DWC3_EVENT_BUFFERS_SIZE;
2633                 left -= 4;
2634
2635                 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(buf), 4);
2636         }
2637
2638         evt->count = 0;
2639         evt->flags &= ~DWC3_EVENT_PENDING;
2640         ret = IRQ_HANDLED;
2641
2642         /* Unmask interrupt */
2643         reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(buf));
2644         reg &= ~DWC3_GEVNTSIZ_INTMASK;
2645         dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(buf), reg);
2646
2647         return ret;
2648 }
2649
2650 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc)
2651 {
2652         struct dwc3 *dwc = _dwc;
2653         unsigned long flags;
2654         irqreturn_t ret = IRQ_NONE;
2655         int i;
2656
2657         spin_lock_irqsave(&dwc->lock, flags);
2658
2659         for (i = 0; i < dwc->num_event_buffers; i++)
2660                 ret |= dwc3_process_event_buf(dwc, i);
2661
2662         spin_unlock_irqrestore(&dwc->lock, flags);
2663
2664         return ret;
2665 }
2666
2667 static irqreturn_t dwc3_check_event_buf(struct dwc3 *dwc, u32 buf)
2668 {
2669         struct dwc3_event_buffer *evt;
2670         u32 count;
2671         u32 reg;
2672
2673         evt = dwc->ev_buffs[buf];
2674
2675         count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(buf));
2676         count &= DWC3_GEVNTCOUNT_MASK;
2677         if (!count)
2678                 return IRQ_NONE;
2679
2680         evt->count = count;
2681         evt->flags |= DWC3_EVENT_PENDING;
2682
2683         /* Mask interrupt */
2684         reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(buf));
2685         reg |= DWC3_GEVNTSIZ_INTMASK;
2686         dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(buf), reg);
2687
2688         return IRQ_WAKE_THREAD;
2689 }
2690
2691 static irqreturn_t dwc3_interrupt(int irq, void *_dwc)
2692 {
2693         struct dwc3                     *dwc = _dwc;
2694         int                             i;
2695         irqreturn_t                     ret = IRQ_NONE;
2696
2697         for (i = 0; i < dwc->num_event_buffers; i++) {
2698                 irqreturn_t status;
2699
2700                 status = dwc3_check_event_buf(dwc, i);
2701                 if (status == IRQ_WAKE_THREAD)
2702                         ret = status;
2703         }
2704
2705         return ret;
2706 }
2707
2708 /**
2709  * dwc3_gadget_init - Initializes gadget related registers
2710  * @dwc: pointer to our controller context structure
2711  *
2712  * Returns 0 on success otherwise negative errno.
2713  */
2714 int dwc3_gadget_init(struct dwc3 *dwc)
2715 {
2716         int                                     ret;
2717
2718         dwc->ctrl_req = dma_alloc_coherent(dwc->dev, sizeof(*dwc->ctrl_req),
2719                         &dwc->ctrl_req_addr, GFP_KERNEL);
2720         if (!dwc->ctrl_req) {
2721                 dev_err(dwc->dev, "failed to allocate ctrl request\n");
2722                 ret = -ENOMEM;
2723                 goto err0;
2724         }
2725
2726         dwc->ep0_trb = dma_alloc_coherent(dwc->dev, sizeof(*dwc->ep0_trb) * 2,
2727                         &dwc->ep0_trb_addr, GFP_KERNEL);
2728         if (!dwc->ep0_trb) {
2729                 dev_err(dwc->dev, "failed to allocate ep0 trb\n");
2730                 ret = -ENOMEM;
2731                 goto err1;
2732         }
2733
2734         dwc->setup_buf = kzalloc(DWC3_EP0_BOUNCE_SIZE, GFP_KERNEL);
2735         if (!dwc->setup_buf) {
2736                 ret = -ENOMEM;
2737                 goto err2;
2738         }
2739
2740         dwc->ep0_bounce = dma_alloc_coherent(dwc->dev,
2741                         DWC3_EP0_BOUNCE_SIZE, &dwc->ep0_bounce_addr,
2742                         GFP_KERNEL);
2743         if (!dwc->ep0_bounce) {
2744                 dev_err(dwc->dev, "failed to allocate ep0 bounce buffer\n");
2745                 ret = -ENOMEM;
2746                 goto err3;
2747         }
2748
2749         dwc->zlp_buf = kzalloc(DWC3_ZLP_BUF_SIZE, GFP_KERNEL);
2750         if (!dwc->zlp_buf) {
2751                 ret = -ENOMEM;
2752                 goto err4;
2753         }
2754
2755         dwc->gadget.ops                 = &dwc3_gadget_ops;
2756         dwc->gadget.speed               = USB_SPEED_UNKNOWN;
2757         dwc->gadget.sg_supported        = true;
2758         dwc->gadget.name                = "dwc3-gadget";
2759         dwc->gadget.is_otg              = dwc->dr_mode == USB_DR_MODE_OTG;
2760
2761         /*
2762          * FIXME We might be setting max_speed to <SUPER, however versions
2763          * <2.20a of dwc3 have an issue with metastability (documented
2764          * elsewhere in this driver) which tells us we can't set max speed to
2765          * anything lower than SUPER.
2766          *
2767          * Because gadget.max_speed is only used by composite.c and function
2768          * drivers (i.e. it won't go into dwc3's registers) we are allowing this
2769          * to happen so we avoid sending SuperSpeed Capability descriptor
2770          * together with our BOS descriptor as that could confuse host into
2771          * thinking we can handle super speed.
2772          *
2773          * Note that, in fact, we won't even support GetBOS requests when speed
2774          * is less than super speed because we don't have means, yet, to tell
2775          * composite.c that we are USB 2.0 + LPM ECN.
2776          */
2777         if (dwc->revision < DWC3_REVISION_220A)
2778                 dwc3_trace(trace_dwc3_gadget,
2779                                 "Changing max_speed on rev %08x\n",
2780                                 dwc->revision);
2781
2782         dwc->gadget.max_speed           = dwc->maximum_speed;
2783
2784         /*
2785          * Per databook, DWC3 needs buffer size to be aligned to MaxPacketSize
2786          * on ep out.
2787          */
2788         dwc->gadget.quirk_ep_out_aligned_size = true;
2789
2790         /*
2791          * REVISIT: Here we should clear all pending IRQs to be
2792          * sure we're starting from a well known location.
2793          */
2794
2795         ret = dwc3_gadget_init_endpoints(dwc);
2796         if (ret)
2797                 goto err5;
2798
2799         ret = usb_add_gadget_udc(dwc->dev, &dwc->gadget);
2800         if (ret) {
2801                 dev_err(dwc->dev, "failed to register udc\n");
2802                 goto err5;
2803         }
2804
2805         return 0;
2806
2807 err5:
2808         kfree(dwc->zlp_buf);
2809
2810 err4:
2811         dwc3_gadget_free_endpoints(dwc);
2812         dma_free_coherent(dwc->dev, DWC3_EP0_BOUNCE_SIZE,
2813                         dwc->ep0_bounce, dwc->ep0_bounce_addr);
2814
2815 err3:
2816         kfree(dwc->setup_buf);
2817
2818 err2:
2819         dma_free_coherent(dwc->dev, sizeof(*dwc->ep0_trb),
2820                         dwc->ep0_trb, dwc->ep0_trb_addr);
2821
2822 err1:
2823         dma_free_coherent(dwc->dev, sizeof(*dwc->ctrl_req),
2824                         dwc->ctrl_req, dwc->ctrl_req_addr);
2825
2826 err0:
2827         return ret;
2828 }
2829
2830 /* -------------------------------------------------------------------------- */
2831
2832 void dwc3_gadget_exit(struct dwc3 *dwc)
2833 {
2834         usb_del_gadget_udc(&dwc->gadget);
2835
2836         dwc3_gadget_free_endpoints(dwc);
2837
2838         dma_free_coherent(dwc->dev, DWC3_EP0_BOUNCE_SIZE,
2839                         dwc->ep0_bounce, dwc->ep0_bounce_addr);
2840
2841         kfree(dwc->setup_buf);
2842         kfree(dwc->zlp_buf);
2843
2844         dma_free_coherent(dwc->dev, sizeof(*dwc->ep0_trb),
2845                         dwc->ep0_trb, dwc->ep0_trb_addr);
2846
2847         dma_free_coherent(dwc->dev, sizeof(*dwc->ctrl_req),
2848                         dwc->ctrl_req, dwc->ctrl_req_addr);
2849 }
2850
2851 int dwc3_gadget_suspend(struct dwc3 *dwc)
2852 {
2853         if (dwc->pullups_connected) {
2854                 dwc3_gadget_disable_irq(dwc);
2855                 dwc3_gadget_run_stop(dwc, true, true);
2856         }
2857
2858         __dwc3_gadget_ep_disable(dwc->eps[0]);
2859         __dwc3_gadget_ep_disable(dwc->eps[1]);
2860
2861         dwc->dcfg = dwc3_readl(dwc->regs, DWC3_DCFG);
2862
2863         return 0;
2864 }
2865
2866 int dwc3_gadget_resume(struct dwc3 *dwc)
2867 {
2868         struct dwc3_ep          *dep;
2869         int                     ret;
2870
2871         /* Start with SuperSpeed Default */
2872         dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2873
2874         dep = dwc->eps[0];
2875         ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL, false,
2876                         false);
2877         if (ret)
2878                 goto err0;
2879
2880         dep = dwc->eps[1];
2881         ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL, false,
2882                         false);
2883         if (ret)
2884                 goto err1;
2885
2886         /* begin to receive SETUP packets */
2887         dwc->ep0state = EP0_SETUP_PHASE;
2888         dwc3_ep0_out_start(dwc);
2889
2890         dwc3_writel(dwc->regs, DWC3_DCFG, dwc->dcfg);
2891
2892         if (dwc->pullups_connected) {
2893                 dwc3_gadget_enable_irq(dwc);
2894                 dwc3_gadget_run_stop(dwc, true, false);
2895         }
2896
2897         return 0;
2898
2899 err1:
2900         __dwc3_gadget_ep_disable(dwc->eps[0]);
2901
2902 err0:
2903         return ret;
2904 }