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