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