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