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