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