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