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