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