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