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