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