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