]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/usb/dwc2/gadget.c
Merge branch 'next' of git://git.kernel.org/pub/scm/linux/kernel/git/rzhang/linux
[linux.git] / drivers / usb / dwc2 / gadget.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2011 Samsung Electronics Co., Ltd.
4  *              http://www.samsung.com
5  *
6  * Copyright 2008 Openmoko, Inc.
7  * Copyright 2008 Simtec Electronics
8  *      Ben Dooks <ben@simtec.co.uk>
9  *      http://armlinux.simtec.co.uk/
10  *
11  * S3C USB2.0 High-speed / OtG driver
12  */
13
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/spinlock.h>
17 #include <linux/interrupt.h>
18 #include <linux/platform_device.h>
19 #include <linux/dma-mapping.h>
20 #include <linux/mutex.h>
21 #include <linux/seq_file.h>
22 #include <linux/delay.h>
23 #include <linux/io.h>
24 #include <linux/slab.h>
25 #include <linux/of_platform.h>
26
27 #include <linux/usb/ch9.h>
28 #include <linux/usb/gadget.h>
29 #include <linux/usb/phy.h>
30
31 #include "core.h"
32 #include "hw.h"
33
34 /* conversion functions */
35 static inline struct dwc2_hsotg_req *our_req(struct usb_request *req)
36 {
37         return container_of(req, struct dwc2_hsotg_req, req);
38 }
39
40 static inline struct dwc2_hsotg_ep *our_ep(struct usb_ep *ep)
41 {
42         return container_of(ep, struct dwc2_hsotg_ep, ep);
43 }
44
45 static inline struct dwc2_hsotg *to_hsotg(struct usb_gadget *gadget)
46 {
47         return container_of(gadget, struct dwc2_hsotg, gadget);
48 }
49
50 static inline void dwc2_set_bit(struct dwc2_hsotg *hsotg, u32 offset, u32 val)
51 {
52         dwc2_writel(hsotg, dwc2_readl(hsotg, offset) | val, offset);
53 }
54
55 static inline void dwc2_clear_bit(struct dwc2_hsotg *hsotg, u32 offset, u32 val)
56 {
57         dwc2_writel(hsotg, dwc2_readl(hsotg, offset) & ~val, offset);
58 }
59
60 static inline struct dwc2_hsotg_ep *index_to_ep(struct dwc2_hsotg *hsotg,
61                                                 u32 ep_index, u32 dir_in)
62 {
63         if (dir_in)
64                 return hsotg->eps_in[ep_index];
65         else
66                 return hsotg->eps_out[ep_index];
67 }
68
69 /* forward declaration of functions */
70 static void dwc2_hsotg_dump(struct dwc2_hsotg *hsotg);
71
72 /**
73  * using_dma - return the DMA status of the driver.
74  * @hsotg: The driver state.
75  *
76  * Return true if we're using DMA.
77  *
78  * Currently, we have the DMA support code worked into everywhere
79  * that needs it, but the AMBA DMA implementation in the hardware can
80  * only DMA from 32bit aligned addresses. This means that gadgets such
81  * as the CDC Ethernet cannot work as they often pass packets which are
82  * not 32bit aligned.
83  *
84  * Unfortunately the choice to use DMA or not is global to the controller
85  * and seems to be only settable when the controller is being put through
86  * a core reset. This means we either need to fix the gadgets to take
87  * account of DMA alignment, or add bounce buffers (yuerk).
88  *
89  * g_using_dma is set depending on dts flag.
90  */
91 static inline bool using_dma(struct dwc2_hsotg *hsotg)
92 {
93         return hsotg->params.g_dma;
94 }
95
96 /*
97  * using_desc_dma - return the descriptor DMA status of the driver.
98  * @hsotg: The driver state.
99  *
100  * Return true if we're using descriptor DMA.
101  */
102 static inline bool using_desc_dma(struct dwc2_hsotg *hsotg)
103 {
104         return hsotg->params.g_dma_desc;
105 }
106
107 /**
108  * dwc2_gadget_incr_frame_num - Increments the targeted frame number.
109  * @hs_ep: The endpoint
110  *
111  * This function will also check if the frame number overruns DSTS_SOFFN_LIMIT.
112  * If an overrun occurs it will wrap the value and set the frame_overrun flag.
113  */
114 static inline void dwc2_gadget_incr_frame_num(struct dwc2_hsotg_ep *hs_ep)
115 {
116         hs_ep->target_frame += hs_ep->interval;
117         if (hs_ep->target_frame > DSTS_SOFFN_LIMIT) {
118                 hs_ep->frame_overrun = true;
119                 hs_ep->target_frame &= DSTS_SOFFN_LIMIT;
120         } else {
121                 hs_ep->frame_overrun = false;
122         }
123 }
124
125 /**
126  * dwc2_gadget_dec_frame_num_by_one - Decrements the targeted frame number
127  *                                    by one.
128  * @hs_ep: The endpoint.
129  *
130  * This function used in service interval based scheduling flow to calculate
131  * descriptor frame number filed value. For service interval mode frame
132  * number in descriptor should point to last (u)frame in the interval.
133  *
134  */
135 static inline void dwc2_gadget_dec_frame_num_by_one(struct dwc2_hsotg_ep *hs_ep)
136 {
137         if (hs_ep->target_frame)
138                 hs_ep->target_frame -= 1;
139         else
140                 hs_ep->target_frame = DSTS_SOFFN_LIMIT;
141 }
142
143 /**
144  * dwc2_hsotg_en_gsint - enable one or more of the general interrupt
145  * @hsotg: The device state
146  * @ints: A bitmask of the interrupts to enable
147  */
148 static void dwc2_hsotg_en_gsint(struct dwc2_hsotg *hsotg, u32 ints)
149 {
150         u32 gsintmsk = dwc2_readl(hsotg, GINTMSK);
151         u32 new_gsintmsk;
152
153         new_gsintmsk = gsintmsk | ints;
154
155         if (new_gsintmsk != gsintmsk) {
156                 dev_dbg(hsotg->dev, "gsintmsk now 0x%08x\n", new_gsintmsk);
157                 dwc2_writel(hsotg, new_gsintmsk, GINTMSK);
158         }
159 }
160
161 /**
162  * dwc2_hsotg_disable_gsint - disable one or more of the general interrupt
163  * @hsotg: The device state
164  * @ints: A bitmask of the interrupts to enable
165  */
166 static void dwc2_hsotg_disable_gsint(struct dwc2_hsotg *hsotg, u32 ints)
167 {
168         u32 gsintmsk = dwc2_readl(hsotg, GINTMSK);
169         u32 new_gsintmsk;
170
171         new_gsintmsk = gsintmsk & ~ints;
172
173         if (new_gsintmsk != gsintmsk)
174                 dwc2_writel(hsotg, new_gsintmsk, GINTMSK);
175 }
176
177 /**
178  * dwc2_hsotg_ctrl_epint - enable/disable an endpoint irq
179  * @hsotg: The device state
180  * @ep: The endpoint index
181  * @dir_in: True if direction is in.
182  * @en: The enable value, true to enable
183  *
184  * Set or clear the mask for an individual endpoint's interrupt
185  * request.
186  */
187 static void dwc2_hsotg_ctrl_epint(struct dwc2_hsotg *hsotg,
188                                   unsigned int ep, unsigned int dir_in,
189                                  unsigned int en)
190 {
191         unsigned long flags;
192         u32 bit = 1 << ep;
193         u32 daint;
194
195         if (!dir_in)
196                 bit <<= 16;
197
198         local_irq_save(flags);
199         daint = dwc2_readl(hsotg, DAINTMSK);
200         if (en)
201                 daint |= bit;
202         else
203                 daint &= ~bit;
204         dwc2_writel(hsotg, daint, DAINTMSK);
205         local_irq_restore(flags);
206 }
207
208 /**
209  * dwc2_hsotg_tx_fifo_count - return count of TX FIFOs in device mode
210  *
211  * @hsotg: Programming view of the DWC_otg controller
212  */
213 int dwc2_hsotg_tx_fifo_count(struct dwc2_hsotg *hsotg)
214 {
215         if (hsotg->hw_params.en_multiple_tx_fifo)
216                 /* In dedicated FIFO mode we need count of IN EPs */
217                 return hsotg->hw_params.num_dev_in_eps;
218         else
219                 /* In shared FIFO mode we need count of Periodic IN EPs */
220                 return hsotg->hw_params.num_dev_perio_in_ep;
221 }
222
223 /**
224  * dwc2_hsotg_tx_fifo_total_depth - return total FIFO depth available for
225  * device mode TX FIFOs
226  *
227  * @hsotg: Programming view of the DWC_otg controller
228  */
229 int dwc2_hsotg_tx_fifo_total_depth(struct dwc2_hsotg *hsotg)
230 {
231         int addr;
232         int tx_addr_max;
233         u32 np_tx_fifo_size;
234
235         np_tx_fifo_size = min_t(u32, hsotg->hw_params.dev_nperio_tx_fifo_size,
236                                 hsotg->params.g_np_tx_fifo_size);
237
238         /* Get Endpoint Info Control block size in DWORDs. */
239         tx_addr_max = hsotg->hw_params.total_fifo_size;
240
241         addr = hsotg->params.g_rx_fifo_size + np_tx_fifo_size;
242         if (tx_addr_max <= addr)
243                 return 0;
244
245         return tx_addr_max - addr;
246 }
247
248 /**
249  * dwc2_gadget_wkup_alert_handler - Handler for WKUP_ALERT interrupt
250  *
251  * @hsotg: Programming view of the DWC_otg controller
252  *
253  */
254 static void dwc2_gadget_wkup_alert_handler(struct dwc2_hsotg *hsotg)
255 {
256         u32 gintsts2;
257         u32 gintmsk2;
258
259         gintsts2 = dwc2_readl(hsotg, GINTSTS2);
260         gintmsk2 = dwc2_readl(hsotg, GINTMSK2);
261
262         if (gintsts2 & GINTSTS2_WKUP_ALERT_INT) {
263                 dev_dbg(hsotg->dev, "%s: Wkup_Alert_Int\n", __func__);
264                 dwc2_clear_bit(hsotg, GINTSTS2, GINTSTS2_WKUP_ALERT_INT);
265                 dwc2_set_bit(hsotg, DCFG, DCTL_RMTWKUPSIG);
266         }
267 }
268
269 /**
270  * dwc2_hsotg_tx_fifo_average_depth - returns average depth of device mode
271  * TX FIFOs
272  *
273  * @hsotg: Programming view of the DWC_otg controller
274  */
275 int dwc2_hsotg_tx_fifo_average_depth(struct dwc2_hsotg *hsotg)
276 {
277         int tx_fifo_count;
278         int tx_fifo_depth;
279
280         tx_fifo_depth = dwc2_hsotg_tx_fifo_total_depth(hsotg);
281
282         tx_fifo_count = dwc2_hsotg_tx_fifo_count(hsotg);
283
284         if (!tx_fifo_count)
285                 return tx_fifo_depth;
286         else
287                 return tx_fifo_depth / tx_fifo_count;
288 }
289
290 /**
291  * dwc2_hsotg_init_fifo - initialise non-periodic FIFOs
292  * @hsotg: The device instance.
293  */
294 static void dwc2_hsotg_init_fifo(struct dwc2_hsotg *hsotg)
295 {
296         unsigned int ep;
297         unsigned int addr;
298         int timeout;
299
300         u32 val;
301         u32 *txfsz = hsotg->params.g_tx_fifo_size;
302
303         /* Reset fifo map if not correctly cleared during previous session */
304         WARN_ON(hsotg->fifo_map);
305         hsotg->fifo_map = 0;
306
307         /* set RX/NPTX FIFO sizes */
308         dwc2_writel(hsotg, hsotg->params.g_rx_fifo_size, GRXFSIZ);
309         dwc2_writel(hsotg, (hsotg->params.g_rx_fifo_size <<
310                     FIFOSIZE_STARTADDR_SHIFT) |
311                     (hsotg->params.g_np_tx_fifo_size << FIFOSIZE_DEPTH_SHIFT),
312                     GNPTXFSIZ);
313
314         /*
315          * arange all the rest of the TX FIFOs, as some versions of this
316          * block have overlapping default addresses. This also ensures
317          * that if the settings have been changed, then they are set to
318          * known values.
319          */
320
321         /* start at the end of the GNPTXFSIZ, rounded up */
322         addr = hsotg->params.g_rx_fifo_size + hsotg->params.g_np_tx_fifo_size;
323
324         /*
325          * Configure fifos sizes from provided configuration and assign
326          * them to endpoints dynamically according to maxpacket size value of
327          * given endpoint.
328          */
329         for (ep = 1; ep < MAX_EPS_CHANNELS; ep++) {
330                 if (!txfsz[ep])
331                         continue;
332                 val = addr;
333                 val |= txfsz[ep] << FIFOSIZE_DEPTH_SHIFT;
334                 WARN_ONCE(addr + txfsz[ep] > hsotg->fifo_mem,
335                           "insufficient fifo memory");
336                 addr += txfsz[ep];
337
338                 dwc2_writel(hsotg, val, DPTXFSIZN(ep));
339                 val = dwc2_readl(hsotg, DPTXFSIZN(ep));
340         }
341
342         dwc2_writel(hsotg, hsotg->hw_params.total_fifo_size |
343                     addr << GDFIFOCFG_EPINFOBASE_SHIFT,
344                     GDFIFOCFG);
345         /*
346          * according to p428 of the design guide, we need to ensure that
347          * all fifos are flushed before continuing
348          */
349
350         dwc2_writel(hsotg, GRSTCTL_TXFNUM(0x10) | GRSTCTL_TXFFLSH |
351                GRSTCTL_RXFFLSH, GRSTCTL);
352
353         /* wait until the fifos are both flushed */
354         timeout = 100;
355         while (1) {
356                 val = dwc2_readl(hsotg, GRSTCTL);
357
358                 if ((val & (GRSTCTL_TXFFLSH | GRSTCTL_RXFFLSH)) == 0)
359                         break;
360
361                 if (--timeout == 0) {
362                         dev_err(hsotg->dev,
363                                 "%s: timeout flushing fifos (GRSTCTL=%08x)\n",
364                                 __func__, val);
365                         break;
366                 }
367
368                 udelay(1);
369         }
370
371         dev_dbg(hsotg->dev, "FIFOs reset, timeout at %d\n", timeout);
372 }
373
374 /**
375  * dwc2_hsotg_ep_alloc_request - allocate USB rerequest structure
376  * @ep: USB endpoint to allocate request for.
377  * @flags: Allocation flags
378  *
379  * Allocate a new USB request structure appropriate for the specified endpoint
380  */
381 static struct usb_request *dwc2_hsotg_ep_alloc_request(struct usb_ep *ep,
382                                                        gfp_t flags)
383 {
384         struct dwc2_hsotg_req *req;
385
386         req = kzalloc(sizeof(*req), flags);
387         if (!req)
388                 return NULL;
389
390         INIT_LIST_HEAD(&req->queue);
391
392         return &req->req;
393 }
394
395 /**
396  * is_ep_periodic - return true if the endpoint is in periodic mode.
397  * @hs_ep: The endpoint to query.
398  *
399  * Returns true if the endpoint is in periodic mode, meaning it is being
400  * used for an Interrupt or ISO transfer.
401  */
402 static inline int is_ep_periodic(struct dwc2_hsotg_ep *hs_ep)
403 {
404         return hs_ep->periodic;
405 }
406
407 /**
408  * dwc2_hsotg_unmap_dma - unmap the DMA memory being used for the request
409  * @hsotg: The device state.
410  * @hs_ep: The endpoint for the request
411  * @hs_req: The request being processed.
412  *
413  * This is the reverse of dwc2_hsotg_map_dma(), called for the completion
414  * of a request to ensure the buffer is ready for access by the caller.
415  */
416 static void dwc2_hsotg_unmap_dma(struct dwc2_hsotg *hsotg,
417                                  struct dwc2_hsotg_ep *hs_ep,
418                                 struct dwc2_hsotg_req *hs_req)
419 {
420         struct usb_request *req = &hs_req->req;
421
422         usb_gadget_unmap_request(&hsotg->gadget, req, hs_ep->dir_in);
423 }
424
425 /*
426  * dwc2_gadget_alloc_ctrl_desc_chains - allocate DMA descriptor chains
427  * for Control endpoint
428  * @hsotg: The device state.
429  *
430  * This function will allocate 4 descriptor chains for EP 0: 2 for
431  * Setup stage, per one for IN and OUT data/status transactions.
432  */
433 static int dwc2_gadget_alloc_ctrl_desc_chains(struct dwc2_hsotg *hsotg)
434 {
435         hsotg->setup_desc[0] =
436                 dmam_alloc_coherent(hsotg->dev,
437                                     sizeof(struct dwc2_dma_desc),
438                                     &hsotg->setup_desc_dma[0],
439                                     GFP_KERNEL);
440         if (!hsotg->setup_desc[0])
441                 goto fail;
442
443         hsotg->setup_desc[1] =
444                 dmam_alloc_coherent(hsotg->dev,
445                                     sizeof(struct dwc2_dma_desc),
446                                     &hsotg->setup_desc_dma[1],
447                                     GFP_KERNEL);
448         if (!hsotg->setup_desc[1])
449                 goto fail;
450
451         hsotg->ctrl_in_desc =
452                 dmam_alloc_coherent(hsotg->dev,
453                                     sizeof(struct dwc2_dma_desc),
454                                     &hsotg->ctrl_in_desc_dma,
455                                     GFP_KERNEL);
456         if (!hsotg->ctrl_in_desc)
457                 goto fail;
458
459         hsotg->ctrl_out_desc =
460                 dmam_alloc_coherent(hsotg->dev,
461                                     sizeof(struct dwc2_dma_desc),
462                                     &hsotg->ctrl_out_desc_dma,
463                                     GFP_KERNEL);
464         if (!hsotg->ctrl_out_desc)
465                 goto fail;
466
467         return 0;
468
469 fail:
470         return -ENOMEM;
471 }
472
473 /**
474  * dwc2_hsotg_write_fifo - write packet Data to the TxFIFO
475  * @hsotg: The controller state.
476  * @hs_ep: The endpoint we're going to write for.
477  * @hs_req: The request to write data for.
478  *
479  * This is called when the TxFIFO has some space in it to hold a new
480  * transmission and we have something to give it. The actual setup of
481  * the data size is done elsewhere, so all we have to do is to actually
482  * write the data.
483  *
484  * The return value is zero if there is more space (or nothing was done)
485  * otherwise -ENOSPC is returned if the FIFO space was used up.
486  *
487  * This routine is only needed for PIO
488  */
489 static int dwc2_hsotg_write_fifo(struct dwc2_hsotg *hsotg,
490                                  struct dwc2_hsotg_ep *hs_ep,
491                                 struct dwc2_hsotg_req *hs_req)
492 {
493         bool periodic = is_ep_periodic(hs_ep);
494         u32 gnptxsts = dwc2_readl(hsotg, GNPTXSTS);
495         int buf_pos = hs_req->req.actual;
496         int to_write = hs_ep->size_loaded;
497         void *data;
498         int can_write;
499         int pkt_round;
500         int max_transfer;
501
502         to_write -= (buf_pos - hs_ep->last_load);
503
504         /* if there's nothing to write, get out early */
505         if (to_write == 0)
506                 return 0;
507
508         if (periodic && !hsotg->dedicated_fifos) {
509                 u32 epsize = dwc2_readl(hsotg, DIEPTSIZ(hs_ep->index));
510                 int size_left;
511                 int size_done;
512
513                 /*
514                  * work out how much data was loaded so we can calculate
515                  * how much data is left in the fifo.
516                  */
517
518                 size_left = DXEPTSIZ_XFERSIZE_GET(epsize);
519
520                 /*
521                  * if shared fifo, we cannot write anything until the
522                  * previous data has been completely sent.
523                  */
524                 if (hs_ep->fifo_load != 0) {
525                         dwc2_hsotg_en_gsint(hsotg, GINTSTS_PTXFEMP);
526                         return -ENOSPC;
527                 }
528
529                 dev_dbg(hsotg->dev, "%s: left=%d, load=%d, fifo=%d, size %d\n",
530                         __func__, size_left,
531                         hs_ep->size_loaded, hs_ep->fifo_load, hs_ep->fifo_size);
532
533                 /* how much of the data has moved */
534                 size_done = hs_ep->size_loaded - size_left;
535
536                 /* how much data is left in the fifo */
537                 can_write = hs_ep->fifo_load - size_done;
538                 dev_dbg(hsotg->dev, "%s: => can_write1=%d\n",
539                         __func__, can_write);
540
541                 can_write = hs_ep->fifo_size - can_write;
542                 dev_dbg(hsotg->dev, "%s: => can_write2=%d\n",
543                         __func__, can_write);
544
545                 if (can_write <= 0) {
546                         dwc2_hsotg_en_gsint(hsotg, GINTSTS_PTXFEMP);
547                         return -ENOSPC;
548                 }
549         } else if (hsotg->dedicated_fifos && hs_ep->index != 0) {
550                 can_write = dwc2_readl(hsotg,
551                                        DTXFSTS(hs_ep->fifo_index));
552
553                 can_write &= 0xffff;
554                 can_write *= 4;
555         } else {
556                 if (GNPTXSTS_NP_TXQ_SPC_AVAIL_GET(gnptxsts) == 0) {
557                         dev_dbg(hsotg->dev,
558                                 "%s: no queue slots available (0x%08x)\n",
559                                 __func__, gnptxsts);
560
561                         dwc2_hsotg_en_gsint(hsotg, GINTSTS_NPTXFEMP);
562                         return -ENOSPC;
563                 }
564
565                 can_write = GNPTXSTS_NP_TXF_SPC_AVAIL_GET(gnptxsts);
566                 can_write *= 4; /* fifo size is in 32bit quantities. */
567         }
568
569         max_transfer = hs_ep->ep.maxpacket * hs_ep->mc;
570
571         dev_dbg(hsotg->dev, "%s: GNPTXSTS=%08x, can=%d, to=%d, max_transfer %d\n",
572                 __func__, gnptxsts, can_write, to_write, max_transfer);
573
574         /*
575          * limit to 512 bytes of data, it seems at least on the non-periodic
576          * FIFO, requests of >512 cause the endpoint to get stuck with a
577          * fragment of the end of the transfer in it.
578          */
579         if (can_write > 512 && !periodic)
580                 can_write = 512;
581
582         /*
583          * limit the write to one max-packet size worth of data, but allow
584          * the transfer to return that it did not run out of fifo space
585          * doing it.
586          */
587         if (to_write > max_transfer) {
588                 to_write = max_transfer;
589
590                 /* it's needed only when we do not use dedicated fifos */
591                 if (!hsotg->dedicated_fifos)
592                         dwc2_hsotg_en_gsint(hsotg,
593                                             periodic ? GINTSTS_PTXFEMP :
594                                            GINTSTS_NPTXFEMP);
595         }
596
597         /* see if we can write data */
598
599         if (to_write > can_write) {
600                 to_write = can_write;
601                 pkt_round = to_write % max_transfer;
602
603                 /*
604                  * Round the write down to an
605                  * exact number of packets.
606                  *
607                  * Note, we do not currently check to see if we can ever
608                  * write a full packet or not to the FIFO.
609                  */
610
611                 if (pkt_round)
612                         to_write -= pkt_round;
613
614                 /*
615                  * enable correct FIFO interrupt to alert us when there
616                  * is more room left.
617                  */
618
619                 /* it's needed only when we do not use dedicated fifos */
620                 if (!hsotg->dedicated_fifos)
621                         dwc2_hsotg_en_gsint(hsotg,
622                                             periodic ? GINTSTS_PTXFEMP :
623                                            GINTSTS_NPTXFEMP);
624         }
625
626         dev_dbg(hsotg->dev, "write %d/%d, can_write %d, done %d\n",
627                 to_write, hs_req->req.length, can_write, buf_pos);
628
629         if (to_write <= 0)
630                 return -ENOSPC;
631
632         hs_req->req.actual = buf_pos + to_write;
633         hs_ep->total_data += to_write;
634
635         if (periodic)
636                 hs_ep->fifo_load += to_write;
637
638         to_write = DIV_ROUND_UP(to_write, 4);
639         data = hs_req->req.buf + buf_pos;
640
641         dwc2_writel_rep(hsotg, EPFIFO(hs_ep->index), data, to_write);
642
643         return (to_write >= can_write) ? -ENOSPC : 0;
644 }
645
646 /**
647  * get_ep_limit - get the maximum data legnth for this endpoint
648  * @hs_ep: The endpoint
649  *
650  * Return the maximum data that can be queued in one go on a given endpoint
651  * so that transfers that are too long can be split.
652  */
653 static unsigned int get_ep_limit(struct dwc2_hsotg_ep *hs_ep)
654 {
655         int index = hs_ep->index;
656         unsigned int maxsize;
657         unsigned int maxpkt;
658
659         if (index != 0) {
660                 maxsize = DXEPTSIZ_XFERSIZE_LIMIT + 1;
661                 maxpkt = DXEPTSIZ_PKTCNT_LIMIT + 1;
662         } else {
663                 maxsize = 64 + 64;
664                 if (hs_ep->dir_in)
665                         maxpkt = DIEPTSIZ0_PKTCNT_LIMIT + 1;
666                 else
667                         maxpkt = 2;
668         }
669
670         /* we made the constant loading easier above by using +1 */
671         maxpkt--;
672         maxsize--;
673
674         /*
675          * constrain by packet count if maxpkts*pktsize is greater
676          * than the length register size.
677          */
678
679         if ((maxpkt * hs_ep->ep.maxpacket) < maxsize)
680                 maxsize = maxpkt * hs_ep->ep.maxpacket;
681
682         return maxsize;
683 }
684
685 /**
686  * dwc2_hsotg_read_frameno - read current frame number
687  * @hsotg: The device instance
688  *
689  * Return the current frame number
690  */
691 static u32 dwc2_hsotg_read_frameno(struct dwc2_hsotg *hsotg)
692 {
693         u32 dsts;
694
695         dsts = dwc2_readl(hsotg, DSTS);
696         dsts &= DSTS_SOFFN_MASK;
697         dsts >>= DSTS_SOFFN_SHIFT;
698
699         return dsts;
700 }
701
702 /**
703  * dwc2_gadget_get_chain_limit - get the maximum data payload value of the
704  * DMA descriptor chain prepared for specific endpoint
705  * @hs_ep: The endpoint
706  *
707  * Return the maximum data that can be queued in one go on a given endpoint
708  * depending on its descriptor chain capacity so that transfers that
709  * are too long can be split.
710  */
711 static unsigned int dwc2_gadget_get_chain_limit(struct dwc2_hsotg_ep *hs_ep)
712 {
713         int is_isoc = hs_ep->isochronous;
714         unsigned int maxsize;
715
716         if (is_isoc)
717                 maxsize = hs_ep->dir_in ? DEV_DMA_ISOC_TX_NBYTES_LIMIT :
718                                            DEV_DMA_ISOC_RX_NBYTES_LIMIT;
719         else
720                 maxsize = DEV_DMA_NBYTES_LIMIT;
721
722         /* Above size of one descriptor was chosen, multiple it */
723         maxsize *= MAX_DMA_DESC_NUM_GENERIC;
724
725         return maxsize;
726 }
727
728 /*
729  * dwc2_gadget_get_desc_params - get DMA descriptor parameters.
730  * @hs_ep: The endpoint
731  * @mask: RX/TX bytes mask to be defined
732  *
733  * Returns maximum data payload for one descriptor after analyzing endpoint
734  * characteristics.
735  * DMA descriptor transfer bytes limit depends on EP type:
736  * Control out - MPS,
737  * Isochronous - descriptor rx/tx bytes bitfield limit,
738  * Control In/Bulk/Interrupt - multiple of mps. This will allow to not
739  * have concatenations from various descriptors within one packet.
740  *
741  * Selects corresponding mask for RX/TX bytes as well.
742  */
743 static u32 dwc2_gadget_get_desc_params(struct dwc2_hsotg_ep *hs_ep, u32 *mask)
744 {
745         u32 mps = hs_ep->ep.maxpacket;
746         int dir_in = hs_ep->dir_in;
747         u32 desc_size = 0;
748
749         if (!hs_ep->index && !dir_in) {
750                 desc_size = mps;
751                 *mask = DEV_DMA_NBYTES_MASK;
752         } else if (hs_ep->isochronous) {
753                 if (dir_in) {
754                         desc_size = DEV_DMA_ISOC_TX_NBYTES_LIMIT;
755                         *mask = DEV_DMA_ISOC_TX_NBYTES_MASK;
756                 } else {
757                         desc_size = DEV_DMA_ISOC_RX_NBYTES_LIMIT;
758                         *mask = DEV_DMA_ISOC_RX_NBYTES_MASK;
759                 }
760         } else {
761                 desc_size = DEV_DMA_NBYTES_LIMIT;
762                 *mask = DEV_DMA_NBYTES_MASK;
763
764                 /* Round down desc_size to be mps multiple */
765                 desc_size -= desc_size % mps;
766         }
767
768         return desc_size;
769 }
770
771 /*
772  * dwc2_gadget_config_nonisoc_xfer_ddma - prepare non ISOC DMA desc chain.
773  * @hs_ep: The endpoint
774  * @dma_buff: DMA address to use
775  * @len: Length of the transfer
776  *
777  * This function will iterate over descriptor chain and fill its entries
778  * with corresponding information based on transfer data.
779  */
780 static void dwc2_gadget_config_nonisoc_xfer_ddma(struct dwc2_hsotg_ep *hs_ep,
781                                                  dma_addr_t dma_buff,
782                                                  unsigned int len)
783 {
784         struct dwc2_hsotg *hsotg = hs_ep->parent;
785         int dir_in = hs_ep->dir_in;
786         struct dwc2_dma_desc *desc = hs_ep->desc_list;
787         u32 mps = hs_ep->ep.maxpacket;
788         u32 maxsize = 0;
789         u32 offset = 0;
790         u32 mask = 0;
791         int i;
792
793         maxsize = dwc2_gadget_get_desc_params(hs_ep, &mask);
794
795         hs_ep->desc_count = (len / maxsize) +
796                                 ((len % maxsize) ? 1 : 0);
797         if (len == 0)
798                 hs_ep->desc_count = 1;
799
800         for (i = 0; i < hs_ep->desc_count; ++i) {
801                 desc->status = 0;
802                 desc->status |= (DEV_DMA_BUFF_STS_HBUSY
803                                  << DEV_DMA_BUFF_STS_SHIFT);
804
805                 if (len > maxsize) {
806                         if (!hs_ep->index && !dir_in)
807                                 desc->status |= (DEV_DMA_L | DEV_DMA_IOC);
808
809                         desc->status |= (maxsize <<
810                                                 DEV_DMA_NBYTES_SHIFT & mask);
811                         desc->buf = dma_buff + offset;
812
813                         len -= maxsize;
814                         offset += maxsize;
815                 } else {
816                         desc->status |= (DEV_DMA_L | DEV_DMA_IOC);
817
818                         if (dir_in)
819                                 desc->status |= (len % mps) ? DEV_DMA_SHORT :
820                                         ((hs_ep->send_zlp) ? DEV_DMA_SHORT : 0);
821                         if (len > maxsize)
822                                 dev_err(hsotg->dev, "wrong len %d\n", len);
823
824                         desc->status |=
825                                 len << DEV_DMA_NBYTES_SHIFT & mask;
826                         desc->buf = dma_buff + offset;
827                 }
828
829                 desc->status &= ~DEV_DMA_BUFF_STS_MASK;
830                 desc->status |= (DEV_DMA_BUFF_STS_HREADY
831                                  << DEV_DMA_BUFF_STS_SHIFT);
832                 desc++;
833         }
834 }
835
836 /*
837  * dwc2_gadget_fill_isoc_desc - fills next isochronous descriptor in chain.
838  * @hs_ep: The isochronous endpoint.
839  * @dma_buff: usb requests dma buffer.
840  * @len: usb request transfer length.
841  *
842  * Fills next free descriptor with the data of the arrived usb request,
843  * frame info, sets Last and IOC bits increments next_desc. If filled
844  * descriptor is not the first one, removes L bit from the previous descriptor
845  * status.
846  */
847 static int dwc2_gadget_fill_isoc_desc(struct dwc2_hsotg_ep *hs_ep,
848                                       dma_addr_t dma_buff, unsigned int len)
849 {
850         struct dwc2_dma_desc *desc;
851         struct dwc2_hsotg *hsotg = hs_ep->parent;
852         u32 index;
853         u32 maxsize = 0;
854         u32 mask = 0;
855         u8 pid = 0;
856
857         maxsize = dwc2_gadget_get_desc_params(hs_ep, &mask);
858
859         index = hs_ep->next_desc;
860         desc = &hs_ep->desc_list[index];
861
862         /* Check if descriptor chain full */
863         if ((desc->status >> DEV_DMA_BUFF_STS_SHIFT) ==
864             DEV_DMA_BUFF_STS_HREADY) {
865                 dev_dbg(hsotg->dev, "%s: desc chain full\n", __func__);
866                 return 1;
867         }
868
869         /* Clear L bit of previous desc if more than one entries in the chain */
870         if (hs_ep->next_desc)
871                 hs_ep->desc_list[index - 1].status &= ~DEV_DMA_L;
872
873         dev_dbg(hsotg->dev, "%s: Filling ep %d, dir %s isoc desc # %d\n",
874                 __func__, hs_ep->index, hs_ep->dir_in ? "in" : "out", index);
875
876         desc->status = 0;
877         desc->status |= (DEV_DMA_BUFF_STS_HBUSY << DEV_DMA_BUFF_STS_SHIFT);
878
879         desc->buf = dma_buff;
880         desc->status |= (DEV_DMA_L | DEV_DMA_IOC |
881                          ((len << DEV_DMA_NBYTES_SHIFT) & mask));
882
883         if (hs_ep->dir_in) {
884                 if (len)
885                         pid = DIV_ROUND_UP(len, hs_ep->ep.maxpacket);
886                 else
887                         pid = 1;
888                 desc->status |= ((pid << DEV_DMA_ISOC_PID_SHIFT) &
889                                  DEV_DMA_ISOC_PID_MASK) |
890                                 ((len % hs_ep->ep.maxpacket) ?
891                                  DEV_DMA_SHORT : 0) |
892                                 ((hs_ep->target_frame <<
893                                   DEV_DMA_ISOC_FRNUM_SHIFT) &
894                                  DEV_DMA_ISOC_FRNUM_MASK);
895         }
896
897         desc->status &= ~DEV_DMA_BUFF_STS_MASK;
898         desc->status |= (DEV_DMA_BUFF_STS_HREADY << DEV_DMA_BUFF_STS_SHIFT);
899
900         /* Increment frame number by interval for IN */
901         if (hs_ep->dir_in)
902                 dwc2_gadget_incr_frame_num(hs_ep);
903
904         /* Update index of last configured entry in the chain */
905         hs_ep->next_desc++;
906         if (hs_ep->next_desc >= MAX_DMA_DESC_NUM_GENERIC)
907                 hs_ep->next_desc = 0;
908
909         return 0;
910 }
911
912 /*
913  * dwc2_gadget_start_isoc_ddma - start isochronous transfer in DDMA
914  * @hs_ep: The isochronous endpoint.
915  *
916  * Prepare descriptor chain for isochronous endpoints. Afterwards
917  * write DMA address to HW and enable the endpoint.
918  */
919 static void dwc2_gadget_start_isoc_ddma(struct dwc2_hsotg_ep *hs_ep)
920 {
921         struct dwc2_hsotg *hsotg = hs_ep->parent;
922         struct dwc2_hsotg_req *hs_req, *treq;
923         int index = hs_ep->index;
924         int ret;
925         int i;
926         u32 dma_reg;
927         u32 depctl;
928         u32 ctrl;
929         struct dwc2_dma_desc *desc;
930
931         if (list_empty(&hs_ep->queue)) {
932                 hs_ep->target_frame = TARGET_FRAME_INITIAL;
933                 dev_dbg(hsotg->dev, "%s: No requests in queue\n", __func__);
934                 return;
935         }
936
937         /* Initialize descriptor chain by Host Busy status */
938         for (i = 0; i < MAX_DMA_DESC_NUM_GENERIC; i++) {
939                 desc = &hs_ep->desc_list[i];
940                 desc->status = 0;
941                 desc->status |= (DEV_DMA_BUFF_STS_HBUSY
942                                     << DEV_DMA_BUFF_STS_SHIFT);
943         }
944
945         hs_ep->next_desc = 0;
946         list_for_each_entry_safe(hs_req, treq, &hs_ep->queue, queue) {
947                 ret = dwc2_gadget_fill_isoc_desc(hs_ep, hs_req->req.dma,
948                                                  hs_req->req.length);
949                 if (ret)
950                         break;
951         }
952
953         hs_ep->compl_desc = 0;
954         depctl = hs_ep->dir_in ? DIEPCTL(index) : DOEPCTL(index);
955         dma_reg = hs_ep->dir_in ? DIEPDMA(index) : DOEPDMA(index);
956
957         /* write descriptor chain address to control register */
958         dwc2_writel(hsotg, hs_ep->desc_list_dma, dma_reg);
959
960         ctrl = dwc2_readl(hsotg, depctl);
961         ctrl |= DXEPCTL_EPENA | DXEPCTL_CNAK;
962         dwc2_writel(hsotg, ctrl, depctl);
963 }
964
965 /**
966  * dwc2_hsotg_start_req - start a USB request from an endpoint's queue
967  * @hsotg: The controller state.
968  * @hs_ep: The endpoint to process a request for
969  * @hs_req: The request to start.
970  * @continuing: True if we are doing more for the current request.
971  *
972  * Start the given request running by setting the endpoint registers
973  * appropriately, and writing any data to the FIFOs.
974  */
975 static void dwc2_hsotg_start_req(struct dwc2_hsotg *hsotg,
976                                  struct dwc2_hsotg_ep *hs_ep,
977                                 struct dwc2_hsotg_req *hs_req,
978                                 bool continuing)
979 {
980         struct usb_request *ureq = &hs_req->req;
981         int index = hs_ep->index;
982         int dir_in = hs_ep->dir_in;
983         u32 epctrl_reg;
984         u32 epsize_reg;
985         u32 epsize;
986         u32 ctrl;
987         unsigned int length;
988         unsigned int packets;
989         unsigned int maxreq;
990         unsigned int dma_reg;
991
992         if (index != 0) {
993                 if (hs_ep->req && !continuing) {
994                         dev_err(hsotg->dev, "%s: active request\n", __func__);
995                         WARN_ON(1);
996                         return;
997                 } else if (hs_ep->req != hs_req && continuing) {
998                         dev_err(hsotg->dev,
999                                 "%s: continue different req\n", __func__);
1000                         WARN_ON(1);
1001                         return;
1002                 }
1003         }
1004
1005         dma_reg = dir_in ? DIEPDMA(index) : DOEPDMA(index);
1006         epctrl_reg = dir_in ? DIEPCTL(index) : DOEPCTL(index);
1007         epsize_reg = dir_in ? DIEPTSIZ(index) : DOEPTSIZ(index);
1008
1009         dev_dbg(hsotg->dev, "%s: DxEPCTL=0x%08x, ep %d, dir %s\n",
1010                 __func__, dwc2_readl(hsotg, epctrl_reg), index,
1011                 hs_ep->dir_in ? "in" : "out");
1012
1013         /* If endpoint is stalled, we will restart request later */
1014         ctrl = dwc2_readl(hsotg, epctrl_reg);
1015
1016         if (index && ctrl & DXEPCTL_STALL) {
1017                 dev_warn(hsotg->dev, "%s: ep%d is stalled\n", __func__, index);
1018                 return;
1019         }
1020
1021         length = ureq->length - ureq->actual;
1022         dev_dbg(hsotg->dev, "ureq->length:%d ureq->actual:%d\n",
1023                 ureq->length, ureq->actual);
1024
1025         if (!using_desc_dma(hsotg))
1026                 maxreq = get_ep_limit(hs_ep);
1027         else
1028                 maxreq = dwc2_gadget_get_chain_limit(hs_ep);
1029
1030         if (length > maxreq) {
1031                 int round = maxreq % hs_ep->ep.maxpacket;
1032
1033                 dev_dbg(hsotg->dev, "%s: length %d, max-req %d, r %d\n",
1034                         __func__, length, maxreq, round);
1035
1036                 /* round down to multiple of packets */
1037                 if (round)
1038                         maxreq -= round;
1039
1040                 length = maxreq;
1041         }
1042
1043         if (length)
1044                 packets = DIV_ROUND_UP(length, hs_ep->ep.maxpacket);
1045         else
1046                 packets = 1;    /* send one packet if length is zero. */
1047
1048         if (hs_ep->isochronous && length > (hs_ep->mc * hs_ep->ep.maxpacket)) {
1049                 dev_err(hsotg->dev, "req length > maxpacket*mc\n");
1050                 return;
1051         }
1052
1053         if (dir_in && index != 0)
1054                 if (hs_ep->isochronous)
1055                         epsize = DXEPTSIZ_MC(packets);
1056                 else
1057                         epsize = DXEPTSIZ_MC(1);
1058         else
1059                 epsize = 0;
1060
1061         /*
1062          * zero length packet should be programmed on its own and should not
1063          * be counted in DIEPTSIZ.PktCnt with other packets.
1064          */
1065         if (dir_in && ureq->zero && !continuing) {
1066                 /* Test if zlp is actually required. */
1067                 if ((ureq->length >= hs_ep->ep.maxpacket) &&
1068                     !(ureq->length % hs_ep->ep.maxpacket))
1069                         hs_ep->send_zlp = 1;
1070         }
1071
1072         epsize |= DXEPTSIZ_PKTCNT(packets);
1073         epsize |= DXEPTSIZ_XFERSIZE(length);
1074
1075         dev_dbg(hsotg->dev, "%s: %d@%d/%d, 0x%08x => 0x%08x\n",
1076                 __func__, packets, length, ureq->length, epsize, epsize_reg);
1077
1078         /* store the request as the current one we're doing */
1079         hs_ep->req = hs_req;
1080
1081         if (using_desc_dma(hsotg)) {
1082                 u32 offset = 0;
1083                 u32 mps = hs_ep->ep.maxpacket;
1084
1085                 /* Adjust length: EP0 - MPS, other OUT EPs - multiple of MPS */
1086                 if (!dir_in) {
1087                         if (!index)
1088                                 length = mps;
1089                         else if (length % mps)
1090                                 length += (mps - (length % mps));
1091                 }
1092
1093                 /*
1094                  * If more data to send, adjust DMA for EP0 out data stage.
1095                  * ureq->dma stays unchanged, hence increment it by already
1096                  * passed passed data count before starting new transaction.
1097                  */
1098                 if (!index && hsotg->ep0_state == DWC2_EP0_DATA_OUT &&
1099                     continuing)
1100                         offset = ureq->actual;
1101
1102                 /* Fill DDMA chain entries */
1103                 dwc2_gadget_config_nonisoc_xfer_ddma(hs_ep, ureq->dma + offset,
1104                                                      length);
1105
1106                 /* write descriptor chain address to control register */
1107                 dwc2_writel(hsotg, hs_ep->desc_list_dma, dma_reg);
1108
1109                 dev_dbg(hsotg->dev, "%s: %08x pad => 0x%08x\n",
1110                         __func__, (u32)hs_ep->desc_list_dma, dma_reg);
1111         } else {
1112                 /* write size / packets */
1113                 dwc2_writel(hsotg, epsize, epsize_reg);
1114
1115                 if (using_dma(hsotg) && !continuing && (length != 0)) {
1116                         /*
1117                          * write DMA address to control register, buffer
1118                          * already synced by dwc2_hsotg_ep_queue().
1119                          */
1120
1121                         dwc2_writel(hsotg, ureq->dma, dma_reg);
1122
1123                         dev_dbg(hsotg->dev, "%s: %pad => 0x%08x\n",
1124                                 __func__, &ureq->dma, dma_reg);
1125                 }
1126         }
1127
1128         if (hs_ep->isochronous && hs_ep->interval == 1) {
1129                 hs_ep->target_frame = dwc2_hsotg_read_frameno(hsotg);
1130                 dwc2_gadget_incr_frame_num(hs_ep);
1131
1132                 if (hs_ep->target_frame & 0x1)
1133                         ctrl |= DXEPCTL_SETODDFR;
1134                 else
1135                         ctrl |= DXEPCTL_SETEVENFR;
1136         }
1137
1138         ctrl |= DXEPCTL_EPENA;  /* ensure ep enabled */
1139
1140         dev_dbg(hsotg->dev, "ep0 state:%d\n", hsotg->ep0_state);
1141
1142         /* For Setup request do not clear NAK */
1143         if (!(index == 0 && hsotg->ep0_state == DWC2_EP0_SETUP))
1144                 ctrl |= DXEPCTL_CNAK;   /* clear NAK set by core */
1145
1146         dev_dbg(hsotg->dev, "%s: DxEPCTL=0x%08x\n", __func__, ctrl);
1147         dwc2_writel(hsotg, ctrl, epctrl_reg);
1148
1149         /*
1150          * set these, it seems that DMA support increments past the end
1151          * of the packet buffer so we need to calculate the length from
1152          * this information.
1153          */
1154         hs_ep->size_loaded = length;
1155         hs_ep->last_load = ureq->actual;
1156
1157         if (dir_in && !using_dma(hsotg)) {
1158                 /* set these anyway, we may need them for non-periodic in */
1159                 hs_ep->fifo_load = 0;
1160
1161                 dwc2_hsotg_write_fifo(hsotg, hs_ep, hs_req);
1162         }
1163
1164         /*
1165          * Note, trying to clear the NAK here causes problems with transmit
1166          * on the S3C6400 ending up with the TXFIFO becoming full.
1167          */
1168
1169         /* check ep is enabled */
1170         if (!(dwc2_readl(hsotg, epctrl_reg) & DXEPCTL_EPENA))
1171                 dev_dbg(hsotg->dev,
1172                         "ep%d: failed to become enabled (DXEPCTL=0x%08x)?\n",
1173                          index, dwc2_readl(hsotg, epctrl_reg));
1174
1175         dev_dbg(hsotg->dev, "%s: DXEPCTL=0x%08x\n",
1176                 __func__, dwc2_readl(hsotg, epctrl_reg));
1177
1178         /* enable ep interrupts */
1179         dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index, hs_ep->dir_in, 1);
1180 }
1181
1182 /**
1183  * dwc2_hsotg_map_dma - map the DMA memory being used for the request
1184  * @hsotg: The device state.
1185  * @hs_ep: The endpoint the request is on.
1186  * @req: The request being processed.
1187  *
1188  * We've been asked to queue a request, so ensure that the memory buffer
1189  * is correctly setup for DMA. If we've been passed an extant DMA address
1190  * then ensure the buffer has been synced to memory. If our buffer has no
1191  * DMA memory, then we map the memory and mark our request to allow us to
1192  * cleanup on completion.
1193  */
1194 static int dwc2_hsotg_map_dma(struct dwc2_hsotg *hsotg,
1195                               struct dwc2_hsotg_ep *hs_ep,
1196                              struct usb_request *req)
1197 {
1198         int ret;
1199
1200         ret = usb_gadget_map_request(&hsotg->gadget, req, hs_ep->dir_in);
1201         if (ret)
1202                 goto dma_error;
1203
1204         return 0;
1205
1206 dma_error:
1207         dev_err(hsotg->dev, "%s: failed to map buffer %p, %d bytes\n",
1208                 __func__, req->buf, req->length);
1209
1210         return -EIO;
1211 }
1212
1213 static int dwc2_hsotg_handle_unaligned_buf_start(struct dwc2_hsotg *hsotg,
1214                                                  struct dwc2_hsotg_ep *hs_ep,
1215                                                  struct dwc2_hsotg_req *hs_req)
1216 {
1217         void *req_buf = hs_req->req.buf;
1218
1219         /* If dma is not being used or buffer is aligned */
1220         if (!using_dma(hsotg) || !((long)req_buf & 3))
1221                 return 0;
1222
1223         WARN_ON(hs_req->saved_req_buf);
1224
1225         dev_dbg(hsotg->dev, "%s: %s: buf=%p length=%d\n", __func__,
1226                 hs_ep->ep.name, req_buf, hs_req->req.length);
1227
1228         hs_req->req.buf = kmalloc(hs_req->req.length, GFP_ATOMIC);
1229         if (!hs_req->req.buf) {
1230                 hs_req->req.buf = req_buf;
1231                 dev_err(hsotg->dev,
1232                         "%s: unable to allocate memory for bounce buffer\n",
1233                         __func__);
1234                 return -ENOMEM;
1235         }
1236
1237         /* Save actual buffer */
1238         hs_req->saved_req_buf = req_buf;
1239
1240         if (hs_ep->dir_in)
1241                 memcpy(hs_req->req.buf, req_buf, hs_req->req.length);
1242         return 0;
1243 }
1244
1245 static void
1246 dwc2_hsotg_handle_unaligned_buf_complete(struct dwc2_hsotg *hsotg,
1247                                          struct dwc2_hsotg_ep *hs_ep,
1248                                          struct dwc2_hsotg_req *hs_req)
1249 {
1250         /* If dma is not being used or buffer was aligned */
1251         if (!using_dma(hsotg) || !hs_req->saved_req_buf)
1252                 return;
1253
1254         dev_dbg(hsotg->dev, "%s: %s: status=%d actual-length=%d\n", __func__,
1255                 hs_ep->ep.name, hs_req->req.status, hs_req->req.actual);
1256
1257         /* Copy data from bounce buffer on successful out transfer */
1258         if (!hs_ep->dir_in && !hs_req->req.status)
1259                 memcpy(hs_req->saved_req_buf, hs_req->req.buf,
1260                        hs_req->req.actual);
1261
1262         /* Free bounce buffer */
1263         kfree(hs_req->req.buf);
1264
1265         hs_req->req.buf = hs_req->saved_req_buf;
1266         hs_req->saved_req_buf = NULL;
1267 }
1268
1269 /**
1270  * dwc2_gadget_target_frame_elapsed - Checks target frame
1271  * @hs_ep: The driver endpoint to check
1272  *
1273  * Returns 1 if targeted frame elapsed. If returned 1 then we need to drop
1274  * corresponding transfer.
1275  */
1276 static bool dwc2_gadget_target_frame_elapsed(struct dwc2_hsotg_ep *hs_ep)
1277 {
1278         struct dwc2_hsotg *hsotg = hs_ep->parent;
1279         u32 target_frame = hs_ep->target_frame;
1280         u32 current_frame = hsotg->frame_number;
1281         bool frame_overrun = hs_ep->frame_overrun;
1282
1283         if (!frame_overrun && current_frame >= target_frame)
1284                 return true;
1285
1286         if (frame_overrun && current_frame >= target_frame &&
1287             ((current_frame - target_frame) < DSTS_SOFFN_LIMIT / 2))
1288                 return true;
1289
1290         return false;
1291 }
1292
1293 /*
1294  * dwc2_gadget_set_ep0_desc_chain - Set EP's desc chain pointers
1295  * @hsotg: The driver state
1296  * @hs_ep: the ep descriptor chain is for
1297  *
1298  * Called to update EP0 structure's pointers depend on stage of
1299  * control transfer.
1300  */
1301 static int dwc2_gadget_set_ep0_desc_chain(struct dwc2_hsotg *hsotg,
1302                                           struct dwc2_hsotg_ep *hs_ep)
1303 {
1304         switch (hsotg->ep0_state) {
1305         case DWC2_EP0_SETUP:
1306         case DWC2_EP0_STATUS_OUT:
1307                 hs_ep->desc_list = hsotg->setup_desc[0];
1308                 hs_ep->desc_list_dma = hsotg->setup_desc_dma[0];
1309                 break;
1310         case DWC2_EP0_DATA_IN:
1311         case DWC2_EP0_STATUS_IN:
1312                 hs_ep->desc_list = hsotg->ctrl_in_desc;
1313                 hs_ep->desc_list_dma = hsotg->ctrl_in_desc_dma;
1314                 break;
1315         case DWC2_EP0_DATA_OUT:
1316                 hs_ep->desc_list = hsotg->ctrl_out_desc;
1317                 hs_ep->desc_list_dma = hsotg->ctrl_out_desc_dma;
1318                 break;
1319         default:
1320                 dev_err(hsotg->dev, "invalid EP 0 state in queue %d\n",
1321                         hsotg->ep0_state);
1322                 return -EINVAL;
1323         }
1324
1325         return 0;
1326 }
1327
1328 static int dwc2_hsotg_ep_queue(struct usb_ep *ep, struct usb_request *req,
1329                                gfp_t gfp_flags)
1330 {
1331         struct dwc2_hsotg_req *hs_req = our_req(req);
1332         struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
1333         struct dwc2_hsotg *hs = hs_ep->parent;
1334         bool first;
1335         int ret;
1336         u32 maxsize = 0;
1337         u32 mask = 0;
1338
1339
1340         dev_dbg(hs->dev, "%s: req %p: %d@%p, noi=%d, zero=%d, snok=%d\n",
1341                 ep->name, req, req->length, req->buf, req->no_interrupt,
1342                 req->zero, req->short_not_ok);
1343
1344         /* Prevent new request submission when controller is suspended */
1345         if (hs->lx_state != DWC2_L0) {
1346                 dev_dbg(hs->dev, "%s: submit request only in active state\n",
1347                         __func__);
1348                 return -EAGAIN;
1349         }
1350
1351         /* initialise status of the request */
1352         INIT_LIST_HEAD(&hs_req->queue);
1353         req->actual = 0;
1354         req->status = -EINPROGRESS;
1355
1356         /* In DDMA mode for ISOC's don't queue request if length greater
1357          * than descriptor limits.
1358          */
1359         if (using_desc_dma(hs) && hs_ep->isochronous) {
1360                 maxsize = dwc2_gadget_get_desc_params(hs_ep, &mask);
1361                 if (hs_ep->dir_in && req->length > maxsize) {
1362                         dev_err(hs->dev, "wrong length %d (maxsize=%d)\n",
1363                                 req->length, maxsize);
1364                         return -EINVAL;
1365                 }
1366
1367                 if (!hs_ep->dir_in && req->length > hs_ep->ep.maxpacket) {
1368                         dev_err(hs->dev, "ISOC OUT: wrong length %d (mps=%d)\n",
1369                                 req->length, hs_ep->ep.maxpacket);
1370                         return -EINVAL;
1371                 }
1372         }
1373
1374         ret = dwc2_hsotg_handle_unaligned_buf_start(hs, hs_ep, hs_req);
1375         if (ret)
1376                 return ret;
1377
1378         /* if we're using DMA, sync the buffers as necessary */
1379         if (using_dma(hs)) {
1380                 ret = dwc2_hsotg_map_dma(hs, hs_ep, req);
1381                 if (ret)
1382                         return ret;
1383         }
1384         /* If using descriptor DMA configure EP0 descriptor chain pointers */
1385         if (using_desc_dma(hs) && !hs_ep->index) {
1386                 ret = dwc2_gadget_set_ep0_desc_chain(hs, hs_ep);
1387                 if (ret)
1388                         return ret;
1389         }
1390
1391         first = list_empty(&hs_ep->queue);
1392         list_add_tail(&hs_req->queue, &hs_ep->queue);
1393
1394         /*
1395          * Handle DDMA isochronous transfers separately - just add new entry
1396          * to the descriptor chain.
1397          * Transfer will be started once SW gets either one of NAK or
1398          * OutTknEpDis interrupts.
1399          */
1400         if (using_desc_dma(hs) && hs_ep->isochronous) {
1401                 if (hs_ep->target_frame != TARGET_FRAME_INITIAL) {
1402                         dwc2_gadget_fill_isoc_desc(hs_ep, hs_req->req.dma,
1403                                                    hs_req->req.length);
1404                 }
1405                 return 0;
1406         }
1407
1408         if (first) {
1409                 if (!hs_ep->isochronous) {
1410                         dwc2_hsotg_start_req(hs, hs_ep, hs_req, false);
1411                         return 0;
1412                 }
1413
1414                 /* Update current frame number value. */
1415                 hs->frame_number = dwc2_hsotg_read_frameno(hs);
1416                 while (dwc2_gadget_target_frame_elapsed(hs_ep)) {
1417                         dwc2_gadget_incr_frame_num(hs_ep);
1418                         /* Update current frame number value once more as it
1419                          * changes here.
1420                          */
1421                         hs->frame_number = dwc2_hsotg_read_frameno(hs);
1422                 }
1423
1424                 if (hs_ep->target_frame != TARGET_FRAME_INITIAL)
1425                         dwc2_hsotg_start_req(hs, hs_ep, hs_req, false);
1426         }
1427         return 0;
1428 }
1429
1430 static int dwc2_hsotg_ep_queue_lock(struct usb_ep *ep, struct usb_request *req,
1431                                     gfp_t gfp_flags)
1432 {
1433         struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
1434         struct dwc2_hsotg *hs = hs_ep->parent;
1435         unsigned long flags = 0;
1436         int ret = 0;
1437
1438         spin_lock_irqsave(&hs->lock, flags);
1439         ret = dwc2_hsotg_ep_queue(ep, req, gfp_flags);
1440         spin_unlock_irqrestore(&hs->lock, flags);
1441
1442         return ret;
1443 }
1444
1445 static void dwc2_hsotg_ep_free_request(struct usb_ep *ep,
1446                                        struct usb_request *req)
1447 {
1448         struct dwc2_hsotg_req *hs_req = our_req(req);
1449
1450         kfree(hs_req);
1451 }
1452
1453 /**
1454  * dwc2_hsotg_complete_oursetup - setup completion callback
1455  * @ep: The endpoint the request was on.
1456  * @req: The request completed.
1457  *
1458  * Called on completion of any requests the driver itself
1459  * submitted that need cleaning up.
1460  */
1461 static void dwc2_hsotg_complete_oursetup(struct usb_ep *ep,
1462                                          struct usb_request *req)
1463 {
1464         struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
1465         struct dwc2_hsotg *hsotg = hs_ep->parent;
1466
1467         dev_dbg(hsotg->dev, "%s: ep %p, req %p\n", __func__, ep, req);
1468
1469         dwc2_hsotg_ep_free_request(ep, req);
1470 }
1471
1472 /**
1473  * ep_from_windex - convert control wIndex value to endpoint
1474  * @hsotg: The driver state.
1475  * @windex: The control request wIndex field (in host order).
1476  *
1477  * Convert the given wIndex into a pointer to an driver endpoint
1478  * structure, or return NULL if it is not a valid endpoint.
1479  */
1480 static struct dwc2_hsotg_ep *ep_from_windex(struct dwc2_hsotg *hsotg,
1481                                             u32 windex)
1482 {
1483         struct dwc2_hsotg_ep *ep;
1484         int dir = (windex & USB_DIR_IN) ? 1 : 0;
1485         int idx = windex & 0x7F;
1486
1487         if (windex >= 0x100)
1488                 return NULL;
1489
1490         if (idx > hsotg->num_of_eps)
1491                 return NULL;
1492
1493         ep = index_to_ep(hsotg, idx, dir);
1494
1495         if (idx && ep->dir_in != dir)
1496                 return NULL;
1497
1498         return ep;
1499 }
1500
1501 /**
1502  * dwc2_hsotg_set_test_mode - Enable usb Test Modes
1503  * @hsotg: The driver state.
1504  * @testmode: requested usb test mode
1505  * Enable usb Test Mode requested by the Host.
1506  */
1507 int dwc2_hsotg_set_test_mode(struct dwc2_hsotg *hsotg, int testmode)
1508 {
1509         int dctl = dwc2_readl(hsotg, DCTL);
1510
1511         dctl &= ~DCTL_TSTCTL_MASK;
1512         switch (testmode) {
1513         case TEST_J:
1514         case TEST_K:
1515         case TEST_SE0_NAK:
1516         case TEST_PACKET:
1517         case TEST_FORCE_EN:
1518                 dctl |= testmode << DCTL_TSTCTL_SHIFT;
1519                 break;
1520         default:
1521                 return -EINVAL;
1522         }
1523         dwc2_writel(hsotg, dctl, DCTL);
1524         return 0;
1525 }
1526
1527 /**
1528  * dwc2_hsotg_send_reply - send reply to control request
1529  * @hsotg: The device state
1530  * @ep: Endpoint 0
1531  * @buff: Buffer for request
1532  * @length: Length of reply.
1533  *
1534  * Create a request and queue it on the given endpoint. This is useful as
1535  * an internal method of sending replies to certain control requests, etc.
1536  */
1537 static int dwc2_hsotg_send_reply(struct dwc2_hsotg *hsotg,
1538                                  struct dwc2_hsotg_ep *ep,
1539                                 void *buff,
1540                                 int length)
1541 {
1542         struct usb_request *req;
1543         int ret;
1544
1545         dev_dbg(hsotg->dev, "%s: buff %p, len %d\n", __func__, buff, length);
1546
1547         req = dwc2_hsotg_ep_alloc_request(&ep->ep, GFP_ATOMIC);
1548         hsotg->ep0_reply = req;
1549         if (!req) {
1550                 dev_warn(hsotg->dev, "%s: cannot alloc req\n", __func__);
1551                 return -ENOMEM;
1552         }
1553
1554         req->buf = hsotg->ep0_buff;
1555         req->length = length;
1556         /*
1557          * zero flag is for sending zlp in DATA IN stage. It has no impact on
1558          * STATUS stage.
1559          */
1560         req->zero = 0;
1561         req->complete = dwc2_hsotg_complete_oursetup;
1562
1563         if (length)
1564                 memcpy(req->buf, buff, length);
1565
1566         ret = dwc2_hsotg_ep_queue(&ep->ep, req, GFP_ATOMIC);
1567         if (ret) {
1568                 dev_warn(hsotg->dev, "%s: cannot queue req\n", __func__);
1569                 return ret;
1570         }
1571
1572         return 0;
1573 }
1574
1575 /**
1576  * dwc2_hsotg_process_req_status - process request GET_STATUS
1577  * @hsotg: The device state
1578  * @ctrl: USB control request
1579  */
1580 static int dwc2_hsotg_process_req_status(struct dwc2_hsotg *hsotg,
1581                                          struct usb_ctrlrequest *ctrl)
1582 {
1583         struct dwc2_hsotg_ep *ep0 = hsotg->eps_out[0];
1584         struct dwc2_hsotg_ep *ep;
1585         __le16 reply;
1586         int ret;
1587
1588         dev_dbg(hsotg->dev, "%s: USB_REQ_GET_STATUS\n", __func__);
1589
1590         if (!ep0->dir_in) {
1591                 dev_warn(hsotg->dev, "%s: direction out?\n", __func__);
1592                 return -EINVAL;
1593         }
1594
1595         switch (ctrl->bRequestType & USB_RECIP_MASK) {
1596         case USB_RECIP_DEVICE:
1597                 /*
1598                  * bit 0 => self powered
1599                  * bit 1 => remote wakeup
1600                  */
1601                 reply = cpu_to_le16(0);
1602                 break;
1603
1604         case USB_RECIP_INTERFACE:
1605                 /* currently, the data result should be zero */
1606                 reply = cpu_to_le16(0);
1607                 break;
1608
1609         case USB_RECIP_ENDPOINT:
1610                 ep = ep_from_windex(hsotg, le16_to_cpu(ctrl->wIndex));
1611                 if (!ep)
1612                         return -ENOENT;
1613
1614                 reply = cpu_to_le16(ep->halted ? 1 : 0);
1615                 break;
1616
1617         default:
1618                 return 0;
1619         }
1620
1621         if (le16_to_cpu(ctrl->wLength) != 2)
1622                 return -EINVAL;
1623
1624         ret = dwc2_hsotg_send_reply(hsotg, ep0, &reply, 2);
1625         if (ret) {
1626                 dev_err(hsotg->dev, "%s: failed to send reply\n", __func__);
1627                 return ret;
1628         }
1629
1630         return 1;
1631 }
1632
1633 static int dwc2_hsotg_ep_sethalt(struct usb_ep *ep, int value, bool now);
1634
1635 /**
1636  * get_ep_head - return the first request on the endpoint
1637  * @hs_ep: The controller endpoint to get
1638  *
1639  * Get the first request on the endpoint.
1640  */
1641 static struct dwc2_hsotg_req *get_ep_head(struct dwc2_hsotg_ep *hs_ep)
1642 {
1643         return list_first_entry_or_null(&hs_ep->queue, struct dwc2_hsotg_req,
1644                                         queue);
1645 }
1646
1647 /**
1648  * dwc2_gadget_start_next_request - Starts next request from ep queue
1649  * @hs_ep: Endpoint structure
1650  *
1651  * If queue is empty and EP is ISOC-OUT - unmasks OUTTKNEPDIS which is masked
1652  * in its handler. Hence we need to unmask it here to be able to do
1653  * resynchronization.
1654  */
1655 static void dwc2_gadget_start_next_request(struct dwc2_hsotg_ep *hs_ep)
1656 {
1657         u32 mask;
1658         struct dwc2_hsotg *hsotg = hs_ep->parent;
1659         int dir_in = hs_ep->dir_in;
1660         struct dwc2_hsotg_req *hs_req;
1661         u32 epmsk_reg = dir_in ? DIEPMSK : DOEPMSK;
1662
1663         if (!list_empty(&hs_ep->queue)) {
1664                 hs_req = get_ep_head(hs_ep);
1665                 dwc2_hsotg_start_req(hsotg, hs_ep, hs_req, false);
1666                 return;
1667         }
1668         if (!hs_ep->isochronous)
1669                 return;
1670
1671         if (dir_in) {
1672                 dev_dbg(hsotg->dev, "%s: No more ISOC-IN requests\n",
1673                         __func__);
1674         } else {
1675                 dev_dbg(hsotg->dev, "%s: No more ISOC-OUT requests\n",
1676                         __func__);
1677                 mask = dwc2_readl(hsotg, epmsk_reg);
1678                 mask |= DOEPMSK_OUTTKNEPDISMSK;
1679                 dwc2_writel(hsotg, mask, epmsk_reg);
1680         }
1681 }
1682
1683 /**
1684  * dwc2_hsotg_process_req_feature - process request {SET,CLEAR}_FEATURE
1685  * @hsotg: The device state
1686  * @ctrl: USB control request
1687  */
1688 static int dwc2_hsotg_process_req_feature(struct dwc2_hsotg *hsotg,
1689                                           struct usb_ctrlrequest *ctrl)
1690 {
1691         struct dwc2_hsotg_ep *ep0 = hsotg->eps_out[0];
1692         struct dwc2_hsotg_req *hs_req;
1693         bool set = (ctrl->bRequest == USB_REQ_SET_FEATURE);
1694         struct dwc2_hsotg_ep *ep;
1695         int ret;
1696         bool halted;
1697         u32 recip;
1698         u32 wValue;
1699         u32 wIndex;
1700
1701         dev_dbg(hsotg->dev, "%s: %s_FEATURE\n",
1702                 __func__, set ? "SET" : "CLEAR");
1703
1704         wValue = le16_to_cpu(ctrl->wValue);
1705         wIndex = le16_to_cpu(ctrl->wIndex);
1706         recip = ctrl->bRequestType & USB_RECIP_MASK;
1707
1708         switch (recip) {
1709         case USB_RECIP_DEVICE:
1710                 switch (wValue) {
1711                 case USB_DEVICE_REMOTE_WAKEUP:
1712                         hsotg->remote_wakeup_allowed = 1;
1713                         break;
1714
1715                 case USB_DEVICE_TEST_MODE:
1716                         if ((wIndex & 0xff) != 0)
1717                                 return -EINVAL;
1718                         if (!set)
1719                                 return -EINVAL;
1720
1721                         hsotg->test_mode = wIndex >> 8;
1722                         ret = dwc2_hsotg_send_reply(hsotg, ep0, NULL, 0);
1723                         if (ret) {
1724                                 dev_err(hsotg->dev,
1725                                         "%s: failed to send reply\n", __func__);
1726                                 return ret;
1727                         }
1728                         break;
1729                 default:
1730                         return -ENOENT;
1731                 }
1732                 break;
1733
1734         case USB_RECIP_ENDPOINT:
1735                 ep = ep_from_windex(hsotg, wIndex);
1736                 if (!ep) {
1737                         dev_dbg(hsotg->dev, "%s: no endpoint for 0x%04x\n",
1738                                 __func__, wIndex);
1739                         return -ENOENT;
1740                 }
1741
1742                 switch (wValue) {
1743                 case USB_ENDPOINT_HALT:
1744                         halted = ep->halted;
1745
1746                         dwc2_hsotg_ep_sethalt(&ep->ep, set, true);
1747
1748                         ret = dwc2_hsotg_send_reply(hsotg, ep0, NULL, 0);
1749                         if (ret) {
1750                                 dev_err(hsotg->dev,
1751                                         "%s: failed to send reply\n", __func__);
1752                                 return ret;
1753                         }
1754
1755                         /*
1756                          * we have to complete all requests for ep if it was
1757                          * halted, and the halt was cleared by CLEAR_FEATURE
1758                          */
1759
1760                         if (!set && halted) {
1761                                 /*
1762                                  * If we have request in progress,
1763                                  * then complete it
1764                                  */
1765                                 if (ep->req) {
1766                                         hs_req = ep->req;
1767                                         ep->req = NULL;
1768                                         list_del_init(&hs_req->queue);
1769                                         if (hs_req->req.complete) {
1770                                                 spin_unlock(&hsotg->lock);
1771                                                 usb_gadget_giveback_request(
1772                                                         &ep->ep, &hs_req->req);
1773                                                 spin_lock(&hsotg->lock);
1774                                         }
1775                                 }
1776
1777                                 /* If we have pending request, then start it */
1778                                 if (!ep->req)
1779                                         dwc2_gadget_start_next_request(ep);
1780                         }
1781
1782                         break;
1783
1784                 default:
1785                         return -ENOENT;
1786                 }
1787                 break;
1788         default:
1789                 return -ENOENT;
1790         }
1791         return 1;
1792 }
1793
1794 static void dwc2_hsotg_enqueue_setup(struct dwc2_hsotg *hsotg);
1795
1796 /**
1797  * dwc2_hsotg_stall_ep0 - stall ep0
1798  * @hsotg: The device state
1799  *
1800  * Set stall for ep0 as response for setup request.
1801  */
1802 static void dwc2_hsotg_stall_ep0(struct dwc2_hsotg *hsotg)
1803 {
1804         struct dwc2_hsotg_ep *ep0 = hsotg->eps_out[0];
1805         u32 reg;
1806         u32 ctrl;
1807
1808         dev_dbg(hsotg->dev, "ep0 stall (dir=%d)\n", ep0->dir_in);
1809         reg = (ep0->dir_in) ? DIEPCTL0 : DOEPCTL0;
1810
1811         /*
1812          * DxEPCTL_Stall will be cleared by EP once it has
1813          * taken effect, so no need to clear later.
1814          */
1815
1816         ctrl = dwc2_readl(hsotg, reg);
1817         ctrl |= DXEPCTL_STALL;
1818         ctrl |= DXEPCTL_CNAK;
1819         dwc2_writel(hsotg, ctrl, reg);
1820
1821         dev_dbg(hsotg->dev,
1822                 "written DXEPCTL=0x%08x to %08x (DXEPCTL=0x%08x)\n",
1823                 ctrl, reg, dwc2_readl(hsotg, reg));
1824
1825          /*
1826           * complete won't be called, so we enqueue
1827           * setup request here
1828           */
1829          dwc2_hsotg_enqueue_setup(hsotg);
1830 }
1831
1832 /**
1833  * dwc2_hsotg_process_control - process a control request
1834  * @hsotg: The device state
1835  * @ctrl: The control request received
1836  *
1837  * The controller has received the SETUP phase of a control request, and
1838  * needs to work out what to do next (and whether to pass it on to the
1839  * gadget driver).
1840  */
1841 static void dwc2_hsotg_process_control(struct dwc2_hsotg *hsotg,
1842                                        struct usb_ctrlrequest *ctrl)
1843 {
1844         struct dwc2_hsotg_ep *ep0 = hsotg->eps_out[0];
1845         int ret = 0;
1846         u32 dcfg;
1847
1848         dev_dbg(hsotg->dev,
1849                 "ctrl Type=%02x, Req=%02x, V=%04x, I=%04x, L=%04x\n",
1850                 ctrl->bRequestType, ctrl->bRequest, ctrl->wValue,
1851                 ctrl->wIndex, ctrl->wLength);
1852
1853         if (ctrl->wLength == 0) {
1854                 ep0->dir_in = 1;
1855                 hsotg->ep0_state = DWC2_EP0_STATUS_IN;
1856         } else if (ctrl->bRequestType & USB_DIR_IN) {
1857                 ep0->dir_in = 1;
1858                 hsotg->ep0_state = DWC2_EP0_DATA_IN;
1859         } else {
1860                 ep0->dir_in = 0;
1861                 hsotg->ep0_state = DWC2_EP0_DATA_OUT;
1862         }
1863
1864         if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) {
1865                 switch (ctrl->bRequest) {
1866                 case USB_REQ_SET_ADDRESS:
1867                         hsotg->connected = 1;
1868                         dcfg = dwc2_readl(hsotg, DCFG);
1869                         dcfg &= ~DCFG_DEVADDR_MASK;
1870                         dcfg |= (le16_to_cpu(ctrl->wValue) <<
1871                                  DCFG_DEVADDR_SHIFT) & DCFG_DEVADDR_MASK;
1872                         dwc2_writel(hsotg, dcfg, DCFG);
1873
1874                         dev_info(hsotg->dev, "new address %d\n", ctrl->wValue);
1875
1876                         ret = dwc2_hsotg_send_reply(hsotg, ep0, NULL, 0);
1877                         return;
1878
1879                 case USB_REQ_GET_STATUS:
1880                         ret = dwc2_hsotg_process_req_status(hsotg, ctrl);
1881                         break;
1882
1883                 case USB_REQ_CLEAR_FEATURE:
1884                 case USB_REQ_SET_FEATURE:
1885                         ret = dwc2_hsotg_process_req_feature(hsotg, ctrl);
1886                         break;
1887                 }
1888         }
1889
1890         /* as a fallback, try delivering it to the driver to deal with */
1891
1892         if (ret == 0 && hsotg->driver) {
1893                 spin_unlock(&hsotg->lock);
1894                 ret = hsotg->driver->setup(&hsotg->gadget, ctrl);
1895                 spin_lock(&hsotg->lock);
1896                 if (ret < 0)
1897                         dev_dbg(hsotg->dev, "driver->setup() ret %d\n", ret);
1898         }
1899
1900         /*
1901          * the request is either unhandlable, or is not formatted correctly
1902          * so respond with a STALL for the status stage to indicate failure.
1903          */
1904
1905         if (ret < 0)
1906                 dwc2_hsotg_stall_ep0(hsotg);
1907 }
1908
1909 /**
1910  * dwc2_hsotg_complete_setup - completion of a setup transfer
1911  * @ep: The endpoint the request was on.
1912  * @req: The request completed.
1913  *
1914  * Called on completion of any requests the driver itself submitted for
1915  * EP0 setup packets
1916  */
1917 static void dwc2_hsotg_complete_setup(struct usb_ep *ep,
1918                                       struct usb_request *req)
1919 {
1920         struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
1921         struct dwc2_hsotg *hsotg = hs_ep->parent;
1922
1923         if (req->status < 0) {
1924                 dev_dbg(hsotg->dev, "%s: failed %d\n", __func__, req->status);
1925                 return;
1926         }
1927
1928         spin_lock(&hsotg->lock);
1929         if (req->actual == 0)
1930                 dwc2_hsotg_enqueue_setup(hsotg);
1931         else
1932                 dwc2_hsotg_process_control(hsotg, req->buf);
1933         spin_unlock(&hsotg->lock);
1934 }
1935
1936 /**
1937  * dwc2_hsotg_enqueue_setup - start a request for EP0 packets
1938  * @hsotg: The device state.
1939  *
1940  * Enqueue a request on EP0 if necessary to received any SETUP packets
1941  * received from the host.
1942  */
1943 static void dwc2_hsotg_enqueue_setup(struct dwc2_hsotg *hsotg)
1944 {
1945         struct usb_request *req = hsotg->ctrl_req;
1946         struct dwc2_hsotg_req *hs_req = our_req(req);
1947         int ret;
1948
1949         dev_dbg(hsotg->dev, "%s: queueing setup request\n", __func__);
1950
1951         req->zero = 0;
1952         req->length = 8;
1953         req->buf = hsotg->ctrl_buff;
1954         req->complete = dwc2_hsotg_complete_setup;
1955
1956         if (!list_empty(&hs_req->queue)) {
1957                 dev_dbg(hsotg->dev, "%s already queued???\n", __func__);
1958                 return;
1959         }
1960
1961         hsotg->eps_out[0]->dir_in = 0;
1962         hsotg->eps_out[0]->send_zlp = 0;
1963         hsotg->ep0_state = DWC2_EP0_SETUP;
1964
1965         ret = dwc2_hsotg_ep_queue(&hsotg->eps_out[0]->ep, req, GFP_ATOMIC);
1966         if (ret < 0) {
1967                 dev_err(hsotg->dev, "%s: failed queue (%d)\n", __func__, ret);
1968                 /*
1969                  * Don't think there's much we can do other than watch the
1970                  * driver fail.
1971                  */
1972         }
1973 }
1974
1975 static void dwc2_hsotg_program_zlp(struct dwc2_hsotg *hsotg,
1976                                    struct dwc2_hsotg_ep *hs_ep)
1977 {
1978         u32 ctrl;
1979         u8 index = hs_ep->index;
1980         u32 epctl_reg = hs_ep->dir_in ? DIEPCTL(index) : DOEPCTL(index);
1981         u32 epsiz_reg = hs_ep->dir_in ? DIEPTSIZ(index) : DOEPTSIZ(index);
1982
1983         if (hs_ep->dir_in)
1984                 dev_dbg(hsotg->dev, "Sending zero-length packet on ep%d\n",
1985                         index);
1986         else
1987                 dev_dbg(hsotg->dev, "Receiving zero-length packet on ep%d\n",
1988                         index);
1989         if (using_desc_dma(hsotg)) {
1990                 /* Not specific buffer needed for ep0 ZLP */
1991                 dma_addr_t dma = hs_ep->desc_list_dma;
1992
1993                 if (!index)
1994                         dwc2_gadget_set_ep0_desc_chain(hsotg, hs_ep);
1995
1996                 dwc2_gadget_config_nonisoc_xfer_ddma(hs_ep, dma, 0);
1997         } else {
1998                 dwc2_writel(hsotg, DXEPTSIZ_MC(1) | DXEPTSIZ_PKTCNT(1) |
1999                             DXEPTSIZ_XFERSIZE(0),
2000                             epsiz_reg);
2001         }
2002
2003         ctrl = dwc2_readl(hsotg, epctl_reg);
2004         ctrl |= DXEPCTL_CNAK;  /* clear NAK set by core */
2005         ctrl |= DXEPCTL_EPENA; /* ensure ep enabled */
2006         ctrl |= DXEPCTL_USBACTEP;
2007         dwc2_writel(hsotg, ctrl, epctl_reg);
2008 }
2009
2010 /**
2011  * dwc2_hsotg_complete_request - complete a request given to us
2012  * @hsotg: The device state.
2013  * @hs_ep: The endpoint the request was on.
2014  * @hs_req: The request to complete.
2015  * @result: The result code (0 => Ok, otherwise errno)
2016  *
2017  * The given request has finished, so call the necessary completion
2018  * if it has one and then look to see if we can start a new request
2019  * on the endpoint.
2020  *
2021  * Note, expects the ep to already be locked as appropriate.
2022  */
2023 static void dwc2_hsotg_complete_request(struct dwc2_hsotg *hsotg,
2024                                         struct dwc2_hsotg_ep *hs_ep,
2025                                        struct dwc2_hsotg_req *hs_req,
2026                                        int result)
2027 {
2028         if (!hs_req) {
2029                 dev_dbg(hsotg->dev, "%s: nothing to complete?\n", __func__);
2030                 return;
2031         }
2032
2033         dev_dbg(hsotg->dev, "complete: ep %p %s, req %p, %d => %p\n",
2034                 hs_ep, hs_ep->ep.name, hs_req, result, hs_req->req.complete);
2035
2036         /*
2037          * only replace the status if we've not already set an error
2038          * from a previous transaction
2039          */
2040
2041         if (hs_req->req.status == -EINPROGRESS)
2042                 hs_req->req.status = result;
2043
2044         if (using_dma(hsotg))
2045                 dwc2_hsotg_unmap_dma(hsotg, hs_ep, hs_req);
2046
2047         dwc2_hsotg_handle_unaligned_buf_complete(hsotg, hs_ep, hs_req);
2048
2049         hs_ep->req = NULL;
2050         list_del_init(&hs_req->queue);
2051
2052         /*
2053          * call the complete request with the locks off, just in case the
2054          * request tries to queue more work for this endpoint.
2055          */
2056
2057         if (hs_req->req.complete) {
2058                 spin_unlock(&hsotg->lock);
2059                 usb_gadget_giveback_request(&hs_ep->ep, &hs_req->req);
2060                 spin_lock(&hsotg->lock);
2061         }
2062
2063         /* In DDMA don't need to proceed to starting of next ISOC request */
2064         if (using_desc_dma(hsotg) && hs_ep->isochronous)
2065                 return;
2066
2067         /*
2068          * Look to see if there is anything else to do. Note, the completion
2069          * of the previous request may have caused a new request to be started
2070          * so be careful when doing this.
2071          */
2072
2073         if (!hs_ep->req && result >= 0)
2074                 dwc2_gadget_start_next_request(hs_ep);
2075 }
2076
2077 /*
2078  * dwc2_gadget_complete_isoc_request_ddma - complete an isoc request in DDMA
2079  * @hs_ep: The endpoint the request was on.
2080  *
2081  * Get first request from the ep queue, determine descriptor on which complete
2082  * happened. SW discovers which descriptor currently in use by HW, adjusts
2083  * dma_address and calculates index of completed descriptor based on the value
2084  * of DEPDMA register. Update actual length of request, giveback to gadget.
2085  */
2086 static void dwc2_gadget_complete_isoc_request_ddma(struct dwc2_hsotg_ep *hs_ep)
2087 {
2088         struct dwc2_hsotg *hsotg = hs_ep->parent;
2089         struct dwc2_hsotg_req *hs_req;
2090         struct usb_request *ureq;
2091         u32 desc_sts;
2092         u32 mask;
2093
2094         desc_sts = hs_ep->desc_list[hs_ep->compl_desc].status;
2095
2096         /* Process only descriptors with buffer status set to DMA done */
2097         while ((desc_sts & DEV_DMA_BUFF_STS_MASK) >>
2098                 DEV_DMA_BUFF_STS_SHIFT == DEV_DMA_BUFF_STS_DMADONE) {
2099
2100                 hs_req = get_ep_head(hs_ep);
2101                 if (!hs_req) {
2102                         dev_warn(hsotg->dev, "%s: ISOC EP queue empty\n", __func__);
2103                         return;
2104                 }
2105                 ureq = &hs_req->req;
2106
2107                 /* Check completion status */
2108                 if ((desc_sts & DEV_DMA_STS_MASK) >> DEV_DMA_STS_SHIFT ==
2109                         DEV_DMA_STS_SUCC) {
2110                         mask = hs_ep->dir_in ? DEV_DMA_ISOC_TX_NBYTES_MASK :
2111                                 DEV_DMA_ISOC_RX_NBYTES_MASK;
2112                         ureq->actual = ureq->length - ((desc_sts & mask) >>
2113                                 DEV_DMA_ISOC_NBYTES_SHIFT);
2114
2115                         /* Adjust actual len for ISOC Out if len is
2116                          * not align of 4
2117                          */
2118                         if (!hs_ep->dir_in && ureq->length & 0x3)
2119                                 ureq->actual += 4 - (ureq->length & 0x3);
2120                 }
2121
2122                 dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, 0);
2123
2124                 hs_ep->compl_desc++;
2125                 if (hs_ep->compl_desc > (MAX_DMA_DESC_NUM_GENERIC - 1))
2126                         hs_ep->compl_desc = 0;
2127                 desc_sts = hs_ep->desc_list[hs_ep->compl_desc].status;
2128         }
2129 }
2130
2131 /*
2132  * dwc2_gadget_handle_isoc_bna - handle BNA interrupt for ISOC.
2133  * @hs_ep: The isochronous endpoint.
2134  *
2135  * If EP ISOC OUT then need to flush RX FIFO to remove source of BNA
2136  * interrupt. Reset target frame and next_desc to allow to start
2137  * ISOC's on NAK interrupt for IN direction or on OUTTKNEPDIS
2138  * interrupt for OUT direction.
2139  */
2140 static void dwc2_gadget_handle_isoc_bna(struct dwc2_hsotg_ep *hs_ep)
2141 {
2142         struct dwc2_hsotg *hsotg = hs_ep->parent;
2143
2144         if (!hs_ep->dir_in)
2145                 dwc2_flush_rx_fifo(hsotg);
2146         dwc2_hsotg_complete_request(hsotg, hs_ep, get_ep_head(hs_ep), 0);
2147
2148         hs_ep->target_frame = TARGET_FRAME_INITIAL;
2149         hs_ep->next_desc = 0;
2150         hs_ep->compl_desc = 0;
2151 }
2152
2153 /**
2154  * dwc2_hsotg_rx_data - receive data from the FIFO for an endpoint
2155  * @hsotg: The device state.
2156  * @ep_idx: The endpoint index for the data
2157  * @size: The size of data in the fifo, in bytes
2158  *
2159  * The FIFO status shows there is data to read from the FIFO for a given
2160  * endpoint, so sort out whether we need to read the data into a request
2161  * that has been made for that endpoint.
2162  */
2163 static void dwc2_hsotg_rx_data(struct dwc2_hsotg *hsotg, int ep_idx, int size)
2164 {
2165         struct dwc2_hsotg_ep *hs_ep = hsotg->eps_out[ep_idx];
2166         struct dwc2_hsotg_req *hs_req = hs_ep->req;
2167         int to_read;
2168         int max_req;
2169         int read_ptr;
2170
2171         if (!hs_req) {
2172                 u32 epctl = dwc2_readl(hsotg, DOEPCTL(ep_idx));
2173                 int ptr;
2174
2175                 dev_dbg(hsotg->dev,
2176                         "%s: FIFO %d bytes on ep%d but no req (DXEPCTl=0x%08x)\n",
2177                          __func__, size, ep_idx, epctl);
2178
2179                 /* dump the data from the FIFO, we've nothing we can do */
2180                 for (ptr = 0; ptr < size; ptr += 4)
2181                         (void)dwc2_readl(hsotg, EPFIFO(ep_idx));
2182
2183                 return;
2184         }
2185
2186         to_read = size;
2187         read_ptr = hs_req->req.actual;
2188         max_req = hs_req->req.length - read_ptr;
2189
2190         dev_dbg(hsotg->dev, "%s: read %d/%d, done %d/%d\n",
2191                 __func__, to_read, max_req, read_ptr, hs_req->req.length);
2192
2193         if (to_read > max_req) {
2194                 /*
2195                  * more data appeared than we where willing
2196                  * to deal with in this request.
2197                  */
2198
2199                 /* currently we don't deal this */
2200                 WARN_ON_ONCE(1);
2201         }
2202
2203         hs_ep->total_data += to_read;
2204         hs_req->req.actual += to_read;
2205         to_read = DIV_ROUND_UP(to_read, 4);
2206
2207         /*
2208          * note, we might over-write the buffer end by 3 bytes depending on
2209          * alignment of the data.
2210          */
2211         dwc2_readl_rep(hsotg, EPFIFO(ep_idx),
2212                        hs_req->req.buf + read_ptr, to_read);
2213 }
2214
2215 /**
2216  * dwc2_hsotg_ep0_zlp - send/receive zero-length packet on control endpoint
2217  * @hsotg: The device instance
2218  * @dir_in: If IN zlp
2219  *
2220  * Generate a zero-length IN packet request for terminating a SETUP
2221  * transaction.
2222  *
2223  * Note, since we don't write any data to the TxFIFO, then it is
2224  * currently believed that we do not need to wait for any space in
2225  * the TxFIFO.
2226  */
2227 static void dwc2_hsotg_ep0_zlp(struct dwc2_hsotg *hsotg, bool dir_in)
2228 {
2229         /* eps_out[0] is used in both directions */
2230         hsotg->eps_out[0]->dir_in = dir_in;
2231         hsotg->ep0_state = dir_in ? DWC2_EP0_STATUS_IN : DWC2_EP0_STATUS_OUT;
2232
2233         dwc2_hsotg_program_zlp(hsotg, hsotg->eps_out[0]);
2234 }
2235
2236 static void dwc2_hsotg_change_ep_iso_parity(struct dwc2_hsotg *hsotg,
2237                                             u32 epctl_reg)
2238 {
2239         u32 ctrl;
2240
2241         ctrl = dwc2_readl(hsotg, epctl_reg);
2242         if (ctrl & DXEPCTL_EOFRNUM)
2243                 ctrl |= DXEPCTL_SETEVENFR;
2244         else
2245                 ctrl |= DXEPCTL_SETODDFR;
2246         dwc2_writel(hsotg, ctrl, epctl_reg);
2247 }
2248
2249 /*
2250  * dwc2_gadget_get_xfersize_ddma - get transferred bytes amount from desc
2251  * @hs_ep - The endpoint on which transfer went
2252  *
2253  * Iterate over endpoints descriptor chain and get info on bytes remained
2254  * in DMA descriptors after transfer has completed. Used for non isoc EPs.
2255  */
2256 static unsigned int dwc2_gadget_get_xfersize_ddma(struct dwc2_hsotg_ep *hs_ep)
2257 {
2258         struct dwc2_hsotg *hsotg = hs_ep->parent;
2259         unsigned int bytes_rem = 0;
2260         struct dwc2_dma_desc *desc = hs_ep->desc_list;
2261         int i;
2262         u32 status;
2263
2264         if (!desc)
2265                 return -EINVAL;
2266
2267         for (i = 0; i < hs_ep->desc_count; ++i) {
2268                 status = desc->status;
2269                 bytes_rem += status & DEV_DMA_NBYTES_MASK;
2270
2271                 if (status & DEV_DMA_STS_MASK)
2272                         dev_err(hsotg->dev, "descriptor %d closed with %x\n",
2273                                 i, status & DEV_DMA_STS_MASK);
2274         }
2275
2276         return bytes_rem;
2277 }
2278
2279 /**
2280  * dwc2_hsotg_handle_outdone - handle receiving OutDone/SetupDone from RXFIFO
2281  * @hsotg: The device instance
2282  * @epnum: The endpoint received from
2283  *
2284  * The RXFIFO has delivered an OutDone event, which means that the data
2285  * transfer for an OUT endpoint has been completed, either by a short
2286  * packet or by the finish of a transfer.
2287  */
2288 static void dwc2_hsotg_handle_outdone(struct dwc2_hsotg *hsotg, int epnum)
2289 {
2290         u32 epsize = dwc2_readl(hsotg, DOEPTSIZ(epnum));
2291         struct dwc2_hsotg_ep *hs_ep = hsotg->eps_out[epnum];
2292         struct dwc2_hsotg_req *hs_req = hs_ep->req;
2293         struct usb_request *req = &hs_req->req;
2294         unsigned int size_left = DXEPTSIZ_XFERSIZE_GET(epsize);
2295         int result = 0;
2296
2297         if (!hs_req) {
2298                 dev_dbg(hsotg->dev, "%s: no request active\n", __func__);
2299                 return;
2300         }
2301
2302         if (epnum == 0 && hsotg->ep0_state == DWC2_EP0_STATUS_OUT) {
2303                 dev_dbg(hsotg->dev, "zlp packet received\n");
2304                 dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, 0);
2305                 dwc2_hsotg_enqueue_setup(hsotg);
2306                 return;
2307         }
2308
2309         if (using_desc_dma(hsotg))
2310                 size_left = dwc2_gadget_get_xfersize_ddma(hs_ep);
2311
2312         if (using_dma(hsotg)) {
2313                 unsigned int size_done;
2314
2315                 /*
2316                  * Calculate the size of the transfer by checking how much
2317                  * is left in the endpoint size register and then working it
2318                  * out from the amount we loaded for the transfer.
2319                  *
2320                  * We need to do this as DMA pointers are always 32bit aligned
2321                  * so may overshoot/undershoot the transfer.
2322                  */
2323
2324                 size_done = hs_ep->size_loaded - size_left;
2325                 size_done += hs_ep->last_load;
2326
2327                 req->actual = size_done;
2328         }
2329
2330         /* if there is more request to do, schedule new transfer */
2331         if (req->actual < req->length && size_left == 0) {
2332                 dwc2_hsotg_start_req(hsotg, hs_ep, hs_req, true);
2333                 return;
2334         }
2335
2336         if (req->actual < req->length && req->short_not_ok) {
2337                 dev_dbg(hsotg->dev, "%s: got %d/%d (short not ok) => error\n",
2338                         __func__, req->actual, req->length);
2339
2340                 /*
2341                  * todo - what should we return here? there's no one else
2342                  * even bothering to check the status.
2343                  */
2344         }
2345
2346         /* DDMA IN status phase will start from StsPhseRcvd interrupt */
2347         if (!using_desc_dma(hsotg) && epnum == 0 &&
2348             hsotg->ep0_state == DWC2_EP0_DATA_OUT) {
2349                 /* Move to STATUS IN */
2350                 dwc2_hsotg_ep0_zlp(hsotg, true);
2351                 return;
2352         }
2353
2354         /*
2355          * Slave mode OUT transfers do not go through XferComplete so
2356          * adjust the ISOC parity here.
2357          */
2358         if (!using_dma(hsotg)) {
2359                 if (hs_ep->isochronous && hs_ep->interval == 1)
2360                         dwc2_hsotg_change_ep_iso_parity(hsotg, DOEPCTL(epnum));
2361                 else if (hs_ep->isochronous && hs_ep->interval > 1)
2362                         dwc2_gadget_incr_frame_num(hs_ep);
2363         }
2364
2365         dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, result);
2366 }
2367
2368 /**
2369  * dwc2_hsotg_handle_rx - RX FIFO has data
2370  * @hsotg: The device instance
2371  *
2372  * The IRQ handler has detected that the RX FIFO has some data in it
2373  * that requires processing, so find out what is in there and do the
2374  * appropriate read.
2375  *
2376  * The RXFIFO is a true FIFO, the packets coming out are still in packet
2377  * chunks, so if you have x packets received on an endpoint you'll get x
2378  * FIFO events delivered, each with a packet's worth of data in it.
2379  *
2380  * When using DMA, we should not be processing events from the RXFIFO
2381  * as the actual data should be sent to the memory directly and we turn
2382  * on the completion interrupts to get notifications of transfer completion.
2383  */
2384 static void dwc2_hsotg_handle_rx(struct dwc2_hsotg *hsotg)
2385 {
2386         u32 grxstsr = dwc2_readl(hsotg, GRXSTSP);
2387         u32 epnum, status, size;
2388
2389         WARN_ON(using_dma(hsotg));
2390
2391         epnum = grxstsr & GRXSTS_EPNUM_MASK;
2392         status = grxstsr & GRXSTS_PKTSTS_MASK;
2393
2394         size = grxstsr & GRXSTS_BYTECNT_MASK;
2395         size >>= GRXSTS_BYTECNT_SHIFT;
2396
2397         dev_dbg(hsotg->dev, "%s: GRXSTSP=0x%08x (%d@%d)\n",
2398                 __func__, grxstsr, size, epnum);
2399
2400         switch ((status & GRXSTS_PKTSTS_MASK) >> GRXSTS_PKTSTS_SHIFT) {
2401         case GRXSTS_PKTSTS_GLOBALOUTNAK:
2402                 dev_dbg(hsotg->dev, "GLOBALOUTNAK\n");
2403                 break;
2404
2405         case GRXSTS_PKTSTS_OUTDONE:
2406                 dev_dbg(hsotg->dev, "OutDone (Frame=0x%08x)\n",
2407                         dwc2_hsotg_read_frameno(hsotg));
2408
2409                 if (!using_dma(hsotg))
2410                         dwc2_hsotg_handle_outdone(hsotg, epnum);
2411                 break;
2412
2413         case GRXSTS_PKTSTS_SETUPDONE:
2414                 dev_dbg(hsotg->dev,
2415                         "SetupDone (Frame=0x%08x, DOPEPCTL=0x%08x)\n",
2416                         dwc2_hsotg_read_frameno(hsotg),
2417                         dwc2_readl(hsotg, DOEPCTL(0)));
2418                 /*
2419                  * Call dwc2_hsotg_handle_outdone here if it was not called from
2420                  * GRXSTS_PKTSTS_OUTDONE. That is, if the core didn't
2421                  * generate GRXSTS_PKTSTS_OUTDONE for setup packet.
2422                  */
2423                 if (hsotg->ep0_state == DWC2_EP0_SETUP)
2424                         dwc2_hsotg_handle_outdone(hsotg, epnum);
2425                 break;
2426
2427         case GRXSTS_PKTSTS_OUTRX:
2428                 dwc2_hsotg_rx_data(hsotg, epnum, size);
2429                 break;
2430
2431         case GRXSTS_PKTSTS_SETUPRX:
2432                 dev_dbg(hsotg->dev,
2433                         "SetupRX (Frame=0x%08x, DOPEPCTL=0x%08x)\n",
2434                         dwc2_hsotg_read_frameno(hsotg),
2435                         dwc2_readl(hsotg, DOEPCTL(0)));
2436
2437                 WARN_ON(hsotg->ep0_state != DWC2_EP0_SETUP);
2438
2439                 dwc2_hsotg_rx_data(hsotg, epnum, size);
2440                 break;
2441
2442         default:
2443                 dev_warn(hsotg->dev, "%s: unknown status %08x\n",
2444                          __func__, grxstsr);
2445
2446                 dwc2_hsotg_dump(hsotg);
2447                 break;
2448         }
2449 }
2450
2451 /**
2452  * dwc2_hsotg_ep0_mps - turn max packet size into register setting
2453  * @mps: The maximum packet size in bytes.
2454  */
2455 static u32 dwc2_hsotg_ep0_mps(unsigned int mps)
2456 {
2457         switch (mps) {
2458         case 64:
2459                 return D0EPCTL_MPS_64;
2460         case 32:
2461                 return D0EPCTL_MPS_32;
2462         case 16:
2463                 return D0EPCTL_MPS_16;
2464         case 8:
2465                 return D0EPCTL_MPS_8;
2466         }
2467
2468         /* bad max packet size, warn and return invalid result */
2469         WARN_ON(1);
2470         return (u32)-1;
2471 }
2472
2473 /**
2474  * dwc2_hsotg_set_ep_maxpacket - set endpoint's max-packet field
2475  * @hsotg: The driver state.
2476  * @ep: The index number of the endpoint
2477  * @mps: The maximum packet size in bytes
2478  * @mc: The multicount value
2479  * @dir_in: True if direction is in.
2480  *
2481  * Configure the maximum packet size for the given endpoint, updating
2482  * the hardware control registers to reflect this.
2483  */
2484 static void dwc2_hsotg_set_ep_maxpacket(struct dwc2_hsotg *hsotg,
2485                                         unsigned int ep, unsigned int mps,
2486                                         unsigned int mc, unsigned int dir_in)
2487 {
2488         struct dwc2_hsotg_ep *hs_ep;
2489         u32 reg;
2490
2491         hs_ep = index_to_ep(hsotg, ep, dir_in);
2492         if (!hs_ep)
2493                 return;
2494
2495         if (ep == 0) {
2496                 u32 mps_bytes = mps;
2497
2498                 /* EP0 is a special case */
2499                 mps = dwc2_hsotg_ep0_mps(mps_bytes);
2500                 if (mps > 3)
2501                         goto bad_mps;
2502                 hs_ep->ep.maxpacket = mps_bytes;
2503                 hs_ep->mc = 1;
2504         } else {
2505                 if (mps > 1024)
2506                         goto bad_mps;
2507                 hs_ep->mc = mc;
2508                 if (mc > 3)
2509                         goto bad_mps;
2510                 hs_ep->ep.maxpacket = mps;
2511         }
2512
2513         if (dir_in) {
2514                 reg = dwc2_readl(hsotg, DIEPCTL(ep));
2515                 reg &= ~DXEPCTL_MPS_MASK;
2516                 reg |= mps;
2517                 dwc2_writel(hsotg, reg, DIEPCTL(ep));
2518         } else {
2519                 reg = dwc2_readl(hsotg, DOEPCTL(ep));
2520                 reg &= ~DXEPCTL_MPS_MASK;
2521                 reg |= mps;
2522                 dwc2_writel(hsotg, reg, DOEPCTL(ep));
2523         }
2524
2525         return;
2526
2527 bad_mps:
2528         dev_err(hsotg->dev, "ep%d: bad mps of %d\n", ep, mps);
2529 }
2530
2531 /**
2532  * dwc2_hsotg_txfifo_flush - flush Tx FIFO
2533  * @hsotg: The driver state
2534  * @idx: The index for the endpoint (0..15)
2535  */
2536 static void dwc2_hsotg_txfifo_flush(struct dwc2_hsotg *hsotg, unsigned int idx)
2537 {
2538         dwc2_writel(hsotg, GRSTCTL_TXFNUM(idx) | GRSTCTL_TXFFLSH,
2539                     GRSTCTL);
2540
2541         /* wait until the fifo is flushed */
2542         if (dwc2_hsotg_wait_bit_clear(hsotg, GRSTCTL, GRSTCTL_TXFFLSH, 100))
2543                 dev_warn(hsotg->dev, "%s: timeout flushing fifo GRSTCTL_TXFFLSH\n",
2544                          __func__);
2545 }
2546
2547 /**
2548  * dwc2_hsotg_trytx - check to see if anything needs transmitting
2549  * @hsotg: The driver state
2550  * @hs_ep: The driver endpoint to check.
2551  *
2552  * Check to see if there is a request that has data to send, and if so
2553  * make an attempt to write data into the FIFO.
2554  */
2555 static int dwc2_hsotg_trytx(struct dwc2_hsotg *hsotg,
2556                             struct dwc2_hsotg_ep *hs_ep)
2557 {
2558         struct dwc2_hsotg_req *hs_req = hs_ep->req;
2559
2560         if (!hs_ep->dir_in || !hs_req) {
2561                 /**
2562                  * if request is not enqueued, we disable interrupts
2563                  * for endpoints, excepting ep0
2564                  */
2565                 if (hs_ep->index != 0)
2566                         dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index,
2567                                               hs_ep->dir_in, 0);
2568                 return 0;
2569         }
2570
2571         if (hs_req->req.actual < hs_req->req.length) {
2572                 dev_dbg(hsotg->dev, "trying to write more for ep%d\n",
2573                         hs_ep->index);
2574                 return dwc2_hsotg_write_fifo(hsotg, hs_ep, hs_req);
2575         }
2576
2577         return 0;
2578 }
2579
2580 /**
2581  * dwc2_hsotg_complete_in - complete IN transfer
2582  * @hsotg: The device state.
2583  * @hs_ep: The endpoint that has just completed.
2584  *
2585  * An IN transfer has been completed, update the transfer's state and then
2586  * call the relevant completion routines.
2587  */
2588 static void dwc2_hsotg_complete_in(struct dwc2_hsotg *hsotg,
2589                                    struct dwc2_hsotg_ep *hs_ep)
2590 {
2591         struct dwc2_hsotg_req *hs_req = hs_ep->req;
2592         u32 epsize = dwc2_readl(hsotg, DIEPTSIZ(hs_ep->index));
2593         int size_left, size_done;
2594
2595         if (!hs_req) {
2596                 dev_dbg(hsotg->dev, "XferCompl but no req\n");
2597                 return;
2598         }
2599
2600         /* Finish ZLP handling for IN EP0 transactions */
2601         if (hs_ep->index == 0 && hsotg->ep0_state == DWC2_EP0_STATUS_IN) {
2602                 dev_dbg(hsotg->dev, "zlp packet sent\n");
2603
2604                 /*
2605                  * While send zlp for DWC2_EP0_STATUS_IN EP direction was
2606                  * changed to IN. Change back to complete OUT transfer request
2607                  */
2608                 hs_ep->dir_in = 0;
2609
2610                 dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, 0);
2611                 if (hsotg->test_mode) {
2612                         int ret;
2613
2614                         ret = dwc2_hsotg_set_test_mode(hsotg, hsotg->test_mode);
2615                         if (ret < 0) {
2616                                 dev_dbg(hsotg->dev, "Invalid Test #%d\n",
2617                                         hsotg->test_mode);
2618                                 dwc2_hsotg_stall_ep0(hsotg);
2619                                 return;
2620                         }
2621                 }
2622                 dwc2_hsotg_enqueue_setup(hsotg);
2623                 return;
2624         }
2625
2626         /*
2627          * Calculate the size of the transfer by checking how much is left
2628          * in the endpoint size register and then working it out from
2629          * the amount we loaded for the transfer.
2630          *
2631          * We do this even for DMA, as the transfer may have incremented
2632          * past the end of the buffer (DMA transfers are always 32bit
2633          * aligned).
2634          */
2635         if (using_desc_dma(hsotg)) {
2636                 size_left = dwc2_gadget_get_xfersize_ddma(hs_ep);
2637                 if (size_left < 0)
2638                         dev_err(hsotg->dev, "error parsing DDMA results %d\n",
2639                                 size_left);
2640         } else {
2641                 size_left = DXEPTSIZ_XFERSIZE_GET(epsize);
2642         }
2643
2644         size_done = hs_ep->size_loaded - size_left;
2645         size_done += hs_ep->last_load;
2646
2647         if (hs_req->req.actual != size_done)
2648                 dev_dbg(hsotg->dev, "%s: adjusting size done %d => %d\n",
2649                         __func__, hs_req->req.actual, size_done);
2650
2651         hs_req->req.actual = size_done;
2652         dev_dbg(hsotg->dev, "req->length:%d req->actual:%d req->zero:%d\n",
2653                 hs_req->req.length, hs_req->req.actual, hs_req->req.zero);
2654
2655         if (!size_left && hs_req->req.actual < hs_req->req.length) {
2656                 dev_dbg(hsotg->dev, "%s trying more for req...\n", __func__);
2657                 dwc2_hsotg_start_req(hsotg, hs_ep, hs_req, true);
2658                 return;
2659         }
2660
2661         /* Zlp for all endpoints, for ep0 only in DATA IN stage */
2662         if (hs_ep->send_zlp) {
2663                 dwc2_hsotg_program_zlp(hsotg, hs_ep);
2664                 hs_ep->send_zlp = 0;
2665                 /* transfer will be completed on next complete interrupt */
2666                 return;
2667         }
2668
2669         if (hs_ep->index == 0 && hsotg->ep0_state == DWC2_EP0_DATA_IN) {
2670                 /* Move to STATUS OUT */
2671                 dwc2_hsotg_ep0_zlp(hsotg, false);
2672                 return;
2673         }
2674
2675         dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req, 0);
2676 }
2677
2678 /**
2679  * dwc2_gadget_read_ep_interrupts - reads interrupts for given ep
2680  * @hsotg: The device state.
2681  * @idx: Index of ep.
2682  * @dir_in: Endpoint direction 1-in 0-out.
2683  *
2684  * Reads for endpoint with given index and direction, by masking
2685  * epint_reg with coresponding mask.
2686  */
2687 static u32 dwc2_gadget_read_ep_interrupts(struct dwc2_hsotg *hsotg,
2688                                           unsigned int idx, int dir_in)
2689 {
2690         u32 epmsk_reg = dir_in ? DIEPMSK : DOEPMSK;
2691         u32 epint_reg = dir_in ? DIEPINT(idx) : DOEPINT(idx);
2692         u32 ints;
2693         u32 mask;
2694         u32 diepempmsk;
2695
2696         mask = dwc2_readl(hsotg, epmsk_reg);
2697         diepempmsk = dwc2_readl(hsotg, DIEPEMPMSK);
2698         mask |= ((diepempmsk >> idx) & 0x1) ? DIEPMSK_TXFIFOEMPTY : 0;
2699         mask |= DXEPINT_SETUP_RCVD;
2700
2701         ints = dwc2_readl(hsotg, epint_reg);
2702         ints &= mask;
2703         return ints;
2704 }
2705
2706 /**
2707  * dwc2_gadget_handle_ep_disabled - handle DXEPINT_EPDISBLD
2708  * @hs_ep: The endpoint on which interrupt is asserted.
2709  *
2710  * This interrupt indicates that the endpoint has been disabled per the
2711  * application's request.
2712  *
2713  * For IN endpoints flushes txfifo, in case of BULK clears DCTL_CGNPINNAK,
2714  * in case of ISOC completes current request.
2715  *
2716  * For ISOC-OUT endpoints completes expired requests. If there is remaining
2717  * request starts it.
2718  */
2719 static void dwc2_gadget_handle_ep_disabled(struct dwc2_hsotg_ep *hs_ep)
2720 {
2721         struct dwc2_hsotg *hsotg = hs_ep->parent;
2722         struct dwc2_hsotg_req *hs_req;
2723         unsigned char idx = hs_ep->index;
2724         int dir_in = hs_ep->dir_in;
2725         u32 epctl_reg = dir_in ? DIEPCTL(idx) : DOEPCTL(idx);
2726         int dctl = dwc2_readl(hsotg, DCTL);
2727
2728         dev_dbg(hsotg->dev, "%s: EPDisbld\n", __func__);
2729
2730         if (dir_in) {
2731                 int epctl = dwc2_readl(hsotg, epctl_reg);
2732
2733                 dwc2_hsotg_txfifo_flush(hsotg, hs_ep->fifo_index);
2734
2735                 if (hs_ep->isochronous) {
2736                         dwc2_hsotg_complete_in(hsotg, hs_ep);
2737                         return;
2738                 }
2739
2740                 if ((epctl & DXEPCTL_STALL) && (epctl & DXEPCTL_EPTYPE_BULK)) {
2741                         int dctl = dwc2_readl(hsotg, DCTL);
2742
2743                         dctl |= DCTL_CGNPINNAK;
2744                         dwc2_writel(hsotg, dctl, DCTL);
2745                 }
2746                 return;
2747         }
2748
2749         if (dctl & DCTL_GOUTNAKSTS) {
2750                 dctl |= DCTL_CGOUTNAK;
2751                 dwc2_writel(hsotg, dctl, DCTL);
2752         }
2753
2754         if (!hs_ep->isochronous)
2755                 return;
2756
2757         if (list_empty(&hs_ep->queue)) {
2758                 dev_dbg(hsotg->dev, "%s: complete_ep 0x%p, ep->queue empty!\n",
2759                         __func__, hs_ep);
2760                 return;
2761         }
2762
2763         do {
2764                 hs_req = get_ep_head(hs_ep);
2765                 if (hs_req)
2766                         dwc2_hsotg_complete_request(hsotg, hs_ep, hs_req,
2767                                                     -ENODATA);
2768                 dwc2_gadget_incr_frame_num(hs_ep);
2769                 /* Update current frame number value. */
2770                 hsotg->frame_number = dwc2_hsotg_read_frameno(hsotg);
2771         } while (dwc2_gadget_target_frame_elapsed(hs_ep));
2772
2773         dwc2_gadget_start_next_request(hs_ep);
2774 }
2775
2776 /**
2777  * dwc2_gadget_handle_out_token_ep_disabled - handle DXEPINT_OUTTKNEPDIS
2778  * @ep: The endpoint on which interrupt is asserted.
2779  *
2780  * This is starting point for ISOC-OUT transfer, synchronization done with
2781  * first out token received from host while corresponding EP is disabled.
2782  *
2783  * Device does not know initial frame in which out token will come. For this
2784  * HW generates OUTTKNEPDIS - out token is received while EP is disabled. Upon
2785  * getting this interrupt SW starts calculation for next transfer frame.
2786  */
2787 static void dwc2_gadget_handle_out_token_ep_disabled(struct dwc2_hsotg_ep *ep)
2788 {
2789         struct dwc2_hsotg *hsotg = ep->parent;
2790         int dir_in = ep->dir_in;
2791         u32 doepmsk;
2792
2793         if (dir_in || !ep->isochronous)
2794                 return;
2795
2796         if (using_desc_dma(hsotg)) {
2797                 if (ep->target_frame == TARGET_FRAME_INITIAL) {
2798                         /* Start first ISO Out */
2799                         ep->target_frame = hsotg->frame_number;
2800                         dwc2_gadget_start_isoc_ddma(ep);
2801                 }
2802                 return;
2803         }
2804
2805         if (ep->interval > 1 &&
2806             ep->target_frame == TARGET_FRAME_INITIAL) {
2807                 u32 ctrl;
2808
2809                 ep->target_frame = hsotg->frame_number;
2810                 dwc2_gadget_incr_frame_num(ep);
2811
2812                 ctrl = dwc2_readl(hsotg, DOEPCTL(ep->index));
2813                 if (ep->target_frame & 0x1)
2814                         ctrl |= DXEPCTL_SETODDFR;
2815                 else
2816                         ctrl |= DXEPCTL_SETEVENFR;
2817
2818                 dwc2_writel(hsotg, ctrl, DOEPCTL(ep->index));
2819         }
2820
2821         dwc2_gadget_start_next_request(ep);
2822         doepmsk = dwc2_readl(hsotg, DOEPMSK);
2823         doepmsk &= ~DOEPMSK_OUTTKNEPDISMSK;
2824         dwc2_writel(hsotg, doepmsk, DOEPMSK);
2825 }
2826
2827 /**
2828  * dwc2_gadget_handle_nak - handle NAK interrupt
2829  * @hs_ep: The endpoint on which interrupt is asserted.
2830  *
2831  * This is starting point for ISOC-IN transfer, synchronization done with
2832  * first IN token received from host while corresponding EP is disabled.
2833  *
2834  * Device does not know when first one token will arrive from host. On first
2835  * token arrival HW generates 2 interrupts: 'in token received while FIFO empty'
2836  * and 'NAK'. NAK interrupt for ISOC-IN means that token has arrived and ZLP was
2837  * sent in response to that as there was no data in FIFO. SW is basing on this
2838  * interrupt to obtain frame in which token has come and then based on the
2839  * interval calculates next frame for transfer.
2840  */
2841 static void dwc2_gadget_handle_nak(struct dwc2_hsotg_ep *hs_ep)
2842 {
2843         struct dwc2_hsotg *hsotg = hs_ep->parent;
2844         int dir_in = hs_ep->dir_in;
2845
2846         if (!dir_in || !hs_ep->isochronous)
2847                 return;
2848
2849         if (hs_ep->target_frame == TARGET_FRAME_INITIAL) {
2850
2851                 if (using_desc_dma(hsotg)) {
2852                         hs_ep->target_frame = hsotg->frame_number;
2853                         dwc2_gadget_incr_frame_num(hs_ep);
2854
2855                         /* In service interval mode target_frame must
2856                          * be set to last (u)frame of the service interval.
2857                          */
2858                         if (hsotg->params.service_interval) {
2859                                 /* Set target_frame to the first (u)frame of
2860                                  * the service interval
2861                                  */
2862                                 hs_ep->target_frame &= ~hs_ep->interval + 1;
2863
2864                                 /* Set target_frame to the last (u)frame of
2865                                  * the service interval
2866                                  */
2867                                 dwc2_gadget_incr_frame_num(hs_ep);
2868                                 dwc2_gadget_dec_frame_num_by_one(hs_ep);
2869                         }
2870
2871                         dwc2_gadget_start_isoc_ddma(hs_ep);
2872                         return;
2873                 }
2874
2875                 hs_ep->target_frame = hsotg->frame_number;
2876                 if (hs_ep->interval > 1) {
2877                         u32 ctrl = dwc2_readl(hsotg,
2878                                               DIEPCTL(hs_ep->index));
2879                         if (hs_ep->target_frame & 0x1)
2880                                 ctrl |= DXEPCTL_SETODDFR;
2881                         else
2882                                 ctrl |= DXEPCTL_SETEVENFR;
2883
2884                         dwc2_writel(hsotg, ctrl, DIEPCTL(hs_ep->index));
2885                 }
2886
2887                 dwc2_hsotg_complete_request(hsotg, hs_ep,
2888                                             get_ep_head(hs_ep), 0);
2889         }
2890
2891         if (!using_desc_dma(hsotg))
2892                 dwc2_gadget_incr_frame_num(hs_ep);
2893 }
2894
2895 /**
2896  * dwc2_hsotg_epint - handle an in/out endpoint interrupt
2897  * @hsotg: The driver state
2898  * @idx: The index for the endpoint (0..15)
2899  * @dir_in: Set if this is an IN endpoint
2900  *
2901  * Process and clear any interrupt pending for an individual endpoint
2902  */
2903 static void dwc2_hsotg_epint(struct dwc2_hsotg *hsotg, unsigned int idx,
2904                              int dir_in)
2905 {
2906         struct dwc2_hsotg_ep *hs_ep = index_to_ep(hsotg, idx, dir_in);
2907         u32 epint_reg = dir_in ? DIEPINT(idx) : DOEPINT(idx);
2908         u32 epctl_reg = dir_in ? DIEPCTL(idx) : DOEPCTL(idx);
2909         u32 epsiz_reg = dir_in ? DIEPTSIZ(idx) : DOEPTSIZ(idx);
2910         u32 ints;
2911         u32 ctrl;
2912
2913         ints = dwc2_gadget_read_ep_interrupts(hsotg, idx, dir_in);
2914         ctrl = dwc2_readl(hsotg, epctl_reg);
2915
2916         /* Clear endpoint interrupts */
2917         dwc2_writel(hsotg, ints, epint_reg);
2918
2919         if (!hs_ep) {
2920                 dev_err(hsotg->dev, "%s:Interrupt for unconfigured ep%d(%s)\n",
2921                         __func__, idx, dir_in ? "in" : "out");
2922                 return;
2923         }
2924
2925         dev_dbg(hsotg->dev, "%s: ep%d(%s) DxEPINT=0x%08x\n",
2926                 __func__, idx, dir_in ? "in" : "out", ints);
2927
2928         /* Don't process XferCompl interrupt if it is a setup packet */
2929         if (idx == 0 && (ints & (DXEPINT_SETUP | DXEPINT_SETUP_RCVD)))
2930                 ints &= ~DXEPINT_XFERCOMPL;
2931
2932         /*
2933          * Don't process XferCompl interrupt in DDMA if EP0 is still in SETUP
2934          * stage and xfercomplete was generated without SETUP phase done
2935          * interrupt. SW should parse received setup packet only after host's
2936          * exit from setup phase of control transfer.
2937          */
2938         if (using_desc_dma(hsotg) && idx == 0 && !hs_ep->dir_in &&
2939             hsotg->ep0_state == DWC2_EP0_SETUP && !(ints & DXEPINT_SETUP))
2940                 ints &= ~DXEPINT_XFERCOMPL;
2941
2942         if (ints & DXEPINT_XFERCOMPL) {
2943                 dev_dbg(hsotg->dev,
2944                         "%s: XferCompl: DxEPCTL=0x%08x, DXEPTSIZ=%08x\n",
2945                         __func__, dwc2_readl(hsotg, epctl_reg),
2946                         dwc2_readl(hsotg, epsiz_reg));
2947
2948                 /* In DDMA handle isochronous requests separately */
2949                 if (using_desc_dma(hsotg) && hs_ep->isochronous) {
2950                         /* XferCompl set along with BNA */
2951                         if (!(ints & DXEPINT_BNAINTR))
2952                                 dwc2_gadget_complete_isoc_request_ddma(hs_ep);
2953                 } else if (dir_in) {
2954                         /*
2955                          * We get OutDone from the FIFO, so we only
2956                          * need to look at completing IN requests here
2957                          * if operating slave mode
2958                          */
2959                         if (hs_ep->isochronous && hs_ep->interval > 1)
2960                                 dwc2_gadget_incr_frame_num(hs_ep);
2961
2962                         dwc2_hsotg_complete_in(hsotg, hs_ep);
2963                         if (ints & DXEPINT_NAKINTRPT)
2964                                 ints &= ~DXEPINT_NAKINTRPT;
2965
2966                         if (idx == 0 && !hs_ep->req)
2967                                 dwc2_hsotg_enqueue_setup(hsotg);
2968                 } else if (using_dma(hsotg)) {
2969                         /*
2970                          * We're using DMA, we need to fire an OutDone here
2971                          * as we ignore the RXFIFO.
2972                          */
2973                         if (hs_ep->isochronous && hs_ep->interval > 1)
2974                                 dwc2_gadget_incr_frame_num(hs_ep);
2975
2976                         dwc2_hsotg_handle_outdone(hsotg, idx);
2977                 }
2978         }
2979
2980         if (ints & DXEPINT_EPDISBLD)
2981                 dwc2_gadget_handle_ep_disabled(hs_ep);
2982
2983         if (ints & DXEPINT_OUTTKNEPDIS)
2984                 dwc2_gadget_handle_out_token_ep_disabled(hs_ep);
2985
2986         if (ints & DXEPINT_NAKINTRPT)
2987                 dwc2_gadget_handle_nak(hs_ep);
2988
2989         if (ints & DXEPINT_AHBERR)
2990                 dev_dbg(hsotg->dev, "%s: AHBErr\n", __func__);
2991
2992         if (ints & DXEPINT_SETUP) {  /* Setup or Timeout */
2993                 dev_dbg(hsotg->dev, "%s: Setup/Timeout\n",  __func__);
2994
2995                 if (using_dma(hsotg) && idx == 0) {
2996                         /*
2997                          * this is the notification we've received a
2998                          * setup packet. In non-DMA mode we'd get this
2999                          * from the RXFIFO, instead we need to process
3000                          * the setup here.
3001                          */
3002
3003                         if (dir_in)
3004                                 WARN_ON_ONCE(1);
3005                         else
3006                                 dwc2_hsotg_handle_outdone(hsotg, 0);
3007                 }
3008         }
3009
3010         if (ints & DXEPINT_STSPHSERCVD) {
3011                 dev_dbg(hsotg->dev, "%s: StsPhseRcvd\n", __func__);
3012
3013                 /* Safety check EP0 state when STSPHSERCVD asserted */
3014                 if (hsotg->ep0_state == DWC2_EP0_DATA_OUT) {
3015                         /* Move to STATUS IN for DDMA */
3016                         if (using_desc_dma(hsotg))
3017                                 dwc2_hsotg_ep0_zlp(hsotg, true);
3018                 }
3019
3020         }
3021
3022         if (ints & DXEPINT_BACK2BACKSETUP)
3023                 dev_dbg(hsotg->dev, "%s: B2BSetup/INEPNakEff\n", __func__);
3024
3025         if (ints & DXEPINT_BNAINTR) {
3026                 dev_dbg(hsotg->dev, "%s: BNA interrupt\n", __func__);
3027                 if (hs_ep->isochronous)
3028                         dwc2_gadget_handle_isoc_bna(hs_ep);
3029         }
3030
3031         if (dir_in && !hs_ep->isochronous) {
3032                 /* not sure if this is important, but we'll clear it anyway */
3033                 if (ints & DXEPINT_INTKNTXFEMP) {
3034                         dev_dbg(hsotg->dev, "%s: ep%d: INTknTXFEmpMsk\n",
3035                                 __func__, idx);
3036                 }
3037
3038                 /* this probably means something bad is happening */
3039                 if (ints & DXEPINT_INTKNEPMIS) {
3040                         dev_warn(hsotg->dev, "%s: ep%d: INTknEP\n",
3041                                  __func__, idx);
3042                 }
3043
3044                 /* FIFO has space or is empty (see GAHBCFG) */
3045                 if (hsotg->dedicated_fifos &&
3046                     ints & DXEPINT_TXFEMP) {
3047                         dev_dbg(hsotg->dev, "%s: ep%d: TxFIFOEmpty\n",
3048                                 __func__, idx);
3049                         if (!using_dma(hsotg))
3050                                 dwc2_hsotg_trytx(hsotg, hs_ep);
3051                 }
3052         }
3053 }
3054
3055 /**
3056  * dwc2_hsotg_irq_enumdone - Handle EnumDone interrupt (enumeration done)
3057  * @hsotg: The device state.
3058  *
3059  * Handle updating the device settings after the enumeration phase has
3060  * been completed.
3061  */
3062 static void dwc2_hsotg_irq_enumdone(struct dwc2_hsotg *hsotg)
3063 {
3064         u32 dsts = dwc2_readl(hsotg, DSTS);
3065         int ep0_mps = 0, ep_mps = 8;
3066
3067         /*
3068          * This should signal the finish of the enumeration phase
3069          * of the USB handshaking, so we should now know what rate
3070          * we connected at.
3071          */
3072
3073         dev_dbg(hsotg->dev, "EnumDone (DSTS=0x%08x)\n", dsts);
3074
3075         /*
3076          * note, since we're limited by the size of transfer on EP0, and
3077          * it seems IN transfers must be a even number of packets we do
3078          * not advertise a 64byte MPS on EP0.
3079          */
3080
3081         /* catch both EnumSpd_FS and EnumSpd_FS48 */
3082         switch ((dsts & DSTS_ENUMSPD_MASK) >> DSTS_ENUMSPD_SHIFT) {
3083         case DSTS_ENUMSPD_FS:
3084         case DSTS_ENUMSPD_FS48:
3085                 hsotg->gadget.speed = USB_SPEED_FULL;
3086                 ep0_mps = EP0_MPS_LIMIT;
3087                 ep_mps = 1023;
3088                 break;
3089
3090         case DSTS_ENUMSPD_HS:
3091                 hsotg->gadget.speed = USB_SPEED_HIGH;
3092                 ep0_mps = EP0_MPS_LIMIT;
3093                 ep_mps = 1024;
3094                 break;
3095
3096         case DSTS_ENUMSPD_LS:
3097                 hsotg->gadget.speed = USB_SPEED_LOW;
3098                 ep0_mps = 8;
3099                 ep_mps = 8;
3100                 /*
3101                  * note, we don't actually support LS in this driver at the
3102                  * moment, and the documentation seems to imply that it isn't
3103                  * supported by the PHYs on some of the devices.
3104                  */
3105                 break;
3106         }
3107         dev_info(hsotg->dev, "new device is %s\n",
3108                  usb_speed_string(hsotg->gadget.speed));
3109
3110         /*
3111          * we should now know the maximum packet size for an
3112          * endpoint, so set the endpoints to a default value.
3113          */
3114
3115         if (ep0_mps) {
3116                 int i;
3117                 /* Initialize ep0 for both in and out directions */
3118                 dwc2_hsotg_set_ep_maxpacket(hsotg, 0, ep0_mps, 0, 1);
3119                 dwc2_hsotg_set_ep_maxpacket(hsotg, 0, ep0_mps, 0, 0);
3120                 for (i = 1; i < hsotg->num_of_eps; i++) {
3121                         if (hsotg->eps_in[i])
3122                                 dwc2_hsotg_set_ep_maxpacket(hsotg, i, ep_mps,
3123                                                             0, 1);
3124                         if (hsotg->eps_out[i])
3125                                 dwc2_hsotg_set_ep_maxpacket(hsotg, i, ep_mps,
3126                                                             0, 0);
3127                 }
3128         }
3129
3130         /* ensure after enumeration our EP0 is active */
3131
3132         dwc2_hsotg_enqueue_setup(hsotg);
3133
3134         dev_dbg(hsotg->dev, "EP0: DIEPCTL0=0x%08x, DOEPCTL0=0x%08x\n",
3135                 dwc2_readl(hsotg, DIEPCTL0),
3136                 dwc2_readl(hsotg, DOEPCTL0));
3137 }
3138
3139 /**
3140  * kill_all_requests - remove all requests from the endpoint's queue
3141  * @hsotg: The device state.
3142  * @ep: The endpoint the requests may be on.
3143  * @result: The result code to use.
3144  *
3145  * Go through the requests on the given endpoint and mark them
3146  * completed with the given result code.
3147  */
3148 static void kill_all_requests(struct dwc2_hsotg *hsotg,
3149                               struct dwc2_hsotg_ep *ep,
3150                               int result)
3151 {
3152         struct dwc2_hsotg_req *req, *treq;
3153         unsigned int size;
3154
3155         ep->req = NULL;
3156
3157         list_for_each_entry_safe(req, treq, &ep->queue, queue)
3158                 dwc2_hsotg_complete_request(hsotg, ep, req,
3159                                             result);
3160
3161         if (!hsotg->dedicated_fifos)
3162                 return;
3163         size = (dwc2_readl(hsotg, DTXFSTS(ep->fifo_index)) & 0xffff) * 4;
3164         if (size < ep->fifo_size)
3165                 dwc2_hsotg_txfifo_flush(hsotg, ep->fifo_index);
3166 }
3167
3168 static int dwc2_hsotg_ep_disable(struct usb_ep *ep);
3169
3170 /**
3171  * dwc2_hsotg_disconnect - disconnect service
3172  * @hsotg: The device state.
3173  *
3174  * The device has been disconnected. Remove all current
3175  * transactions and signal the gadget driver that this
3176  * has happened.
3177  */
3178 void dwc2_hsotg_disconnect(struct dwc2_hsotg *hsotg)
3179 {
3180         unsigned int ep;
3181
3182         if (!hsotg->connected)
3183                 return;
3184
3185         hsotg->connected = 0;
3186         hsotg->test_mode = 0;
3187
3188         /* all endpoints should be shutdown */
3189         for (ep = 0; ep < hsotg->num_of_eps; ep++) {
3190                 if (hsotg->eps_in[ep])
3191                         dwc2_hsotg_ep_disable(&hsotg->eps_in[ep]->ep);
3192                 if (hsotg->eps_out[ep])
3193                         dwc2_hsotg_ep_disable(&hsotg->eps_out[ep]->ep);
3194         }
3195
3196         call_gadget(hsotg, disconnect);
3197         hsotg->lx_state = DWC2_L3;
3198
3199         usb_gadget_set_state(&hsotg->gadget, USB_STATE_NOTATTACHED);
3200 }
3201
3202 /**
3203  * dwc2_hsotg_irq_fifoempty - TX FIFO empty interrupt handler
3204  * @hsotg: The device state:
3205  * @periodic: True if this is a periodic FIFO interrupt
3206  */
3207 static void dwc2_hsotg_irq_fifoempty(struct dwc2_hsotg *hsotg, bool periodic)
3208 {
3209         struct dwc2_hsotg_ep *ep;
3210         int epno, ret;
3211
3212         /* look through for any more data to transmit */
3213         for (epno = 0; epno < hsotg->num_of_eps; epno++) {
3214                 ep = index_to_ep(hsotg, epno, 1);
3215
3216                 if (!ep)
3217                         continue;
3218
3219                 if (!ep->dir_in)
3220                         continue;
3221
3222                 if ((periodic && !ep->periodic) ||
3223                     (!periodic && ep->periodic))
3224                         continue;
3225
3226                 ret = dwc2_hsotg_trytx(hsotg, ep);
3227                 if (ret < 0)
3228                         break;
3229         }
3230 }
3231
3232 /* IRQ flags which will trigger a retry around the IRQ loop */
3233 #define IRQ_RETRY_MASK (GINTSTS_NPTXFEMP | \
3234                         GINTSTS_PTXFEMP |  \
3235                         GINTSTS_RXFLVL)
3236
3237 /**
3238  * dwc2_hsotg_core_init - issue softreset to the core
3239  * @hsotg: The device state
3240  * @is_usb_reset: Usb resetting flag
3241  *
3242  * Issue a soft reset to the core, and await the core finishing it.
3243  */
3244 void dwc2_hsotg_core_init_disconnected(struct dwc2_hsotg *hsotg,
3245                                        bool is_usb_reset)
3246 {
3247         u32 intmsk;
3248         u32 val;
3249         u32 usbcfg;
3250         u32 dcfg = 0;
3251         int ep;
3252
3253         /* Kill any ep0 requests as controller will be reinitialized */
3254         kill_all_requests(hsotg, hsotg->eps_out[0], -ECONNRESET);
3255
3256         if (!is_usb_reset) {
3257                 if (dwc2_core_reset(hsotg, true))
3258                         return;
3259         } else {
3260                 /* all endpoints should be shutdown */
3261                 for (ep = 1; ep < hsotg->num_of_eps; ep++) {
3262                         if (hsotg->eps_in[ep])
3263                                 dwc2_hsotg_ep_disable(&hsotg->eps_in[ep]->ep);
3264                         if (hsotg->eps_out[ep])
3265                                 dwc2_hsotg_ep_disable(&hsotg->eps_out[ep]->ep);
3266                 }
3267         }
3268
3269         /*
3270          * we must now enable ep0 ready for host detection and then
3271          * set configuration.
3272          */
3273
3274         /* keep other bits untouched (so e.g. forced modes are not lost) */
3275         usbcfg = dwc2_readl(hsotg, GUSBCFG);
3276         usbcfg &= ~(GUSBCFG_TOUTCAL_MASK | GUSBCFG_PHYIF16 | GUSBCFG_SRPCAP |
3277                 GUSBCFG_HNPCAP | GUSBCFG_USBTRDTIM_MASK);
3278
3279         if (hsotg->params.phy_type == DWC2_PHY_TYPE_PARAM_FS &&
3280             (hsotg->params.speed == DWC2_SPEED_PARAM_FULL ||
3281              hsotg->params.speed == DWC2_SPEED_PARAM_LOW)) {
3282                 /* FS/LS Dedicated Transceiver Interface */
3283                 usbcfg |= GUSBCFG_PHYSEL;
3284         } else {
3285                 /* set the PLL on, remove the HNP/SRP and set the PHY */
3286                 val = (hsotg->phyif == GUSBCFG_PHYIF8) ? 9 : 5;
3287                 usbcfg |= hsotg->phyif | GUSBCFG_TOUTCAL(7) |
3288                         (val << GUSBCFG_USBTRDTIM_SHIFT);
3289         }
3290         dwc2_writel(hsotg, usbcfg, GUSBCFG);
3291
3292         dwc2_hsotg_init_fifo(hsotg);
3293
3294         if (!is_usb_reset)
3295                 dwc2_set_bit(hsotg, DCTL, DCTL_SFTDISCON);
3296
3297         dcfg |= DCFG_EPMISCNT(1);
3298
3299         switch (hsotg->params.speed) {
3300         case DWC2_SPEED_PARAM_LOW:
3301                 dcfg |= DCFG_DEVSPD_LS;
3302                 break;
3303         case DWC2_SPEED_PARAM_FULL:
3304                 if (hsotg->params.phy_type == DWC2_PHY_TYPE_PARAM_FS)
3305                         dcfg |= DCFG_DEVSPD_FS48;
3306                 else
3307                         dcfg |= DCFG_DEVSPD_FS;
3308                 break;
3309         default:
3310                 dcfg |= DCFG_DEVSPD_HS;
3311         }
3312
3313         if (hsotg->params.ipg_isoc_en)
3314                 dcfg |= DCFG_IPG_ISOC_SUPPORDED;
3315
3316         dwc2_writel(hsotg, dcfg,  DCFG);
3317
3318         /* Clear any pending OTG interrupts */
3319         dwc2_writel(hsotg, 0xffffffff, GOTGINT);
3320
3321         /* Clear any pending interrupts */
3322         dwc2_writel(hsotg, 0xffffffff, GINTSTS);
3323         intmsk = GINTSTS_ERLYSUSP | GINTSTS_SESSREQINT |
3324                 GINTSTS_GOUTNAKEFF | GINTSTS_GINNAKEFF |
3325                 GINTSTS_USBRST | GINTSTS_RESETDET |
3326                 GINTSTS_ENUMDONE | GINTSTS_OTGINT |
3327                 GINTSTS_USBSUSP | GINTSTS_WKUPINT |
3328                 GINTSTS_LPMTRANRCVD;
3329
3330         if (!using_desc_dma(hsotg))
3331                 intmsk |= GINTSTS_INCOMPL_SOIN | GINTSTS_INCOMPL_SOOUT;
3332
3333         if (!hsotg->params.external_id_pin_ctl)
3334                 intmsk |= GINTSTS_CONIDSTSCHNG;
3335
3336         dwc2_writel(hsotg, intmsk, GINTMSK);
3337
3338         if (using_dma(hsotg)) {
3339                 dwc2_writel(hsotg, GAHBCFG_GLBL_INTR_EN | GAHBCFG_DMA_EN |
3340                             hsotg->params.ahbcfg,
3341                             GAHBCFG);
3342
3343                 /* Set DDMA mode support in the core if needed */
3344                 if (using_desc_dma(hsotg))
3345                         dwc2_set_bit(hsotg, DCFG, DCFG_DESCDMA_EN);
3346
3347         } else {
3348                 dwc2_writel(hsotg, ((hsotg->dedicated_fifos) ?
3349                                                 (GAHBCFG_NP_TXF_EMP_LVL |
3350                                                  GAHBCFG_P_TXF_EMP_LVL) : 0) |
3351                             GAHBCFG_GLBL_INTR_EN, GAHBCFG);
3352         }
3353
3354         /*
3355          * If INTknTXFEmpMsk is enabled, it's important to disable ep interrupts
3356          * when we have no data to transfer. Otherwise we get being flooded by
3357          * interrupts.
3358          */
3359
3360         dwc2_writel(hsotg, ((hsotg->dedicated_fifos && !using_dma(hsotg)) ?
3361                 DIEPMSK_TXFIFOEMPTY | DIEPMSK_INTKNTXFEMPMSK : 0) |
3362                 DIEPMSK_EPDISBLDMSK | DIEPMSK_XFERCOMPLMSK |
3363                 DIEPMSK_TIMEOUTMSK | DIEPMSK_AHBERRMSK,
3364                 DIEPMSK);
3365
3366         /*
3367          * don't need XferCompl, we get that from RXFIFO in slave mode. In
3368          * DMA mode we may need this and StsPhseRcvd.
3369          */
3370         dwc2_writel(hsotg, (using_dma(hsotg) ? (DIEPMSK_XFERCOMPLMSK |
3371                 DOEPMSK_STSPHSERCVDMSK) : 0) |
3372                 DOEPMSK_EPDISBLDMSK | DOEPMSK_AHBERRMSK |
3373                 DOEPMSK_SETUPMSK,
3374                 DOEPMSK);
3375
3376         /* Enable BNA interrupt for DDMA */
3377         if (using_desc_dma(hsotg)) {
3378                 dwc2_set_bit(hsotg, DOEPMSK, DOEPMSK_BNAMSK);
3379                 dwc2_set_bit(hsotg, DIEPMSK, DIEPMSK_BNAININTRMSK);
3380         }
3381
3382         /* Enable Service Interval mode if supported */
3383         if (using_desc_dma(hsotg) && hsotg->params.service_interval)
3384                 dwc2_set_bit(hsotg, DCTL, DCTL_SERVICE_INTERVAL_SUPPORTED);
3385
3386         dwc2_writel(hsotg, 0, DAINTMSK);
3387
3388         dev_dbg(hsotg->dev, "EP0: DIEPCTL0=0x%08x, DOEPCTL0=0x%08x\n",
3389                 dwc2_readl(hsotg, DIEPCTL0),
3390                 dwc2_readl(hsotg, DOEPCTL0));
3391
3392         /* enable in and out endpoint interrupts */
3393         dwc2_hsotg_en_gsint(hsotg, GINTSTS_OEPINT | GINTSTS_IEPINT);
3394
3395         /*
3396          * Enable the RXFIFO when in slave mode, as this is how we collect
3397          * the data. In DMA mode, we get events from the FIFO but also
3398          * things we cannot process, so do not use it.
3399          */
3400         if (!using_dma(hsotg))
3401                 dwc2_hsotg_en_gsint(hsotg, GINTSTS_RXFLVL);
3402
3403         /* Enable interrupts for EP0 in and out */
3404         dwc2_hsotg_ctrl_epint(hsotg, 0, 0, 1);
3405         dwc2_hsotg_ctrl_epint(hsotg, 0, 1, 1);
3406
3407         if (!is_usb_reset) {
3408                 dwc2_set_bit(hsotg, DCTL, DCTL_PWRONPRGDONE);
3409                 udelay(10);  /* see openiboot */
3410                 dwc2_clear_bit(hsotg, DCTL, DCTL_PWRONPRGDONE);
3411         }
3412
3413         dev_dbg(hsotg->dev, "DCTL=0x%08x\n", dwc2_readl(hsotg, DCTL));
3414
3415         /*
3416          * DxEPCTL_USBActEp says RO in manual, but seems to be set by
3417          * writing to the EPCTL register..
3418          */
3419
3420         /* set to read 1 8byte packet */
3421         dwc2_writel(hsotg, DXEPTSIZ_MC(1) | DXEPTSIZ_PKTCNT(1) |
3422                DXEPTSIZ_XFERSIZE(8), DOEPTSIZ0);
3423
3424         dwc2_writel(hsotg, dwc2_hsotg_ep0_mps(hsotg->eps_out[0]->ep.maxpacket) |
3425                DXEPCTL_CNAK | DXEPCTL_EPENA |
3426                DXEPCTL_USBACTEP,
3427                DOEPCTL0);
3428
3429         /* enable, but don't activate EP0in */
3430         dwc2_writel(hsotg, dwc2_hsotg_ep0_mps(hsotg->eps_out[0]->ep.maxpacket) |
3431                DXEPCTL_USBACTEP, DIEPCTL0);
3432
3433         /* clear global NAKs */
3434         val = DCTL_CGOUTNAK | DCTL_CGNPINNAK;
3435         if (!is_usb_reset)
3436                 val |= DCTL_SFTDISCON;
3437         dwc2_set_bit(hsotg, DCTL, val);
3438
3439         /* configure the core to support LPM */
3440         dwc2_gadget_init_lpm(hsotg);
3441
3442         /* program GREFCLK register if needed */
3443         if (using_desc_dma(hsotg) && hsotg->params.service_interval)
3444                 dwc2_gadget_program_ref_clk(hsotg);
3445
3446         /* must be at-least 3ms to allow bus to see disconnect */
3447         mdelay(3);
3448
3449         hsotg->lx_state = DWC2_L0;
3450
3451         dwc2_hsotg_enqueue_setup(hsotg);
3452
3453         dev_dbg(hsotg->dev, "EP0: DIEPCTL0=0x%08x, DOEPCTL0=0x%08x\n",
3454                 dwc2_readl(hsotg, DIEPCTL0),
3455                 dwc2_readl(hsotg, DOEPCTL0));
3456 }
3457
3458 static void dwc2_hsotg_core_disconnect(struct dwc2_hsotg *hsotg)
3459 {
3460         /* set the soft-disconnect bit */
3461         dwc2_set_bit(hsotg, DCTL, DCTL_SFTDISCON);
3462 }
3463
3464 void dwc2_hsotg_core_connect(struct dwc2_hsotg *hsotg)
3465 {
3466         /* remove the soft-disconnect and let's go */
3467         dwc2_clear_bit(hsotg, DCTL, DCTL_SFTDISCON);
3468 }
3469
3470 /**
3471  * dwc2_gadget_handle_incomplete_isoc_in - handle incomplete ISO IN Interrupt.
3472  * @hsotg: The device state:
3473  *
3474  * This interrupt indicates one of the following conditions occurred while
3475  * transmitting an ISOC transaction.
3476  * - Corrupted IN Token for ISOC EP.
3477  * - Packet not complete in FIFO.
3478  *
3479  * The following actions will be taken:
3480  * - Determine the EP
3481  * - Disable EP; when 'Endpoint Disabled' interrupt is received Flush FIFO
3482  */
3483 static void dwc2_gadget_handle_incomplete_isoc_in(struct dwc2_hsotg *hsotg)
3484 {
3485         struct dwc2_hsotg_ep *hs_ep;
3486         u32 epctrl;
3487         u32 daintmsk;
3488         u32 idx;
3489
3490         dev_dbg(hsotg->dev, "Incomplete isoc in interrupt received:\n");
3491
3492         daintmsk = dwc2_readl(hsotg, DAINTMSK);
3493
3494         for (idx = 1; idx < hsotg->num_of_eps; idx++) {
3495                 hs_ep = hsotg->eps_in[idx];
3496                 /* Proceed only unmasked ISOC EPs */
3497                 if ((BIT(idx) & ~daintmsk) || !hs_ep->isochronous)
3498                         continue;
3499
3500                 epctrl = dwc2_readl(hsotg, DIEPCTL(idx));
3501                 if ((epctrl & DXEPCTL_EPENA) &&
3502                     dwc2_gadget_target_frame_elapsed(hs_ep)) {
3503                         epctrl |= DXEPCTL_SNAK;
3504                         epctrl |= DXEPCTL_EPDIS;
3505                         dwc2_writel(hsotg, epctrl, DIEPCTL(idx));
3506                 }
3507         }
3508
3509         /* Clear interrupt */
3510         dwc2_writel(hsotg, GINTSTS_INCOMPL_SOIN, GINTSTS);
3511 }
3512
3513 /**
3514  * dwc2_gadget_handle_incomplete_isoc_out - handle incomplete ISO OUT Interrupt
3515  * @hsotg: The device state:
3516  *
3517  * This interrupt indicates one of the following conditions occurred while
3518  * transmitting an ISOC transaction.
3519  * - Corrupted OUT Token for ISOC EP.
3520  * - Packet not complete in FIFO.
3521  *
3522  * The following actions will be taken:
3523  * - Determine the EP
3524  * - Set DCTL_SGOUTNAK and unmask GOUTNAKEFF if target frame elapsed.
3525  */
3526 static void dwc2_gadget_handle_incomplete_isoc_out(struct dwc2_hsotg *hsotg)
3527 {
3528         u32 gintsts;
3529         u32 gintmsk;
3530         u32 daintmsk;
3531         u32 epctrl;
3532         struct dwc2_hsotg_ep *hs_ep;
3533         int idx;
3534
3535         dev_dbg(hsotg->dev, "%s: GINTSTS_INCOMPL_SOOUT\n", __func__);
3536
3537         daintmsk = dwc2_readl(hsotg, DAINTMSK);
3538         daintmsk >>= DAINT_OUTEP_SHIFT;
3539
3540         for (idx = 1; idx < hsotg->num_of_eps; idx++) {
3541                 hs_ep = hsotg->eps_out[idx];
3542                 /* Proceed only unmasked ISOC EPs */
3543                 if ((BIT(idx) & ~daintmsk) || !hs_ep->isochronous)
3544                         continue;
3545
3546                 epctrl = dwc2_readl(hsotg, DOEPCTL(idx));
3547                 if ((epctrl & DXEPCTL_EPENA) &&
3548                     dwc2_gadget_target_frame_elapsed(hs_ep)) {
3549                         /* Unmask GOUTNAKEFF interrupt */
3550                         gintmsk = dwc2_readl(hsotg, GINTMSK);
3551                         gintmsk |= GINTSTS_GOUTNAKEFF;
3552                         dwc2_writel(hsotg, gintmsk, GINTMSK);
3553
3554                         gintsts = dwc2_readl(hsotg, GINTSTS);
3555                         if (!(gintsts & GINTSTS_GOUTNAKEFF)) {
3556                                 dwc2_set_bit(hsotg, DCTL, DCTL_SGOUTNAK);
3557                                 break;
3558                         }
3559                 }
3560         }
3561
3562         /* Clear interrupt */
3563         dwc2_writel(hsotg, GINTSTS_INCOMPL_SOOUT, GINTSTS);
3564 }
3565
3566 /**
3567  * dwc2_hsotg_irq - handle device interrupt
3568  * @irq: The IRQ number triggered
3569  * @pw: The pw value when registered the handler.
3570  */
3571 static irqreturn_t dwc2_hsotg_irq(int irq, void *pw)
3572 {
3573         struct dwc2_hsotg *hsotg = pw;
3574         int retry_count = 8;
3575         u32 gintsts;
3576         u32 gintmsk;
3577
3578         if (!dwc2_is_device_mode(hsotg))
3579                 return IRQ_NONE;
3580
3581         spin_lock(&hsotg->lock);
3582 irq_retry:
3583         gintsts = dwc2_readl(hsotg, GINTSTS);
3584         gintmsk = dwc2_readl(hsotg, GINTMSK);
3585
3586         dev_dbg(hsotg->dev, "%s: %08x %08x (%08x) retry %d\n",
3587                 __func__, gintsts, gintsts & gintmsk, gintmsk, retry_count);
3588
3589         gintsts &= gintmsk;
3590
3591         if (gintsts & GINTSTS_RESETDET) {
3592                 dev_dbg(hsotg->dev, "%s: USBRstDet\n", __func__);
3593
3594                 dwc2_writel(hsotg, GINTSTS_RESETDET, GINTSTS);
3595
3596                 /* This event must be used only if controller is suspended */
3597                 if (hsotg->lx_state == DWC2_L2) {
3598                         dwc2_exit_partial_power_down(hsotg, true);
3599                         hsotg->lx_state = DWC2_L0;
3600                 }
3601         }
3602
3603         if (gintsts & (GINTSTS_USBRST | GINTSTS_RESETDET)) {
3604                 u32 usb_status = dwc2_readl(hsotg, GOTGCTL);
3605                 u32 connected = hsotg->connected;
3606
3607                 dev_dbg(hsotg->dev, "%s: USBRst\n", __func__);
3608                 dev_dbg(hsotg->dev, "GNPTXSTS=%08x\n",
3609                         dwc2_readl(hsotg, GNPTXSTS));
3610
3611                 dwc2_writel(hsotg, GINTSTS_USBRST, GINTSTS);
3612
3613                 /* Report disconnection if it is not already done. */
3614                 dwc2_hsotg_disconnect(hsotg);
3615
3616                 /* Reset device address to zero */
3617                 dwc2_clear_bit(hsotg, DCFG, DCFG_DEVADDR_MASK);
3618
3619                 if (usb_status & GOTGCTL_BSESVLD && connected)
3620                         dwc2_hsotg_core_init_disconnected(hsotg, true);
3621         }
3622
3623         if (gintsts & GINTSTS_ENUMDONE) {
3624                 dwc2_writel(hsotg, GINTSTS_ENUMDONE, GINTSTS);
3625
3626                 dwc2_hsotg_irq_enumdone(hsotg);
3627         }
3628
3629         if (gintsts & (GINTSTS_OEPINT | GINTSTS_IEPINT)) {
3630                 u32 daint = dwc2_readl(hsotg, DAINT);
3631                 u32 daintmsk = dwc2_readl(hsotg, DAINTMSK);
3632                 u32 daint_out, daint_in;
3633                 int ep;
3634
3635                 daint &= daintmsk;
3636                 daint_out = daint >> DAINT_OUTEP_SHIFT;
3637                 daint_in = daint & ~(daint_out << DAINT_OUTEP_SHIFT);
3638
3639                 dev_dbg(hsotg->dev, "%s: daint=%08x\n", __func__, daint);
3640
3641                 for (ep = 0; ep < hsotg->num_of_eps && daint_out;
3642                                                 ep++, daint_out >>= 1) {
3643                         if (daint_out & 1)
3644                                 dwc2_hsotg_epint(hsotg, ep, 0);
3645                 }
3646
3647                 for (ep = 0; ep < hsotg->num_of_eps  && daint_in;
3648                                                 ep++, daint_in >>= 1) {
3649                         if (daint_in & 1)
3650                                 dwc2_hsotg_epint(hsotg, ep, 1);
3651                 }
3652         }
3653
3654         /* check both FIFOs */
3655
3656         if (gintsts & GINTSTS_NPTXFEMP) {
3657                 dev_dbg(hsotg->dev, "NPTxFEmp\n");
3658
3659                 /*
3660                  * Disable the interrupt to stop it happening again
3661                  * unless one of these endpoint routines decides that
3662                  * it needs re-enabling
3663                  */
3664
3665                 dwc2_hsotg_disable_gsint(hsotg, GINTSTS_NPTXFEMP);
3666                 dwc2_hsotg_irq_fifoempty(hsotg, false);
3667         }
3668
3669         if (gintsts & GINTSTS_PTXFEMP) {
3670                 dev_dbg(hsotg->dev, "PTxFEmp\n");
3671
3672                 /* See note in GINTSTS_NPTxFEmp */
3673
3674                 dwc2_hsotg_disable_gsint(hsotg, GINTSTS_PTXFEMP);
3675                 dwc2_hsotg_irq_fifoempty(hsotg, true);
3676         }
3677
3678         if (gintsts & GINTSTS_RXFLVL) {
3679                 /*
3680                  * note, since GINTSTS_RxFLvl doubles as FIFO-not-empty,
3681                  * we need to retry dwc2_hsotg_handle_rx if this is still
3682                  * set.
3683                  */
3684
3685                 dwc2_hsotg_handle_rx(hsotg);
3686         }
3687
3688         if (gintsts & GINTSTS_ERLYSUSP) {
3689                 dev_dbg(hsotg->dev, "GINTSTS_ErlySusp\n");
3690                 dwc2_writel(hsotg, GINTSTS_ERLYSUSP, GINTSTS);
3691         }
3692
3693         /*
3694          * these next two seem to crop-up occasionally causing the core
3695          * to shutdown the USB transfer, so try clearing them and logging
3696          * the occurrence.
3697          */
3698
3699         if (gintsts & GINTSTS_GOUTNAKEFF) {
3700                 u8 idx;
3701                 u32 epctrl;
3702                 u32 gintmsk;
3703                 u32 daintmsk;
3704                 struct dwc2_hsotg_ep *hs_ep;
3705
3706                 daintmsk = dwc2_readl(hsotg, DAINTMSK);
3707                 daintmsk >>= DAINT_OUTEP_SHIFT;
3708                 /* Mask this interrupt */
3709                 gintmsk = dwc2_readl(hsotg, GINTMSK);
3710                 gintmsk &= ~GINTSTS_GOUTNAKEFF;
3711                 dwc2_writel(hsotg, gintmsk, GINTMSK);
3712
3713                 dev_dbg(hsotg->dev, "GOUTNakEff triggered\n");
3714                 for (idx = 1; idx < hsotg->num_of_eps; idx++) {
3715                         hs_ep = hsotg->eps_out[idx];
3716                         /* Proceed only unmasked ISOC EPs */
3717                         if ((BIT(idx) & ~daintmsk) || !hs_ep->isochronous)
3718                                 continue;
3719
3720                         epctrl = dwc2_readl(hsotg, DOEPCTL(idx));
3721
3722                         if (epctrl & DXEPCTL_EPENA) {
3723                                 epctrl |= DXEPCTL_SNAK;
3724                                 epctrl |= DXEPCTL_EPDIS;
3725                                 dwc2_writel(hsotg, epctrl, DOEPCTL(idx));
3726                         }
3727                 }
3728
3729                 /* This interrupt bit is cleared in DXEPINT_EPDISBLD handler */
3730         }
3731
3732         if (gintsts & GINTSTS_GINNAKEFF) {
3733                 dev_info(hsotg->dev, "GINNakEff triggered\n");
3734
3735                 dwc2_set_bit(hsotg, DCTL, DCTL_CGNPINNAK);
3736
3737                 dwc2_hsotg_dump(hsotg);
3738         }
3739
3740         if (gintsts & GINTSTS_INCOMPL_SOIN)
3741                 dwc2_gadget_handle_incomplete_isoc_in(hsotg);
3742
3743         if (gintsts & GINTSTS_INCOMPL_SOOUT)
3744                 dwc2_gadget_handle_incomplete_isoc_out(hsotg);
3745
3746         /*
3747          * if we've had fifo events, we should try and go around the
3748          * loop again to see if there's any point in returning yet.
3749          */
3750
3751         if (gintsts & IRQ_RETRY_MASK && --retry_count > 0)
3752                 goto irq_retry;
3753
3754         /* Check WKUP_ALERT interrupt*/
3755         if (hsotg->params.service_interval)
3756                 dwc2_gadget_wkup_alert_handler(hsotg);
3757
3758         spin_unlock(&hsotg->lock);
3759
3760         return IRQ_HANDLED;
3761 }
3762
3763 static void dwc2_hsotg_ep_stop_xfr(struct dwc2_hsotg *hsotg,
3764                                    struct dwc2_hsotg_ep *hs_ep)
3765 {
3766         u32 epctrl_reg;
3767         u32 epint_reg;
3768
3769         epctrl_reg = hs_ep->dir_in ? DIEPCTL(hs_ep->index) :
3770                 DOEPCTL(hs_ep->index);
3771         epint_reg = hs_ep->dir_in ? DIEPINT(hs_ep->index) :
3772                 DOEPINT(hs_ep->index);
3773
3774         dev_dbg(hsotg->dev, "%s: stopping transfer on %s\n", __func__,
3775                 hs_ep->name);
3776
3777         if (hs_ep->dir_in) {
3778                 if (hsotg->dedicated_fifos || hs_ep->periodic) {
3779                         dwc2_set_bit(hsotg, epctrl_reg, DXEPCTL_SNAK);
3780                         /* Wait for Nak effect */
3781                         if (dwc2_hsotg_wait_bit_set(hsotg, epint_reg,
3782                                                     DXEPINT_INEPNAKEFF, 100))
3783                                 dev_warn(hsotg->dev,
3784                                          "%s: timeout DIEPINT.NAKEFF\n",
3785                                          __func__);
3786                 } else {
3787                         dwc2_set_bit(hsotg, DCTL, DCTL_SGNPINNAK);
3788                         /* Wait for Nak effect */
3789                         if (dwc2_hsotg_wait_bit_set(hsotg, GINTSTS,
3790                                                     GINTSTS_GINNAKEFF, 100))
3791                                 dev_warn(hsotg->dev,
3792                                          "%s: timeout GINTSTS.GINNAKEFF\n",
3793                                          __func__);
3794                 }
3795         } else {
3796                 if (!(dwc2_readl(hsotg, GINTSTS) & GINTSTS_GOUTNAKEFF))
3797                         dwc2_set_bit(hsotg, DCTL, DCTL_SGOUTNAK);
3798
3799                 /* Wait for global nak to take effect */
3800                 if (dwc2_hsotg_wait_bit_set(hsotg, GINTSTS,
3801                                             GINTSTS_GOUTNAKEFF, 100))
3802                         dev_warn(hsotg->dev, "%s: timeout GINTSTS.GOUTNAKEFF\n",
3803                                  __func__);
3804         }
3805
3806         /* Disable ep */
3807         dwc2_set_bit(hsotg, epctrl_reg, DXEPCTL_EPDIS | DXEPCTL_SNAK);
3808
3809         /* Wait for ep to be disabled */
3810         if (dwc2_hsotg_wait_bit_set(hsotg, epint_reg, DXEPINT_EPDISBLD, 100))
3811                 dev_warn(hsotg->dev,
3812                          "%s: timeout DOEPCTL.EPDisable\n", __func__);
3813
3814         /* Clear EPDISBLD interrupt */
3815         dwc2_set_bit(hsotg, epint_reg, DXEPINT_EPDISBLD);
3816
3817         if (hs_ep->dir_in) {
3818                 unsigned short fifo_index;
3819
3820                 if (hsotg->dedicated_fifos || hs_ep->periodic)
3821                         fifo_index = hs_ep->fifo_index;
3822                 else
3823                         fifo_index = 0;
3824
3825                 /* Flush TX FIFO */
3826                 dwc2_flush_tx_fifo(hsotg, fifo_index);
3827
3828                 /* Clear Global In NP NAK in Shared FIFO for non periodic ep */
3829                 if (!hsotg->dedicated_fifos && !hs_ep->periodic)
3830                         dwc2_set_bit(hsotg, DCTL, DCTL_CGNPINNAK);
3831
3832         } else {
3833                 /* Remove global NAKs */
3834                 dwc2_set_bit(hsotg, DCTL, DCTL_CGOUTNAK);
3835         }
3836 }
3837
3838 /**
3839  * dwc2_hsotg_ep_enable - enable the given endpoint
3840  * @ep: The USB endpint to configure
3841  * @desc: The USB endpoint descriptor to configure with.
3842  *
3843  * This is called from the USB gadget code's usb_ep_enable().
3844  */
3845 static int dwc2_hsotg_ep_enable(struct usb_ep *ep,
3846                                 const struct usb_endpoint_descriptor *desc)
3847 {
3848         struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
3849         struct dwc2_hsotg *hsotg = hs_ep->parent;
3850         unsigned long flags;
3851         unsigned int index = hs_ep->index;
3852         u32 epctrl_reg;
3853         u32 epctrl;
3854         u32 mps;
3855         u32 mc;
3856         u32 mask;
3857         unsigned int dir_in;
3858         unsigned int i, val, size;
3859         int ret = 0;
3860         unsigned char ep_type;
3861
3862         dev_dbg(hsotg->dev,
3863                 "%s: ep %s: a 0x%02x, attr 0x%02x, mps 0x%04x, intr %d\n",
3864                 __func__, ep->name, desc->bEndpointAddress, desc->bmAttributes,
3865                 desc->wMaxPacketSize, desc->bInterval);
3866
3867         /* not to be called for EP0 */
3868         if (index == 0) {
3869                 dev_err(hsotg->dev, "%s: called for EP 0\n", __func__);
3870                 return -EINVAL;
3871         }
3872
3873         dir_in = (desc->bEndpointAddress & USB_ENDPOINT_DIR_MASK) ? 1 : 0;
3874         if (dir_in != hs_ep->dir_in) {
3875                 dev_err(hsotg->dev, "%s: direction mismatch!\n", __func__);
3876                 return -EINVAL;
3877         }
3878
3879         ep_type = desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
3880         mps = usb_endpoint_maxp(desc);
3881         mc = usb_endpoint_maxp_mult(desc);
3882
3883         /* ISOC IN in DDMA supported bInterval up to 10 */
3884         if (using_desc_dma(hsotg) && ep_type == USB_ENDPOINT_XFER_ISOC &&
3885             dir_in && desc->bInterval > 10) {
3886                 dev_err(hsotg->dev,
3887                         "%s: ISOC IN, DDMA: bInterval>10 not supported!\n", __func__);
3888                 return -EINVAL;
3889         }
3890
3891         /* High bandwidth ISOC OUT in DDMA not supported */
3892         if (using_desc_dma(hsotg) && ep_type == USB_ENDPOINT_XFER_ISOC &&
3893             !dir_in && mc > 1) {
3894                 dev_err(hsotg->dev,
3895                         "%s: ISOC OUT, DDMA: HB not supported!\n", __func__);
3896                 return -EINVAL;
3897         }
3898
3899         /* note, we handle this here instead of dwc2_hsotg_set_ep_maxpacket */
3900
3901         epctrl_reg = dir_in ? DIEPCTL(index) : DOEPCTL(index);
3902         epctrl = dwc2_readl(hsotg, epctrl_reg);
3903
3904         dev_dbg(hsotg->dev, "%s: read DxEPCTL=0x%08x from 0x%08x\n",
3905                 __func__, epctrl, epctrl_reg);
3906
3907         /* Allocate DMA descriptor chain for non-ctrl endpoints */
3908         if (using_desc_dma(hsotg) && !hs_ep->desc_list) {
3909                 hs_ep->desc_list = dmam_alloc_coherent(hsotg->dev,
3910                         MAX_DMA_DESC_NUM_GENERIC *
3911                         sizeof(struct dwc2_dma_desc),
3912                         &hs_ep->desc_list_dma, GFP_ATOMIC);
3913                 if (!hs_ep->desc_list) {
3914                         ret = -ENOMEM;
3915                         goto error2;
3916                 }
3917         }
3918
3919         spin_lock_irqsave(&hsotg->lock, flags);
3920
3921         epctrl &= ~(DXEPCTL_EPTYPE_MASK | DXEPCTL_MPS_MASK);
3922         epctrl |= DXEPCTL_MPS(mps);
3923
3924         /*
3925          * mark the endpoint as active, otherwise the core may ignore
3926          * transactions entirely for this endpoint
3927          */
3928         epctrl |= DXEPCTL_USBACTEP;
3929
3930         /* update the endpoint state */
3931         dwc2_hsotg_set_ep_maxpacket(hsotg, hs_ep->index, mps, mc, dir_in);
3932
3933         /* default, set to non-periodic */
3934         hs_ep->isochronous = 0;
3935         hs_ep->periodic = 0;
3936         hs_ep->halted = 0;
3937         hs_ep->interval = desc->bInterval;
3938
3939         switch (ep_type) {
3940         case USB_ENDPOINT_XFER_ISOC:
3941                 epctrl |= DXEPCTL_EPTYPE_ISO;
3942                 epctrl |= DXEPCTL_SETEVENFR;
3943                 hs_ep->isochronous = 1;
3944                 hs_ep->interval = 1 << (desc->bInterval - 1);
3945                 hs_ep->target_frame = TARGET_FRAME_INITIAL;
3946                 hs_ep->next_desc = 0;
3947                 hs_ep->compl_desc = 0;
3948                 if (dir_in) {
3949                         hs_ep->periodic = 1;
3950                         mask = dwc2_readl(hsotg, DIEPMSK);
3951                         mask |= DIEPMSK_NAKMSK;
3952                         dwc2_writel(hsotg, mask, DIEPMSK);
3953                 } else {
3954                         mask = dwc2_readl(hsotg, DOEPMSK);
3955                         mask |= DOEPMSK_OUTTKNEPDISMSK;
3956                         dwc2_writel(hsotg, mask, DOEPMSK);
3957                 }
3958                 break;
3959
3960         case USB_ENDPOINT_XFER_BULK:
3961                 epctrl |= DXEPCTL_EPTYPE_BULK;
3962                 break;
3963
3964         case USB_ENDPOINT_XFER_INT:
3965                 if (dir_in)
3966                         hs_ep->periodic = 1;
3967
3968                 if (hsotg->gadget.speed == USB_SPEED_HIGH)
3969                         hs_ep->interval = 1 << (desc->bInterval - 1);
3970
3971                 epctrl |= DXEPCTL_EPTYPE_INTERRUPT;
3972                 break;
3973
3974         case USB_ENDPOINT_XFER_CONTROL:
3975                 epctrl |= DXEPCTL_EPTYPE_CONTROL;
3976                 break;
3977         }
3978
3979         /*
3980          * if the hardware has dedicated fifos, we must give each IN EP
3981          * a unique tx-fifo even if it is non-periodic.
3982          */
3983         if (dir_in && hsotg->dedicated_fifos) {
3984                 u32 fifo_index = 0;
3985                 u32 fifo_size = UINT_MAX;
3986
3987                 size = hs_ep->ep.maxpacket * hs_ep->mc;
3988                 for (i = 1; i < hsotg->num_of_eps; ++i) {
3989                         if (hsotg->fifo_map & (1 << i))
3990                                 continue;
3991                         val = dwc2_readl(hsotg, DPTXFSIZN(i));
3992                         val = (val >> FIFOSIZE_DEPTH_SHIFT) * 4;
3993                         if (val < size)
3994                                 continue;
3995                         /* Search for smallest acceptable fifo */
3996                         if (val < fifo_size) {
3997                                 fifo_size = val;
3998                                 fifo_index = i;
3999                         }
4000                 }
4001                 if (!fifo_index) {
4002                         dev_err(hsotg->dev,
4003                                 "%s: No suitable fifo found\n", __func__);
4004                         ret = -ENOMEM;
4005                         goto error1;
4006                 }
4007                 hsotg->fifo_map |= 1 << fifo_index;
4008                 epctrl |= DXEPCTL_TXFNUM(fifo_index);
4009                 hs_ep->fifo_index = fifo_index;
4010                 hs_ep->fifo_size = fifo_size;
4011         }
4012
4013         /* for non control endpoints, set PID to D0 */
4014         if (index && !hs_ep->isochronous)
4015                 epctrl |= DXEPCTL_SETD0PID;
4016
4017         /* WA for Full speed ISOC IN in DDMA mode.
4018          * By Clear NAK status of EP, core will send ZLP
4019          * to IN token and assert NAK interrupt relying
4020          * on TxFIFO status only
4021          */
4022
4023         if (hsotg->gadget.speed == USB_SPEED_FULL &&
4024             hs_ep->isochronous && dir_in) {
4025                 /* The WA applies only to core versions from 2.72a
4026                  * to 4.00a (including both). Also for FS_IOT_1.00a
4027                  * and HS_IOT_1.00a.
4028                  */
4029                 u32 gsnpsid = dwc2_readl(hsotg, GSNPSID);
4030
4031                 if ((gsnpsid >= DWC2_CORE_REV_2_72a &&
4032                      gsnpsid <= DWC2_CORE_REV_4_00a) ||
4033                      gsnpsid == DWC2_FS_IOT_REV_1_00a ||
4034                      gsnpsid == DWC2_HS_IOT_REV_1_00a)
4035                         epctrl |= DXEPCTL_CNAK;
4036         }
4037
4038         dev_dbg(hsotg->dev, "%s: write DxEPCTL=0x%08x\n",
4039                 __func__, epctrl);
4040
4041         dwc2_writel(hsotg, epctrl, epctrl_reg);
4042         dev_dbg(hsotg->dev, "%s: read DxEPCTL=0x%08x\n",
4043                 __func__, dwc2_readl(hsotg, epctrl_reg));
4044
4045         /* enable the endpoint interrupt */
4046         dwc2_hsotg_ctrl_epint(hsotg, index, dir_in, 1);
4047
4048 error1:
4049         spin_unlock_irqrestore(&hsotg->lock, flags);
4050
4051 error2:
4052         if (ret && using_desc_dma(hsotg) && hs_ep->desc_list) {
4053                 dmam_free_coherent(hsotg->dev, MAX_DMA_DESC_NUM_GENERIC *
4054                         sizeof(struct dwc2_dma_desc),
4055                         hs_ep->desc_list, hs_ep->desc_list_dma);
4056                 hs_ep->desc_list = NULL;
4057         }
4058
4059         return ret;
4060 }
4061
4062 /**
4063  * dwc2_hsotg_ep_disable - disable given endpoint
4064  * @ep: The endpoint to disable.
4065  */
4066 static int dwc2_hsotg_ep_disable(struct usb_ep *ep)
4067 {
4068         struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
4069         struct dwc2_hsotg *hsotg = hs_ep->parent;
4070         int dir_in = hs_ep->dir_in;
4071         int index = hs_ep->index;
4072         unsigned long flags;
4073         u32 epctrl_reg;
4074         u32 ctrl;
4075         int locked;
4076
4077         dev_dbg(hsotg->dev, "%s(ep %p)\n", __func__, ep);
4078
4079         if (ep == &hsotg->eps_out[0]->ep) {
4080                 dev_err(hsotg->dev, "%s: called for ep0\n", __func__);
4081                 return -EINVAL;
4082         }
4083
4084         if (hsotg->op_state != OTG_STATE_B_PERIPHERAL) {
4085                 dev_err(hsotg->dev, "%s: called in host mode?\n", __func__);
4086                 return -EINVAL;
4087         }
4088
4089         epctrl_reg = dir_in ? DIEPCTL(index) : DOEPCTL(index);
4090
4091         locked = spin_is_locked(&hsotg->lock);
4092         if (!locked)
4093                 spin_lock_irqsave(&hsotg->lock, flags);
4094
4095         ctrl = dwc2_readl(hsotg, epctrl_reg);
4096
4097         if (ctrl & DXEPCTL_EPENA)
4098                 dwc2_hsotg_ep_stop_xfr(hsotg, hs_ep);
4099
4100         ctrl &= ~DXEPCTL_EPENA;
4101         ctrl &= ~DXEPCTL_USBACTEP;
4102         ctrl |= DXEPCTL_SNAK;
4103
4104         dev_dbg(hsotg->dev, "%s: DxEPCTL=0x%08x\n", __func__, ctrl);
4105         dwc2_writel(hsotg, ctrl, epctrl_reg);
4106
4107         /* disable endpoint interrupts */
4108         dwc2_hsotg_ctrl_epint(hsotg, hs_ep->index, hs_ep->dir_in, 0);
4109
4110         /* terminate all requests with shutdown */
4111         kill_all_requests(hsotg, hs_ep, -ESHUTDOWN);
4112
4113         hsotg->fifo_map &= ~(1 << hs_ep->fifo_index);
4114         hs_ep->fifo_index = 0;
4115         hs_ep->fifo_size = 0;
4116
4117         if (!locked)
4118                 spin_unlock_irqrestore(&hsotg->lock, flags);
4119
4120         return 0;
4121 }
4122
4123 /**
4124  * on_list - check request is on the given endpoint
4125  * @ep: The endpoint to check.
4126  * @test: The request to test if it is on the endpoint.
4127  */
4128 static bool on_list(struct dwc2_hsotg_ep *ep, struct dwc2_hsotg_req *test)
4129 {
4130         struct dwc2_hsotg_req *req, *treq;
4131
4132         list_for_each_entry_safe(req, treq, &ep->queue, queue) {
4133                 if (req == test)
4134                         return true;
4135         }
4136
4137         return false;
4138 }
4139
4140 /**
4141  * dwc2_hsotg_ep_dequeue - dequeue given endpoint
4142  * @ep: The endpoint to dequeue.
4143  * @req: The request to be removed from a queue.
4144  */
4145 static int dwc2_hsotg_ep_dequeue(struct usb_ep *ep, struct usb_request *req)
4146 {
4147         struct dwc2_hsotg_req *hs_req = our_req(req);
4148         struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
4149         struct dwc2_hsotg *hs = hs_ep->parent;
4150         unsigned long flags;
4151
4152         dev_dbg(hs->dev, "ep_dequeue(%p,%p)\n", ep, req);
4153
4154         spin_lock_irqsave(&hs->lock, flags);
4155
4156         if (!on_list(hs_ep, hs_req)) {
4157                 spin_unlock_irqrestore(&hs->lock, flags);
4158                 return -EINVAL;
4159         }
4160
4161         /* Dequeue already started request */
4162         if (req == &hs_ep->req->req)
4163                 dwc2_hsotg_ep_stop_xfr(hs, hs_ep);
4164
4165         dwc2_hsotg_complete_request(hs, hs_ep, hs_req, -ECONNRESET);
4166         spin_unlock_irqrestore(&hs->lock, flags);
4167
4168         return 0;
4169 }
4170
4171 /**
4172  * dwc2_hsotg_ep_sethalt - set halt on a given endpoint
4173  * @ep: The endpoint to set halt.
4174  * @value: Set or unset the halt.
4175  * @now: If true, stall the endpoint now. Otherwise return -EAGAIN if
4176  *       the endpoint is busy processing requests.
4177  *
4178  * We need to stall the endpoint immediately if request comes from set_feature
4179  * protocol command handler.
4180  */
4181 static int dwc2_hsotg_ep_sethalt(struct usb_ep *ep, int value, bool now)
4182 {
4183         struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
4184         struct dwc2_hsotg *hs = hs_ep->parent;
4185         int index = hs_ep->index;
4186         u32 epreg;
4187         u32 epctl;
4188         u32 xfertype;
4189
4190         dev_info(hs->dev, "%s(ep %p %s, %d)\n", __func__, ep, ep->name, value);
4191
4192         if (index == 0) {
4193                 if (value)
4194                         dwc2_hsotg_stall_ep0(hs);
4195                 else
4196                         dev_warn(hs->dev,
4197                                  "%s: can't clear halt on ep0\n", __func__);
4198                 return 0;
4199         }
4200
4201         if (hs_ep->isochronous) {
4202                 dev_err(hs->dev, "%s is Isochronous Endpoint\n", ep->name);
4203                 return -EINVAL;
4204         }
4205
4206         if (!now && value && !list_empty(&hs_ep->queue)) {
4207                 dev_dbg(hs->dev, "%s request is pending, cannot halt\n",
4208                         ep->name);
4209                 return -EAGAIN;
4210         }
4211
4212         if (hs_ep->dir_in) {
4213                 epreg = DIEPCTL(index);
4214                 epctl = dwc2_readl(hs, epreg);
4215
4216                 if (value) {
4217                         epctl |= DXEPCTL_STALL | DXEPCTL_SNAK;
4218                         if (epctl & DXEPCTL_EPENA)
4219                                 epctl |= DXEPCTL_EPDIS;
4220                 } else {
4221                         epctl &= ~DXEPCTL_STALL;
4222                         xfertype = epctl & DXEPCTL_EPTYPE_MASK;
4223                         if (xfertype == DXEPCTL_EPTYPE_BULK ||
4224                             xfertype == DXEPCTL_EPTYPE_INTERRUPT)
4225                                 epctl |= DXEPCTL_SETD0PID;
4226                 }
4227                 dwc2_writel(hs, epctl, epreg);
4228         } else {
4229                 epreg = DOEPCTL(index);
4230                 epctl = dwc2_readl(hs, epreg);
4231
4232                 if (value) {
4233                         epctl |= DXEPCTL_STALL;
4234                 } else {
4235                         epctl &= ~DXEPCTL_STALL;
4236                         xfertype = epctl & DXEPCTL_EPTYPE_MASK;
4237                         if (xfertype == DXEPCTL_EPTYPE_BULK ||
4238                             xfertype == DXEPCTL_EPTYPE_INTERRUPT)
4239                                 epctl |= DXEPCTL_SETD0PID;
4240                 }
4241                 dwc2_writel(hs, epctl, epreg);
4242         }
4243
4244         hs_ep->halted = value;
4245
4246         return 0;
4247 }
4248
4249 /**
4250  * dwc2_hsotg_ep_sethalt_lock - set halt on a given endpoint with lock held
4251  * @ep: The endpoint to set halt.
4252  * @value: Set or unset the halt.
4253  */
4254 static int dwc2_hsotg_ep_sethalt_lock(struct usb_ep *ep, int value)
4255 {
4256         struct dwc2_hsotg_ep *hs_ep = our_ep(ep);
4257         struct dwc2_hsotg *hs = hs_ep->parent;
4258         unsigned long flags = 0;
4259         int ret = 0;
4260
4261         spin_lock_irqsave(&hs->lock, flags);
4262         ret = dwc2_hsotg_ep_sethalt(ep, value, false);
4263         spin_unlock_irqrestore(&hs->lock, flags);
4264
4265         return ret;
4266 }
4267
4268 static const struct usb_ep_ops dwc2_hsotg_ep_ops = {
4269         .enable         = dwc2_hsotg_ep_enable,
4270         .disable        = dwc2_hsotg_ep_disable,
4271         .alloc_request  = dwc2_hsotg_ep_alloc_request,
4272         .free_request   = dwc2_hsotg_ep_free_request,
4273         .queue          = dwc2_hsotg_ep_queue_lock,
4274         .dequeue        = dwc2_hsotg_ep_dequeue,
4275         .set_halt       = dwc2_hsotg_ep_sethalt_lock,
4276         /* note, don't believe we have any call for the fifo routines */
4277 };
4278
4279 /**
4280  * dwc2_hsotg_init - initialize the usb core
4281  * @hsotg: The driver state
4282  */
4283 static void dwc2_hsotg_init(struct dwc2_hsotg *hsotg)
4284 {
4285         u32 trdtim;
4286         u32 usbcfg;
4287         /* unmask subset of endpoint interrupts */
4288
4289         dwc2_writel(hsotg, DIEPMSK_TIMEOUTMSK | DIEPMSK_AHBERRMSK |
4290                     DIEPMSK_EPDISBLDMSK | DIEPMSK_XFERCOMPLMSK,
4291                     DIEPMSK);
4292
4293         dwc2_writel(hsotg, DOEPMSK_SETUPMSK | DOEPMSK_AHBERRMSK |
4294                     DOEPMSK_EPDISBLDMSK | DOEPMSK_XFERCOMPLMSK,
4295                     DOEPMSK);
4296
4297         dwc2_writel(hsotg, 0, DAINTMSK);
4298
4299         /* Be in disconnected state until gadget is registered */
4300         dwc2_set_bit(hsotg, DCTL, DCTL_SFTDISCON);
4301
4302         /* setup fifos */
4303
4304         dev_dbg(hsotg->dev, "GRXFSIZ=0x%08x, GNPTXFSIZ=0x%08x\n",
4305                 dwc2_readl(hsotg, GRXFSIZ),
4306                 dwc2_readl(hsotg, GNPTXFSIZ));
4307
4308         dwc2_hsotg_init_fifo(hsotg);
4309
4310         /* keep other bits untouched (so e.g. forced modes are not lost) */
4311         usbcfg = dwc2_readl(hsotg, GUSBCFG);
4312         usbcfg &= ~(GUSBCFG_TOUTCAL_MASK | GUSBCFG_PHYIF16 | GUSBCFG_SRPCAP |
4313                 GUSBCFG_HNPCAP | GUSBCFG_USBTRDTIM_MASK);
4314
4315         /* set the PLL on, remove the HNP/SRP and set the PHY */
4316         trdtim = (hsotg->phyif == GUSBCFG_PHYIF8) ? 9 : 5;
4317         usbcfg |= hsotg->phyif | GUSBCFG_TOUTCAL(7) |
4318                 (trdtim << GUSBCFG_USBTRDTIM_SHIFT);
4319         dwc2_writel(hsotg, usbcfg, GUSBCFG);
4320
4321         if (using_dma(hsotg))
4322                 dwc2_set_bit(hsotg, GAHBCFG, GAHBCFG_DMA_EN);
4323 }
4324
4325 /**
4326  * dwc2_hsotg_udc_start - prepare the udc for work
4327  * @gadget: The usb gadget state
4328  * @driver: The usb gadget driver
4329  *
4330  * Perform initialization to prepare udc device and driver
4331  * to work.
4332  */
4333 static int dwc2_hsotg_udc_start(struct usb_gadget *gadget,
4334                                 struct usb_gadget_driver *driver)
4335 {
4336         struct dwc2_hsotg *hsotg = to_hsotg(gadget);
4337         unsigned long flags;
4338         int ret;
4339
4340         if (!hsotg) {
4341                 pr_err("%s: called with no device\n", __func__);
4342                 return -ENODEV;
4343         }
4344
4345         if (!driver) {
4346                 dev_err(hsotg->dev, "%s: no driver\n", __func__);
4347                 return -EINVAL;
4348         }
4349
4350         if (driver->max_speed < USB_SPEED_FULL)
4351                 dev_err(hsotg->dev, "%s: bad speed\n", __func__);
4352
4353         if (!driver->setup) {
4354                 dev_err(hsotg->dev, "%s: missing entry points\n", __func__);
4355                 return -EINVAL;
4356         }
4357
4358         WARN_ON(hsotg->driver);
4359
4360         driver->driver.bus = NULL;
4361         hsotg->driver = driver;
4362         hsotg->gadget.dev.of_node = hsotg->dev->of_node;
4363         hsotg->gadget.speed = USB_SPEED_UNKNOWN;
4364
4365         if (hsotg->dr_mode == USB_DR_MODE_PERIPHERAL) {
4366                 ret = dwc2_lowlevel_hw_enable(hsotg);
4367                 if (ret)
4368                         goto err;
4369         }
4370
4371         if (!IS_ERR_OR_NULL(hsotg->uphy))
4372                 otg_set_peripheral(hsotg->uphy->otg, &hsotg->gadget);
4373
4374         spin_lock_irqsave(&hsotg->lock, flags);
4375         if (dwc2_hw_is_device(hsotg)) {
4376                 dwc2_hsotg_init(hsotg);
4377                 dwc2_hsotg_core_init_disconnected(hsotg, false);
4378         }
4379
4380         hsotg->enabled = 0;
4381         spin_unlock_irqrestore(&hsotg->lock, flags);
4382
4383         dev_info(hsotg->dev, "bound driver %s\n", driver->driver.name);
4384
4385         return 0;
4386
4387 err:
4388         hsotg->driver = NULL;
4389         return ret;
4390 }
4391
4392 /**
4393  * dwc2_hsotg_udc_stop - stop the udc
4394  * @gadget: The usb gadget state
4395  *
4396  * Stop udc hw block and stay tunned for future transmissions
4397  */
4398 static int dwc2_hsotg_udc_stop(struct usb_gadget *gadget)
4399 {
4400         struct dwc2_hsotg *hsotg = to_hsotg(gadget);
4401         unsigned long flags = 0;
4402         int ep;
4403
4404         if (!hsotg)
4405                 return -ENODEV;
4406
4407         /* all endpoints should be shutdown */
4408         for (ep = 1; ep < hsotg->num_of_eps; ep++) {
4409                 if (hsotg->eps_in[ep])
4410                         dwc2_hsotg_ep_disable(&hsotg->eps_in[ep]->ep);
4411                 if (hsotg->eps_out[ep])
4412                         dwc2_hsotg_ep_disable(&hsotg->eps_out[ep]->ep);
4413         }
4414
4415         spin_lock_irqsave(&hsotg->lock, flags);
4416
4417         hsotg->driver = NULL;
4418         hsotg->gadget.speed = USB_SPEED_UNKNOWN;
4419         hsotg->enabled = 0;
4420
4421         spin_unlock_irqrestore(&hsotg->lock, flags);
4422
4423         if (!IS_ERR_OR_NULL(hsotg->uphy))
4424                 otg_set_peripheral(hsotg->uphy->otg, NULL);
4425
4426         if (hsotg->dr_mode == USB_DR_MODE_PERIPHERAL)
4427                 dwc2_lowlevel_hw_disable(hsotg);
4428
4429         return 0;
4430 }
4431
4432 /**
4433  * dwc2_hsotg_gadget_getframe - read the frame number
4434  * @gadget: The usb gadget state
4435  *
4436  * Read the {micro} frame number
4437  */
4438 static int dwc2_hsotg_gadget_getframe(struct usb_gadget *gadget)
4439 {
4440         return dwc2_hsotg_read_frameno(to_hsotg(gadget));
4441 }
4442
4443 /**
4444  * dwc2_hsotg_pullup - connect/disconnect the USB PHY
4445  * @gadget: The usb gadget state
4446  * @is_on: Current state of the USB PHY
4447  *
4448  * Connect/Disconnect the USB PHY pullup
4449  */
4450 static int dwc2_hsotg_pullup(struct usb_gadget *gadget, int is_on)
4451 {
4452         struct dwc2_hsotg *hsotg = to_hsotg(gadget);
4453         unsigned long flags = 0;
4454
4455         dev_dbg(hsotg->dev, "%s: is_on: %d op_state: %d\n", __func__, is_on,
4456                 hsotg->op_state);
4457
4458         /* Don't modify pullup state while in host mode */
4459         if (hsotg->op_state != OTG_STATE_B_PERIPHERAL) {
4460                 hsotg->enabled = is_on;
4461                 return 0;
4462         }
4463
4464         spin_lock_irqsave(&hsotg->lock, flags);
4465         if (is_on) {
4466                 hsotg->enabled = 1;
4467                 dwc2_hsotg_core_init_disconnected(hsotg, false);
4468                 /* Enable ACG feature in device mode,if supported */
4469                 dwc2_enable_acg(hsotg);
4470                 dwc2_hsotg_core_connect(hsotg);
4471         } else {
4472                 dwc2_hsotg_core_disconnect(hsotg);
4473                 dwc2_hsotg_disconnect(hsotg);
4474                 hsotg->enabled = 0;
4475         }
4476
4477         hsotg->gadget.speed = USB_SPEED_UNKNOWN;
4478         spin_unlock_irqrestore(&hsotg->lock, flags);
4479
4480         return 0;
4481 }
4482
4483 static int dwc2_hsotg_vbus_session(struct usb_gadget *gadget, int is_active)
4484 {
4485         struct dwc2_hsotg *hsotg = to_hsotg(gadget);
4486         unsigned long flags;
4487
4488         dev_dbg(hsotg->dev, "%s: is_active: %d\n", __func__, is_active);
4489         spin_lock_irqsave(&hsotg->lock, flags);
4490
4491         /*
4492          * If controller is hibernated, it must exit from power_down
4493          * before being initialized / de-initialized
4494          */
4495         if (hsotg->lx_state == DWC2_L2)
4496                 dwc2_exit_partial_power_down(hsotg, false);
4497
4498         if (is_active) {
4499                 hsotg->op_state = OTG_STATE_B_PERIPHERAL;
4500
4501                 dwc2_hsotg_core_init_disconnected(hsotg, false);
4502                 if (hsotg->enabled) {
4503                         /* Enable ACG feature in device mode,if supported */
4504                         dwc2_enable_acg(hsotg);
4505                         dwc2_hsotg_core_connect(hsotg);
4506                 }
4507         } else {
4508                 dwc2_hsotg_core_disconnect(hsotg);
4509                 dwc2_hsotg_disconnect(hsotg);
4510         }
4511
4512         spin_unlock_irqrestore(&hsotg->lock, flags);
4513         return 0;
4514 }
4515
4516 /**
4517  * dwc2_hsotg_vbus_draw - report bMaxPower field
4518  * @gadget: The usb gadget state
4519  * @mA: Amount of current
4520  *
4521  * Report how much power the device may consume to the phy.
4522  */
4523 static int dwc2_hsotg_vbus_draw(struct usb_gadget *gadget, unsigned int mA)
4524 {
4525         struct dwc2_hsotg *hsotg = to_hsotg(gadget);
4526
4527         if (IS_ERR_OR_NULL(hsotg->uphy))
4528                 return -ENOTSUPP;
4529         return usb_phy_set_power(hsotg->uphy, mA);
4530 }
4531
4532 static const struct usb_gadget_ops dwc2_hsotg_gadget_ops = {
4533         .get_frame      = dwc2_hsotg_gadget_getframe,
4534         .udc_start              = dwc2_hsotg_udc_start,
4535         .udc_stop               = dwc2_hsotg_udc_stop,
4536         .pullup                 = dwc2_hsotg_pullup,
4537         .vbus_session           = dwc2_hsotg_vbus_session,
4538         .vbus_draw              = dwc2_hsotg_vbus_draw,
4539 };
4540
4541 /**
4542  * dwc2_hsotg_initep - initialise a single endpoint
4543  * @hsotg: The device state.
4544  * @hs_ep: The endpoint to be initialised.
4545  * @epnum: The endpoint number
4546  * @dir_in: True if direction is in.
4547  *
4548  * Initialise the given endpoint (as part of the probe and device state
4549  * creation) to give to the gadget driver. Setup the endpoint name, any
4550  * direction information and other state that may be required.
4551  */
4552 static void dwc2_hsotg_initep(struct dwc2_hsotg *hsotg,
4553                               struct dwc2_hsotg_ep *hs_ep,
4554                                        int epnum,
4555                                        bool dir_in)
4556 {
4557         char *dir;
4558
4559         if (epnum == 0)
4560                 dir = "";
4561         else if (dir_in)
4562                 dir = "in";
4563         else
4564                 dir = "out";
4565
4566         hs_ep->dir_in = dir_in;
4567         hs_ep->index = epnum;
4568
4569         snprintf(hs_ep->name, sizeof(hs_ep->name), "ep%d%s", epnum, dir);
4570
4571         INIT_LIST_HEAD(&hs_ep->queue);
4572         INIT_LIST_HEAD(&hs_ep->ep.ep_list);
4573
4574         /* add to the list of endpoints known by the gadget driver */
4575         if (epnum)
4576                 list_add_tail(&hs_ep->ep.ep_list, &hsotg->gadget.ep_list);
4577
4578         hs_ep->parent = hsotg;
4579         hs_ep->ep.name = hs_ep->name;
4580
4581         if (hsotg->params.speed == DWC2_SPEED_PARAM_LOW)
4582                 usb_ep_set_maxpacket_limit(&hs_ep->ep, 8);
4583         else
4584                 usb_ep_set_maxpacket_limit(&hs_ep->ep,
4585                                            epnum ? 1024 : EP0_MPS_LIMIT);
4586         hs_ep->ep.ops = &dwc2_hsotg_ep_ops;
4587
4588         if (epnum == 0) {
4589                 hs_ep->ep.caps.type_control = true;
4590         } else {
4591                 if (hsotg->params.speed != DWC2_SPEED_PARAM_LOW) {
4592                         hs_ep->ep.caps.type_iso = true;
4593                         hs_ep->ep.caps.type_bulk = true;
4594                 }
4595                 hs_ep->ep.caps.type_int = true;
4596         }
4597
4598         if (dir_in)
4599                 hs_ep->ep.caps.dir_in = true;
4600         else
4601                 hs_ep->ep.caps.dir_out = true;
4602
4603         /*
4604          * if we're using dma, we need to set the next-endpoint pointer
4605          * to be something valid.
4606          */
4607
4608         if (using_dma(hsotg)) {
4609                 u32 next = DXEPCTL_NEXTEP((epnum + 1) % 15);
4610
4611                 if (dir_in)
4612                         dwc2_writel(hsotg, next, DIEPCTL(epnum));
4613                 else
4614                         dwc2_writel(hsotg, next, DOEPCTL(epnum));
4615         }
4616 }
4617
4618 /**
4619  * dwc2_hsotg_hw_cfg - read HW configuration registers
4620  * @hsotg: Programming view of the DWC_otg controller
4621  *
4622  * Read the USB core HW configuration registers
4623  */
4624 static int dwc2_hsotg_hw_cfg(struct dwc2_hsotg *hsotg)
4625 {
4626         u32 cfg;
4627         u32 ep_type;
4628         u32 i;
4629
4630         /* check hardware configuration */
4631
4632         hsotg->num_of_eps = hsotg->hw_params.num_dev_ep;
4633
4634         /* Add ep0 */
4635         hsotg->num_of_eps++;
4636
4637         hsotg->eps_in[0] = devm_kzalloc(hsotg->dev,
4638                                         sizeof(struct dwc2_hsotg_ep),
4639                                         GFP_KERNEL);
4640         if (!hsotg->eps_in[0])
4641                 return -ENOMEM;
4642         /* Same dwc2_hsotg_ep is used in both directions for ep0 */
4643         hsotg->eps_out[0] = hsotg->eps_in[0];
4644
4645         cfg = hsotg->hw_params.dev_ep_dirs;
4646         for (i = 1, cfg >>= 2; i < hsotg->num_of_eps; i++, cfg >>= 2) {
4647                 ep_type = cfg & 3;
4648                 /* Direction in or both */
4649                 if (!(ep_type & 2)) {
4650                         hsotg->eps_in[i] = devm_kzalloc(hsotg->dev,
4651                                 sizeof(struct dwc2_hsotg_ep), GFP_KERNEL);
4652                         if (!hsotg->eps_in[i])
4653                                 return -ENOMEM;
4654                 }
4655                 /* Direction out or both */
4656                 if (!(ep_type & 1)) {
4657                         hsotg->eps_out[i] = devm_kzalloc(hsotg->dev,
4658                                 sizeof(struct dwc2_hsotg_ep), GFP_KERNEL);
4659                         if (!hsotg->eps_out[i])
4660                                 return -ENOMEM;
4661                 }
4662         }
4663
4664         hsotg->fifo_mem = hsotg->hw_params.total_fifo_size;
4665         hsotg->dedicated_fifos = hsotg->hw_params.en_multiple_tx_fifo;
4666
4667         dev_info(hsotg->dev, "EPs: %d, %s fifos, %d entries in SPRAM\n",
4668                  hsotg->num_of_eps,
4669                  hsotg->dedicated_fifos ? "dedicated" : "shared",
4670                  hsotg->fifo_mem);
4671         return 0;
4672 }
4673
4674 /**
4675  * dwc2_hsotg_dump - dump state of the udc
4676  * @hsotg: Programming view of the DWC_otg controller
4677  *
4678  */
4679 static void dwc2_hsotg_dump(struct dwc2_hsotg *hsotg)
4680 {
4681 #ifdef DEBUG
4682         struct device *dev = hsotg->dev;
4683         u32 val;
4684         int idx;
4685
4686         dev_info(dev, "DCFG=0x%08x, DCTL=0x%08x, DIEPMSK=%08x\n",
4687                  dwc2_readl(hsotg, DCFG), dwc2_readl(hsotg, DCTL),
4688                  dwc2_readl(hsotg, DIEPMSK));
4689
4690         dev_info(dev, "GAHBCFG=0x%08x, GHWCFG1=0x%08x\n",
4691                  dwc2_readl(hsotg, GAHBCFG), dwc2_readl(hsotg, GHWCFG1));
4692
4693         dev_info(dev, "GRXFSIZ=0x%08x, GNPTXFSIZ=0x%08x\n",
4694                  dwc2_readl(hsotg, GRXFSIZ), dwc2_readl(hsotg, GNPTXFSIZ));
4695
4696         /* show periodic fifo settings */
4697
4698         for (idx = 1; idx < hsotg->num_of_eps; idx++) {
4699                 val = dwc2_readl(hsotg, DPTXFSIZN(idx));
4700                 dev_info(dev, "DPTx[%d] FSize=%d, StAddr=0x%08x\n", idx,
4701                          val >> FIFOSIZE_DEPTH_SHIFT,
4702                          val & FIFOSIZE_STARTADDR_MASK);
4703         }
4704
4705         for (idx = 0; idx < hsotg->num_of_eps; idx++) {
4706                 dev_info(dev,
4707                          "ep%d-in: EPCTL=0x%08x, SIZ=0x%08x, DMA=0x%08x\n", idx,
4708                          dwc2_readl(hsotg, DIEPCTL(idx)),
4709                          dwc2_readl(hsotg, DIEPTSIZ(idx)),
4710                          dwc2_readl(hsotg, DIEPDMA(idx)));
4711
4712                 val = dwc2_readl(hsotg, DOEPCTL(idx));
4713                 dev_info(dev,
4714                          "ep%d-out: EPCTL=0x%08x, SIZ=0x%08x, DMA=0x%08x\n",
4715                          idx, dwc2_readl(hsotg, DOEPCTL(idx)),
4716                          dwc2_readl(hsotg, DOEPTSIZ(idx)),
4717                          dwc2_readl(hsotg, DOEPDMA(idx)));
4718         }
4719
4720         dev_info(dev, "DVBUSDIS=0x%08x, DVBUSPULSE=%08x\n",
4721                  dwc2_readl(hsotg, DVBUSDIS), dwc2_readl(hsotg, DVBUSPULSE));
4722 #endif
4723 }
4724
4725 /**
4726  * dwc2_gadget_init - init function for gadget
4727  * @hsotg: Programming view of the DWC_otg controller
4728  *
4729  */
4730 int dwc2_gadget_init(struct dwc2_hsotg *hsotg)
4731 {
4732         struct device *dev = hsotg->dev;
4733         int epnum;
4734         int ret;
4735
4736         /* Dump fifo information */
4737         dev_dbg(dev, "NonPeriodic TXFIFO size: %d\n",
4738                 hsotg->params.g_np_tx_fifo_size);
4739         dev_dbg(dev, "RXFIFO size: %d\n", hsotg->params.g_rx_fifo_size);
4740
4741         hsotg->gadget.max_speed = USB_SPEED_HIGH;
4742         hsotg->gadget.ops = &dwc2_hsotg_gadget_ops;
4743         hsotg->gadget.name = dev_name(dev);
4744         hsotg->remote_wakeup_allowed = 0;
4745
4746         if (hsotg->params.lpm)
4747                 hsotg->gadget.lpm_capable = true;
4748
4749         if (hsotg->dr_mode == USB_DR_MODE_OTG)
4750                 hsotg->gadget.is_otg = 1;
4751         else if (hsotg->dr_mode == USB_DR_MODE_PERIPHERAL)
4752                 hsotg->op_state = OTG_STATE_B_PERIPHERAL;
4753
4754         ret = dwc2_hsotg_hw_cfg(hsotg);
4755         if (ret) {
4756                 dev_err(hsotg->dev, "Hardware configuration failed: %d\n", ret);
4757                 return ret;
4758         }
4759
4760         hsotg->ctrl_buff = devm_kzalloc(hsotg->dev,
4761                         DWC2_CTRL_BUFF_SIZE, GFP_KERNEL);
4762         if (!hsotg->ctrl_buff)
4763                 return -ENOMEM;
4764
4765         hsotg->ep0_buff = devm_kzalloc(hsotg->dev,
4766                         DWC2_CTRL_BUFF_SIZE, GFP_KERNEL);
4767         if (!hsotg->ep0_buff)
4768                 return -ENOMEM;
4769
4770         if (using_desc_dma(hsotg)) {
4771                 ret = dwc2_gadget_alloc_ctrl_desc_chains(hsotg);
4772                 if (ret < 0)
4773                         return ret;
4774         }
4775
4776         ret = devm_request_irq(hsotg->dev, hsotg->irq, dwc2_hsotg_irq,
4777                                IRQF_SHARED, dev_name(hsotg->dev), hsotg);
4778         if (ret < 0) {
4779                 dev_err(dev, "cannot claim IRQ for gadget\n");
4780                 return ret;
4781         }
4782
4783         /* hsotg->num_of_eps holds number of EPs other than ep0 */
4784
4785         if (hsotg->num_of_eps == 0) {
4786                 dev_err(dev, "wrong number of EPs (zero)\n");
4787                 return -EINVAL;
4788         }
4789
4790         /* setup endpoint information */
4791
4792         INIT_LIST_HEAD(&hsotg->gadget.ep_list);
4793         hsotg->gadget.ep0 = &hsotg->eps_out[0]->ep;
4794
4795         /* allocate EP0 request */
4796
4797         hsotg->ctrl_req = dwc2_hsotg_ep_alloc_request(&hsotg->eps_out[0]->ep,
4798                                                      GFP_KERNEL);
4799         if (!hsotg->ctrl_req) {
4800                 dev_err(dev, "failed to allocate ctrl req\n");
4801                 return -ENOMEM;
4802         }
4803
4804         /* initialise the endpoints now the core has been initialised */
4805         for (epnum = 0; epnum < hsotg->num_of_eps; epnum++) {
4806                 if (hsotg->eps_in[epnum])
4807                         dwc2_hsotg_initep(hsotg, hsotg->eps_in[epnum],
4808                                           epnum, 1);
4809                 if (hsotg->eps_out[epnum])
4810                         dwc2_hsotg_initep(hsotg, hsotg->eps_out[epnum],
4811                                           epnum, 0);
4812         }
4813
4814         ret = usb_add_gadget_udc(dev, &hsotg->gadget);
4815         if (ret) {
4816                 dwc2_hsotg_ep_free_request(&hsotg->eps_out[0]->ep,
4817                                            hsotg->ctrl_req);
4818                 return ret;
4819         }
4820         dwc2_hsotg_dump(hsotg);
4821
4822         return 0;
4823 }
4824
4825 /**
4826  * dwc2_hsotg_remove - remove function for hsotg driver
4827  * @hsotg: Programming view of the DWC_otg controller
4828  *
4829  */
4830 int dwc2_hsotg_remove(struct dwc2_hsotg *hsotg)
4831 {
4832         usb_del_gadget_udc(&hsotg->gadget);
4833         dwc2_hsotg_ep_free_request(&hsotg->eps_out[0]->ep, hsotg->ctrl_req);
4834
4835         return 0;
4836 }
4837
4838 int dwc2_hsotg_suspend(struct dwc2_hsotg *hsotg)
4839 {
4840         unsigned long flags;
4841
4842         if (hsotg->lx_state != DWC2_L0)
4843                 return 0;
4844
4845         if (hsotg->driver) {
4846                 int ep;
4847
4848                 dev_info(hsotg->dev, "suspending usb gadget %s\n",
4849                          hsotg->driver->driver.name);
4850
4851                 spin_lock_irqsave(&hsotg->lock, flags);
4852                 if (hsotg->enabled)
4853                         dwc2_hsotg_core_disconnect(hsotg);
4854                 dwc2_hsotg_disconnect(hsotg);
4855                 hsotg->gadget.speed = USB_SPEED_UNKNOWN;
4856                 spin_unlock_irqrestore(&hsotg->lock, flags);
4857
4858                 for (ep = 0; ep < hsotg->num_of_eps; ep++) {
4859                         if (hsotg->eps_in[ep])
4860                                 dwc2_hsotg_ep_disable(&hsotg->eps_in[ep]->ep);
4861                         if (hsotg->eps_out[ep])
4862                                 dwc2_hsotg_ep_disable(&hsotg->eps_out[ep]->ep);
4863                 }
4864         }
4865
4866         return 0;
4867 }
4868
4869 int dwc2_hsotg_resume(struct dwc2_hsotg *hsotg)
4870 {
4871         unsigned long flags;
4872
4873         if (hsotg->lx_state == DWC2_L2)
4874                 return 0;
4875
4876         if (hsotg->driver) {
4877                 dev_info(hsotg->dev, "resuming usb gadget %s\n",
4878                          hsotg->driver->driver.name);
4879
4880                 spin_lock_irqsave(&hsotg->lock, flags);
4881                 dwc2_hsotg_core_init_disconnected(hsotg, false);
4882                 if (hsotg->enabled) {
4883                         /* Enable ACG feature in device mode,if supported */
4884                         dwc2_enable_acg(hsotg);
4885                         dwc2_hsotg_core_connect(hsotg);
4886                 }
4887                 spin_unlock_irqrestore(&hsotg->lock, flags);
4888         }
4889
4890         return 0;
4891 }
4892
4893 /**
4894  * dwc2_backup_device_registers() - Backup controller device registers.
4895  * When suspending usb bus, registers needs to be backuped
4896  * if controller power is disabled once suspended.
4897  *
4898  * @hsotg: Programming view of the DWC_otg controller
4899  */
4900 int dwc2_backup_device_registers(struct dwc2_hsotg *hsotg)
4901 {
4902         struct dwc2_dregs_backup *dr;
4903         int i;
4904
4905         dev_dbg(hsotg->dev, "%s\n", __func__);
4906
4907         /* Backup dev regs */
4908         dr = &hsotg->dr_backup;
4909
4910         dr->dcfg = dwc2_readl(hsotg, DCFG);
4911         dr->dctl = dwc2_readl(hsotg, DCTL);
4912         dr->daintmsk = dwc2_readl(hsotg, DAINTMSK);
4913         dr->diepmsk = dwc2_readl(hsotg, DIEPMSK);
4914         dr->doepmsk = dwc2_readl(hsotg, DOEPMSK);
4915
4916         for (i = 0; i < hsotg->num_of_eps; i++) {
4917                 /* Backup IN EPs */
4918                 dr->diepctl[i] = dwc2_readl(hsotg, DIEPCTL(i));
4919
4920                 /* Ensure DATA PID is correctly configured */
4921                 if (dr->diepctl[i] & DXEPCTL_DPID)
4922                         dr->diepctl[i] |= DXEPCTL_SETD1PID;
4923                 else
4924                         dr->diepctl[i] |= DXEPCTL_SETD0PID;
4925
4926                 dr->dieptsiz[i] = dwc2_readl(hsotg, DIEPTSIZ(i));
4927                 dr->diepdma[i] = dwc2_readl(hsotg, DIEPDMA(i));
4928
4929                 /* Backup OUT EPs */
4930                 dr->doepctl[i] = dwc2_readl(hsotg, DOEPCTL(i));
4931
4932                 /* Ensure DATA PID is correctly configured */
4933                 if (dr->doepctl[i] & DXEPCTL_DPID)
4934                         dr->doepctl[i] |= DXEPCTL_SETD1PID;
4935                 else
4936                         dr->doepctl[i] |= DXEPCTL_SETD0PID;
4937
4938                 dr->doeptsiz[i] = dwc2_readl(hsotg, DOEPTSIZ(i));
4939                 dr->doepdma[i] = dwc2_readl(hsotg, DOEPDMA(i));
4940                 dr->dtxfsiz[i] = dwc2_readl(hsotg, DPTXFSIZN(i));
4941         }
4942         dr->valid = true;
4943         return 0;
4944 }
4945
4946 /**
4947  * dwc2_restore_device_registers() - Restore controller device registers.
4948  * When resuming usb bus, device registers needs to be restored
4949  * if controller power were disabled.
4950  *
4951  * @hsotg: Programming view of the DWC_otg controller
4952  * @remote_wakeup: Indicates whether resume is initiated by Device or Host.
4953  *
4954  * Return: 0 if successful, negative error code otherwise
4955  */
4956 int dwc2_restore_device_registers(struct dwc2_hsotg *hsotg, int remote_wakeup)
4957 {
4958         struct dwc2_dregs_backup *dr;
4959         int i;
4960
4961         dev_dbg(hsotg->dev, "%s\n", __func__);
4962
4963         /* Restore dev regs */
4964         dr = &hsotg->dr_backup;
4965         if (!dr->valid) {
4966                 dev_err(hsotg->dev, "%s: no device registers to restore\n",
4967                         __func__);
4968                 return -EINVAL;
4969         }
4970         dr->valid = false;
4971
4972         if (!remote_wakeup)
4973                 dwc2_writel(hsotg, dr->dctl, DCTL);
4974
4975         dwc2_writel(hsotg, dr->daintmsk, DAINTMSK);
4976         dwc2_writel(hsotg, dr->diepmsk, DIEPMSK);
4977         dwc2_writel(hsotg, dr->doepmsk, DOEPMSK);
4978
4979         for (i = 0; i < hsotg->num_of_eps; i++) {
4980                 /* Restore IN EPs */
4981                 dwc2_writel(hsotg, dr->dieptsiz[i], DIEPTSIZ(i));
4982                 dwc2_writel(hsotg, dr->diepdma[i], DIEPDMA(i));
4983                 dwc2_writel(hsotg, dr->doeptsiz[i], DOEPTSIZ(i));
4984                 /** WA for enabled EPx's IN in DDMA mode. On entering to
4985                  * hibernation wrong value read and saved from DIEPDMAx,
4986                  * as result BNA interrupt asserted on hibernation exit
4987                  * by restoring from saved area.
4988                  */
4989                 if (hsotg->params.g_dma_desc &&
4990                     (dr->diepctl[i] & DXEPCTL_EPENA))
4991                         dr->diepdma[i] = hsotg->eps_in[i]->desc_list_dma;
4992                 dwc2_writel(hsotg, dr->dtxfsiz[i], DPTXFSIZN(i));
4993                 dwc2_writel(hsotg, dr->diepctl[i], DIEPCTL(i));
4994                 /* Restore OUT EPs */
4995                 dwc2_writel(hsotg, dr->doeptsiz[i], DOEPTSIZ(i));
4996                 /* WA for enabled EPx's OUT in DDMA mode. On entering to
4997                  * hibernation wrong value read and saved from DOEPDMAx,
4998                  * as result BNA interrupt asserted on hibernation exit
4999                  * by restoring from saved area.
5000                  */
5001                 if (hsotg->params.g_dma_desc &&
5002                     (dr->doepctl[i] & DXEPCTL_EPENA))
5003                         dr->doepdma[i] = hsotg->eps_out[i]->desc_list_dma;
5004                 dwc2_writel(hsotg, dr->doepdma[i], DOEPDMA(i));
5005                 dwc2_writel(hsotg, dr->doepctl[i], DOEPCTL(i));
5006         }
5007
5008         return 0;
5009 }
5010
5011 /**
5012  * dwc2_gadget_init_lpm - Configure the core to support LPM in device mode
5013  *
5014  * @hsotg: Programming view of DWC_otg controller
5015  *
5016  */
5017 void dwc2_gadget_init_lpm(struct dwc2_hsotg *hsotg)
5018 {
5019         u32 val;
5020
5021         if (!hsotg->params.lpm)
5022                 return;
5023
5024         val = GLPMCFG_LPMCAP | GLPMCFG_APPL1RES;
5025         val |= hsotg->params.hird_threshold_en ? GLPMCFG_HIRD_THRES_EN : 0;
5026         val |= hsotg->params.lpm_clock_gating ? GLPMCFG_ENBLSLPM : 0;
5027         val |= hsotg->params.hird_threshold << GLPMCFG_HIRD_THRES_SHIFT;
5028         val |= hsotg->params.besl ? GLPMCFG_ENBESL : 0;
5029         dwc2_writel(hsotg, val, GLPMCFG);
5030         dev_dbg(hsotg->dev, "GLPMCFG=0x%08x\n", dwc2_readl(hsotg, GLPMCFG));
5031
5032         /* Unmask WKUP_ALERT Interrupt */
5033         if (hsotg->params.service_interval)
5034                 dwc2_set_bit(hsotg, GINTMSK2, GINTMSK2_WKUP_ALERT_INT_MSK);
5035 }
5036
5037 /**
5038  * dwc2_gadget_program_ref_clk - Program GREFCLK register in device mode
5039  *
5040  * @hsotg: Programming view of DWC_otg controller
5041  *
5042  */
5043 void dwc2_gadget_program_ref_clk(struct dwc2_hsotg *hsotg)
5044 {
5045         u32 val = 0;
5046
5047         val |= GREFCLK_REF_CLK_MODE;
5048         val |= hsotg->params.ref_clk_per << GREFCLK_REFCLKPER_SHIFT;
5049         val |= hsotg->params.sof_cnt_wkup_alert <<
5050                GREFCLK_SOF_CNT_WKUP_ALERT_SHIFT;
5051
5052         dwc2_writel(hsotg, val, GREFCLK);
5053         dev_dbg(hsotg->dev, "GREFCLK=0x%08x\n", dwc2_readl(hsotg, GREFCLK));
5054 }
5055
5056 /**
5057  * dwc2_gadget_enter_hibernation() - Put controller in Hibernation.
5058  *
5059  * @hsotg: Programming view of the DWC_otg controller
5060  *
5061  * Return non-zero if failed to enter to hibernation.
5062  */
5063 int dwc2_gadget_enter_hibernation(struct dwc2_hsotg *hsotg)
5064 {
5065         u32 gpwrdn;
5066         int ret = 0;
5067
5068         /* Change to L2(suspend) state */
5069         hsotg->lx_state = DWC2_L2;
5070         dev_dbg(hsotg->dev, "Start of hibernation completed\n");
5071         ret = dwc2_backup_global_registers(hsotg);
5072         if (ret) {
5073                 dev_err(hsotg->dev, "%s: failed to backup global registers\n",
5074                         __func__);
5075                 return ret;
5076         }
5077         ret = dwc2_backup_device_registers(hsotg);
5078         if (ret) {
5079                 dev_err(hsotg->dev, "%s: failed to backup device registers\n",
5080                         __func__);
5081                 return ret;
5082         }
5083
5084         gpwrdn = GPWRDN_PWRDNRSTN;
5085         gpwrdn |= GPWRDN_PMUACTV;
5086         dwc2_writel(hsotg, gpwrdn, GPWRDN);
5087         udelay(10);
5088
5089         /* Set flag to indicate that we are in hibernation */
5090         hsotg->hibernated = 1;
5091
5092         /* Enable interrupts from wake up logic */
5093         gpwrdn = dwc2_readl(hsotg, GPWRDN);
5094         gpwrdn |= GPWRDN_PMUINTSEL;
5095         dwc2_writel(hsotg, gpwrdn, GPWRDN);
5096         udelay(10);
5097
5098         /* Unmask device mode interrupts in GPWRDN */
5099         gpwrdn = dwc2_readl(hsotg, GPWRDN);
5100         gpwrdn |= GPWRDN_RST_DET_MSK;
5101         gpwrdn |= GPWRDN_LNSTSCHG_MSK;
5102         gpwrdn |= GPWRDN_STS_CHGINT_MSK;
5103         dwc2_writel(hsotg, gpwrdn, GPWRDN);
5104         udelay(10);
5105
5106         /* Enable Power Down Clamp */
5107         gpwrdn = dwc2_readl(hsotg, GPWRDN);
5108         gpwrdn |= GPWRDN_PWRDNCLMP;
5109         dwc2_writel(hsotg, gpwrdn, GPWRDN);
5110         udelay(10);
5111
5112         /* Switch off VDD */
5113         gpwrdn = dwc2_readl(hsotg, GPWRDN);
5114         gpwrdn |= GPWRDN_PWRDNSWTCH;
5115         dwc2_writel(hsotg, gpwrdn, GPWRDN);
5116         udelay(10);
5117
5118         /* Save gpwrdn register for further usage if stschng interrupt */
5119         hsotg->gr_backup.gpwrdn = dwc2_readl(hsotg, GPWRDN);
5120         dev_dbg(hsotg->dev, "Hibernation completed\n");
5121
5122         return ret;
5123 }
5124
5125 /**
5126  * dwc2_gadget_exit_hibernation()
5127  * This function is for exiting from Device mode hibernation by host initiated
5128  * resume/reset and device initiated remote-wakeup.
5129  *
5130  * @hsotg: Programming view of the DWC_otg controller
5131  * @rem_wakeup: indicates whether resume is initiated by Device or Host.
5132  * @reset: indicates whether resume is initiated by Reset.
5133  *
5134  * Return non-zero if failed to exit from hibernation.
5135  */
5136 int dwc2_gadget_exit_hibernation(struct dwc2_hsotg *hsotg,
5137                                  int rem_wakeup, int reset)
5138 {
5139         u32 pcgcctl;
5140         u32 gpwrdn;
5141         u32 dctl;
5142         int ret = 0;
5143         struct dwc2_gregs_backup *gr;
5144         struct dwc2_dregs_backup *dr;
5145
5146         gr = &hsotg->gr_backup;
5147         dr = &hsotg->dr_backup;
5148
5149         if (!hsotg->hibernated) {
5150                 dev_dbg(hsotg->dev, "Already exited from Hibernation\n");
5151                 return 1;
5152         }
5153         dev_dbg(hsotg->dev,
5154                 "%s: called with rem_wakeup = %d reset = %d\n",
5155                 __func__, rem_wakeup, reset);
5156
5157         dwc2_hib_restore_common(hsotg, rem_wakeup, 0);
5158
5159         if (!reset) {
5160                 /* Clear all pending interupts */
5161                 dwc2_writel(hsotg, 0xffffffff, GINTSTS);
5162         }
5163
5164         /* De-assert Restore */
5165         gpwrdn = dwc2_readl(hsotg, GPWRDN);
5166         gpwrdn &= ~GPWRDN_RESTORE;
5167         dwc2_writel(hsotg, gpwrdn, GPWRDN);
5168         udelay(10);
5169
5170         if (!rem_wakeup) {
5171                 pcgcctl = dwc2_readl(hsotg, PCGCTL);
5172                 pcgcctl &= ~PCGCTL_RSTPDWNMODULE;
5173                 dwc2_writel(hsotg, pcgcctl, PCGCTL);
5174         }
5175
5176         /* Restore GUSBCFG, DCFG and DCTL */
5177         dwc2_writel(hsotg, gr->gusbcfg, GUSBCFG);
5178         dwc2_writel(hsotg, dr->dcfg, DCFG);
5179         dwc2_writel(hsotg, dr->dctl, DCTL);
5180
5181         /* De-assert Wakeup Logic */
5182         gpwrdn = dwc2_readl(hsotg, GPWRDN);
5183         gpwrdn &= ~GPWRDN_PMUACTV;
5184         dwc2_writel(hsotg, gpwrdn, GPWRDN);
5185
5186         if (rem_wakeup) {
5187                 udelay(10);
5188                 /* Start Remote Wakeup Signaling */
5189                 dwc2_writel(hsotg, dr->dctl | DCTL_RMTWKUPSIG, DCTL);
5190         } else {
5191                 udelay(50);
5192                 /* Set Device programming done bit */
5193                 dctl = dwc2_readl(hsotg, DCTL);
5194                 dctl |= DCTL_PWRONPRGDONE;
5195                 dwc2_writel(hsotg, dctl, DCTL);
5196         }
5197         /* Wait for interrupts which must be cleared */
5198         mdelay(2);
5199         /* Clear all pending interupts */
5200         dwc2_writel(hsotg, 0xffffffff, GINTSTS);
5201
5202         /* Restore global registers */
5203         ret = dwc2_restore_global_registers(hsotg);
5204         if (ret) {
5205                 dev_err(hsotg->dev, "%s: failed to restore registers\n",
5206                         __func__);
5207                 return ret;
5208         }
5209
5210         /* Restore device registers */
5211         ret = dwc2_restore_device_registers(hsotg, rem_wakeup);
5212         if (ret) {
5213                 dev_err(hsotg->dev, "%s: failed to restore device registers\n",
5214                         __func__);
5215                 return ret;
5216         }
5217
5218         if (rem_wakeup) {
5219                 mdelay(10);
5220                 dctl = dwc2_readl(hsotg, DCTL);
5221                 dctl &= ~DCTL_RMTWKUPSIG;
5222                 dwc2_writel(hsotg, dctl, DCTL);
5223         }
5224
5225         hsotg->hibernated = 0;
5226         hsotg->lx_state = DWC2_L0;
5227         dev_dbg(hsotg->dev, "Hibernation recovery completes here\n");
5228
5229         return ret;
5230 }