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