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