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