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