OSDN Git Service

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