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