UPSTREAM: PCI: rockchip: Set vendor ID from local core config space
[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         if (s_pkt)
2023                 return 1;
2024         if ((event->status & DEPEVT_STATUS_LST) &&
2025                         (trb->ctrl & (DWC3_TRB_CTRL_LST |
2026                                 DWC3_TRB_CTRL_HWO)))
2027                 return 1;
2028         if ((event->status & DEPEVT_STATUS_IOC) &&
2029                         (trb->ctrl & DWC3_TRB_CTRL_IOC))
2030                 return 1;
2031         return 0;
2032 }
2033
2034 static int dwc3_cleanup_done_reqs(struct dwc3 *dwc, struct dwc3_ep *dep,
2035                 const struct dwc3_event_depevt *event, int status)
2036 {
2037         struct dwc3_request     *req;
2038         struct dwc3_trb         *trb;
2039         unsigned int            slot;
2040         unsigned int            i;
2041         int                     count = 0;
2042         int                     ret;
2043
2044         do {
2045                 req = next_request(&dep->started_list);
2046                 if (WARN_ON_ONCE(!req))
2047                         return 1;
2048
2049                 i = 0;
2050                 do {
2051                         slot = req->first_trb_index + i;
2052                         if (slot == DWC3_TRB_NUM - 1)
2053                                 slot++;
2054                         slot %= DWC3_TRB_NUM;
2055                         trb = &dep->trb_pool[slot];
2056                         count += trb->size & DWC3_TRB_SIZE_MASK;
2057
2058
2059                         ret = __dwc3_cleanup_done_trbs(dwc, dep, req, trb,
2060                                         event, status);
2061                         if (ret)
2062                                 break;
2063                 } while (++i < req->request.num_mapped_sgs);
2064
2065                 /*
2066                  * We assume here we will always receive the entire data block
2067                  * which we should receive. Meaning, if we program RX to
2068                  * receive 4K but we receive only 2K, we assume that's all we
2069                  * should receive and we simply bounce the request back to the
2070                  * gadget driver for further processing.
2071                  */
2072                 req->request.actual += req->request.length - count;
2073                 dwc3_gadget_giveback(dep, req, status);
2074
2075                 if (ret)
2076                         break;
2077         } while (1);
2078
2079         /*
2080          * Our endpoint might get disabled by another thread during
2081          * dwc3_gadget_giveback(). If that happens, we're just gonna return 1
2082          * early on so DWC3_EP_BUSY flag gets cleared
2083          */
2084         if (!dep->endpoint.desc)
2085                 return 1;
2086
2087         if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
2088                         list_empty(&dep->started_list)) {
2089                 if (list_empty(&dep->pending_list)) {
2090                         /*
2091                          * If there is no entry in request list then do
2092                          * not issue END TRANSFER now. Just set PENDING
2093                          * flag, so that END TRANSFER is issued when an
2094                          * entry is added into request list.
2095                          */
2096                         dep->flags = DWC3_EP_PENDING_REQUEST;
2097                 } else {
2098                         dwc3_stop_active_transfer(dwc, dep->number, true);
2099                         dep->flags = DWC3_EP_ENABLED;
2100                 }
2101                 return 1;
2102         }
2103
2104         if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
2105                 if ((event->status & DEPEVT_STATUS_IOC) &&
2106                                 (trb->ctrl & DWC3_TRB_CTRL_IOC))
2107                         return 0;
2108         return 1;
2109 }
2110
2111 static void dwc3_endpoint_transfer_complete(struct dwc3 *dwc,
2112                 struct dwc3_ep *dep, const struct dwc3_event_depevt *event)
2113 {
2114         unsigned                status = 0;
2115         int                     clean_busy;
2116         u32                     is_xfer_complete;
2117
2118         is_xfer_complete = (event->endpoint_event == DWC3_DEPEVT_XFERCOMPLETE);
2119
2120         if (event->status & DEPEVT_STATUS_BUSERR)
2121                 status = -ECONNRESET;
2122
2123         clean_busy = dwc3_cleanup_done_reqs(dwc, dep, event, status);
2124         if (clean_busy && (!dep->endpoint.desc || is_xfer_complete ||
2125                                 usb_endpoint_xfer_isoc(dep->endpoint.desc)))
2126                 dep->flags &= ~DWC3_EP_BUSY;
2127
2128         /*
2129          * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
2130          * See dwc3_gadget_linksts_change_interrupt() for 1st half.
2131          */
2132         if (dwc->revision < DWC3_REVISION_183A) {
2133                 u32             reg;
2134                 int             i;
2135
2136                 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
2137                         dep = dwc->eps[i];
2138
2139                         if (!(dep->flags & DWC3_EP_ENABLED))
2140                                 continue;
2141
2142                         if (!list_empty(&dep->started_list))
2143                                 return;
2144                 }
2145
2146                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2147                 reg |= dwc->u1u2;
2148                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2149
2150                 dwc->u1u2 = 0;
2151         }
2152
2153         /*
2154          * Our endpoint might get disabled by another thread during
2155          * dwc3_gadget_giveback(). If that happens, we're just gonna return 1
2156          * early on so DWC3_EP_BUSY flag gets cleared
2157          */
2158         if (!dep->endpoint.desc)
2159                 return;
2160
2161         if (!usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
2162                 int ret;
2163
2164                 ret = __dwc3_gadget_kick_transfer(dep, 0);
2165                 if (!ret || ret == -EBUSY)
2166                         return;
2167         }
2168 }
2169
2170 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
2171                 const struct dwc3_event_depevt *event)
2172 {
2173         struct dwc3_ep          *dep;
2174         u8                      epnum = event->endpoint_number;
2175
2176         dep = dwc->eps[epnum];
2177
2178         if (!(dep->flags & DWC3_EP_ENABLED))
2179                 return;
2180
2181         if (epnum == 0 || epnum == 1) {
2182                 if (!dwc->connected &&
2183                     event->endpoint_event == DWC3_DEPEVT_XFERCOMPLETE)
2184                         dwc->connected = true;
2185                 dwc3_ep0_interrupt(dwc, event);
2186                 return;
2187         }
2188
2189         switch (event->endpoint_event) {
2190         case DWC3_DEPEVT_XFERCOMPLETE:
2191                 dep->resource_index = 0;
2192
2193                 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
2194                         dwc3_trace(trace_dwc3_gadget,
2195                                         "%s is an Isochronous endpoint",
2196                                         dep->name);
2197                         return;
2198                 }
2199
2200                 dwc3_endpoint_transfer_complete(dwc, dep, event);
2201                 break;
2202         case DWC3_DEPEVT_XFERINPROGRESS:
2203                 dwc3_endpoint_transfer_complete(dwc, dep, event);
2204                 break;
2205         case DWC3_DEPEVT_XFERNOTREADY:
2206                 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
2207                         dwc3_gadget_start_isoc(dwc, dep, event);
2208                 } else {
2209                         int active;
2210                         int ret;
2211
2212                         active = event->status & DEPEVT_STATUS_TRANSFER_ACTIVE;
2213
2214                         dwc3_trace(trace_dwc3_gadget, "%s: reason %s",
2215                                         dep->name, active ? "Transfer Active"
2216                                         : "Transfer Not Active");
2217
2218                         ret = __dwc3_gadget_kick_transfer(dep, 0);
2219                         if (!ret || ret == -EBUSY)
2220                                 return;
2221
2222                         dwc3_trace(trace_dwc3_gadget,
2223                                         "%s: failed to kick transfers",
2224                                         dep->name);
2225                 }
2226
2227                 break;
2228         case DWC3_DEPEVT_STREAMEVT:
2229                 if (!usb_endpoint_xfer_bulk(dep->endpoint.desc)) {
2230                         dev_err(dwc->dev, "Stream event for non-Bulk %s\n",
2231                                         dep->name);
2232                         return;
2233                 }
2234
2235                 switch (event->status) {
2236                 case DEPEVT_STREAMEVT_FOUND:
2237                         dwc3_trace(trace_dwc3_gadget,
2238                                         "Stream %d found and started",
2239                                         event->parameters);
2240
2241                         break;
2242                 case DEPEVT_STREAMEVT_NOTFOUND:
2243                         /* FALLTHROUGH */
2244                 default:
2245                         dwc3_trace(trace_dwc3_gadget,
2246                                         "unable to find suitable stream");
2247                 }
2248                 break;
2249         case DWC3_DEPEVT_RXTXFIFOEVT:
2250                 dwc3_trace(trace_dwc3_gadget, "%s FIFO Overrun", dep->name);
2251                 break;
2252         case DWC3_DEPEVT_EPCMDCMPLT:
2253                 dwc3_trace(trace_dwc3_gadget, "Endpoint Command Complete");
2254                 break;
2255         }
2256 }
2257
2258 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
2259 {
2260         if (dwc->gadget_driver && dwc->gadget_driver->disconnect) {
2261                 spin_unlock(&dwc->lock);
2262                 dwc->gadget_driver->disconnect(&dwc->gadget);
2263                 spin_lock(&dwc->lock);
2264         }
2265 }
2266
2267 static void dwc3_suspend_gadget(struct dwc3 *dwc)
2268 {
2269         if (dwc->gadget_driver && dwc->gadget_driver->suspend) {
2270                 spin_unlock(&dwc->lock);
2271                 dwc->gadget_driver->suspend(&dwc->gadget);
2272                 spin_lock(&dwc->lock);
2273         }
2274 }
2275
2276 static void dwc3_resume_gadget(struct dwc3 *dwc)
2277 {
2278         if (dwc->gadget_driver && dwc->gadget_driver->resume) {
2279                 spin_unlock(&dwc->lock);
2280                 dwc->gadget_driver->resume(&dwc->gadget);
2281                 spin_lock(&dwc->lock);
2282         }
2283 }
2284
2285 static void dwc3_reset_gadget(struct dwc3 *dwc)
2286 {
2287         if (!dwc->gadget_driver)
2288                 return;
2289
2290         if (dwc->gadget.speed != USB_SPEED_UNKNOWN) {
2291                 spin_unlock(&dwc->lock);
2292                 usb_gadget_udc_reset(&dwc->gadget, dwc->gadget_driver);
2293                 spin_lock(&dwc->lock);
2294         }
2295 }
2296
2297 static void dwc3_stop_active_transfer(struct dwc3 *dwc, u32 epnum, bool force)
2298 {
2299         struct dwc3_ep *dep;
2300         struct dwc3_gadget_ep_cmd_params params;
2301         u32 cmd;
2302         int ret;
2303
2304         dep = dwc->eps[epnum];
2305
2306         if (!dep->resource_index)
2307                 return;
2308
2309         /*
2310          * NOTICE: We are violating what the Databook says about the
2311          * EndTransfer command. Ideally we would _always_ wait for the
2312          * EndTransfer Command Completion IRQ, but that's causing too
2313          * much trouble synchronizing between us and gadget driver.
2314          *
2315          * We have discussed this with the IP Provider and it was
2316          * suggested to giveback all requests here, but give HW some
2317          * extra time to synchronize with the interconnect. We're using
2318          * an arbitrary 100us delay for that.
2319          *
2320          * Note also that a similar handling was tested by Synopsys
2321          * (thanks a lot Paul) and nothing bad has come out of it.
2322          * In short, what we're doing is:
2323          *
2324          * - Issue EndTransfer WITH CMDIOC bit set
2325          * - Wait 100us
2326          */
2327
2328         cmd = DWC3_DEPCMD_ENDTRANSFER;
2329         cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
2330         cmd |= DWC3_DEPCMD_CMDIOC;
2331         cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
2332         memset(&params, 0, sizeof(params));
2333         ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
2334         WARN_ON_ONCE(ret);
2335         dep->resource_index = 0;
2336         dep->flags &= ~DWC3_EP_BUSY;
2337         udelay(100);
2338 }
2339
2340 static void dwc3_stop_active_transfers(struct dwc3 *dwc)
2341 {
2342         u32 epnum;
2343
2344         for (epnum = 2; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2345                 struct dwc3_ep *dep;
2346
2347                 dep = dwc->eps[epnum];
2348                 if (!dep)
2349                         continue;
2350
2351                 if (!(dep->flags & DWC3_EP_ENABLED))
2352                         continue;
2353
2354                 dwc3_remove_requests(dwc, dep);
2355         }
2356 }
2357
2358 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
2359 {
2360         u32 epnum;
2361
2362         for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2363                 struct dwc3_ep *dep;
2364                 int ret;
2365
2366                 dep = dwc->eps[epnum];
2367                 if (!dep)
2368                         continue;
2369
2370                 if (!(dep->flags & DWC3_EP_STALL))
2371                         continue;
2372
2373                 dep->flags &= ~DWC3_EP_STALL;
2374
2375                 ret = dwc3_send_clear_stall_ep_cmd(dep);
2376                 WARN_ON_ONCE(ret);
2377         }
2378 }
2379
2380 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
2381 {
2382         int                     reg;
2383
2384         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2385         reg &= ~DWC3_DCTL_INITU1ENA;
2386         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2387
2388         reg &= ~DWC3_DCTL_INITU2ENA;
2389         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2390
2391         dwc3_disconnect_gadget(dwc);
2392
2393         dwc->gadget.speed = USB_SPEED_UNKNOWN;
2394         dwc->setup_packet_pending = false;
2395         usb_gadget_set_state(&dwc->gadget, USB_STATE_NOTATTACHED);
2396
2397         dwc->connected = false;
2398 }
2399
2400 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
2401 {
2402         u32                     reg;
2403
2404         /*
2405          * WORKAROUND: DWC3 revisions <1.88a have an issue which
2406          * would cause a missing Disconnect Event if there's a
2407          * pending Setup Packet in the FIFO.
2408          *
2409          * There's no suggested workaround on the official Bug
2410          * report, which states that "unless the driver/application
2411          * is doing any special handling of a disconnect event,
2412          * there is no functional issue".
2413          *
2414          * Unfortunately, it turns out that we _do_ some special
2415          * handling of a disconnect event, namely complete all
2416          * pending transfers, notify gadget driver of the
2417          * disconnection, and so on.
2418          *
2419          * Our suggested workaround is to follow the Disconnect
2420          * Event steps here, instead, based on a setup_packet_pending
2421          * flag. Such flag gets set whenever we have a SETUP_PENDING
2422          * status for EP0 TRBs and gets cleared on XferComplete for the
2423          * same endpoint.
2424          *
2425          * Refers to:
2426          *
2427          * STAR#9000466709: RTL: Device : Disconnect event not
2428          * generated if setup packet pending in FIFO
2429          */
2430         if (dwc->revision < DWC3_REVISION_188A) {
2431                 if (dwc->setup_packet_pending)
2432                         dwc3_gadget_disconnect_interrupt(dwc);
2433         }
2434
2435         dwc3_reset_gadget(dwc);
2436
2437         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2438         reg &= ~DWC3_DCTL_TSTCTRL_MASK;
2439         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2440         dwc->test_mode = false;
2441
2442         dwc3_stop_active_transfers(dwc);
2443         dwc3_clear_stall_all_ep(dwc);
2444
2445         /* Reset device address to zero */
2446         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2447         reg &= ~(DWC3_DCFG_DEVADDR_MASK);
2448         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2449 }
2450
2451 static void dwc3_update_ram_clk_sel(struct dwc3 *dwc, u32 speed)
2452 {
2453         u32 reg;
2454         u32 usb30_clock = DWC3_GCTL_CLK_BUS;
2455
2456         /*
2457          * We change the clock only at SS but I dunno why I would want to do
2458          * this. Maybe it becomes part of the power saving plan.
2459          */
2460
2461         if (speed != DWC3_DSTS_SUPERSPEED)
2462                 return;
2463
2464         /*
2465          * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
2466          * each time on Connect Done.
2467          */
2468         if (!usb30_clock)
2469                 return;
2470
2471         reg = dwc3_readl(dwc->regs, DWC3_GCTL);
2472         reg |= DWC3_GCTL_RAMCLKSEL(usb30_clock);
2473         dwc3_writel(dwc->regs, DWC3_GCTL, reg);
2474 }
2475
2476 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
2477 {
2478         struct dwc3_ep          *dep;
2479         int                     ret;
2480         u32                     reg;
2481         u8                      speed;
2482
2483         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2484         speed = reg & DWC3_DSTS_CONNECTSPD;
2485         dwc->speed = speed;
2486
2487         dwc3_update_ram_clk_sel(dwc, speed);
2488
2489         switch (speed) {
2490         case DWC3_DSTS_SUPERSPEED:
2491                 /*
2492                  * WORKAROUND: DWC3 revisions <1.90a have an issue which
2493                  * would cause a missing USB3 Reset event.
2494                  *
2495                  * In such situations, we should force a USB3 Reset
2496                  * event by calling our dwc3_gadget_reset_interrupt()
2497                  * routine.
2498                  *
2499                  * Refers to:
2500                  *
2501                  * STAR#9000483510: RTL: SS : USB3 reset event may
2502                  * not be generated always when the link enters poll
2503                  */
2504                 if (dwc->revision < DWC3_REVISION_190A)
2505                         dwc3_gadget_reset_interrupt(dwc);
2506
2507                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2508                 dwc->gadget.ep0->maxpacket = 512;
2509                 dwc->gadget.speed = USB_SPEED_SUPER;
2510                 break;
2511         case DWC3_DSTS_HIGHSPEED:
2512                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
2513                 dwc->gadget.ep0->maxpacket = 64;
2514                 dwc->gadget.speed = USB_SPEED_HIGH;
2515                 break;
2516         case DWC3_DSTS_FULLSPEED2:
2517         case DWC3_DSTS_FULLSPEED1:
2518                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
2519                 dwc->gadget.ep0->maxpacket = 64;
2520                 dwc->gadget.speed = USB_SPEED_FULL;
2521                 break;
2522         case DWC3_DSTS_LOWSPEED:
2523                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(8);
2524                 dwc->gadget.ep0->maxpacket = 8;
2525                 dwc->gadget.speed = USB_SPEED_LOW;
2526                 break;
2527         }
2528
2529         /* Enable USB2 LPM Capability */
2530
2531         if ((dwc->revision > DWC3_REVISION_194A) &&
2532             (speed != DWC3_DSTS_SUPERSPEED)) {
2533                 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2534                 reg |= DWC3_DCFG_LPM_CAP;
2535                 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2536
2537                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2538                 reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
2539
2540                 reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold);
2541
2542                 /*
2543                  * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
2544                  * DCFG.LPMCap is set, core responses with an ACK and the
2545                  * BESL value in the LPM token is less than or equal to LPM
2546                  * NYET threshold.
2547                  */
2548                 WARN_ONCE(dwc->revision < DWC3_REVISION_240A
2549                                 && dwc->has_lpm_erratum,
2550                                 "LPM Erratum not available on dwc3 revisisions < 2.40a\n");
2551
2552                 if (dwc->has_lpm_erratum && dwc->revision >= DWC3_REVISION_240A)
2553                         reg |= DWC3_DCTL_LPM_ERRATA(dwc->lpm_nyet_threshold);
2554
2555                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2556         } else {
2557                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2558                 reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
2559                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2560         }
2561
2562         dep = dwc->eps[0];
2563         ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL, true,
2564                         false);
2565         if (ret) {
2566                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2567                 return;
2568         }
2569
2570         dep = dwc->eps[1];
2571         ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL, true,
2572                         false);
2573         if (ret) {
2574                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2575                 return;
2576         }
2577
2578         /*
2579          * Configure PHY via GUSB3PIPECTLn if required.
2580          *
2581          * Update GTXFIFOSIZn
2582          *
2583          * In both cases reset values should be sufficient.
2584          */
2585 }
2586
2587 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
2588 {
2589         /*
2590          * TODO take core out of low power mode when that's
2591          * implemented.
2592          */
2593
2594         if (dwc->gadget_driver && dwc->gadget_driver->resume) {
2595                 spin_unlock(&dwc->lock);
2596                 dwc->gadget_driver->resume(&dwc->gadget);
2597                 spin_lock(&dwc->lock);
2598         }
2599 }
2600
2601 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
2602                 unsigned int evtinfo)
2603 {
2604         enum dwc3_link_state    next = evtinfo & DWC3_LINK_STATE_MASK;
2605         unsigned int            pwropt;
2606
2607         /*
2608          * WORKAROUND: DWC3 < 2.50a have an issue when configured without
2609          * Hibernation mode enabled which would show up when device detects
2610          * host-initiated U3 exit.
2611          *
2612          * In that case, device will generate a Link State Change Interrupt
2613          * from U3 to RESUME which is only necessary if Hibernation is
2614          * configured in.
2615          *
2616          * There are no functional changes due to such spurious event and we
2617          * just need to ignore it.
2618          *
2619          * Refers to:
2620          *
2621          * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
2622          * operational mode
2623          */
2624         pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
2625         if ((dwc->revision < DWC3_REVISION_250A) &&
2626                         (pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
2627                 if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
2628                                 (next == DWC3_LINK_STATE_RESUME)) {
2629                         dwc3_trace(trace_dwc3_gadget,
2630                                         "ignoring transition U3 -> Resume");
2631                         return;
2632                 }
2633         }
2634
2635         /*
2636          * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
2637          * on the link partner, the USB session might do multiple entry/exit
2638          * of low power states before a transfer takes place.
2639          *
2640          * Due to this problem, we might experience lower throughput. The
2641          * suggested workaround is to disable DCTL[12:9] bits if we're
2642          * transitioning from U1/U2 to U0 and enable those bits again
2643          * after a transfer completes and there are no pending transfers
2644          * on any of the enabled endpoints.
2645          *
2646          * This is the first half of that workaround.
2647          *
2648          * Refers to:
2649          *
2650          * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
2651          * core send LGO_Ux entering U0
2652          */
2653         if (dwc->revision < DWC3_REVISION_183A) {
2654                 if (next == DWC3_LINK_STATE_U0) {
2655                         u32     u1u2;
2656                         u32     reg;
2657
2658                         switch (dwc->link_state) {
2659                         case DWC3_LINK_STATE_U1:
2660                         case DWC3_LINK_STATE_U2:
2661                                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2662                                 u1u2 = reg & (DWC3_DCTL_INITU2ENA
2663                                                 | DWC3_DCTL_ACCEPTU2ENA
2664                                                 | DWC3_DCTL_INITU1ENA
2665                                                 | DWC3_DCTL_ACCEPTU1ENA);
2666
2667                                 if (!dwc->u1u2)
2668                                         dwc->u1u2 = reg & u1u2;
2669
2670                                 reg &= ~u1u2;
2671
2672                                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2673                                 break;
2674                         default:
2675                                 /* do nothing */
2676                                 break;
2677                         }
2678                 }
2679         }
2680
2681         switch (next) {
2682         case DWC3_LINK_STATE_U1:
2683                 if (dwc->speed == USB_SPEED_SUPER)
2684                         dwc3_suspend_gadget(dwc);
2685                 break;
2686         case DWC3_LINK_STATE_U2:
2687         case DWC3_LINK_STATE_U3:
2688                 dwc3_suspend_gadget(dwc);
2689                 break;
2690         case DWC3_LINK_STATE_RESUME:
2691                 dwc3_resume_gadget(dwc);
2692                 break;
2693         default:
2694                 /* do nothing */
2695                 break;
2696         }
2697
2698         dwc->link_state = next;
2699 }
2700
2701 static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc,
2702                                           unsigned int evtinfo)
2703 {
2704         enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
2705
2706         if (dwc->link_state != next && next == DWC3_LINK_STATE_U3)
2707                 dwc3_suspend_gadget(dwc);
2708
2709         dwc->link_state = next;
2710 }
2711
2712 static void dwc3_gadget_hibernation_interrupt(struct dwc3 *dwc,
2713                 unsigned int evtinfo)
2714 {
2715         unsigned int is_ss = evtinfo & BIT(4);
2716
2717         /**
2718          * WORKAROUND: DWC3 revison 2.20a with hibernation support
2719          * have a known issue which can cause USB CV TD.9.23 to fail
2720          * randomly.
2721          *
2722          * Because of this issue, core could generate bogus hibernation
2723          * events which SW needs to ignore.
2724          *
2725          * Refers to:
2726          *
2727          * STAR#9000546576: Device Mode Hibernation: Issue in USB 2.0
2728          * Device Fallback from SuperSpeed
2729          */
2730         if (is_ss ^ (dwc->speed == USB_SPEED_SUPER))
2731                 return;
2732
2733         /* enter hibernation here */
2734 }
2735
2736 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
2737                 const struct dwc3_event_devt *event)
2738 {
2739         switch (event->type) {
2740         case DWC3_DEVICE_EVENT_DISCONNECT:
2741                 dwc3_gadget_disconnect_interrupt(dwc);
2742                 break;
2743         case DWC3_DEVICE_EVENT_RESET:
2744                 dwc3_gadget_reset_interrupt(dwc);
2745                 break;
2746         case DWC3_DEVICE_EVENT_CONNECT_DONE:
2747                 dwc3_gadget_conndone_interrupt(dwc);
2748                 break;
2749         case DWC3_DEVICE_EVENT_WAKEUP:
2750                 dwc3_gadget_wakeup_interrupt(dwc);
2751                 break;
2752         case DWC3_DEVICE_EVENT_HIBER_REQ:
2753                 if (dev_WARN_ONCE(dwc->dev, !dwc->has_hibernation,
2754                                         "unexpected hibernation event\n"))
2755                         break;
2756
2757                 dwc3_gadget_hibernation_interrupt(dwc, event->event_info);
2758                 break;
2759         case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
2760                 dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
2761                 break;
2762         case DWC3_DEVICE_EVENT_EOPF:
2763                 /* It changed to be suspend event for version 2.30a and above */
2764                 if (dwc->revision < DWC3_REVISION_230A) {
2765                         dwc3_trace(trace_dwc3_gadget, "End of Periodic Frame");
2766                 } else {
2767                         dwc3_trace(trace_dwc3_gadget, "U3/L1-L2 Suspend Event");
2768
2769                         /*
2770                          * Ignore suspend event until the gadget enters into
2771                          * USB_STATE_CONFIGURED state.
2772                          */
2773                         if (dwc->gadget.state >= USB_STATE_CONFIGURED)
2774                                 dwc3_gadget_suspend_interrupt(dwc,
2775                                                 event->event_info);
2776                 }
2777                 break;
2778         case DWC3_DEVICE_EVENT_SOF:
2779                 dwc3_trace(trace_dwc3_gadget, "Start of Periodic Frame");
2780                 break;
2781         case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
2782                 dwc3_trace(trace_dwc3_gadget, "Erratic Error");
2783                 break;
2784         case DWC3_DEVICE_EVENT_CMD_CMPL:
2785                 dwc3_trace(trace_dwc3_gadget, "Command Complete");
2786                 break;
2787         case DWC3_DEVICE_EVENT_OVERFLOW:
2788                 dwc3_trace(trace_dwc3_gadget, "Overflow");
2789                 break;
2790         default:
2791                 dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
2792         }
2793 }
2794
2795 static void dwc3_process_event_entry(struct dwc3 *dwc,
2796                 const union dwc3_event *event)
2797 {
2798         trace_dwc3_event(event->raw);
2799
2800         /* Endpoint IRQ, handle it and return early */
2801         if (event->type.is_devspec == 0) {
2802                 /* depevt */
2803                 return dwc3_endpoint_interrupt(dwc, &event->depevt);
2804         }
2805
2806         switch (event->type.type) {
2807         case DWC3_EVENT_TYPE_DEV:
2808                 dwc3_gadget_interrupt(dwc, &event->devt);
2809                 break;
2810         /* REVISIT what to do with Carkit and I2C events ? */
2811         default:
2812                 dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
2813         }
2814 }
2815
2816 static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt)
2817 {
2818         struct dwc3 *dwc = evt->dwc;
2819         irqreturn_t ret = IRQ_NONE;
2820         int left;
2821         u32 reg;
2822
2823         left = evt->count;
2824
2825         if (!(evt->flags & DWC3_EVENT_PENDING))
2826                 return IRQ_NONE;
2827
2828         while (left > 0) {
2829                 union dwc3_event event;
2830
2831                 event.raw = *(u32 *) (evt->buf + evt->lpos);
2832
2833                 dwc3_process_event_entry(dwc, &event);
2834
2835                 /*
2836                  * FIXME we wrap around correctly to the next entry as
2837                  * almost all entries are 4 bytes in size. There is one
2838                  * entry which has 12 bytes which is a regular entry
2839                  * followed by 8 bytes data. ATM I don't know how
2840                  * things are organized if we get next to the a
2841                  * boundary so I worry about that once we try to handle
2842                  * that.
2843                  */
2844                 evt->lpos = (evt->lpos + 4) % DWC3_EVENT_BUFFERS_SIZE;
2845                 left -= 4;
2846
2847                 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), 4);
2848         }
2849
2850         evt->count = 0;
2851         evt->flags &= ~DWC3_EVENT_PENDING;
2852         ret = IRQ_HANDLED;
2853
2854         /* Unmask interrupt */
2855         reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
2856         reg &= ~DWC3_GEVNTSIZ_INTMASK;
2857         dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
2858
2859         return ret;
2860 }
2861
2862 static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt)
2863 {
2864         struct dwc3_event_buffer *evt = _evt;
2865         struct dwc3 *dwc = evt->dwc;
2866         unsigned long flags;
2867         irqreturn_t ret = IRQ_NONE;
2868
2869         spin_lock_irqsave(&dwc->lock, flags);
2870         ret = dwc3_process_event_buf(evt);
2871         spin_unlock_irqrestore(&dwc->lock, flags);
2872
2873         return ret;
2874 }
2875
2876 static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt)
2877 {
2878         struct dwc3 *dwc = evt->dwc;
2879         u32 count;
2880         u32 reg;
2881
2882         reg = dwc3_readl(dwc->regs, DWC3_GCTL);
2883
2884         if (pm_runtime_suspended(dwc->dev) &&
2885             DWC3_GCTL_PRTCAP(reg) != DWC3_GCTL_PRTCAP_HOST) {
2886                 pm_runtime_get(dwc->dev);
2887                 disable_irq_nosync(dwc->irq_gadget);
2888                 dwc->pending_events = true;
2889                 return IRQ_HANDLED;
2890         }
2891
2892         count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
2893         count &= DWC3_GEVNTCOUNT_MASK;
2894         if (!count)
2895                 return IRQ_NONE;
2896
2897         evt->count = count;
2898         evt->flags |= DWC3_EVENT_PENDING;
2899
2900         /* Mask interrupt */
2901         reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
2902         reg |= DWC3_GEVNTSIZ_INTMASK;
2903         dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
2904
2905         return IRQ_WAKE_THREAD;
2906 }
2907
2908 static irqreturn_t dwc3_interrupt(int irq, void *_evt)
2909 {
2910         struct dwc3_event_buffer        *evt = _evt;
2911
2912         return dwc3_check_event_buf(evt);
2913 }
2914
2915 /**
2916  * dwc3_gadget_init - Initializes gadget related registers
2917  * @dwc: pointer to our controller context structure
2918  *
2919  * Returns 0 on success otherwise negative errno.
2920  */
2921 int dwc3_gadget_init(struct dwc3 *dwc)
2922 {
2923         int ret, irq;
2924         struct platform_device *dwc3_pdev = to_platform_device(dwc->dev);
2925
2926         irq = platform_get_irq_byname(dwc3_pdev, "peripheral");
2927         if (irq == -EPROBE_DEFER)
2928                 return irq;
2929
2930         if (irq <= 0) {
2931                 irq = platform_get_irq_byname(dwc3_pdev, "dwc_usb3");
2932                 if (irq == -EPROBE_DEFER)
2933                         return irq;
2934
2935                 if (irq <= 0) {
2936                         irq = platform_get_irq(dwc3_pdev, 0);
2937                         if (irq <= 0) {
2938                                 if (irq != -EPROBE_DEFER) {
2939                                         dev_err(dwc->dev,
2940                                                 "missing peripheral IRQ\n");
2941                                 }
2942                                 if (!irq)
2943                                         irq = -EINVAL;
2944                                 return irq;
2945                         }
2946                 }
2947         }
2948
2949         dwc->irq_gadget = irq;
2950
2951         dwc->ctrl_req = dma_alloc_coherent(dwc->dev, sizeof(*dwc->ctrl_req),
2952                         &dwc->ctrl_req_addr, GFP_KERNEL);
2953         if (!dwc->ctrl_req) {
2954                 dev_err(dwc->dev, "failed to allocate ctrl request\n");
2955                 ret = -ENOMEM;
2956                 goto err0;
2957         }
2958
2959         dwc->ep0_trb = dma_alloc_coherent(dwc->dev, sizeof(*dwc->ep0_trb) * 2,
2960                         &dwc->ep0_trb_addr, GFP_KERNEL);
2961         if (!dwc->ep0_trb) {
2962                 dev_err(dwc->dev, "failed to allocate ep0 trb\n");
2963                 ret = -ENOMEM;
2964                 goto err1;
2965         }
2966
2967         dwc->setup_buf = kzalloc(DWC3_EP0_BOUNCE_SIZE, GFP_KERNEL);
2968         if (!dwc->setup_buf) {
2969                 ret = -ENOMEM;
2970                 goto err2;
2971         }
2972
2973         dwc->ep0_bounce = dma_alloc_coherent(dwc->dev,
2974                         DWC3_EP0_BOUNCE_SIZE, &dwc->ep0_bounce_addr,
2975                         GFP_KERNEL);
2976         if (!dwc->ep0_bounce) {
2977                 dev_err(dwc->dev, "failed to allocate ep0 bounce buffer\n");
2978                 ret = -ENOMEM;
2979                 goto err3;
2980         }
2981
2982         dwc->zlp_buf = kzalloc(DWC3_ZLP_BUF_SIZE, GFP_KERNEL);
2983         if (!dwc->zlp_buf) {
2984                 ret = -ENOMEM;
2985                 goto err4;
2986         }
2987
2988         dwc->gadget.ops                 = &dwc3_gadget_ops;
2989         dwc->gadget.speed               = USB_SPEED_UNKNOWN;
2990         dwc->gadget.sg_supported        = true;
2991         dwc->gadget.name                = "dwc3-gadget";
2992         dwc->gadget.is_otg              = dwc->dr_mode == USB_DR_MODE_OTG;
2993
2994         /*
2995          * FIXME We might be setting max_speed to <SUPER, however versions
2996          * <2.20a of dwc3 have an issue with metastability (documented
2997          * elsewhere in this driver) which tells us we can't set max speed to
2998          * anything lower than SUPER.
2999          *
3000          * Because gadget.max_speed is only used by composite.c and function
3001          * drivers (i.e. it won't go into dwc3's registers) we are allowing this
3002          * to happen so we avoid sending SuperSpeed Capability descriptor
3003          * together with our BOS descriptor as that could confuse host into
3004          * thinking we can handle super speed.
3005          *
3006          * Note that, in fact, we won't even support GetBOS requests when speed
3007          * is less than super speed because we don't have means, yet, to tell
3008          * composite.c that we are USB 2.0 + LPM ECN.
3009          */
3010         if (dwc->revision < DWC3_REVISION_220A)
3011                 dwc3_trace(trace_dwc3_gadget,
3012                                 "Changing max_speed on rev %08x",
3013                                 dwc->revision);
3014
3015         dwc->gadget.max_speed           = dwc->maximum_speed;
3016
3017         /*
3018          * Per databook, DWC3 needs buffer size to be aligned to MaxPacketSize
3019          * on ep out.
3020          */
3021         dwc->gadget.quirk_ep_out_aligned_size = true;
3022
3023         /*
3024          * REVISIT: Here we should clear all pending IRQs to be
3025          * sure we're starting from a well known location.
3026          */
3027
3028         ret = dwc3_gadget_init_endpoints(dwc);
3029         if (ret)
3030                 goto err5;
3031
3032         ret = usb_add_gadget_udc(dwc->dev, &dwc->gadget);
3033         if (ret) {
3034                 dev_err(dwc->dev, "failed to register udc\n");
3035                 goto err5;
3036         }
3037
3038         return 0;
3039
3040 err5:
3041         kfree(dwc->zlp_buf);
3042
3043 err4:
3044         dwc3_gadget_free_endpoints(dwc);
3045         dma_free_coherent(dwc->dev, DWC3_EP0_BOUNCE_SIZE,
3046                         dwc->ep0_bounce, dwc->ep0_bounce_addr);
3047
3048 err3:
3049         kfree(dwc->setup_buf);
3050
3051 err2:
3052         dma_free_coherent(dwc->dev, sizeof(*dwc->ep0_trb) * 2,
3053                         dwc->ep0_trb, dwc->ep0_trb_addr);
3054
3055 err1:
3056         dma_free_coherent(dwc->dev, sizeof(*dwc->ctrl_req),
3057                         dwc->ctrl_req, dwc->ctrl_req_addr);
3058
3059 err0:
3060         return ret;
3061 }
3062
3063 /* -------------------------------------------------------------------------- */
3064
3065 void dwc3_gadget_exit(struct dwc3 *dwc)
3066 {
3067         usb_del_gadget_udc(&dwc->gadget);
3068
3069         dwc3_gadget_free_endpoints(dwc);
3070
3071         dma_free_coherent(dwc->dev, DWC3_EP0_BOUNCE_SIZE,
3072                         dwc->ep0_bounce, dwc->ep0_bounce_addr);
3073
3074         kfree(dwc->setup_buf);
3075         kfree(dwc->zlp_buf);
3076
3077         dma_free_coherent(dwc->dev, sizeof(*dwc->ep0_trb) * 2,
3078                         dwc->ep0_trb, dwc->ep0_trb_addr);
3079
3080         dma_free_coherent(dwc->dev, sizeof(*dwc->ctrl_req),
3081                         dwc->ctrl_req, dwc->ctrl_req_addr);
3082 }
3083
3084 int dwc3_gadget_suspend(struct dwc3 *dwc)
3085 {
3086         int ret;
3087
3088         if (!dwc->gadget_driver)
3089                 return 0;
3090
3091         ret = dwc3_gadget_run_stop(dwc, false, false);
3092         if (ret < 0)
3093                 dev_err(dwc->dev, "dwc3 gadget stop timeout\n");
3094
3095         dwc3_disconnect_gadget(dwc);
3096         __dwc3_gadget_stop(dwc);
3097
3098         return 0;
3099 }
3100
3101 int dwc3_gadget_resume(struct dwc3 *dwc)
3102 {
3103         int                     ret;
3104
3105         if (!dwc->gadget_driver)
3106                 return 0;
3107
3108         ret = __dwc3_gadget_start(dwc);
3109         if (ret < 0)
3110                 goto err0;
3111
3112         ret = dwc3_gadget_run_stop(dwc, true, false);
3113         if (ret < 0)
3114                 goto err1;
3115
3116         return 0;
3117
3118 err1:
3119         __dwc3_gadget_stop(dwc);
3120
3121 err0:
3122         return ret;
3123 }
3124
3125 void dwc3_gadget_process_pending_events(struct dwc3 *dwc)
3126 {
3127         if (dwc->pending_events) {
3128                 dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf);
3129                 dwc->pending_events = false;
3130                 enable_irq(dwc->irq_gadget);
3131         }
3132 }