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