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