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