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