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