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