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