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