irqchip/qcom: Fix check for spurious interrupts
[linux-2.6-microblaze.git] / drivers / usb / dwc2 / hcd.c
1 // SPDX-License-Identifier: (GPL-2.0+ OR BSD-3-Clause)
2 /*
3  * hcd.c - DesignWare HS OTG Controller host-mode routines
4  *
5  * Copyright (C) 2004-2013 Synopsys, Inc.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions, and the following disclaimer,
12  *    without modification.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The names of the above-listed copyright holders may not be used
17  *    to endorse or promote products derived from this software without
18  *    specific prior written permission.
19  *
20  * ALTERNATIVELY, this software may be distributed under the terms of the
21  * GNU General Public License ("GPL") as published by the Free Software
22  * Foundation; either version 2 of the License, or (at your option) any
23  * later version.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
26  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
27  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37
38 /*
39  * This file contains the core HCD code, and implements the Linux hc_driver
40  * API
41  */
42 #include <linux/kernel.h>
43 #include <linux/module.h>
44 #include <linux/spinlock.h>
45 #include <linux/interrupt.h>
46 #include <linux/platform_device.h>
47 #include <linux/dma-mapping.h>
48 #include <linux/delay.h>
49 #include <linux/io.h>
50 #include <linux/slab.h>
51 #include <linux/usb.h>
52
53 #include <linux/usb/hcd.h>
54 #include <linux/usb/ch11.h>
55
56 #include "core.h"
57 #include "hcd.h"
58
59 static void dwc2_port_resume(struct dwc2_hsotg *hsotg);
60
61 /*
62  * =========================================================================
63  *  Host Core Layer Functions
64  * =========================================================================
65  */
66
67 /**
68  * dwc2_enable_common_interrupts() - Initializes the commmon interrupts,
69  * used in both device and host modes
70  *
71  * @hsotg: Programming view of the DWC_otg controller
72  */
73 static void dwc2_enable_common_interrupts(struct dwc2_hsotg *hsotg)
74 {
75         u32 intmsk;
76
77         /* Clear any pending OTG Interrupts */
78         dwc2_writel(0xffffffff, hsotg->regs + GOTGINT);
79
80         /* Clear any pending interrupts */
81         dwc2_writel(0xffffffff, hsotg->regs + GINTSTS);
82
83         /* Enable the interrupts in the GINTMSK */
84         intmsk = GINTSTS_MODEMIS | GINTSTS_OTGINT;
85
86         if (!hsotg->params.host_dma)
87                 intmsk |= GINTSTS_RXFLVL;
88         if (!hsotg->params.external_id_pin_ctl)
89                 intmsk |= GINTSTS_CONIDSTSCHNG;
90
91         intmsk |= GINTSTS_WKUPINT | GINTSTS_USBSUSP |
92                   GINTSTS_SESSREQINT;
93
94         if (dwc2_is_device_mode(hsotg) && hsotg->params.lpm)
95                 intmsk |= GINTSTS_LPMTRANRCVD;
96
97         dwc2_writel(intmsk, hsotg->regs + GINTMSK);
98 }
99
100 /*
101  * Initializes the FSLSPClkSel field of the HCFG register depending on the
102  * PHY type
103  */
104 static void dwc2_init_fs_ls_pclk_sel(struct dwc2_hsotg *hsotg)
105 {
106         u32 hcfg, val;
107
108         if ((hsotg->hw_params.hs_phy_type == GHWCFG2_HS_PHY_TYPE_ULPI &&
109              hsotg->hw_params.fs_phy_type == GHWCFG2_FS_PHY_TYPE_DEDICATED &&
110              hsotg->params.ulpi_fs_ls) ||
111             hsotg->params.phy_type == DWC2_PHY_TYPE_PARAM_FS) {
112                 /* Full speed PHY */
113                 val = HCFG_FSLSPCLKSEL_48_MHZ;
114         } else {
115                 /* High speed PHY running at full speed or high speed */
116                 val = HCFG_FSLSPCLKSEL_30_60_MHZ;
117         }
118
119         dev_dbg(hsotg->dev, "Initializing HCFG.FSLSPClkSel to %08x\n", val);
120         hcfg = dwc2_readl(hsotg->regs + HCFG);
121         hcfg &= ~HCFG_FSLSPCLKSEL_MASK;
122         hcfg |= val << HCFG_FSLSPCLKSEL_SHIFT;
123         dwc2_writel(hcfg, hsotg->regs + HCFG);
124 }
125
126 static int dwc2_fs_phy_init(struct dwc2_hsotg *hsotg, bool select_phy)
127 {
128         u32 usbcfg, ggpio, i2cctl;
129         int retval = 0;
130
131         /*
132          * core_init() is now called on every switch so only call the
133          * following for the first time through
134          */
135         if (select_phy) {
136                 dev_dbg(hsotg->dev, "FS PHY selected\n");
137
138                 usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
139                 if (!(usbcfg & GUSBCFG_PHYSEL)) {
140                         usbcfg |= GUSBCFG_PHYSEL;
141                         dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
142
143                         /* Reset after a PHY select */
144                         retval = dwc2_core_reset(hsotg, false);
145
146                         if (retval) {
147                                 dev_err(hsotg->dev,
148                                         "%s: Reset failed, aborting", __func__);
149                                 return retval;
150                         }
151                 }
152
153                 if (hsotg->params.activate_stm_fs_transceiver) {
154                         ggpio = dwc2_readl(hsotg->regs + GGPIO);
155                         if (!(ggpio & GGPIO_STM32_OTG_GCCFG_PWRDWN)) {
156                                 dev_dbg(hsotg->dev, "Activating transceiver\n");
157                                 /*
158                                  * STM32F4x9 uses the GGPIO register as general
159                                  * core configuration register.
160                                  */
161                                 ggpio |= GGPIO_STM32_OTG_GCCFG_PWRDWN;
162                                 dwc2_writel(ggpio, hsotg->regs + GGPIO);
163                         }
164                 }
165         }
166
167         /*
168          * Program DCFG.DevSpd or HCFG.FSLSPclkSel to 48Mhz in FS. Also
169          * do this on HNP Dev/Host mode switches (done in dev_init and
170          * host_init).
171          */
172         if (dwc2_is_host_mode(hsotg))
173                 dwc2_init_fs_ls_pclk_sel(hsotg);
174
175         if (hsotg->params.i2c_enable) {
176                 dev_dbg(hsotg->dev, "FS PHY enabling I2C\n");
177
178                 /* Program GUSBCFG.OtgUtmiFsSel to I2C */
179                 usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
180                 usbcfg |= GUSBCFG_OTG_UTMI_FS_SEL;
181                 dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
182
183                 /* Program GI2CCTL.I2CEn */
184                 i2cctl = dwc2_readl(hsotg->regs + GI2CCTL);
185                 i2cctl &= ~GI2CCTL_I2CDEVADDR_MASK;
186                 i2cctl |= 1 << GI2CCTL_I2CDEVADDR_SHIFT;
187                 i2cctl &= ~GI2CCTL_I2CEN;
188                 dwc2_writel(i2cctl, hsotg->regs + GI2CCTL);
189                 i2cctl |= GI2CCTL_I2CEN;
190                 dwc2_writel(i2cctl, hsotg->regs + GI2CCTL);
191         }
192
193         return retval;
194 }
195
196 static int dwc2_hs_phy_init(struct dwc2_hsotg *hsotg, bool select_phy)
197 {
198         u32 usbcfg, usbcfg_old;
199         int retval = 0;
200
201         if (!select_phy)
202                 return 0;
203
204         usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
205         usbcfg_old = usbcfg;
206
207         /*
208          * HS PHY parameters. These parameters are preserved during soft reset
209          * so only program the first time. Do a soft reset immediately after
210          * setting phyif.
211          */
212         switch (hsotg->params.phy_type) {
213         case DWC2_PHY_TYPE_PARAM_ULPI:
214                 /* ULPI interface */
215                 dev_dbg(hsotg->dev, "HS ULPI PHY selected\n");
216                 usbcfg |= GUSBCFG_ULPI_UTMI_SEL;
217                 usbcfg &= ~(GUSBCFG_PHYIF16 | GUSBCFG_DDRSEL);
218                 if (hsotg->params.phy_ulpi_ddr)
219                         usbcfg |= GUSBCFG_DDRSEL;
220
221                 /* Set external VBUS indicator as needed. */
222                 if (hsotg->params.oc_disable)
223                         usbcfg |= (GUSBCFG_ULPI_INT_VBUS_IND |
224                                    GUSBCFG_INDICATORPASSTHROUGH);
225                 break;
226         case DWC2_PHY_TYPE_PARAM_UTMI:
227                 /* UTMI+ interface */
228                 dev_dbg(hsotg->dev, "HS UTMI+ PHY selected\n");
229                 usbcfg &= ~(GUSBCFG_ULPI_UTMI_SEL | GUSBCFG_PHYIF16);
230                 if (hsotg->params.phy_utmi_width == 16)
231                         usbcfg |= GUSBCFG_PHYIF16;
232                 break;
233         default:
234                 dev_err(hsotg->dev, "FS PHY selected at HS!\n");
235                 break;
236         }
237
238         if (usbcfg != usbcfg_old) {
239                 dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
240
241                 /* Reset after setting the PHY parameters */
242                 retval = dwc2_core_reset(hsotg, false);
243                 if (retval) {
244                         dev_err(hsotg->dev,
245                                 "%s: Reset failed, aborting", __func__);
246                         return retval;
247                 }
248         }
249
250         return retval;
251 }
252
253 static int dwc2_phy_init(struct dwc2_hsotg *hsotg, bool select_phy)
254 {
255         u32 usbcfg;
256         int retval = 0;
257
258         if ((hsotg->params.speed == DWC2_SPEED_PARAM_FULL ||
259              hsotg->params.speed == DWC2_SPEED_PARAM_LOW) &&
260             hsotg->params.phy_type == DWC2_PHY_TYPE_PARAM_FS) {
261                 /* If FS/LS mode with FS/LS PHY */
262                 retval = dwc2_fs_phy_init(hsotg, select_phy);
263                 if (retval)
264                         return retval;
265         } else {
266                 /* High speed PHY */
267                 retval = dwc2_hs_phy_init(hsotg, select_phy);
268                 if (retval)
269                         return retval;
270         }
271
272         if (hsotg->hw_params.hs_phy_type == GHWCFG2_HS_PHY_TYPE_ULPI &&
273             hsotg->hw_params.fs_phy_type == GHWCFG2_FS_PHY_TYPE_DEDICATED &&
274             hsotg->params.ulpi_fs_ls) {
275                 dev_dbg(hsotg->dev, "Setting ULPI FSLS\n");
276                 usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
277                 usbcfg |= GUSBCFG_ULPI_FS_LS;
278                 usbcfg |= GUSBCFG_ULPI_CLK_SUSP_M;
279                 dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
280         } else {
281                 usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
282                 usbcfg &= ~GUSBCFG_ULPI_FS_LS;
283                 usbcfg &= ~GUSBCFG_ULPI_CLK_SUSP_M;
284                 dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
285         }
286
287         return retval;
288 }
289
290 static int dwc2_gahbcfg_init(struct dwc2_hsotg *hsotg)
291 {
292         u32 ahbcfg = dwc2_readl(hsotg->regs + GAHBCFG);
293
294         switch (hsotg->hw_params.arch) {
295         case GHWCFG2_EXT_DMA_ARCH:
296                 dev_err(hsotg->dev, "External DMA Mode not supported\n");
297                 return -EINVAL;
298
299         case GHWCFG2_INT_DMA_ARCH:
300                 dev_dbg(hsotg->dev, "Internal DMA Mode\n");
301                 if (hsotg->params.ahbcfg != -1) {
302                         ahbcfg &= GAHBCFG_CTRL_MASK;
303                         ahbcfg |= hsotg->params.ahbcfg &
304                                   ~GAHBCFG_CTRL_MASK;
305                 }
306                 break;
307
308         case GHWCFG2_SLAVE_ONLY_ARCH:
309         default:
310                 dev_dbg(hsotg->dev, "Slave Only Mode\n");
311                 break;
312         }
313
314         if (hsotg->params.host_dma)
315                 ahbcfg |= GAHBCFG_DMA_EN;
316         else
317                 hsotg->params.dma_desc_enable = false;
318
319         dwc2_writel(ahbcfg, hsotg->regs + GAHBCFG);
320
321         return 0;
322 }
323
324 static void dwc2_gusbcfg_init(struct dwc2_hsotg *hsotg)
325 {
326         u32 usbcfg;
327
328         usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
329         usbcfg &= ~(GUSBCFG_HNPCAP | GUSBCFG_SRPCAP);
330
331         switch (hsotg->hw_params.op_mode) {
332         case GHWCFG2_OP_MODE_HNP_SRP_CAPABLE:
333                 if (hsotg->params.otg_cap ==
334                                 DWC2_CAP_PARAM_HNP_SRP_CAPABLE)
335                         usbcfg |= GUSBCFG_HNPCAP;
336                 if (hsotg->params.otg_cap !=
337                                 DWC2_CAP_PARAM_NO_HNP_SRP_CAPABLE)
338                         usbcfg |= GUSBCFG_SRPCAP;
339                 break;
340
341         case GHWCFG2_OP_MODE_SRP_ONLY_CAPABLE:
342         case GHWCFG2_OP_MODE_SRP_CAPABLE_DEVICE:
343         case GHWCFG2_OP_MODE_SRP_CAPABLE_HOST:
344                 if (hsotg->params.otg_cap !=
345                                 DWC2_CAP_PARAM_NO_HNP_SRP_CAPABLE)
346                         usbcfg |= GUSBCFG_SRPCAP;
347                 break;
348
349         case GHWCFG2_OP_MODE_NO_HNP_SRP_CAPABLE:
350         case GHWCFG2_OP_MODE_NO_SRP_CAPABLE_DEVICE:
351         case GHWCFG2_OP_MODE_NO_SRP_CAPABLE_HOST:
352         default:
353                 break;
354         }
355
356         dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
357 }
358
359 static int dwc2_vbus_supply_init(struct dwc2_hsotg *hsotg)
360 {
361         hsotg->vbus_supply = devm_regulator_get_optional(hsotg->dev, "vbus");
362         if (IS_ERR(hsotg->vbus_supply))
363                 return 0;
364
365         return regulator_enable(hsotg->vbus_supply);
366 }
367
368 static int dwc2_vbus_supply_exit(struct dwc2_hsotg *hsotg)
369 {
370         if (hsotg->vbus_supply)
371                 return regulator_disable(hsotg->vbus_supply);
372
373         return 0;
374 }
375
376 /**
377  * dwc2_enable_host_interrupts() - Enables the Host mode interrupts
378  *
379  * @hsotg: Programming view of DWC_otg controller
380  */
381 static void dwc2_enable_host_interrupts(struct dwc2_hsotg *hsotg)
382 {
383         u32 intmsk;
384
385         dev_dbg(hsotg->dev, "%s()\n", __func__);
386
387         /* Disable all interrupts */
388         dwc2_writel(0, hsotg->regs + GINTMSK);
389         dwc2_writel(0, hsotg->regs + HAINTMSK);
390
391         /* Enable the common interrupts */
392         dwc2_enable_common_interrupts(hsotg);
393
394         /* Enable host mode interrupts without disturbing common interrupts */
395         intmsk = dwc2_readl(hsotg->regs + GINTMSK);
396         intmsk |= GINTSTS_DISCONNINT | GINTSTS_PRTINT | GINTSTS_HCHINT;
397         dwc2_writel(intmsk, hsotg->regs + GINTMSK);
398 }
399
400 /**
401  * dwc2_disable_host_interrupts() - Disables the Host Mode interrupts
402  *
403  * @hsotg: Programming view of DWC_otg controller
404  */
405 static void dwc2_disable_host_interrupts(struct dwc2_hsotg *hsotg)
406 {
407         u32 intmsk = dwc2_readl(hsotg->regs + GINTMSK);
408
409         /* Disable host mode interrupts without disturbing common interrupts */
410         intmsk &= ~(GINTSTS_SOF | GINTSTS_PRTINT | GINTSTS_HCHINT |
411                     GINTSTS_PTXFEMP | GINTSTS_NPTXFEMP | GINTSTS_DISCONNINT);
412         dwc2_writel(intmsk, hsotg->regs + GINTMSK);
413 }
414
415 /*
416  * dwc2_calculate_dynamic_fifo() - Calculates the default fifo size
417  * For system that have a total fifo depth that is smaller than the default
418  * RX + TX fifo size.
419  *
420  * @hsotg: Programming view of DWC_otg controller
421  */
422 static void dwc2_calculate_dynamic_fifo(struct dwc2_hsotg *hsotg)
423 {
424         struct dwc2_core_params *params = &hsotg->params;
425         struct dwc2_hw_params *hw = &hsotg->hw_params;
426         u32 rxfsiz, nptxfsiz, ptxfsiz, total_fifo_size;
427
428         total_fifo_size = hw->total_fifo_size;
429         rxfsiz = params->host_rx_fifo_size;
430         nptxfsiz = params->host_nperio_tx_fifo_size;
431         ptxfsiz = params->host_perio_tx_fifo_size;
432
433         /*
434          * Will use Method 2 defined in the DWC2 spec: minimum FIFO depth
435          * allocation with support for high bandwidth endpoints. Synopsys
436          * defines MPS(Max Packet size) for a periodic EP=1024, and for
437          * non-periodic as 512.
438          */
439         if (total_fifo_size < (rxfsiz + nptxfsiz + ptxfsiz)) {
440                 /*
441                  * For Buffer DMA mode/Scatter Gather DMA mode
442                  * 2 * ((Largest Packet size / 4) + 1 + 1) + n
443                  * with n = number of host channel.
444                  * 2 * ((1024/4) + 2) = 516
445                  */
446                 rxfsiz = 516 + hw->host_channels;
447
448                 /*
449                  * min non-periodic tx fifo depth
450                  * 2 * (largest non-periodic USB packet used / 4)
451                  * 2 * (512/4) = 256
452                  */
453                 nptxfsiz = 256;
454
455                 /*
456                  * min periodic tx fifo depth
457                  * (largest packet size*MC)/4
458                  * (1024 * 3)/4 = 768
459                  */
460                 ptxfsiz = 768;
461
462                 params->host_rx_fifo_size = rxfsiz;
463                 params->host_nperio_tx_fifo_size = nptxfsiz;
464                 params->host_perio_tx_fifo_size = ptxfsiz;
465         }
466
467         /*
468          * If the summation of RX, NPTX and PTX fifo sizes is still
469          * bigger than the total_fifo_size, then we have a problem.
470          *
471          * We won't be able to allocate as many endpoints. Right now,
472          * we're just printing an error message, but ideally this FIFO
473          * allocation algorithm would be improved in the future.
474          *
475          * FIXME improve this FIFO allocation algorithm.
476          */
477         if (unlikely(total_fifo_size < (rxfsiz + nptxfsiz + ptxfsiz)))
478                 dev_err(hsotg->dev, "invalid fifo sizes\n");
479 }
480
481 static void dwc2_config_fifos(struct dwc2_hsotg *hsotg)
482 {
483         struct dwc2_core_params *params = &hsotg->params;
484         u32 nptxfsiz, hptxfsiz, dfifocfg, grxfsiz;
485
486         if (!params->enable_dynamic_fifo)
487                 return;
488
489         dwc2_calculate_dynamic_fifo(hsotg);
490
491         /* Rx FIFO */
492         grxfsiz = dwc2_readl(hsotg->regs + GRXFSIZ);
493         dev_dbg(hsotg->dev, "initial grxfsiz=%08x\n", grxfsiz);
494         grxfsiz &= ~GRXFSIZ_DEPTH_MASK;
495         grxfsiz |= params->host_rx_fifo_size <<
496                    GRXFSIZ_DEPTH_SHIFT & GRXFSIZ_DEPTH_MASK;
497         dwc2_writel(grxfsiz, hsotg->regs + GRXFSIZ);
498         dev_dbg(hsotg->dev, "new grxfsiz=%08x\n",
499                 dwc2_readl(hsotg->regs + GRXFSIZ));
500
501         /* Non-periodic Tx FIFO */
502         dev_dbg(hsotg->dev, "initial gnptxfsiz=%08x\n",
503                 dwc2_readl(hsotg->regs + GNPTXFSIZ));
504         nptxfsiz = params->host_nperio_tx_fifo_size <<
505                    FIFOSIZE_DEPTH_SHIFT & FIFOSIZE_DEPTH_MASK;
506         nptxfsiz |= params->host_rx_fifo_size <<
507                     FIFOSIZE_STARTADDR_SHIFT & FIFOSIZE_STARTADDR_MASK;
508         dwc2_writel(nptxfsiz, hsotg->regs + GNPTXFSIZ);
509         dev_dbg(hsotg->dev, "new gnptxfsiz=%08x\n",
510                 dwc2_readl(hsotg->regs + GNPTXFSIZ));
511
512         /* Periodic Tx FIFO */
513         dev_dbg(hsotg->dev, "initial hptxfsiz=%08x\n",
514                 dwc2_readl(hsotg->regs + HPTXFSIZ));
515         hptxfsiz = params->host_perio_tx_fifo_size <<
516                    FIFOSIZE_DEPTH_SHIFT & FIFOSIZE_DEPTH_MASK;
517         hptxfsiz |= (params->host_rx_fifo_size +
518                      params->host_nperio_tx_fifo_size) <<
519                     FIFOSIZE_STARTADDR_SHIFT & FIFOSIZE_STARTADDR_MASK;
520         dwc2_writel(hptxfsiz, hsotg->regs + HPTXFSIZ);
521         dev_dbg(hsotg->dev, "new hptxfsiz=%08x\n",
522                 dwc2_readl(hsotg->regs + HPTXFSIZ));
523
524         if (hsotg->params.en_multiple_tx_fifo &&
525             hsotg->hw_params.snpsid >= DWC2_CORE_REV_2_91a) {
526                 /*
527                  * This feature was implemented in 2.91a version
528                  * Global DFIFOCFG calculation for Host mode -
529                  * include RxFIFO, NPTXFIFO and HPTXFIFO
530                  */
531                 dfifocfg = dwc2_readl(hsotg->regs + GDFIFOCFG);
532                 dfifocfg &= ~GDFIFOCFG_EPINFOBASE_MASK;
533                 dfifocfg |= (params->host_rx_fifo_size +
534                              params->host_nperio_tx_fifo_size +
535                              params->host_perio_tx_fifo_size) <<
536                             GDFIFOCFG_EPINFOBASE_SHIFT &
537                             GDFIFOCFG_EPINFOBASE_MASK;
538                 dwc2_writel(dfifocfg, hsotg->regs + GDFIFOCFG);
539         }
540 }
541
542 /**
543  * dwc2_calc_frame_interval() - Calculates the correct frame Interval value for
544  * the HFIR register according to PHY type and speed
545  *
546  * @hsotg: Programming view of DWC_otg controller
547  *
548  * NOTE: The caller can modify the value of the HFIR register only after the
549  * Port Enable bit of the Host Port Control and Status register (HPRT.EnaPort)
550  * has been set
551  */
552 u32 dwc2_calc_frame_interval(struct dwc2_hsotg *hsotg)
553 {
554         u32 usbcfg;
555         u32 hprt0;
556         int clock = 60; /* default value */
557
558         usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
559         hprt0 = dwc2_readl(hsotg->regs + HPRT0);
560
561         if (!(usbcfg & GUSBCFG_PHYSEL) && (usbcfg & GUSBCFG_ULPI_UTMI_SEL) &&
562             !(usbcfg & GUSBCFG_PHYIF16))
563                 clock = 60;
564         if ((usbcfg & GUSBCFG_PHYSEL) && hsotg->hw_params.fs_phy_type ==
565             GHWCFG2_FS_PHY_TYPE_SHARED_ULPI)
566                 clock = 48;
567         if (!(usbcfg & GUSBCFG_PHY_LP_CLK_SEL) && !(usbcfg & GUSBCFG_PHYSEL) &&
568             !(usbcfg & GUSBCFG_ULPI_UTMI_SEL) && (usbcfg & GUSBCFG_PHYIF16))
569                 clock = 30;
570         if (!(usbcfg & GUSBCFG_PHY_LP_CLK_SEL) && !(usbcfg & GUSBCFG_PHYSEL) &&
571             !(usbcfg & GUSBCFG_ULPI_UTMI_SEL) && !(usbcfg & GUSBCFG_PHYIF16))
572                 clock = 60;
573         if ((usbcfg & GUSBCFG_PHY_LP_CLK_SEL) && !(usbcfg & GUSBCFG_PHYSEL) &&
574             !(usbcfg & GUSBCFG_ULPI_UTMI_SEL) && (usbcfg & GUSBCFG_PHYIF16))
575                 clock = 48;
576         if ((usbcfg & GUSBCFG_PHYSEL) && !(usbcfg & GUSBCFG_PHYIF16) &&
577             hsotg->hw_params.fs_phy_type == GHWCFG2_FS_PHY_TYPE_SHARED_UTMI)
578                 clock = 48;
579         if ((usbcfg & GUSBCFG_PHYSEL) &&
580             hsotg->hw_params.fs_phy_type == GHWCFG2_FS_PHY_TYPE_DEDICATED)
581                 clock = 48;
582
583         if ((hprt0 & HPRT0_SPD_MASK) >> HPRT0_SPD_SHIFT == HPRT0_SPD_HIGH_SPEED)
584                 /* High speed case */
585                 return 125 * clock - 1;
586
587         /* FS/LS case */
588         return 1000 * clock - 1;
589 }
590
591 /**
592  * dwc2_read_packet() - Reads a packet from the Rx FIFO into the destination
593  * buffer
594  *
595  * @core_if: Programming view of DWC_otg controller
596  * @dest:    Destination buffer for the packet
597  * @bytes:   Number of bytes to copy to the destination
598  */
599 void dwc2_read_packet(struct dwc2_hsotg *hsotg, u8 *dest, u16 bytes)
600 {
601         u32 __iomem *fifo = hsotg->regs + HCFIFO(0);
602         u32 *data_buf = (u32 *)dest;
603         int word_count = (bytes + 3) / 4;
604         int i;
605
606         /*
607          * Todo: Account for the case where dest is not dword aligned. This
608          * requires reading data from the FIFO into a u32 temp buffer, then
609          * moving it into the data buffer.
610          */
611
612         dev_vdbg(hsotg->dev, "%s(%p,%p,%d)\n", __func__, hsotg, dest, bytes);
613
614         for (i = 0; i < word_count; i++, data_buf++)
615                 *data_buf = dwc2_readl(fifo);
616 }
617
618 /**
619  * dwc2_dump_channel_info() - Prints the state of a host channel
620  *
621  * @hsotg: Programming view of DWC_otg controller
622  * @chan:  Pointer to the channel to dump
623  *
624  * Must be called with interrupt disabled and spinlock held
625  *
626  * NOTE: This function will be removed once the peripheral controller code
627  * is integrated and the driver is stable
628  */
629 static void dwc2_dump_channel_info(struct dwc2_hsotg *hsotg,
630                                    struct dwc2_host_chan *chan)
631 {
632 #ifdef VERBOSE_DEBUG
633         int num_channels = hsotg->params.host_channels;
634         struct dwc2_qh *qh;
635         u32 hcchar;
636         u32 hcsplt;
637         u32 hctsiz;
638         u32 hc_dma;
639         int i;
640
641         if (!chan)
642                 return;
643
644         hcchar = dwc2_readl(hsotg->regs + HCCHAR(chan->hc_num));
645         hcsplt = dwc2_readl(hsotg->regs + HCSPLT(chan->hc_num));
646         hctsiz = dwc2_readl(hsotg->regs + HCTSIZ(chan->hc_num));
647         hc_dma = dwc2_readl(hsotg->regs + HCDMA(chan->hc_num));
648
649         dev_dbg(hsotg->dev, "  Assigned to channel %p:\n", chan);
650         dev_dbg(hsotg->dev, "    hcchar 0x%08x, hcsplt 0x%08x\n",
651                 hcchar, hcsplt);
652         dev_dbg(hsotg->dev, "    hctsiz 0x%08x, hc_dma 0x%08x\n",
653                 hctsiz, hc_dma);
654         dev_dbg(hsotg->dev, "    dev_addr: %d, ep_num: %d, ep_is_in: %d\n",
655                 chan->dev_addr, chan->ep_num, chan->ep_is_in);
656         dev_dbg(hsotg->dev, "    ep_type: %d\n", chan->ep_type);
657         dev_dbg(hsotg->dev, "    max_packet: %d\n", chan->max_packet);
658         dev_dbg(hsotg->dev, "    data_pid_start: %d\n", chan->data_pid_start);
659         dev_dbg(hsotg->dev, "    xfer_started: %d\n", chan->xfer_started);
660         dev_dbg(hsotg->dev, "    halt_status: %d\n", chan->halt_status);
661         dev_dbg(hsotg->dev, "    xfer_buf: %p\n", chan->xfer_buf);
662         dev_dbg(hsotg->dev, "    xfer_dma: %08lx\n",
663                 (unsigned long)chan->xfer_dma);
664         dev_dbg(hsotg->dev, "    xfer_len: %d\n", chan->xfer_len);
665         dev_dbg(hsotg->dev, "    qh: %p\n", chan->qh);
666         dev_dbg(hsotg->dev, "  NP inactive sched:\n");
667         list_for_each_entry(qh, &hsotg->non_periodic_sched_inactive,
668                             qh_list_entry)
669                 dev_dbg(hsotg->dev, "    %p\n", qh);
670         dev_dbg(hsotg->dev, "  NP waiting sched:\n");
671         list_for_each_entry(qh, &hsotg->non_periodic_sched_waiting,
672                             qh_list_entry)
673                 dev_dbg(hsotg->dev, "    %p\n", qh);
674         dev_dbg(hsotg->dev, "  NP active sched:\n");
675         list_for_each_entry(qh, &hsotg->non_periodic_sched_active,
676                             qh_list_entry)
677                 dev_dbg(hsotg->dev, "    %p\n", qh);
678         dev_dbg(hsotg->dev, "  Channels:\n");
679         for (i = 0; i < num_channels; i++) {
680                 struct dwc2_host_chan *chan = hsotg->hc_ptr_array[i];
681
682                 dev_dbg(hsotg->dev, "    %2d: %p\n", i, chan);
683         }
684 #endif /* VERBOSE_DEBUG */
685 }
686
687 static int _dwc2_hcd_start(struct usb_hcd *hcd);
688
689 static void dwc2_host_start(struct dwc2_hsotg *hsotg)
690 {
691         struct usb_hcd *hcd = dwc2_hsotg_to_hcd(hsotg);
692
693         hcd->self.is_b_host = dwc2_hcd_is_b_host(hsotg);
694         _dwc2_hcd_start(hcd);
695 }
696
697 static void dwc2_host_disconnect(struct dwc2_hsotg *hsotg)
698 {
699         struct usb_hcd *hcd = dwc2_hsotg_to_hcd(hsotg);
700
701         hcd->self.is_b_host = 0;
702 }
703
704 static void dwc2_host_hub_info(struct dwc2_hsotg *hsotg, void *context,
705                                int *hub_addr, int *hub_port)
706 {
707         struct urb *urb = context;
708
709         if (urb->dev->tt)
710                 *hub_addr = urb->dev->tt->hub->devnum;
711         else
712                 *hub_addr = 0;
713         *hub_port = urb->dev->ttport;
714 }
715
716 /*
717  * =========================================================================
718  *  Low Level Host Channel Access Functions
719  * =========================================================================
720  */
721
722 static void dwc2_hc_enable_slave_ints(struct dwc2_hsotg *hsotg,
723                                       struct dwc2_host_chan *chan)
724 {
725         u32 hcintmsk = HCINTMSK_CHHLTD;
726
727         switch (chan->ep_type) {
728         case USB_ENDPOINT_XFER_CONTROL:
729         case USB_ENDPOINT_XFER_BULK:
730                 dev_vdbg(hsotg->dev, "control/bulk\n");
731                 hcintmsk |= HCINTMSK_XFERCOMPL;
732                 hcintmsk |= HCINTMSK_STALL;
733                 hcintmsk |= HCINTMSK_XACTERR;
734                 hcintmsk |= HCINTMSK_DATATGLERR;
735                 if (chan->ep_is_in) {
736                         hcintmsk |= HCINTMSK_BBLERR;
737                 } else {
738                         hcintmsk |= HCINTMSK_NAK;
739                         hcintmsk |= HCINTMSK_NYET;
740                         if (chan->do_ping)
741                                 hcintmsk |= HCINTMSK_ACK;
742                 }
743
744                 if (chan->do_split) {
745                         hcintmsk |= HCINTMSK_NAK;
746                         if (chan->complete_split)
747                                 hcintmsk |= HCINTMSK_NYET;
748                         else
749                                 hcintmsk |= HCINTMSK_ACK;
750                 }
751
752                 if (chan->error_state)
753                         hcintmsk |= HCINTMSK_ACK;
754                 break;
755
756         case USB_ENDPOINT_XFER_INT:
757                 if (dbg_perio())
758                         dev_vdbg(hsotg->dev, "intr\n");
759                 hcintmsk |= HCINTMSK_XFERCOMPL;
760                 hcintmsk |= HCINTMSK_NAK;
761                 hcintmsk |= HCINTMSK_STALL;
762                 hcintmsk |= HCINTMSK_XACTERR;
763                 hcintmsk |= HCINTMSK_DATATGLERR;
764                 hcintmsk |= HCINTMSK_FRMOVRUN;
765
766                 if (chan->ep_is_in)
767                         hcintmsk |= HCINTMSK_BBLERR;
768                 if (chan->error_state)
769                         hcintmsk |= HCINTMSK_ACK;
770                 if (chan->do_split) {
771                         if (chan->complete_split)
772                                 hcintmsk |= HCINTMSK_NYET;
773                         else
774                                 hcintmsk |= HCINTMSK_ACK;
775                 }
776                 break;
777
778         case USB_ENDPOINT_XFER_ISOC:
779                 if (dbg_perio())
780                         dev_vdbg(hsotg->dev, "isoc\n");
781                 hcintmsk |= HCINTMSK_XFERCOMPL;
782                 hcintmsk |= HCINTMSK_FRMOVRUN;
783                 hcintmsk |= HCINTMSK_ACK;
784
785                 if (chan->ep_is_in) {
786                         hcintmsk |= HCINTMSK_XACTERR;
787                         hcintmsk |= HCINTMSK_BBLERR;
788                 }
789                 break;
790         default:
791                 dev_err(hsotg->dev, "## Unknown EP type ##\n");
792                 break;
793         }
794
795         dwc2_writel(hcintmsk, hsotg->regs + HCINTMSK(chan->hc_num));
796         if (dbg_hc(chan))
797                 dev_vdbg(hsotg->dev, "set HCINTMSK to %08x\n", hcintmsk);
798 }
799
800 static void dwc2_hc_enable_dma_ints(struct dwc2_hsotg *hsotg,
801                                     struct dwc2_host_chan *chan)
802 {
803         u32 hcintmsk = HCINTMSK_CHHLTD;
804
805         /*
806          * For Descriptor DMA mode core halts the channel on AHB error.
807          * Interrupt is not required.
808          */
809         if (!hsotg->params.dma_desc_enable) {
810                 if (dbg_hc(chan))
811                         dev_vdbg(hsotg->dev, "desc DMA disabled\n");
812                 hcintmsk |= HCINTMSK_AHBERR;
813         } else {
814                 if (dbg_hc(chan))
815                         dev_vdbg(hsotg->dev, "desc DMA enabled\n");
816                 if (chan->ep_type == USB_ENDPOINT_XFER_ISOC)
817                         hcintmsk |= HCINTMSK_XFERCOMPL;
818         }
819
820         if (chan->error_state && !chan->do_split &&
821             chan->ep_type != USB_ENDPOINT_XFER_ISOC) {
822                 if (dbg_hc(chan))
823                         dev_vdbg(hsotg->dev, "setting ACK\n");
824                 hcintmsk |= HCINTMSK_ACK;
825                 if (chan->ep_is_in) {
826                         hcintmsk |= HCINTMSK_DATATGLERR;
827                         if (chan->ep_type != USB_ENDPOINT_XFER_INT)
828                                 hcintmsk |= HCINTMSK_NAK;
829                 }
830         }
831
832         dwc2_writel(hcintmsk, hsotg->regs + HCINTMSK(chan->hc_num));
833         if (dbg_hc(chan))
834                 dev_vdbg(hsotg->dev, "set HCINTMSK to %08x\n", hcintmsk);
835 }
836
837 static void dwc2_hc_enable_ints(struct dwc2_hsotg *hsotg,
838                                 struct dwc2_host_chan *chan)
839 {
840         u32 intmsk;
841
842         if (hsotg->params.host_dma) {
843                 if (dbg_hc(chan))
844                         dev_vdbg(hsotg->dev, "DMA enabled\n");
845                 dwc2_hc_enable_dma_ints(hsotg, chan);
846         } else {
847                 if (dbg_hc(chan))
848                         dev_vdbg(hsotg->dev, "DMA disabled\n");
849                 dwc2_hc_enable_slave_ints(hsotg, chan);
850         }
851
852         /* Enable the top level host channel interrupt */
853         intmsk = dwc2_readl(hsotg->regs + HAINTMSK);
854         intmsk |= 1 << chan->hc_num;
855         dwc2_writel(intmsk, hsotg->regs + HAINTMSK);
856         if (dbg_hc(chan))
857                 dev_vdbg(hsotg->dev, "set HAINTMSK to %08x\n", intmsk);
858
859         /* Make sure host channel interrupts are enabled */
860         intmsk = dwc2_readl(hsotg->regs + GINTMSK);
861         intmsk |= GINTSTS_HCHINT;
862         dwc2_writel(intmsk, hsotg->regs + GINTMSK);
863         if (dbg_hc(chan))
864                 dev_vdbg(hsotg->dev, "set GINTMSK to %08x\n", intmsk);
865 }
866
867 /**
868  * dwc2_hc_init() - Prepares a host channel for transferring packets to/from
869  * a specific endpoint
870  *
871  * @hsotg: Programming view of DWC_otg controller
872  * @chan:  Information needed to initialize the host channel
873  *
874  * The HCCHARn register is set up with the characteristics specified in chan.
875  * Host channel interrupts that may need to be serviced while this transfer is
876  * in progress are enabled.
877  */
878 static void dwc2_hc_init(struct dwc2_hsotg *hsotg, struct dwc2_host_chan *chan)
879 {
880         u8 hc_num = chan->hc_num;
881         u32 hcintmsk;
882         u32 hcchar;
883         u32 hcsplt = 0;
884
885         if (dbg_hc(chan))
886                 dev_vdbg(hsotg->dev, "%s()\n", __func__);
887
888         /* Clear old interrupt conditions for this host channel */
889         hcintmsk = 0xffffffff;
890         hcintmsk &= ~HCINTMSK_RESERVED14_31;
891         dwc2_writel(hcintmsk, hsotg->regs + HCINT(hc_num));
892
893         /* Enable channel interrupts required for this transfer */
894         dwc2_hc_enable_ints(hsotg, chan);
895
896         /*
897          * Program the HCCHARn register with the endpoint characteristics for
898          * the current transfer
899          */
900         hcchar = chan->dev_addr << HCCHAR_DEVADDR_SHIFT & HCCHAR_DEVADDR_MASK;
901         hcchar |= chan->ep_num << HCCHAR_EPNUM_SHIFT & HCCHAR_EPNUM_MASK;
902         if (chan->ep_is_in)
903                 hcchar |= HCCHAR_EPDIR;
904         if (chan->speed == USB_SPEED_LOW)
905                 hcchar |= HCCHAR_LSPDDEV;
906         hcchar |= chan->ep_type << HCCHAR_EPTYPE_SHIFT & HCCHAR_EPTYPE_MASK;
907         hcchar |= chan->max_packet << HCCHAR_MPS_SHIFT & HCCHAR_MPS_MASK;
908         dwc2_writel(hcchar, hsotg->regs + HCCHAR(hc_num));
909         if (dbg_hc(chan)) {
910                 dev_vdbg(hsotg->dev, "set HCCHAR(%d) to %08x\n",
911                          hc_num, hcchar);
912
913                 dev_vdbg(hsotg->dev, "%s: Channel %d\n",
914                          __func__, hc_num);
915                 dev_vdbg(hsotg->dev, "   Dev Addr: %d\n",
916                          chan->dev_addr);
917                 dev_vdbg(hsotg->dev, "   Ep Num: %d\n",
918                          chan->ep_num);
919                 dev_vdbg(hsotg->dev, "   Is In: %d\n",
920                          chan->ep_is_in);
921                 dev_vdbg(hsotg->dev, "   Is Low Speed: %d\n",
922                          chan->speed == USB_SPEED_LOW);
923                 dev_vdbg(hsotg->dev, "   Ep Type: %d\n",
924                          chan->ep_type);
925                 dev_vdbg(hsotg->dev, "   Max Pkt: %d\n",
926                          chan->max_packet);
927         }
928
929         /* Program the HCSPLT register for SPLITs */
930         if (chan->do_split) {
931                 if (dbg_hc(chan))
932                         dev_vdbg(hsotg->dev,
933                                  "Programming HC %d with split --> %s\n",
934                                  hc_num,
935                                  chan->complete_split ? "CSPLIT" : "SSPLIT");
936                 if (chan->complete_split)
937                         hcsplt |= HCSPLT_COMPSPLT;
938                 hcsplt |= chan->xact_pos << HCSPLT_XACTPOS_SHIFT &
939                           HCSPLT_XACTPOS_MASK;
940                 hcsplt |= chan->hub_addr << HCSPLT_HUBADDR_SHIFT &
941                           HCSPLT_HUBADDR_MASK;
942                 hcsplt |= chan->hub_port << HCSPLT_PRTADDR_SHIFT &
943                           HCSPLT_PRTADDR_MASK;
944                 if (dbg_hc(chan)) {
945                         dev_vdbg(hsotg->dev, "    comp split %d\n",
946                                  chan->complete_split);
947                         dev_vdbg(hsotg->dev, "    xact pos %d\n",
948                                  chan->xact_pos);
949                         dev_vdbg(hsotg->dev, "    hub addr %d\n",
950                                  chan->hub_addr);
951                         dev_vdbg(hsotg->dev, "    hub port %d\n",
952                                  chan->hub_port);
953                         dev_vdbg(hsotg->dev, "    is_in %d\n",
954                                  chan->ep_is_in);
955                         dev_vdbg(hsotg->dev, "    Max Pkt %d\n",
956                                  chan->max_packet);
957                         dev_vdbg(hsotg->dev, "    xferlen %d\n",
958                                  chan->xfer_len);
959                 }
960         }
961
962         dwc2_writel(hcsplt, hsotg->regs + HCSPLT(hc_num));
963 }
964
965 /**
966  * dwc2_hc_halt() - Attempts to halt a host channel
967  *
968  * @hsotg:       Controller register interface
969  * @chan:        Host channel to halt
970  * @halt_status: Reason for halting the channel
971  *
972  * This function should only be called in Slave mode or to abort a transfer in
973  * either Slave mode or DMA mode. Under normal circumstances in DMA mode, the
974  * controller halts the channel when the transfer is complete or a condition
975  * occurs that requires application intervention.
976  *
977  * In slave mode, checks for a free request queue entry, then sets the Channel
978  * Enable and Channel Disable bits of the Host Channel Characteristics
979  * register of the specified channel to intiate the halt. If there is no free
980  * request queue entry, sets only the Channel Disable bit of the HCCHARn
981  * register to flush requests for this channel. In the latter case, sets a
982  * flag to indicate that the host channel needs to be halted when a request
983  * queue slot is open.
984  *
985  * In DMA mode, always sets the Channel Enable and Channel Disable bits of the
986  * HCCHARn register. The controller ensures there is space in the request
987  * queue before submitting the halt request.
988  *
989  * Some time may elapse before the core flushes any posted requests for this
990  * host channel and halts. The Channel Halted interrupt handler completes the
991  * deactivation of the host channel.
992  */
993 void dwc2_hc_halt(struct dwc2_hsotg *hsotg, struct dwc2_host_chan *chan,
994                   enum dwc2_halt_status halt_status)
995 {
996         u32 nptxsts, hptxsts, hcchar;
997
998         if (dbg_hc(chan))
999                 dev_vdbg(hsotg->dev, "%s()\n", __func__);
1000
1001         /*
1002          * In buffer DMA or external DMA mode channel can't be halted
1003          * for non-split periodic channels. At the end of the next
1004          * uframe/frame (in the worst case), the core generates a channel
1005          * halted and disables the channel automatically.
1006          */
1007         if ((hsotg->params.g_dma && !hsotg->params.g_dma_desc) ||
1008             hsotg->hw_params.arch == GHWCFG2_EXT_DMA_ARCH) {
1009                 if (!chan->do_split &&
1010                     (chan->ep_type == USB_ENDPOINT_XFER_ISOC ||
1011                      chan->ep_type == USB_ENDPOINT_XFER_INT)) {
1012                         dev_err(hsotg->dev, "%s() Channel can't be halted\n",
1013                                 __func__);
1014                         return;
1015                 }
1016         }
1017
1018         if (halt_status == DWC2_HC_XFER_NO_HALT_STATUS)
1019                 dev_err(hsotg->dev, "!!! halt_status = %d !!!\n", halt_status);
1020
1021         if (halt_status == DWC2_HC_XFER_URB_DEQUEUE ||
1022             halt_status == DWC2_HC_XFER_AHB_ERR) {
1023                 /*
1024                  * Disable all channel interrupts except Ch Halted. The QTD
1025                  * and QH state associated with this transfer has been cleared
1026                  * (in the case of URB_DEQUEUE), so the channel needs to be
1027                  * shut down carefully to prevent crashes.
1028                  */
1029                 u32 hcintmsk = HCINTMSK_CHHLTD;
1030
1031                 dev_vdbg(hsotg->dev, "dequeue/error\n");
1032                 dwc2_writel(hcintmsk, hsotg->regs + HCINTMSK(chan->hc_num));
1033
1034                 /*
1035                  * Make sure no other interrupts besides halt are currently
1036                  * pending. Handling another interrupt could cause a crash due
1037                  * to the QTD and QH state.
1038                  */
1039                 dwc2_writel(~hcintmsk, hsotg->regs + HCINT(chan->hc_num));
1040
1041                 /*
1042                  * Make sure the halt status is set to URB_DEQUEUE or AHB_ERR
1043                  * even if the channel was already halted for some other
1044                  * reason
1045                  */
1046                 chan->halt_status = halt_status;
1047
1048                 hcchar = dwc2_readl(hsotg->regs + HCCHAR(chan->hc_num));
1049                 if (!(hcchar & HCCHAR_CHENA)) {
1050                         /*
1051                          * The channel is either already halted or it hasn't
1052                          * started yet. In DMA mode, the transfer may halt if
1053                          * it finishes normally or a condition occurs that
1054                          * requires driver intervention. Don't want to halt
1055                          * the channel again. In either Slave or DMA mode,
1056                          * it's possible that the transfer has been assigned
1057                          * to a channel, but not started yet when an URB is
1058                          * dequeued. Don't want to halt a channel that hasn't
1059                          * started yet.
1060                          */
1061                         return;
1062                 }
1063         }
1064         if (chan->halt_pending) {
1065                 /*
1066                  * A halt has already been issued for this channel. This might
1067                  * happen when a transfer is aborted by a higher level in
1068                  * the stack.
1069                  */
1070                 dev_vdbg(hsotg->dev,
1071                          "*** %s: Channel %d, chan->halt_pending already set ***\n",
1072                          __func__, chan->hc_num);
1073                 return;
1074         }
1075
1076         hcchar = dwc2_readl(hsotg->regs + HCCHAR(chan->hc_num));
1077
1078         /* No need to set the bit in DDMA for disabling the channel */
1079         /* TODO check it everywhere channel is disabled */
1080         if (!hsotg->params.dma_desc_enable) {
1081                 if (dbg_hc(chan))
1082                         dev_vdbg(hsotg->dev, "desc DMA disabled\n");
1083                 hcchar |= HCCHAR_CHENA;
1084         } else {
1085                 if (dbg_hc(chan))
1086                         dev_dbg(hsotg->dev, "desc DMA enabled\n");
1087         }
1088         hcchar |= HCCHAR_CHDIS;
1089
1090         if (!hsotg->params.host_dma) {
1091                 if (dbg_hc(chan))
1092                         dev_vdbg(hsotg->dev, "DMA not enabled\n");
1093                 hcchar |= HCCHAR_CHENA;
1094
1095                 /* Check for space in the request queue to issue the halt */
1096                 if (chan->ep_type == USB_ENDPOINT_XFER_CONTROL ||
1097                     chan->ep_type == USB_ENDPOINT_XFER_BULK) {
1098                         dev_vdbg(hsotg->dev, "control/bulk\n");
1099                         nptxsts = dwc2_readl(hsotg->regs + GNPTXSTS);
1100                         if ((nptxsts & TXSTS_QSPCAVAIL_MASK) == 0) {
1101                                 dev_vdbg(hsotg->dev, "Disabling channel\n");
1102                                 hcchar &= ~HCCHAR_CHENA;
1103                         }
1104                 } else {
1105                         if (dbg_perio())
1106                                 dev_vdbg(hsotg->dev, "isoc/intr\n");
1107                         hptxsts = dwc2_readl(hsotg->regs + HPTXSTS);
1108                         if ((hptxsts & TXSTS_QSPCAVAIL_MASK) == 0 ||
1109                             hsotg->queuing_high_bandwidth) {
1110                                 if (dbg_perio())
1111                                         dev_vdbg(hsotg->dev, "Disabling channel\n");
1112                                 hcchar &= ~HCCHAR_CHENA;
1113                         }
1114                 }
1115         } else {
1116                 if (dbg_hc(chan))
1117                         dev_vdbg(hsotg->dev, "DMA enabled\n");
1118         }
1119
1120         dwc2_writel(hcchar, hsotg->regs + HCCHAR(chan->hc_num));
1121         chan->halt_status = halt_status;
1122
1123         if (hcchar & HCCHAR_CHENA) {
1124                 if (dbg_hc(chan))
1125                         dev_vdbg(hsotg->dev, "Channel enabled\n");
1126                 chan->halt_pending = 1;
1127                 chan->halt_on_queue = 0;
1128         } else {
1129                 if (dbg_hc(chan))
1130                         dev_vdbg(hsotg->dev, "Channel disabled\n");
1131                 chan->halt_on_queue = 1;
1132         }
1133
1134         if (dbg_hc(chan)) {
1135                 dev_vdbg(hsotg->dev, "%s: Channel %d\n", __func__,
1136                          chan->hc_num);
1137                 dev_vdbg(hsotg->dev, "   hcchar: 0x%08x\n",
1138                          hcchar);
1139                 dev_vdbg(hsotg->dev, "   halt_pending: %d\n",
1140                          chan->halt_pending);
1141                 dev_vdbg(hsotg->dev, "   halt_on_queue: %d\n",
1142                          chan->halt_on_queue);
1143                 dev_vdbg(hsotg->dev, "   halt_status: %d\n",
1144                          chan->halt_status);
1145         }
1146 }
1147
1148 /**
1149  * dwc2_hc_cleanup() - Clears the transfer state for a host channel
1150  *
1151  * @hsotg: Programming view of DWC_otg controller
1152  * @chan:  Identifies the host channel to clean up
1153  *
1154  * This function is normally called after a transfer is done and the host
1155  * channel is being released
1156  */
1157 void dwc2_hc_cleanup(struct dwc2_hsotg *hsotg, struct dwc2_host_chan *chan)
1158 {
1159         u32 hcintmsk;
1160
1161         chan->xfer_started = 0;
1162
1163         list_del_init(&chan->split_order_list_entry);
1164
1165         /*
1166          * Clear channel interrupt enables and any unhandled channel interrupt
1167          * conditions
1168          */
1169         dwc2_writel(0, hsotg->regs + HCINTMSK(chan->hc_num));
1170         hcintmsk = 0xffffffff;
1171         hcintmsk &= ~HCINTMSK_RESERVED14_31;
1172         dwc2_writel(hcintmsk, hsotg->regs + HCINT(chan->hc_num));
1173 }
1174
1175 /**
1176  * dwc2_hc_set_even_odd_frame() - Sets the channel property that indicates in
1177  * which frame a periodic transfer should occur
1178  *
1179  * @hsotg:  Programming view of DWC_otg controller
1180  * @chan:   Identifies the host channel to set up and its properties
1181  * @hcchar: Current value of the HCCHAR register for the specified host channel
1182  *
1183  * This function has no effect on non-periodic transfers
1184  */
1185 static void dwc2_hc_set_even_odd_frame(struct dwc2_hsotg *hsotg,
1186                                        struct dwc2_host_chan *chan, u32 *hcchar)
1187 {
1188         if (chan->ep_type == USB_ENDPOINT_XFER_INT ||
1189             chan->ep_type == USB_ENDPOINT_XFER_ISOC) {
1190                 int host_speed;
1191                 int xfer_ns;
1192                 int xfer_us;
1193                 int bytes_in_fifo;
1194                 u16 fifo_space;
1195                 u16 frame_number;
1196                 u16 wire_frame;
1197
1198                 /*
1199                  * Try to figure out if we're an even or odd frame. If we set
1200                  * even and the current frame number is even the the transfer
1201                  * will happen immediately.  Similar if both are odd. If one is
1202                  * even and the other is odd then the transfer will happen when
1203                  * the frame number ticks.
1204                  *
1205                  * There's a bit of a balancing act to get this right.
1206                  * Sometimes we may want to send data in the current frame (AK
1207                  * right away).  We might want to do this if the frame number
1208                  * _just_ ticked, but we might also want to do this in order
1209                  * to continue a split transaction that happened late in a
1210                  * microframe (so we didn't know to queue the next transfer
1211                  * until the frame number had ticked).  The problem is that we
1212                  * need a lot of knowledge to know if there's actually still
1213                  * time to send things or if it would be better to wait until
1214                  * the next frame.
1215                  *
1216                  * We can look at how much time is left in the current frame
1217                  * and make a guess about whether we'll have time to transfer.
1218                  * We'll do that.
1219                  */
1220
1221                 /* Get speed host is running at */
1222                 host_speed = (chan->speed != USB_SPEED_HIGH &&
1223                               !chan->do_split) ? chan->speed : USB_SPEED_HIGH;
1224
1225                 /* See how many bytes are in the periodic FIFO right now */
1226                 fifo_space = (dwc2_readl(hsotg->regs + HPTXSTS) &
1227                               TXSTS_FSPCAVAIL_MASK) >> TXSTS_FSPCAVAIL_SHIFT;
1228                 bytes_in_fifo = sizeof(u32) *
1229                                 (hsotg->params.host_perio_tx_fifo_size -
1230                                  fifo_space);
1231
1232                 /*
1233                  * Roughly estimate bus time for everything in the periodic
1234                  * queue + our new transfer.  This is "rough" because we're
1235                  * using a function that makes takes into account IN/OUT
1236                  * and INT/ISO and we're just slamming in one value for all
1237                  * transfers.  This should be an over-estimate and that should
1238                  * be OK, but we can probably tighten it.
1239                  */
1240                 xfer_ns = usb_calc_bus_time(host_speed, false, false,
1241                                             chan->xfer_len + bytes_in_fifo);
1242                 xfer_us = NS_TO_US(xfer_ns);
1243
1244                 /* See what frame number we'll be at by the time we finish */
1245                 frame_number = dwc2_hcd_get_future_frame_number(hsotg, xfer_us);
1246
1247                 /* This is when we were scheduled to be on the wire */
1248                 wire_frame = dwc2_frame_num_inc(chan->qh->next_active_frame, 1);
1249
1250                 /*
1251                  * If we'd finish _after_ the frame we're scheduled in then
1252                  * it's hopeless.  Just schedule right away and hope for the
1253                  * best.  Note that it _might_ be wise to call back into the
1254                  * scheduler to pick a better frame, but this is better than
1255                  * nothing.
1256                  */
1257                 if (dwc2_frame_num_gt(frame_number, wire_frame)) {
1258                         dwc2_sch_vdbg(hsotg,
1259                                       "QH=%p EO MISS fr=%04x=>%04x (%+d)\n",
1260                                       chan->qh, wire_frame, frame_number,
1261                                       dwc2_frame_num_dec(frame_number,
1262                                                          wire_frame));
1263                         wire_frame = frame_number;
1264
1265                         /*
1266                          * We picked a different frame number; communicate this
1267                          * back to the scheduler so it doesn't try to schedule
1268                          * another in the same frame.
1269                          *
1270                          * Remember that next_active_frame is 1 before the wire
1271                          * frame.
1272                          */
1273                         chan->qh->next_active_frame =
1274                                 dwc2_frame_num_dec(frame_number, 1);
1275                 }
1276
1277                 if (wire_frame & 1)
1278                         *hcchar |= HCCHAR_ODDFRM;
1279                 else
1280                         *hcchar &= ~HCCHAR_ODDFRM;
1281         }
1282 }
1283
1284 static void dwc2_set_pid_isoc(struct dwc2_host_chan *chan)
1285 {
1286         /* Set up the initial PID for the transfer */
1287         if (chan->speed == USB_SPEED_HIGH) {
1288                 if (chan->ep_is_in) {
1289                         if (chan->multi_count == 1)
1290                                 chan->data_pid_start = DWC2_HC_PID_DATA0;
1291                         else if (chan->multi_count == 2)
1292                                 chan->data_pid_start = DWC2_HC_PID_DATA1;
1293                         else
1294                                 chan->data_pid_start = DWC2_HC_PID_DATA2;
1295                 } else {
1296                         if (chan->multi_count == 1)
1297                                 chan->data_pid_start = DWC2_HC_PID_DATA0;
1298                         else
1299                                 chan->data_pid_start = DWC2_HC_PID_MDATA;
1300                 }
1301         } else {
1302                 chan->data_pid_start = DWC2_HC_PID_DATA0;
1303         }
1304 }
1305
1306 /**
1307  * dwc2_hc_write_packet() - Writes a packet into the Tx FIFO associated with
1308  * the Host Channel
1309  *
1310  * @hsotg: Programming view of DWC_otg controller
1311  * @chan:  Information needed to initialize the host channel
1312  *
1313  * This function should only be called in Slave mode. For a channel associated
1314  * with a non-periodic EP, the non-periodic Tx FIFO is written. For a channel
1315  * associated with a periodic EP, the periodic Tx FIFO is written.
1316  *
1317  * Upon return the xfer_buf and xfer_count fields in chan are incremented by
1318  * the number of bytes written to the Tx FIFO.
1319  */
1320 static void dwc2_hc_write_packet(struct dwc2_hsotg *hsotg,
1321                                  struct dwc2_host_chan *chan)
1322 {
1323         u32 i;
1324         u32 remaining_count;
1325         u32 byte_count;
1326         u32 dword_count;
1327         u32 __iomem *data_fifo;
1328         u32 *data_buf = (u32 *)chan->xfer_buf;
1329
1330         if (dbg_hc(chan))
1331                 dev_vdbg(hsotg->dev, "%s()\n", __func__);
1332
1333         data_fifo = (u32 __iomem *)(hsotg->regs + HCFIFO(chan->hc_num));
1334
1335         remaining_count = chan->xfer_len - chan->xfer_count;
1336         if (remaining_count > chan->max_packet)
1337                 byte_count = chan->max_packet;
1338         else
1339                 byte_count = remaining_count;
1340
1341         dword_count = (byte_count + 3) / 4;
1342
1343         if (((unsigned long)data_buf & 0x3) == 0) {
1344                 /* xfer_buf is DWORD aligned */
1345                 for (i = 0; i < dword_count; i++, data_buf++)
1346                         dwc2_writel(*data_buf, data_fifo);
1347         } else {
1348                 /* xfer_buf is not DWORD aligned */
1349                 for (i = 0; i < dword_count; i++, data_buf++) {
1350                         u32 data = data_buf[0] | data_buf[1] << 8 |
1351                                    data_buf[2] << 16 | data_buf[3] << 24;
1352                         dwc2_writel(data, data_fifo);
1353                 }
1354         }
1355
1356         chan->xfer_count += byte_count;
1357         chan->xfer_buf += byte_count;
1358 }
1359
1360 /**
1361  * dwc2_hc_do_ping() - Starts a PING transfer
1362  *
1363  * @hsotg: Programming view of DWC_otg controller
1364  * @chan:  Information needed to initialize the host channel
1365  *
1366  * This function should only be called in Slave mode. The Do Ping bit is set in
1367  * the HCTSIZ register, then the channel is enabled.
1368  */
1369 static void dwc2_hc_do_ping(struct dwc2_hsotg *hsotg,
1370                             struct dwc2_host_chan *chan)
1371 {
1372         u32 hcchar;
1373         u32 hctsiz;
1374
1375         if (dbg_hc(chan))
1376                 dev_vdbg(hsotg->dev, "%s: Channel %d\n", __func__,
1377                          chan->hc_num);
1378
1379         hctsiz = TSIZ_DOPNG;
1380         hctsiz |= 1 << TSIZ_PKTCNT_SHIFT;
1381         dwc2_writel(hctsiz, hsotg->regs + HCTSIZ(chan->hc_num));
1382
1383         hcchar = dwc2_readl(hsotg->regs + HCCHAR(chan->hc_num));
1384         hcchar |= HCCHAR_CHENA;
1385         hcchar &= ~HCCHAR_CHDIS;
1386         dwc2_writel(hcchar, hsotg->regs + HCCHAR(chan->hc_num));
1387 }
1388
1389 /**
1390  * dwc2_hc_start_transfer() - Does the setup for a data transfer for a host
1391  * channel and starts the transfer
1392  *
1393  * @hsotg: Programming view of DWC_otg controller
1394  * @chan:  Information needed to initialize the host channel. The xfer_len value
1395  *         may be reduced to accommodate the max widths of the XferSize and
1396  *         PktCnt fields in the HCTSIZn register. The multi_count value may be
1397  *         changed to reflect the final xfer_len value.
1398  *
1399  * This function may be called in either Slave mode or DMA mode. In Slave mode,
1400  * the caller must ensure that there is sufficient space in the request queue
1401  * and Tx Data FIFO.
1402  *
1403  * For an OUT transfer in Slave mode, it loads a data packet into the
1404  * appropriate FIFO. If necessary, additional data packets are loaded in the
1405  * Host ISR.
1406  *
1407  * For an IN transfer in Slave mode, a data packet is requested. The data
1408  * packets are unloaded from the Rx FIFO in the Host ISR. If necessary,
1409  * additional data packets are requested in the Host ISR.
1410  *
1411  * For a PING transfer in Slave mode, the Do Ping bit is set in the HCTSIZ
1412  * register along with a packet count of 1 and the channel is enabled. This
1413  * causes a single PING transaction to occur. Other fields in HCTSIZ are
1414  * simply set to 0 since no data transfer occurs in this case.
1415  *
1416  * For a PING transfer in DMA mode, the HCTSIZ register is initialized with
1417  * all the information required to perform the subsequent data transfer. In
1418  * addition, the Do Ping bit is set in the HCTSIZ register. In this case, the
1419  * controller performs the entire PING protocol, then starts the data
1420  * transfer.
1421  */
1422 static void dwc2_hc_start_transfer(struct dwc2_hsotg *hsotg,
1423                                    struct dwc2_host_chan *chan)
1424 {
1425         u32 max_hc_xfer_size = hsotg->params.max_transfer_size;
1426         u16 max_hc_pkt_count = hsotg->params.max_packet_count;
1427         u32 hcchar;
1428         u32 hctsiz = 0;
1429         u16 num_packets;
1430         u32 ec_mc;
1431
1432         if (dbg_hc(chan))
1433                 dev_vdbg(hsotg->dev, "%s()\n", __func__);
1434
1435         if (chan->do_ping) {
1436                 if (!hsotg->params.host_dma) {
1437                         if (dbg_hc(chan))
1438                                 dev_vdbg(hsotg->dev, "ping, no DMA\n");
1439                         dwc2_hc_do_ping(hsotg, chan);
1440                         chan->xfer_started = 1;
1441                         return;
1442                 }
1443
1444                 if (dbg_hc(chan))
1445                         dev_vdbg(hsotg->dev, "ping, DMA\n");
1446
1447                 hctsiz |= TSIZ_DOPNG;
1448         }
1449
1450         if (chan->do_split) {
1451                 if (dbg_hc(chan))
1452                         dev_vdbg(hsotg->dev, "split\n");
1453                 num_packets = 1;
1454
1455                 if (chan->complete_split && !chan->ep_is_in)
1456                         /*
1457                          * For CSPLIT OUT Transfer, set the size to 0 so the
1458                          * core doesn't expect any data written to the FIFO
1459                          */
1460                         chan->xfer_len = 0;
1461                 else if (chan->ep_is_in || chan->xfer_len > chan->max_packet)
1462                         chan->xfer_len = chan->max_packet;
1463                 else if (!chan->ep_is_in && chan->xfer_len > 188)
1464                         chan->xfer_len = 188;
1465
1466                 hctsiz |= chan->xfer_len << TSIZ_XFERSIZE_SHIFT &
1467                           TSIZ_XFERSIZE_MASK;
1468
1469                 /* For split set ec_mc for immediate retries */
1470                 if (chan->ep_type == USB_ENDPOINT_XFER_INT ||
1471                     chan->ep_type == USB_ENDPOINT_XFER_ISOC)
1472                         ec_mc = 3;
1473                 else
1474                         ec_mc = 1;
1475         } else {
1476                 if (dbg_hc(chan))
1477                         dev_vdbg(hsotg->dev, "no split\n");
1478                 /*
1479                  * Ensure that the transfer length and packet count will fit
1480                  * in the widths allocated for them in the HCTSIZn register
1481                  */
1482                 if (chan->ep_type == USB_ENDPOINT_XFER_INT ||
1483                     chan->ep_type == USB_ENDPOINT_XFER_ISOC) {
1484                         /*
1485                          * Make sure the transfer size is no larger than one
1486                          * (micro)frame's worth of data. (A check was done
1487                          * when the periodic transfer was accepted to ensure
1488                          * that a (micro)frame's worth of data can be
1489                          * programmed into a channel.)
1490                          */
1491                         u32 max_periodic_len =
1492                                 chan->multi_count * chan->max_packet;
1493
1494                         if (chan->xfer_len > max_periodic_len)
1495                                 chan->xfer_len = max_periodic_len;
1496                 } else if (chan->xfer_len > max_hc_xfer_size) {
1497                         /*
1498                          * Make sure that xfer_len is a multiple of max packet
1499                          * size
1500                          */
1501                         chan->xfer_len =
1502                                 max_hc_xfer_size - chan->max_packet + 1;
1503                 }
1504
1505                 if (chan->xfer_len > 0) {
1506                         num_packets = (chan->xfer_len + chan->max_packet - 1) /
1507                                         chan->max_packet;
1508                         if (num_packets > max_hc_pkt_count) {
1509                                 num_packets = max_hc_pkt_count;
1510                                 chan->xfer_len = num_packets * chan->max_packet;
1511                         }
1512                 } else {
1513                         /* Need 1 packet for transfer length of 0 */
1514                         num_packets = 1;
1515                 }
1516
1517                 if (chan->ep_is_in)
1518                         /*
1519                          * Always program an integral # of max packets for IN
1520                          * transfers
1521                          */
1522                         chan->xfer_len = num_packets * chan->max_packet;
1523
1524                 if (chan->ep_type == USB_ENDPOINT_XFER_INT ||
1525                     chan->ep_type == USB_ENDPOINT_XFER_ISOC)
1526                         /*
1527                          * Make sure that the multi_count field matches the
1528                          * actual transfer length
1529                          */
1530                         chan->multi_count = num_packets;
1531
1532                 if (chan->ep_type == USB_ENDPOINT_XFER_ISOC)
1533                         dwc2_set_pid_isoc(chan);
1534
1535                 hctsiz |= chan->xfer_len << TSIZ_XFERSIZE_SHIFT &
1536                           TSIZ_XFERSIZE_MASK;
1537
1538                 /* The ec_mc gets the multi_count for non-split */
1539                 ec_mc = chan->multi_count;
1540         }
1541
1542         chan->start_pkt_count = num_packets;
1543         hctsiz |= num_packets << TSIZ_PKTCNT_SHIFT & TSIZ_PKTCNT_MASK;
1544         hctsiz |= chan->data_pid_start << TSIZ_SC_MC_PID_SHIFT &
1545                   TSIZ_SC_MC_PID_MASK;
1546         dwc2_writel(hctsiz, hsotg->regs + HCTSIZ(chan->hc_num));
1547         if (dbg_hc(chan)) {
1548                 dev_vdbg(hsotg->dev, "Wrote %08x to HCTSIZ(%d)\n",
1549                          hctsiz, chan->hc_num);
1550
1551                 dev_vdbg(hsotg->dev, "%s: Channel %d\n", __func__,
1552                          chan->hc_num);
1553                 dev_vdbg(hsotg->dev, "   Xfer Size: %d\n",
1554                          (hctsiz & TSIZ_XFERSIZE_MASK) >>
1555                          TSIZ_XFERSIZE_SHIFT);
1556                 dev_vdbg(hsotg->dev, "   Num Pkts: %d\n",
1557                          (hctsiz & TSIZ_PKTCNT_MASK) >>
1558                          TSIZ_PKTCNT_SHIFT);
1559                 dev_vdbg(hsotg->dev, "   Start PID: %d\n",
1560                          (hctsiz & TSIZ_SC_MC_PID_MASK) >>
1561                          TSIZ_SC_MC_PID_SHIFT);
1562         }
1563
1564         if (hsotg->params.host_dma) {
1565                 dwc2_writel((u32)chan->xfer_dma,
1566                             hsotg->regs + HCDMA(chan->hc_num));
1567                 if (dbg_hc(chan))
1568                         dev_vdbg(hsotg->dev, "Wrote %08lx to HCDMA(%d)\n",
1569                                  (unsigned long)chan->xfer_dma, chan->hc_num);
1570         }
1571
1572         /* Start the split */
1573         if (chan->do_split) {
1574                 u32 hcsplt = dwc2_readl(hsotg->regs + HCSPLT(chan->hc_num));
1575
1576                 hcsplt |= HCSPLT_SPLTENA;
1577                 dwc2_writel(hcsplt, hsotg->regs + HCSPLT(chan->hc_num));
1578         }
1579
1580         hcchar = dwc2_readl(hsotg->regs + HCCHAR(chan->hc_num));
1581         hcchar &= ~HCCHAR_MULTICNT_MASK;
1582         hcchar |= (ec_mc << HCCHAR_MULTICNT_SHIFT) & HCCHAR_MULTICNT_MASK;
1583         dwc2_hc_set_even_odd_frame(hsotg, chan, &hcchar);
1584
1585         if (hcchar & HCCHAR_CHDIS)
1586                 dev_warn(hsotg->dev,
1587                          "%s: chdis set, channel %d, hcchar 0x%08x\n",
1588                          __func__, chan->hc_num, hcchar);
1589
1590         /* Set host channel enable after all other setup is complete */
1591         hcchar |= HCCHAR_CHENA;
1592         hcchar &= ~HCCHAR_CHDIS;
1593
1594         if (dbg_hc(chan))
1595                 dev_vdbg(hsotg->dev, "   Multi Cnt: %d\n",
1596                          (hcchar & HCCHAR_MULTICNT_MASK) >>
1597                          HCCHAR_MULTICNT_SHIFT);
1598
1599         dwc2_writel(hcchar, hsotg->regs + HCCHAR(chan->hc_num));
1600         if (dbg_hc(chan))
1601                 dev_vdbg(hsotg->dev, "Wrote %08x to HCCHAR(%d)\n", hcchar,
1602                          chan->hc_num);
1603
1604         chan->xfer_started = 1;
1605         chan->requests++;
1606
1607         if (!hsotg->params.host_dma &&
1608             !chan->ep_is_in && chan->xfer_len > 0)
1609                 /* Load OUT packet into the appropriate Tx FIFO */
1610                 dwc2_hc_write_packet(hsotg, chan);
1611 }
1612
1613 /**
1614  * dwc2_hc_start_transfer_ddma() - Does the setup for a data transfer for a
1615  * host channel and starts the transfer in Descriptor DMA mode
1616  *
1617  * @hsotg: Programming view of DWC_otg controller
1618  * @chan:  Information needed to initialize the host channel
1619  *
1620  * Initializes HCTSIZ register. For a PING transfer the Do Ping bit is set.
1621  * Sets PID and NTD values. For periodic transfers initializes SCHED_INFO field
1622  * with micro-frame bitmap.
1623  *
1624  * Initializes HCDMA register with descriptor list address and CTD value then
1625  * starts the transfer via enabling the channel.
1626  */
1627 void dwc2_hc_start_transfer_ddma(struct dwc2_hsotg *hsotg,
1628                                  struct dwc2_host_chan *chan)
1629 {
1630         u32 hcchar;
1631         u32 hctsiz = 0;
1632
1633         if (chan->do_ping)
1634                 hctsiz |= TSIZ_DOPNG;
1635
1636         if (chan->ep_type == USB_ENDPOINT_XFER_ISOC)
1637                 dwc2_set_pid_isoc(chan);
1638
1639         /* Packet Count and Xfer Size are not used in Descriptor DMA mode */
1640         hctsiz |= chan->data_pid_start << TSIZ_SC_MC_PID_SHIFT &
1641                   TSIZ_SC_MC_PID_MASK;
1642
1643         /* 0 - 1 descriptor, 1 - 2 descriptors, etc */
1644         hctsiz |= (chan->ntd - 1) << TSIZ_NTD_SHIFT & TSIZ_NTD_MASK;
1645
1646         /* Non-zero only for high-speed interrupt endpoints */
1647         hctsiz |= chan->schinfo << TSIZ_SCHINFO_SHIFT & TSIZ_SCHINFO_MASK;
1648
1649         if (dbg_hc(chan)) {
1650                 dev_vdbg(hsotg->dev, "%s: Channel %d\n", __func__,
1651                          chan->hc_num);
1652                 dev_vdbg(hsotg->dev, "   Start PID: %d\n",
1653                          chan->data_pid_start);
1654                 dev_vdbg(hsotg->dev, "   NTD: %d\n", chan->ntd - 1);
1655         }
1656
1657         dwc2_writel(hctsiz, hsotg->regs + HCTSIZ(chan->hc_num));
1658
1659         dma_sync_single_for_device(hsotg->dev, chan->desc_list_addr,
1660                                    chan->desc_list_sz, DMA_TO_DEVICE);
1661
1662         dwc2_writel(chan->desc_list_addr, hsotg->regs + HCDMA(chan->hc_num));
1663
1664         if (dbg_hc(chan))
1665                 dev_vdbg(hsotg->dev, "Wrote %pad to HCDMA(%d)\n",
1666                          &chan->desc_list_addr, chan->hc_num);
1667
1668         hcchar = dwc2_readl(hsotg->regs + HCCHAR(chan->hc_num));
1669         hcchar &= ~HCCHAR_MULTICNT_MASK;
1670         hcchar |= chan->multi_count << HCCHAR_MULTICNT_SHIFT &
1671                   HCCHAR_MULTICNT_MASK;
1672
1673         if (hcchar & HCCHAR_CHDIS)
1674                 dev_warn(hsotg->dev,
1675                          "%s: chdis set, channel %d, hcchar 0x%08x\n",
1676                          __func__, chan->hc_num, hcchar);
1677
1678         /* Set host channel enable after all other setup is complete */
1679         hcchar |= HCCHAR_CHENA;
1680         hcchar &= ~HCCHAR_CHDIS;
1681
1682         if (dbg_hc(chan))
1683                 dev_vdbg(hsotg->dev, "   Multi Cnt: %d\n",
1684                          (hcchar & HCCHAR_MULTICNT_MASK) >>
1685                          HCCHAR_MULTICNT_SHIFT);
1686
1687         dwc2_writel(hcchar, hsotg->regs + HCCHAR(chan->hc_num));
1688         if (dbg_hc(chan))
1689                 dev_vdbg(hsotg->dev, "Wrote %08x to HCCHAR(%d)\n", hcchar,
1690                          chan->hc_num);
1691
1692         chan->xfer_started = 1;
1693         chan->requests++;
1694 }
1695
1696 /**
1697  * dwc2_hc_continue_transfer() - Continues a data transfer that was started by
1698  * a previous call to dwc2_hc_start_transfer()
1699  *
1700  * @hsotg: Programming view of DWC_otg controller
1701  * @chan:  Information needed to initialize the host channel
1702  *
1703  * The caller must ensure there is sufficient space in the request queue and Tx
1704  * Data FIFO. This function should only be called in Slave mode. In DMA mode,
1705  * the controller acts autonomously to complete transfers programmed to a host
1706  * channel.
1707  *
1708  * For an OUT transfer, a new data packet is loaded into the appropriate FIFO
1709  * if there is any data remaining to be queued. For an IN transfer, another
1710  * data packet is always requested. For the SETUP phase of a control transfer,
1711  * this function does nothing.
1712  *
1713  * Return: 1 if a new request is queued, 0 if no more requests are required
1714  * for this transfer
1715  */
1716 static int dwc2_hc_continue_transfer(struct dwc2_hsotg *hsotg,
1717                                      struct dwc2_host_chan *chan)
1718 {
1719         if (dbg_hc(chan))
1720                 dev_vdbg(hsotg->dev, "%s: Channel %d\n", __func__,
1721                          chan->hc_num);
1722
1723         if (chan->do_split)
1724                 /* SPLITs always queue just once per channel */
1725                 return 0;
1726
1727         if (chan->data_pid_start == DWC2_HC_PID_SETUP)
1728                 /* SETUPs are queued only once since they can't be NAK'd */
1729                 return 0;
1730
1731         if (chan->ep_is_in) {
1732                 /*
1733                  * Always queue another request for other IN transfers. If
1734                  * back-to-back INs are issued and NAKs are received for both,
1735                  * the driver may still be processing the first NAK when the
1736                  * second NAK is received. When the interrupt handler clears
1737                  * the NAK interrupt for the first NAK, the second NAK will
1738                  * not be seen. So we can't depend on the NAK interrupt
1739                  * handler to requeue a NAK'd request. Instead, IN requests
1740                  * are issued each time this function is called. When the
1741                  * transfer completes, the extra requests for the channel will
1742                  * be flushed.
1743                  */
1744                 u32 hcchar = dwc2_readl(hsotg->regs + HCCHAR(chan->hc_num));
1745
1746                 dwc2_hc_set_even_odd_frame(hsotg, chan, &hcchar);
1747                 hcchar |= HCCHAR_CHENA;
1748                 hcchar &= ~HCCHAR_CHDIS;
1749                 if (dbg_hc(chan))
1750                         dev_vdbg(hsotg->dev, "   IN xfer: hcchar = 0x%08x\n",
1751                                  hcchar);
1752                 dwc2_writel(hcchar, hsotg->regs + HCCHAR(chan->hc_num));
1753                 chan->requests++;
1754                 return 1;
1755         }
1756
1757         /* OUT transfers */
1758
1759         if (chan->xfer_count < chan->xfer_len) {
1760                 if (chan->ep_type == USB_ENDPOINT_XFER_INT ||
1761                     chan->ep_type == USB_ENDPOINT_XFER_ISOC) {
1762                         u32 hcchar = dwc2_readl(hsotg->regs +
1763                                                 HCCHAR(chan->hc_num));
1764
1765                         dwc2_hc_set_even_odd_frame(hsotg, chan,
1766                                                    &hcchar);
1767                 }
1768
1769                 /* Load OUT packet into the appropriate Tx FIFO */
1770                 dwc2_hc_write_packet(hsotg, chan);
1771                 chan->requests++;
1772                 return 1;
1773         }
1774
1775         return 0;
1776 }
1777
1778 /*
1779  * =========================================================================
1780  *  HCD
1781  * =========================================================================
1782  */
1783
1784 /*
1785  * Processes all the URBs in a single list of QHs. Completes them with
1786  * -ETIMEDOUT and frees the QTD.
1787  *
1788  * Must be called with interrupt disabled and spinlock held
1789  */
1790 static void dwc2_kill_urbs_in_qh_list(struct dwc2_hsotg *hsotg,
1791                                       struct list_head *qh_list)
1792 {
1793         struct dwc2_qh *qh, *qh_tmp;
1794         struct dwc2_qtd *qtd, *qtd_tmp;
1795
1796         list_for_each_entry_safe(qh, qh_tmp, qh_list, qh_list_entry) {
1797                 list_for_each_entry_safe(qtd, qtd_tmp, &qh->qtd_list,
1798                                          qtd_list_entry) {
1799                         dwc2_host_complete(hsotg, qtd, -ECONNRESET);
1800                         dwc2_hcd_qtd_unlink_and_free(hsotg, qtd, qh);
1801                 }
1802         }
1803 }
1804
1805 static void dwc2_qh_list_free(struct dwc2_hsotg *hsotg,
1806                               struct list_head *qh_list)
1807 {
1808         struct dwc2_qtd *qtd, *qtd_tmp;
1809         struct dwc2_qh *qh, *qh_tmp;
1810         unsigned long flags;
1811
1812         if (!qh_list->next)
1813                 /* The list hasn't been initialized yet */
1814                 return;
1815
1816         spin_lock_irqsave(&hsotg->lock, flags);
1817
1818         /* Ensure there are no QTDs or URBs left */
1819         dwc2_kill_urbs_in_qh_list(hsotg, qh_list);
1820
1821         list_for_each_entry_safe(qh, qh_tmp, qh_list, qh_list_entry) {
1822                 dwc2_hcd_qh_unlink(hsotg, qh);
1823
1824                 /* Free each QTD in the QH's QTD list */
1825                 list_for_each_entry_safe(qtd, qtd_tmp, &qh->qtd_list,
1826                                          qtd_list_entry)
1827                         dwc2_hcd_qtd_unlink_and_free(hsotg, qtd, qh);
1828
1829                 if (qh->channel && qh->channel->qh == qh)
1830                         qh->channel->qh = NULL;
1831
1832                 spin_unlock_irqrestore(&hsotg->lock, flags);
1833                 dwc2_hcd_qh_free(hsotg, qh);
1834                 spin_lock_irqsave(&hsotg->lock, flags);
1835         }
1836
1837         spin_unlock_irqrestore(&hsotg->lock, flags);
1838 }
1839
1840 /*
1841  * Responds with an error status of -ETIMEDOUT to all URBs in the non-periodic
1842  * and periodic schedules. The QTD associated with each URB is removed from
1843  * the schedule and freed. This function may be called when a disconnect is
1844  * detected or when the HCD is being stopped.
1845  *
1846  * Must be called with interrupt disabled and spinlock held
1847  */
1848 static void dwc2_kill_all_urbs(struct dwc2_hsotg *hsotg)
1849 {
1850         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->non_periodic_sched_inactive);
1851         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->non_periodic_sched_waiting);
1852         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->non_periodic_sched_active);
1853         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->periodic_sched_inactive);
1854         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->periodic_sched_ready);
1855         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->periodic_sched_assigned);
1856         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->periodic_sched_queued);
1857 }
1858
1859 /**
1860  * dwc2_hcd_start() - Starts the HCD when switching to Host mode
1861  *
1862  * @hsotg: Pointer to struct dwc2_hsotg
1863  */
1864 void dwc2_hcd_start(struct dwc2_hsotg *hsotg)
1865 {
1866         u32 hprt0;
1867
1868         if (hsotg->op_state == OTG_STATE_B_HOST) {
1869                 /*
1870                  * Reset the port. During a HNP mode switch the reset
1871                  * needs to occur within 1ms and have a duration of at
1872                  * least 50ms.
1873                  */
1874                 hprt0 = dwc2_read_hprt0(hsotg);
1875                 hprt0 |= HPRT0_RST;
1876                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
1877         }
1878
1879         queue_delayed_work(hsotg->wq_otg, &hsotg->start_work,
1880                            msecs_to_jiffies(50));
1881 }
1882
1883 /* Must be called with interrupt disabled and spinlock held */
1884 static void dwc2_hcd_cleanup_channels(struct dwc2_hsotg *hsotg)
1885 {
1886         int num_channels = hsotg->params.host_channels;
1887         struct dwc2_host_chan *channel;
1888         u32 hcchar;
1889         int i;
1890
1891         if (!hsotg->params.host_dma) {
1892                 /* Flush out any channel requests in slave mode */
1893                 for (i = 0; i < num_channels; i++) {
1894                         channel = hsotg->hc_ptr_array[i];
1895                         if (!list_empty(&channel->hc_list_entry))
1896                                 continue;
1897                         hcchar = dwc2_readl(hsotg->regs + HCCHAR(i));
1898                         if (hcchar & HCCHAR_CHENA) {
1899                                 hcchar &= ~(HCCHAR_CHENA | HCCHAR_EPDIR);
1900                                 hcchar |= HCCHAR_CHDIS;
1901                                 dwc2_writel(hcchar, hsotg->regs + HCCHAR(i));
1902                         }
1903                 }
1904         }
1905
1906         for (i = 0; i < num_channels; i++) {
1907                 channel = hsotg->hc_ptr_array[i];
1908                 if (!list_empty(&channel->hc_list_entry))
1909                         continue;
1910                 hcchar = dwc2_readl(hsotg->regs + HCCHAR(i));
1911                 if (hcchar & HCCHAR_CHENA) {
1912                         /* Halt the channel */
1913                         hcchar |= HCCHAR_CHDIS;
1914                         dwc2_writel(hcchar, hsotg->regs + HCCHAR(i));
1915                 }
1916
1917                 dwc2_hc_cleanup(hsotg, channel);
1918                 list_add_tail(&channel->hc_list_entry, &hsotg->free_hc_list);
1919                 /*
1920                  * Added for Descriptor DMA to prevent channel double cleanup in
1921                  * release_channel_ddma(), which is called from ep_disable when
1922                  * device disconnects
1923                  */
1924                 channel->qh = NULL;
1925         }
1926         /* All channels have been freed, mark them available */
1927         if (hsotg->params.uframe_sched) {
1928                 hsotg->available_host_channels =
1929                         hsotg->params.host_channels;
1930         } else {
1931                 hsotg->non_periodic_channels = 0;
1932                 hsotg->periodic_channels = 0;
1933         }
1934 }
1935
1936 /**
1937  * dwc2_hcd_connect() - Handles connect of the HCD
1938  *
1939  * @hsotg: Pointer to struct dwc2_hsotg
1940  *
1941  * Must be called with interrupt disabled and spinlock held
1942  */
1943 void dwc2_hcd_connect(struct dwc2_hsotg *hsotg)
1944 {
1945         if (hsotg->lx_state != DWC2_L0)
1946                 usb_hcd_resume_root_hub(hsotg->priv);
1947
1948         hsotg->flags.b.port_connect_status_change = 1;
1949         hsotg->flags.b.port_connect_status = 1;
1950 }
1951
1952 /**
1953  * dwc2_hcd_disconnect() - Handles disconnect of the HCD
1954  *
1955  * @hsotg: Pointer to struct dwc2_hsotg
1956  * @force: If true, we won't try to reconnect even if we see device connected.
1957  *
1958  * Must be called with interrupt disabled and spinlock held
1959  */
1960 void dwc2_hcd_disconnect(struct dwc2_hsotg *hsotg, bool force)
1961 {
1962         u32 intr;
1963         u32 hprt0;
1964
1965         /* Set status flags for the hub driver */
1966         hsotg->flags.b.port_connect_status_change = 1;
1967         hsotg->flags.b.port_connect_status = 0;
1968
1969         /*
1970          * Shutdown any transfers in process by clearing the Tx FIFO Empty
1971          * interrupt mask and status bits and disabling subsequent host
1972          * channel interrupts.
1973          */
1974         intr = dwc2_readl(hsotg->regs + GINTMSK);
1975         intr &= ~(GINTSTS_NPTXFEMP | GINTSTS_PTXFEMP | GINTSTS_HCHINT);
1976         dwc2_writel(intr, hsotg->regs + GINTMSK);
1977         intr = GINTSTS_NPTXFEMP | GINTSTS_PTXFEMP | GINTSTS_HCHINT;
1978         dwc2_writel(intr, hsotg->regs + GINTSTS);
1979
1980         /*
1981          * Turn off the vbus power only if the core has transitioned to device
1982          * mode. If still in host mode, need to keep power on to detect a
1983          * reconnection.
1984          */
1985         if (dwc2_is_device_mode(hsotg)) {
1986                 if (hsotg->op_state != OTG_STATE_A_SUSPEND) {
1987                         dev_dbg(hsotg->dev, "Disconnect: PortPower off\n");
1988                         dwc2_writel(0, hsotg->regs + HPRT0);
1989                 }
1990
1991                 dwc2_disable_host_interrupts(hsotg);
1992         }
1993
1994         /* Respond with an error status to all URBs in the schedule */
1995         dwc2_kill_all_urbs(hsotg);
1996
1997         if (dwc2_is_host_mode(hsotg))
1998                 /* Clean up any host channels that were in use */
1999                 dwc2_hcd_cleanup_channels(hsotg);
2000
2001         dwc2_host_disconnect(hsotg);
2002
2003         /*
2004          * Add an extra check here to see if we're actually connected but
2005          * we don't have a detection interrupt pending.  This can happen if:
2006          *   1. hardware sees connect
2007          *   2. hardware sees disconnect
2008          *   3. hardware sees connect
2009          *   4. dwc2_port_intr() - clears connect interrupt
2010          *   5. dwc2_handle_common_intr() - calls here
2011          *
2012          * Without the extra check here we will end calling disconnect
2013          * and won't get any future interrupts to handle the connect.
2014          */
2015         if (!force) {
2016                 hprt0 = dwc2_readl(hsotg->regs + HPRT0);
2017                 if (!(hprt0 & HPRT0_CONNDET) && (hprt0 & HPRT0_CONNSTS))
2018                         dwc2_hcd_connect(hsotg);
2019         }
2020 }
2021
2022 /**
2023  * dwc2_hcd_rem_wakeup() - Handles Remote Wakeup
2024  *
2025  * @hsotg: Pointer to struct dwc2_hsotg
2026  */
2027 static void dwc2_hcd_rem_wakeup(struct dwc2_hsotg *hsotg)
2028 {
2029         if (hsotg->bus_suspended) {
2030                 hsotg->flags.b.port_suspend_change = 1;
2031                 usb_hcd_resume_root_hub(hsotg->priv);
2032         }
2033
2034         if (hsotg->lx_state == DWC2_L1)
2035                 hsotg->flags.b.port_l1_change = 1;
2036 }
2037
2038 /**
2039  * dwc2_hcd_stop() - Halts the DWC_otg host mode operations in a clean manner
2040  *
2041  * @hsotg: Pointer to struct dwc2_hsotg
2042  *
2043  * Must be called with interrupt disabled and spinlock held
2044  */
2045 void dwc2_hcd_stop(struct dwc2_hsotg *hsotg)
2046 {
2047         dev_dbg(hsotg->dev, "DWC OTG HCD STOP\n");
2048
2049         /*
2050          * The root hub should be disconnected before this function is called.
2051          * The disconnect will clear the QTD lists (via ..._hcd_urb_dequeue)
2052          * and the QH lists (via ..._hcd_endpoint_disable).
2053          */
2054
2055         /* Turn off all host-specific interrupts */
2056         dwc2_disable_host_interrupts(hsotg);
2057
2058         /* Turn off the vbus power */
2059         dev_dbg(hsotg->dev, "PortPower off\n");
2060         dwc2_writel(0, hsotg->regs + HPRT0);
2061 }
2062
2063 /* Caller must hold driver lock */
2064 static int dwc2_hcd_urb_enqueue(struct dwc2_hsotg *hsotg,
2065                                 struct dwc2_hcd_urb *urb, struct dwc2_qh *qh,
2066                                 struct dwc2_qtd *qtd)
2067 {
2068         u32 intr_mask;
2069         int retval;
2070         int dev_speed;
2071
2072         if (!hsotg->flags.b.port_connect_status) {
2073                 /* No longer connected */
2074                 dev_err(hsotg->dev, "Not connected\n");
2075                 return -ENODEV;
2076         }
2077
2078         dev_speed = dwc2_host_get_speed(hsotg, urb->priv);
2079
2080         /* Some configurations cannot support LS traffic on a FS root port */
2081         if ((dev_speed == USB_SPEED_LOW) &&
2082             (hsotg->hw_params.fs_phy_type == GHWCFG2_FS_PHY_TYPE_DEDICATED) &&
2083             (hsotg->hw_params.hs_phy_type == GHWCFG2_HS_PHY_TYPE_UTMI)) {
2084                 u32 hprt0 = dwc2_readl(hsotg->regs + HPRT0);
2085                 u32 prtspd = (hprt0 & HPRT0_SPD_MASK) >> HPRT0_SPD_SHIFT;
2086
2087                 if (prtspd == HPRT0_SPD_FULL_SPEED)
2088                         return -ENODEV;
2089         }
2090
2091         if (!qtd)
2092                 return -EINVAL;
2093
2094         dwc2_hcd_qtd_init(qtd, urb);
2095         retval = dwc2_hcd_qtd_add(hsotg, qtd, qh);
2096         if (retval) {
2097                 dev_err(hsotg->dev,
2098                         "DWC OTG HCD URB Enqueue failed adding QTD. Error status %d\n",
2099                         retval);
2100                 return retval;
2101         }
2102
2103         intr_mask = dwc2_readl(hsotg->regs + GINTMSK);
2104         if (!(intr_mask & GINTSTS_SOF)) {
2105                 enum dwc2_transaction_type tr_type;
2106
2107                 if (qtd->qh->ep_type == USB_ENDPOINT_XFER_BULK &&
2108                     !(qtd->urb->flags & URB_GIVEBACK_ASAP))
2109                         /*
2110                          * Do not schedule SG transactions until qtd has
2111                          * URB_GIVEBACK_ASAP set
2112                          */
2113                         return 0;
2114
2115                 tr_type = dwc2_hcd_select_transactions(hsotg);
2116                 if (tr_type != DWC2_TRANSACTION_NONE)
2117                         dwc2_hcd_queue_transactions(hsotg, tr_type);
2118         }
2119
2120         return 0;
2121 }
2122
2123 /* Must be called with interrupt disabled and spinlock held */
2124 static int dwc2_hcd_urb_dequeue(struct dwc2_hsotg *hsotg,
2125                                 struct dwc2_hcd_urb *urb)
2126 {
2127         struct dwc2_qh *qh;
2128         struct dwc2_qtd *urb_qtd;
2129
2130         urb_qtd = urb->qtd;
2131         if (!urb_qtd) {
2132                 dev_dbg(hsotg->dev, "## Urb QTD is NULL ##\n");
2133                 return -EINVAL;
2134         }
2135
2136         qh = urb_qtd->qh;
2137         if (!qh) {
2138                 dev_dbg(hsotg->dev, "## Urb QTD QH is NULL ##\n");
2139                 return -EINVAL;
2140         }
2141
2142         urb->priv = NULL;
2143
2144         if (urb_qtd->in_process && qh->channel) {
2145                 dwc2_dump_channel_info(hsotg, qh->channel);
2146
2147                 /* The QTD is in process (it has been assigned to a channel) */
2148                 if (hsotg->flags.b.port_connect_status)
2149                         /*
2150                          * If still connected (i.e. in host mode), halt the
2151                          * channel so it can be used for other transfers. If
2152                          * no longer connected, the host registers can't be
2153                          * written to halt the channel since the core is in
2154                          * device mode.
2155                          */
2156                         dwc2_hc_halt(hsotg, qh->channel,
2157                                      DWC2_HC_XFER_URB_DEQUEUE);
2158         }
2159
2160         /*
2161          * Free the QTD and clean up the associated QH. Leave the QH in the
2162          * schedule if it has any remaining QTDs.
2163          */
2164         if (!hsotg->params.dma_desc_enable) {
2165                 u8 in_process = urb_qtd->in_process;
2166
2167                 dwc2_hcd_qtd_unlink_and_free(hsotg, urb_qtd, qh);
2168                 if (in_process) {
2169                         dwc2_hcd_qh_deactivate(hsotg, qh, 0);
2170                         qh->channel = NULL;
2171                 } else if (list_empty(&qh->qtd_list)) {
2172                         dwc2_hcd_qh_unlink(hsotg, qh);
2173                 }
2174         } else {
2175                 dwc2_hcd_qtd_unlink_and_free(hsotg, urb_qtd, qh);
2176         }
2177
2178         return 0;
2179 }
2180
2181 /* Must NOT be called with interrupt disabled or spinlock held */
2182 static int dwc2_hcd_endpoint_disable(struct dwc2_hsotg *hsotg,
2183                                      struct usb_host_endpoint *ep, int retry)
2184 {
2185         struct dwc2_qtd *qtd, *qtd_tmp;
2186         struct dwc2_qh *qh;
2187         unsigned long flags;
2188         int rc;
2189
2190         spin_lock_irqsave(&hsotg->lock, flags);
2191
2192         qh = ep->hcpriv;
2193         if (!qh) {
2194                 rc = -EINVAL;
2195                 goto err;
2196         }
2197
2198         while (!list_empty(&qh->qtd_list) && retry--) {
2199                 if (retry == 0) {
2200                         dev_err(hsotg->dev,
2201                                 "## timeout in dwc2_hcd_endpoint_disable() ##\n");
2202                         rc = -EBUSY;
2203                         goto err;
2204                 }
2205
2206                 spin_unlock_irqrestore(&hsotg->lock, flags);
2207                 msleep(20);
2208                 spin_lock_irqsave(&hsotg->lock, flags);
2209                 qh = ep->hcpriv;
2210                 if (!qh) {
2211                         rc = -EINVAL;
2212                         goto err;
2213                 }
2214         }
2215
2216         dwc2_hcd_qh_unlink(hsotg, qh);
2217
2218         /* Free each QTD in the QH's QTD list */
2219         list_for_each_entry_safe(qtd, qtd_tmp, &qh->qtd_list, qtd_list_entry)
2220                 dwc2_hcd_qtd_unlink_and_free(hsotg, qtd, qh);
2221
2222         ep->hcpriv = NULL;
2223
2224         if (qh->channel && qh->channel->qh == qh)
2225                 qh->channel->qh = NULL;
2226
2227         spin_unlock_irqrestore(&hsotg->lock, flags);
2228
2229         dwc2_hcd_qh_free(hsotg, qh);
2230
2231         return 0;
2232
2233 err:
2234         ep->hcpriv = NULL;
2235         spin_unlock_irqrestore(&hsotg->lock, flags);
2236
2237         return rc;
2238 }
2239
2240 /* Must be called with interrupt disabled and spinlock held */
2241 static int dwc2_hcd_endpoint_reset(struct dwc2_hsotg *hsotg,
2242                                    struct usb_host_endpoint *ep)
2243 {
2244         struct dwc2_qh *qh = ep->hcpriv;
2245
2246         if (!qh)
2247                 return -EINVAL;
2248
2249         qh->data_toggle = DWC2_HC_PID_DATA0;
2250
2251         return 0;
2252 }
2253
2254 /**
2255  * dwc2_core_init() - Initializes the DWC_otg controller registers and
2256  * prepares the core for device mode or host mode operation
2257  *
2258  * @hsotg:         Programming view of the DWC_otg controller
2259  * @initial_setup: If true then this is the first init for this instance.
2260  */
2261 int dwc2_core_init(struct dwc2_hsotg *hsotg, bool initial_setup)
2262 {
2263         u32 usbcfg, otgctl;
2264         int retval;
2265
2266         dev_dbg(hsotg->dev, "%s(%p)\n", __func__, hsotg);
2267
2268         usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
2269
2270         /* Set ULPI External VBUS bit if needed */
2271         usbcfg &= ~GUSBCFG_ULPI_EXT_VBUS_DRV;
2272         if (hsotg->params.phy_ulpi_ext_vbus)
2273                 usbcfg |= GUSBCFG_ULPI_EXT_VBUS_DRV;
2274
2275         /* Set external TS Dline pulsing bit if needed */
2276         usbcfg &= ~GUSBCFG_TERMSELDLPULSE;
2277         if (hsotg->params.ts_dline)
2278                 usbcfg |= GUSBCFG_TERMSELDLPULSE;
2279
2280         dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
2281
2282         /*
2283          * Reset the Controller
2284          *
2285          * We only need to reset the controller if this is a re-init.
2286          * For the first init we know for sure that earlier code reset us (it
2287          * needed to in order to properly detect various parameters).
2288          */
2289         if (!initial_setup) {
2290                 retval = dwc2_core_reset(hsotg, false);
2291                 if (retval) {
2292                         dev_err(hsotg->dev, "%s(): Reset failed, aborting\n",
2293                                 __func__);
2294                         return retval;
2295                 }
2296         }
2297
2298         /*
2299          * This needs to happen in FS mode before any other programming occurs
2300          */
2301         retval = dwc2_phy_init(hsotg, initial_setup);
2302         if (retval)
2303                 return retval;
2304
2305         /* Program the GAHBCFG Register */
2306         retval = dwc2_gahbcfg_init(hsotg);
2307         if (retval)
2308                 return retval;
2309
2310         /* Program the GUSBCFG register */
2311         dwc2_gusbcfg_init(hsotg);
2312
2313         /* Program the GOTGCTL register */
2314         otgctl = dwc2_readl(hsotg->regs + GOTGCTL);
2315         otgctl &= ~GOTGCTL_OTGVER;
2316         dwc2_writel(otgctl, hsotg->regs + GOTGCTL);
2317
2318         /* Clear the SRP success bit for FS-I2c */
2319         hsotg->srp_success = 0;
2320
2321         /* Enable common interrupts */
2322         dwc2_enable_common_interrupts(hsotg);
2323
2324         /*
2325          * Do device or host initialization based on mode during PCD and
2326          * HCD initialization
2327          */
2328         if (dwc2_is_host_mode(hsotg)) {
2329                 dev_dbg(hsotg->dev, "Host Mode\n");
2330                 hsotg->op_state = OTG_STATE_A_HOST;
2331         } else {
2332                 dev_dbg(hsotg->dev, "Device Mode\n");
2333                 hsotg->op_state = OTG_STATE_B_PERIPHERAL;
2334         }
2335
2336         return 0;
2337 }
2338
2339 /**
2340  * dwc2_core_host_init() - Initializes the DWC_otg controller registers for
2341  * Host mode
2342  *
2343  * @hsotg: Programming view of DWC_otg controller
2344  *
2345  * This function flushes the Tx and Rx FIFOs and flushes any entries in the
2346  * request queues. Host channels are reset to ensure that they are ready for
2347  * performing transfers.
2348  */
2349 static void dwc2_core_host_init(struct dwc2_hsotg *hsotg)
2350 {
2351         u32 hcfg, hfir, otgctl, usbcfg;
2352
2353         dev_dbg(hsotg->dev, "%s(%p)\n", __func__, hsotg);
2354
2355         /* Set HS/FS Timeout Calibration to 7 (max available value).
2356          * The number of PHY clocks that the application programs in
2357          * this field is added to the high/full speed interpacket timeout
2358          * duration in the core to account for any additional delays
2359          * introduced by the PHY. This can be required, because the delay
2360          * introduced by the PHY in generating the linestate condition
2361          * can vary from one PHY to another.
2362          */
2363         usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
2364         usbcfg |= GUSBCFG_TOUTCAL(7);
2365         dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
2366
2367         /* Restart the Phy Clock */
2368         dwc2_writel(0, hsotg->regs + PCGCTL);
2369
2370         /* Initialize Host Configuration Register */
2371         dwc2_init_fs_ls_pclk_sel(hsotg);
2372         if (hsotg->params.speed == DWC2_SPEED_PARAM_FULL ||
2373             hsotg->params.speed == DWC2_SPEED_PARAM_LOW) {
2374                 hcfg = dwc2_readl(hsotg->regs + HCFG);
2375                 hcfg |= HCFG_FSLSSUPP;
2376                 dwc2_writel(hcfg, hsotg->regs + HCFG);
2377         }
2378
2379         /*
2380          * This bit allows dynamic reloading of the HFIR register during
2381          * runtime. This bit needs to be programmed during initial configuration
2382          * and its value must not be changed during runtime.
2383          */
2384         if (hsotg->params.reload_ctl) {
2385                 hfir = dwc2_readl(hsotg->regs + HFIR);
2386                 hfir |= HFIR_RLDCTRL;
2387                 dwc2_writel(hfir, hsotg->regs + HFIR);
2388         }
2389
2390         if (hsotg->params.dma_desc_enable) {
2391                 u32 op_mode = hsotg->hw_params.op_mode;
2392
2393                 if (hsotg->hw_params.snpsid < DWC2_CORE_REV_2_90a ||
2394                     !hsotg->hw_params.dma_desc_enable ||
2395                     op_mode == GHWCFG2_OP_MODE_SRP_CAPABLE_DEVICE ||
2396                     op_mode == GHWCFG2_OP_MODE_NO_SRP_CAPABLE_DEVICE ||
2397                     op_mode == GHWCFG2_OP_MODE_UNDEFINED) {
2398                         dev_err(hsotg->dev,
2399                                 "Hardware does not support descriptor DMA mode -\n");
2400                         dev_err(hsotg->dev,
2401                                 "falling back to buffer DMA mode.\n");
2402                         hsotg->params.dma_desc_enable = false;
2403                 } else {
2404                         hcfg = dwc2_readl(hsotg->regs + HCFG);
2405                         hcfg |= HCFG_DESCDMA;
2406                         dwc2_writel(hcfg, hsotg->regs + HCFG);
2407                 }
2408         }
2409
2410         /* Configure data FIFO sizes */
2411         dwc2_config_fifos(hsotg);
2412
2413         /* TODO - check this */
2414         /* Clear Host Set HNP Enable in the OTG Control Register */
2415         otgctl = dwc2_readl(hsotg->regs + GOTGCTL);
2416         otgctl &= ~GOTGCTL_HSTSETHNPEN;
2417         dwc2_writel(otgctl, hsotg->regs + GOTGCTL);
2418
2419         /* Make sure the FIFOs are flushed */
2420         dwc2_flush_tx_fifo(hsotg, 0x10 /* all TX FIFOs */);
2421         dwc2_flush_rx_fifo(hsotg);
2422
2423         /* Clear Host Set HNP Enable in the OTG Control Register */
2424         otgctl = dwc2_readl(hsotg->regs + GOTGCTL);
2425         otgctl &= ~GOTGCTL_HSTSETHNPEN;
2426         dwc2_writel(otgctl, hsotg->regs + GOTGCTL);
2427
2428         if (!hsotg->params.dma_desc_enable) {
2429                 int num_channels, i;
2430                 u32 hcchar;
2431
2432                 /* Flush out any leftover queued requests */
2433                 num_channels = hsotg->params.host_channels;
2434                 for (i = 0; i < num_channels; i++) {
2435                         hcchar = dwc2_readl(hsotg->regs + HCCHAR(i));
2436                         hcchar &= ~HCCHAR_CHENA;
2437                         hcchar |= HCCHAR_CHDIS;
2438                         hcchar &= ~HCCHAR_EPDIR;
2439                         dwc2_writel(hcchar, hsotg->regs + HCCHAR(i));
2440                 }
2441
2442                 /* Halt all channels to put them into a known state */
2443                 for (i = 0; i < num_channels; i++) {
2444                         hcchar = dwc2_readl(hsotg->regs + HCCHAR(i));
2445                         hcchar |= HCCHAR_CHENA | HCCHAR_CHDIS;
2446                         hcchar &= ~HCCHAR_EPDIR;
2447                         dwc2_writel(hcchar, hsotg->regs + HCCHAR(i));
2448                         dev_dbg(hsotg->dev, "%s: Halt channel %d\n",
2449                                 __func__, i);
2450
2451                         if (dwc2_hsotg_wait_bit_clear(hsotg, HCCHAR(i),
2452                                                       HCCHAR_CHENA, 1000)) {
2453                                 dev_warn(hsotg->dev, "Unable to clear enable on channel %d\n",
2454                                          i);
2455                         }
2456                 }
2457         }
2458
2459         /* Enable ACG feature in host mode, if supported */
2460         dwc2_enable_acg(hsotg);
2461
2462         /* Turn on the vbus power */
2463         dev_dbg(hsotg->dev, "Init: Port Power? op_state=%d\n", hsotg->op_state);
2464         if (hsotg->op_state == OTG_STATE_A_HOST) {
2465                 u32 hprt0 = dwc2_read_hprt0(hsotg);
2466
2467                 dev_dbg(hsotg->dev, "Init: Power Port (%d)\n",
2468                         !!(hprt0 & HPRT0_PWR));
2469                 if (!(hprt0 & HPRT0_PWR)) {
2470                         hprt0 |= HPRT0_PWR;
2471                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
2472                 }
2473         }
2474
2475         dwc2_enable_host_interrupts(hsotg);
2476 }
2477
2478 /*
2479  * Initializes dynamic portions of the DWC_otg HCD state
2480  *
2481  * Must be called with interrupt disabled and spinlock held
2482  */
2483 static void dwc2_hcd_reinit(struct dwc2_hsotg *hsotg)
2484 {
2485         struct dwc2_host_chan *chan, *chan_tmp;
2486         int num_channels;
2487         int i;
2488
2489         hsotg->flags.d32 = 0;
2490         hsotg->non_periodic_qh_ptr = &hsotg->non_periodic_sched_active;
2491
2492         if (hsotg->params.uframe_sched) {
2493                 hsotg->available_host_channels =
2494                         hsotg->params.host_channels;
2495         } else {
2496                 hsotg->non_periodic_channels = 0;
2497                 hsotg->periodic_channels = 0;
2498         }
2499
2500         /*
2501          * Put all channels in the free channel list and clean up channel
2502          * states
2503          */
2504         list_for_each_entry_safe(chan, chan_tmp, &hsotg->free_hc_list,
2505                                  hc_list_entry)
2506                 list_del_init(&chan->hc_list_entry);
2507
2508         num_channels = hsotg->params.host_channels;
2509         for (i = 0; i < num_channels; i++) {
2510                 chan = hsotg->hc_ptr_array[i];
2511                 list_add_tail(&chan->hc_list_entry, &hsotg->free_hc_list);
2512                 dwc2_hc_cleanup(hsotg, chan);
2513         }
2514
2515         /* Initialize the DWC core for host mode operation */
2516         dwc2_core_host_init(hsotg);
2517 }
2518
2519 static void dwc2_hc_init_split(struct dwc2_hsotg *hsotg,
2520                                struct dwc2_host_chan *chan,
2521                                struct dwc2_qtd *qtd, struct dwc2_hcd_urb *urb)
2522 {
2523         int hub_addr, hub_port;
2524
2525         chan->do_split = 1;
2526         chan->xact_pos = qtd->isoc_split_pos;
2527         chan->complete_split = qtd->complete_split;
2528         dwc2_host_hub_info(hsotg, urb->priv, &hub_addr, &hub_port);
2529         chan->hub_addr = (u8)hub_addr;
2530         chan->hub_port = (u8)hub_port;
2531 }
2532
2533 static void dwc2_hc_init_xfer(struct dwc2_hsotg *hsotg,
2534                               struct dwc2_host_chan *chan,
2535                               struct dwc2_qtd *qtd)
2536 {
2537         struct dwc2_hcd_urb *urb = qtd->urb;
2538         struct dwc2_hcd_iso_packet_desc *frame_desc;
2539
2540         switch (dwc2_hcd_get_pipe_type(&urb->pipe_info)) {
2541         case USB_ENDPOINT_XFER_CONTROL:
2542                 chan->ep_type = USB_ENDPOINT_XFER_CONTROL;
2543
2544                 switch (qtd->control_phase) {
2545                 case DWC2_CONTROL_SETUP:
2546                         dev_vdbg(hsotg->dev, "  Control setup transaction\n");
2547                         chan->do_ping = 0;
2548                         chan->ep_is_in = 0;
2549                         chan->data_pid_start = DWC2_HC_PID_SETUP;
2550                         if (hsotg->params.host_dma)
2551                                 chan->xfer_dma = urb->setup_dma;
2552                         else
2553                                 chan->xfer_buf = urb->setup_packet;
2554                         chan->xfer_len = 8;
2555                         break;
2556
2557                 case DWC2_CONTROL_DATA:
2558                         dev_vdbg(hsotg->dev, "  Control data transaction\n");
2559                         chan->data_pid_start = qtd->data_toggle;
2560                         break;
2561
2562                 case DWC2_CONTROL_STATUS:
2563                         /*
2564                          * Direction is opposite of data direction or IN if no
2565                          * data
2566                          */
2567                         dev_vdbg(hsotg->dev, "  Control status transaction\n");
2568                         if (urb->length == 0)
2569                                 chan->ep_is_in = 1;
2570                         else
2571                                 chan->ep_is_in =
2572                                         dwc2_hcd_is_pipe_out(&urb->pipe_info);
2573                         if (chan->ep_is_in)
2574                                 chan->do_ping = 0;
2575                         chan->data_pid_start = DWC2_HC_PID_DATA1;
2576                         chan->xfer_len = 0;
2577                         if (hsotg->params.host_dma)
2578                                 chan->xfer_dma = hsotg->status_buf_dma;
2579                         else
2580                                 chan->xfer_buf = hsotg->status_buf;
2581                         break;
2582                 }
2583                 break;
2584
2585         case USB_ENDPOINT_XFER_BULK:
2586                 chan->ep_type = USB_ENDPOINT_XFER_BULK;
2587                 break;
2588
2589         case USB_ENDPOINT_XFER_INT:
2590                 chan->ep_type = USB_ENDPOINT_XFER_INT;
2591                 break;
2592
2593         case USB_ENDPOINT_XFER_ISOC:
2594                 chan->ep_type = USB_ENDPOINT_XFER_ISOC;
2595                 if (hsotg->params.dma_desc_enable)
2596                         break;
2597
2598                 frame_desc = &urb->iso_descs[qtd->isoc_frame_index];
2599                 frame_desc->status = 0;
2600
2601                 if (hsotg->params.host_dma) {
2602                         chan->xfer_dma = urb->dma;
2603                         chan->xfer_dma += frame_desc->offset +
2604                                         qtd->isoc_split_offset;
2605                 } else {
2606                         chan->xfer_buf = urb->buf;
2607                         chan->xfer_buf += frame_desc->offset +
2608                                         qtd->isoc_split_offset;
2609                 }
2610
2611                 chan->xfer_len = frame_desc->length - qtd->isoc_split_offset;
2612
2613                 if (chan->xact_pos == DWC2_HCSPLT_XACTPOS_ALL) {
2614                         if (chan->xfer_len <= 188)
2615                                 chan->xact_pos = DWC2_HCSPLT_XACTPOS_ALL;
2616                         else
2617                                 chan->xact_pos = DWC2_HCSPLT_XACTPOS_BEGIN;
2618                 }
2619                 break;
2620         }
2621 }
2622
2623 #define DWC2_USB_DMA_ALIGN 4
2624
2625 struct dma_aligned_buffer {
2626         void *kmalloc_ptr;
2627         void *old_xfer_buffer;
2628         u8 data[0];
2629 };
2630
2631 static void dwc2_free_dma_aligned_buffer(struct urb *urb)
2632 {
2633         struct dma_aligned_buffer *temp;
2634
2635         if (!(urb->transfer_flags & URB_ALIGNED_TEMP_BUFFER))
2636                 return;
2637
2638         temp = container_of(urb->transfer_buffer,
2639                             struct dma_aligned_buffer, data);
2640
2641         if (usb_urb_dir_in(urb))
2642                 memcpy(temp->old_xfer_buffer, temp->data,
2643                        urb->transfer_buffer_length);
2644         urb->transfer_buffer = temp->old_xfer_buffer;
2645         kfree(temp->kmalloc_ptr);
2646
2647         urb->transfer_flags &= ~URB_ALIGNED_TEMP_BUFFER;
2648 }
2649
2650 static int dwc2_alloc_dma_aligned_buffer(struct urb *urb, gfp_t mem_flags)
2651 {
2652         struct dma_aligned_buffer *temp, *kmalloc_ptr;
2653         size_t kmalloc_size;
2654
2655         if (urb->num_sgs || urb->sg ||
2656             urb->transfer_buffer_length == 0 ||
2657             !((uintptr_t)urb->transfer_buffer & (DWC2_USB_DMA_ALIGN - 1)))
2658                 return 0;
2659
2660         /* Allocate a buffer with enough padding for alignment */
2661         kmalloc_size = urb->transfer_buffer_length +
2662                 sizeof(struct dma_aligned_buffer) + DWC2_USB_DMA_ALIGN - 1;
2663
2664         kmalloc_ptr = kmalloc(kmalloc_size, mem_flags);
2665         if (!kmalloc_ptr)
2666                 return -ENOMEM;
2667
2668         /* Position our struct dma_aligned_buffer such that data is aligned */
2669         temp = PTR_ALIGN(kmalloc_ptr + 1, DWC2_USB_DMA_ALIGN) - 1;
2670         temp->kmalloc_ptr = kmalloc_ptr;
2671         temp->old_xfer_buffer = urb->transfer_buffer;
2672         if (usb_urb_dir_out(urb))
2673                 memcpy(temp->data, urb->transfer_buffer,
2674                        urb->transfer_buffer_length);
2675         urb->transfer_buffer = temp->data;
2676
2677         urb->transfer_flags |= URB_ALIGNED_TEMP_BUFFER;
2678
2679         return 0;
2680 }
2681
2682 static int dwc2_map_urb_for_dma(struct usb_hcd *hcd, struct urb *urb,
2683                                 gfp_t mem_flags)
2684 {
2685         int ret;
2686
2687         /* We assume setup_dma is always aligned; warn if not */
2688         WARN_ON_ONCE(urb->setup_dma &&
2689                      (urb->setup_dma & (DWC2_USB_DMA_ALIGN - 1)));
2690
2691         ret = dwc2_alloc_dma_aligned_buffer(urb, mem_flags);
2692         if (ret)
2693                 return ret;
2694
2695         ret = usb_hcd_map_urb_for_dma(hcd, urb, mem_flags);
2696         if (ret)
2697                 dwc2_free_dma_aligned_buffer(urb);
2698
2699         return ret;
2700 }
2701
2702 static void dwc2_unmap_urb_for_dma(struct usb_hcd *hcd, struct urb *urb)
2703 {
2704         usb_hcd_unmap_urb_for_dma(hcd, urb);
2705         dwc2_free_dma_aligned_buffer(urb);
2706 }
2707
2708 /**
2709  * dwc2_assign_and_init_hc() - Assigns transactions from a QTD to a free host
2710  * channel and initializes the host channel to perform the transactions. The
2711  * host channel is removed from the free list.
2712  *
2713  * @hsotg: The HCD state structure
2714  * @qh:    Transactions from the first QTD for this QH are selected and assigned
2715  *         to a free host channel
2716  */
2717 static int dwc2_assign_and_init_hc(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh)
2718 {
2719         struct dwc2_host_chan *chan;
2720         struct dwc2_hcd_urb *urb;
2721         struct dwc2_qtd *qtd;
2722
2723         if (dbg_qh(qh))
2724                 dev_vdbg(hsotg->dev, "%s(%p,%p)\n", __func__, hsotg, qh);
2725
2726         if (list_empty(&qh->qtd_list)) {
2727                 dev_dbg(hsotg->dev, "No QTDs in QH list\n");
2728                 return -ENOMEM;
2729         }
2730
2731         if (list_empty(&hsotg->free_hc_list)) {
2732                 dev_dbg(hsotg->dev, "No free channel to assign\n");
2733                 return -ENOMEM;
2734         }
2735
2736         chan = list_first_entry(&hsotg->free_hc_list, struct dwc2_host_chan,
2737                                 hc_list_entry);
2738
2739         /* Remove host channel from free list */
2740         list_del_init(&chan->hc_list_entry);
2741
2742         qtd = list_first_entry(&qh->qtd_list, struct dwc2_qtd, qtd_list_entry);
2743         urb = qtd->urb;
2744         qh->channel = chan;
2745         qtd->in_process = 1;
2746
2747         /*
2748          * Use usb_pipedevice to determine device address. This address is
2749          * 0 before the SET_ADDRESS command and the correct address afterward.
2750          */
2751         chan->dev_addr = dwc2_hcd_get_dev_addr(&urb->pipe_info);
2752         chan->ep_num = dwc2_hcd_get_ep_num(&urb->pipe_info);
2753         chan->speed = qh->dev_speed;
2754         chan->max_packet = dwc2_max_packet(qh->maxp);
2755
2756         chan->xfer_started = 0;
2757         chan->halt_status = DWC2_HC_XFER_NO_HALT_STATUS;
2758         chan->error_state = (qtd->error_count > 0);
2759         chan->halt_on_queue = 0;
2760         chan->halt_pending = 0;
2761         chan->requests = 0;
2762
2763         /*
2764          * The following values may be modified in the transfer type section
2765          * below. The xfer_len value may be reduced when the transfer is
2766          * started to accommodate the max widths of the XferSize and PktCnt
2767          * fields in the HCTSIZn register.
2768          */
2769
2770         chan->ep_is_in = (dwc2_hcd_is_pipe_in(&urb->pipe_info) != 0);
2771         if (chan->ep_is_in)
2772                 chan->do_ping = 0;
2773         else
2774                 chan->do_ping = qh->ping_state;
2775
2776         chan->data_pid_start = qh->data_toggle;
2777         chan->multi_count = 1;
2778
2779         if (urb->actual_length > urb->length &&
2780             !dwc2_hcd_is_pipe_in(&urb->pipe_info))
2781                 urb->actual_length = urb->length;
2782
2783         if (hsotg->params.host_dma)
2784                 chan->xfer_dma = urb->dma + urb->actual_length;
2785         else
2786                 chan->xfer_buf = (u8 *)urb->buf + urb->actual_length;
2787
2788         chan->xfer_len = urb->length - urb->actual_length;
2789         chan->xfer_count = 0;
2790
2791         /* Set the split attributes if required */
2792         if (qh->do_split)
2793                 dwc2_hc_init_split(hsotg, chan, qtd, urb);
2794         else
2795                 chan->do_split = 0;
2796
2797         /* Set the transfer attributes */
2798         dwc2_hc_init_xfer(hsotg, chan, qtd);
2799
2800         if (chan->ep_type == USB_ENDPOINT_XFER_INT ||
2801             chan->ep_type == USB_ENDPOINT_XFER_ISOC)
2802                 /*
2803                  * This value may be modified when the transfer is started
2804                  * to reflect the actual transfer length
2805                  */
2806                 chan->multi_count = dwc2_hb_mult(qh->maxp);
2807
2808         if (hsotg->params.dma_desc_enable) {
2809                 chan->desc_list_addr = qh->desc_list_dma;
2810                 chan->desc_list_sz = qh->desc_list_sz;
2811         }
2812
2813         dwc2_hc_init(hsotg, chan);
2814         chan->qh = qh;
2815
2816         return 0;
2817 }
2818
2819 /**
2820  * dwc2_hcd_select_transactions() - Selects transactions from the HCD transfer
2821  * schedule and assigns them to available host channels. Called from the HCD
2822  * interrupt handler functions.
2823  *
2824  * @hsotg: The HCD state structure
2825  *
2826  * Return: The types of new transactions that were assigned to host channels
2827  */
2828 enum dwc2_transaction_type dwc2_hcd_select_transactions(
2829                 struct dwc2_hsotg *hsotg)
2830 {
2831         enum dwc2_transaction_type ret_val = DWC2_TRANSACTION_NONE;
2832         struct list_head *qh_ptr;
2833         struct dwc2_qh *qh;
2834         int num_channels;
2835
2836 #ifdef DWC2_DEBUG_SOF
2837         dev_vdbg(hsotg->dev, "  Select Transactions\n");
2838 #endif
2839
2840         /* Process entries in the periodic ready list */
2841         qh_ptr = hsotg->periodic_sched_ready.next;
2842         while (qh_ptr != &hsotg->periodic_sched_ready) {
2843                 if (list_empty(&hsotg->free_hc_list))
2844                         break;
2845                 if (hsotg->params.uframe_sched) {
2846                         if (hsotg->available_host_channels <= 1)
2847                                 break;
2848                         hsotg->available_host_channels--;
2849                 }
2850                 qh = list_entry(qh_ptr, struct dwc2_qh, qh_list_entry);
2851                 if (dwc2_assign_and_init_hc(hsotg, qh))
2852                         break;
2853
2854                 /*
2855                  * Move the QH from the periodic ready schedule to the
2856                  * periodic assigned schedule
2857                  */
2858                 qh_ptr = qh_ptr->next;
2859                 list_move_tail(&qh->qh_list_entry,
2860                                &hsotg->periodic_sched_assigned);
2861                 ret_val = DWC2_TRANSACTION_PERIODIC;
2862         }
2863
2864         /*
2865          * Process entries in the inactive portion of the non-periodic
2866          * schedule. Some free host channels may not be used if they are
2867          * reserved for periodic transfers.
2868          */
2869         num_channels = hsotg->params.host_channels;
2870         qh_ptr = hsotg->non_periodic_sched_inactive.next;
2871         while (qh_ptr != &hsotg->non_periodic_sched_inactive) {
2872                 if (!hsotg->params.uframe_sched &&
2873                     hsotg->non_periodic_channels >= num_channels -
2874                                                 hsotg->periodic_channels)
2875                         break;
2876                 if (list_empty(&hsotg->free_hc_list))
2877                         break;
2878                 qh = list_entry(qh_ptr, struct dwc2_qh, qh_list_entry);
2879                 if (hsotg->params.uframe_sched) {
2880                         if (hsotg->available_host_channels < 1)
2881                                 break;
2882                         hsotg->available_host_channels--;
2883                 }
2884
2885                 if (dwc2_assign_and_init_hc(hsotg, qh))
2886                         break;
2887
2888                 /*
2889                  * Move the QH from the non-periodic inactive schedule to the
2890                  * non-periodic active schedule
2891                  */
2892                 qh_ptr = qh_ptr->next;
2893                 list_move_tail(&qh->qh_list_entry,
2894                                &hsotg->non_periodic_sched_active);
2895
2896                 if (ret_val == DWC2_TRANSACTION_NONE)
2897                         ret_val = DWC2_TRANSACTION_NON_PERIODIC;
2898                 else
2899                         ret_val = DWC2_TRANSACTION_ALL;
2900
2901                 if (!hsotg->params.uframe_sched)
2902                         hsotg->non_periodic_channels++;
2903         }
2904
2905         return ret_val;
2906 }
2907
2908 /**
2909  * dwc2_queue_transaction() - Attempts to queue a single transaction request for
2910  * a host channel associated with either a periodic or non-periodic transfer
2911  *
2912  * @hsotg: The HCD state structure
2913  * @chan:  Host channel descriptor associated with either a periodic or
2914  *         non-periodic transfer
2915  * @fifo_dwords_avail: Number of DWORDs available in the periodic Tx FIFO
2916  *                     for periodic transfers or the non-periodic Tx FIFO
2917  *                     for non-periodic transfers
2918  *
2919  * Return: 1 if a request is queued and more requests may be needed to
2920  * complete the transfer, 0 if no more requests are required for this
2921  * transfer, -1 if there is insufficient space in the Tx FIFO
2922  *
2923  * This function assumes that there is space available in the appropriate
2924  * request queue. For an OUT transfer or SETUP transaction in Slave mode,
2925  * it checks whether space is available in the appropriate Tx FIFO.
2926  *
2927  * Must be called with interrupt disabled and spinlock held
2928  */
2929 static int dwc2_queue_transaction(struct dwc2_hsotg *hsotg,
2930                                   struct dwc2_host_chan *chan,
2931                                   u16 fifo_dwords_avail)
2932 {
2933         int retval = 0;
2934
2935         if (chan->do_split)
2936                 /* Put ourselves on the list to keep order straight */
2937                 list_move_tail(&chan->split_order_list_entry,
2938                                &hsotg->split_order);
2939
2940         if (hsotg->params.host_dma) {
2941                 if (hsotg->params.dma_desc_enable) {
2942                         if (!chan->xfer_started ||
2943                             chan->ep_type == USB_ENDPOINT_XFER_ISOC) {
2944                                 dwc2_hcd_start_xfer_ddma(hsotg, chan->qh);
2945                                 chan->qh->ping_state = 0;
2946                         }
2947                 } else if (!chan->xfer_started) {
2948                         dwc2_hc_start_transfer(hsotg, chan);
2949                         chan->qh->ping_state = 0;
2950                 }
2951         } else if (chan->halt_pending) {
2952                 /* Don't queue a request if the channel has been halted */
2953         } else if (chan->halt_on_queue) {
2954                 dwc2_hc_halt(hsotg, chan, chan->halt_status);
2955         } else if (chan->do_ping) {
2956                 if (!chan->xfer_started)
2957                         dwc2_hc_start_transfer(hsotg, chan);
2958         } else if (!chan->ep_is_in ||
2959                    chan->data_pid_start == DWC2_HC_PID_SETUP) {
2960                 if ((fifo_dwords_avail * 4) >= chan->max_packet) {
2961                         if (!chan->xfer_started) {
2962                                 dwc2_hc_start_transfer(hsotg, chan);
2963                                 retval = 1;
2964                         } else {
2965                                 retval = dwc2_hc_continue_transfer(hsotg, chan);
2966                         }
2967                 } else {
2968                         retval = -1;
2969                 }
2970         } else {
2971                 if (!chan->xfer_started) {
2972                         dwc2_hc_start_transfer(hsotg, chan);
2973                         retval = 1;
2974                 } else {
2975                         retval = dwc2_hc_continue_transfer(hsotg, chan);
2976                 }
2977         }
2978
2979         return retval;
2980 }
2981
2982 /*
2983  * Processes periodic channels for the next frame and queues transactions for
2984  * these channels to the DWC_otg controller. After queueing transactions, the
2985  * Periodic Tx FIFO Empty interrupt is enabled if there are more transactions
2986  * to queue as Periodic Tx FIFO or request queue space becomes available.
2987  * Otherwise, the Periodic Tx FIFO Empty interrupt is disabled.
2988  *
2989  * Must be called with interrupt disabled and spinlock held
2990  */
2991 static void dwc2_process_periodic_channels(struct dwc2_hsotg *hsotg)
2992 {
2993         struct list_head *qh_ptr;
2994         struct dwc2_qh *qh;
2995         u32 tx_status;
2996         u32 fspcavail;
2997         u32 gintmsk;
2998         int status;
2999         bool no_queue_space = false;
3000         bool no_fifo_space = false;
3001         u32 qspcavail;
3002
3003         /* If empty list then just adjust interrupt enables */
3004         if (list_empty(&hsotg->periodic_sched_assigned))
3005                 goto exit;
3006
3007         if (dbg_perio())
3008                 dev_vdbg(hsotg->dev, "Queue periodic transactions\n");
3009
3010         tx_status = dwc2_readl(hsotg->regs + HPTXSTS);
3011         qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
3012                     TXSTS_QSPCAVAIL_SHIFT;
3013         fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
3014                     TXSTS_FSPCAVAIL_SHIFT;
3015
3016         if (dbg_perio()) {
3017                 dev_vdbg(hsotg->dev, "  P Tx Req Queue Space Avail (before queue): %d\n",
3018                          qspcavail);
3019                 dev_vdbg(hsotg->dev, "  P Tx FIFO Space Avail (before queue): %d\n",
3020                          fspcavail);
3021         }
3022
3023         qh_ptr = hsotg->periodic_sched_assigned.next;
3024         while (qh_ptr != &hsotg->periodic_sched_assigned) {
3025                 tx_status = dwc2_readl(hsotg->regs + HPTXSTS);
3026                 qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
3027                             TXSTS_QSPCAVAIL_SHIFT;
3028                 if (qspcavail == 0) {
3029                         no_queue_space = true;
3030                         break;
3031                 }
3032
3033                 qh = list_entry(qh_ptr, struct dwc2_qh, qh_list_entry);
3034                 if (!qh->channel) {
3035                         qh_ptr = qh_ptr->next;
3036                         continue;
3037                 }
3038
3039                 /* Make sure EP's TT buffer is clean before queueing qtds */
3040                 if (qh->tt_buffer_dirty) {
3041                         qh_ptr = qh_ptr->next;
3042                         continue;
3043                 }
3044
3045                 /*
3046                  * Set a flag if we're queuing high-bandwidth in slave mode.
3047                  * The flag prevents any halts to get into the request queue in
3048                  * the middle of multiple high-bandwidth packets getting queued.
3049                  */
3050                 if (!hsotg->params.host_dma &&
3051                     qh->channel->multi_count > 1)
3052                         hsotg->queuing_high_bandwidth = 1;
3053
3054                 fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
3055                             TXSTS_FSPCAVAIL_SHIFT;
3056                 status = dwc2_queue_transaction(hsotg, qh->channel, fspcavail);
3057                 if (status < 0) {
3058                         no_fifo_space = true;
3059                         break;
3060                 }
3061
3062                 /*
3063                  * In Slave mode, stay on the current transfer until there is
3064                  * nothing more to do or the high-bandwidth request count is
3065                  * reached. In DMA mode, only need to queue one request. The
3066                  * controller automatically handles multiple packets for
3067                  * high-bandwidth transfers.
3068                  */
3069                 if (hsotg->params.host_dma || status == 0 ||
3070                     qh->channel->requests == qh->channel->multi_count) {
3071                         qh_ptr = qh_ptr->next;
3072                         /*
3073                          * Move the QH from the periodic assigned schedule to
3074                          * the periodic queued schedule
3075                          */
3076                         list_move_tail(&qh->qh_list_entry,
3077                                        &hsotg->periodic_sched_queued);
3078
3079                         /* done queuing high bandwidth */
3080                         hsotg->queuing_high_bandwidth = 0;
3081                 }
3082         }
3083
3084 exit:
3085         if (no_queue_space || no_fifo_space ||
3086             (!hsotg->params.host_dma &&
3087              !list_empty(&hsotg->periodic_sched_assigned))) {
3088                 /*
3089                  * May need to queue more transactions as the request
3090                  * queue or Tx FIFO empties. Enable the periodic Tx
3091                  * FIFO empty interrupt. (Always use the half-empty
3092                  * level to ensure that new requests are loaded as
3093                  * soon as possible.)
3094                  */
3095                 gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
3096                 if (!(gintmsk & GINTSTS_PTXFEMP)) {
3097                         gintmsk |= GINTSTS_PTXFEMP;
3098                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
3099                 }
3100         } else {
3101                 /*
3102                  * Disable the Tx FIFO empty interrupt since there are
3103                  * no more transactions that need to be queued right
3104                  * now. This function is called from interrupt
3105                  * handlers to queue more transactions as transfer
3106                  * states change.
3107                  */
3108                 gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
3109                 if (gintmsk & GINTSTS_PTXFEMP) {
3110                         gintmsk &= ~GINTSTS_PTXFEMP;
3111                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
3112                 }
3113         }
3114 }
3115
3116 /*
3117  * Processes active non-periodic channels and queues transactions for these
3118  * channels to the DWC_otg controller. After queueing transactions, the NP Tx
3119  * FIFO Empty interrupt is enabled if there are more transactions to queue as
3120  * NP Tx FIFO or request queue space becomes available. Otherwise, the NP Tx
3121  * FIFO Empty interrupt is disabled.
3122  *
3123  * Must be called with interrupt disabled and spinlock held
3124  */
3125 static void dwc2_process_non_periodic_channels(struct dwc2_hsotg *hsotg)
3126 {
3127         struct list_head *orig_qh_ptr;
3128         struct dwc2_qh *qh;
3129         u32 tx_status;
3130         u32 qspcavail;
3131         u32 fspcavail;
3132         u32 gintmsk;
3133         int status;
3134         int no_queue_space = 0;
3135         int no_fifo_space = 0;
3136         int more_to_do = 0;
3137
3138         dev_vdbg(hsotg->dev, "Queue non-periodic transactions\n");
3139
3140         tx_status = dwc2_readl(hsotg->regs + GNPTXSTS);
3141         qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
3142                     TXSTS_QSPCAVAIL_SHIFT;
3143         fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
3144                     TXSTS_FSPCAVAIL_SHIFT;
3145         dev_vdbg(hsotg->dev, "  NP Tx Req Queue Space Avail (before queue): %d\n",
3146                  qspcavail);
3147         dev_vdbg(hsotg->dev, "  NP Tx FIFO Space Avail (before queue): %d\n",
3148                  fspcavail);
3149
3150         /*
3151          * Keep track of the starting point. Skip over the start-of-list
3152          * entry.
3153          */
3154         if (hsotg->non_periodic_qh_ptr == &hsotg->non_periodic_sched_active)
3155                 hsotg->non_periodic_qh_ptr = hsotg->non_periodic_qh_ptr->next;
3156         orig_qh_ptr = hsotg->non_periodic_qh_ptr;
3157
3158         /*
3159          * Process once through the active list or until no more space is
3160          * available in the request queue or the Tx FIFO
3161          */
3162         do {
3163                 tx_status = dwc2_readl(hsotg->regs + GNPTXSTS);
3164                 qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
3165                             TXSTS_QSPCAVAIL_SHIFT;
3166                 if (!hsotg->params.host_dma && qspcavail == 0) {
3167                         no_queue_space = 1;
3168                         break;
3169                 }
3170
3171                 qh = list_entry(hsotg->non_periodic_qh_ptr, struct dwc2_qh,
3172                                 qh_list_entry);
3173                 if (!qh->channel)
3174                         goto next;
3175
3176                 /* Make sure EP's TT buffer is clean before queueing qtds */
3177                 if (qh->tt_buffer_dirty)
3178                         goto next;
3179
3180                 fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
3181                             TXSTS_FSPCAVAIL_SHIFT;
3182                 status = dwc2_queue_transaction(hsotg, qh->channel, fspcavail);
3183
3184                 if (status > 0) {
3185                         more_to_do = 1;
3186                 } else if (status < 0) {
3187                         no_fifo_space = 1;
3188                         break;
3189                 }
3190 next:
3191                 /* Advance to next QH, skipping start-of-list entry */
3192                 hsotg->non_periodic_qh_ptr = hsotg->non_periodic_qh_ptr->next;
3193                 if (hsotg->non_periodic_qh_ptr ==
3194                                 &hsotg->non_periodic_sched_active)
3195                         hsotg->non_periodic_qh_ptr =
3196                                         hsotg->non_periodic_qh_ptr->next;
3197         } while (hsotg->non_periodic_qh_ptr != orig_qh_ptr);
3198
3199         if (!hsotg->params.host_dma) {
3200                 tx_status = dwc2_readl(hsotg->regs + GNPTXSTS);
3201                 qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
3202                             TXSTS_QSPCAVAIL_SHIFT;
3203                 fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
3204                             TXSTS_FSPCAVAIL_SHIFT;
3205                 dev_vdbg(hsotg->dev,
3206                          "  NP Tx Req Queue Space Avail (after queue): %d\n",
3207                          qspcavail);
3208                 dev_vdbg(hsotg->dev,
3209                          "  NP Tx FIFO Space Avail (after queue): %d\n",
3210                          fspcavail);
3211
3212                 if (more_to_do || no_queue_space || no_fifo_space) {
3213                         /*
3214                          * May need to queue more transactions as the request
3215                          * queue or Tx FIFO empties. Enable the non-periodic
3216                          * Tx FIFO empty interrupt. (Always use the half-empty
3217                          * level to ensure that new requests are loaded as
3218                          * soon as possible.)
3219                          */
3220                         gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
3221                         gintmsk |= GINTSTS_NPTXFEMP;
3222                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
3223                 } else {
3224                         /*
3225                          * Disable the Tx FIFO empty interrupt since there are
3226                          * no more transactions that need to be queued right
3227                          * now. This function is called from interrupt
3228                          * handlers to queue more transactions as transfer
3229                          * states change.
3230                          */
3231                         gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
3232                         gintmsk &= ~GINTSTS_NPTXFEMP;
3233                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
3234                 }
3235         }
3236 }
3237
3238 /**
3239  * dwc2_hcd_queue_transactions() - Processes the currently active host channels
3240  * and queues transactions for these channels to the DWC_otg controller. Called
3241  * from the HCD interrupt handler functions.
3242  *
3243  * @hsotg:   The HCD state structure
3244  * @tr_type: The type(s) of transactions to queue (non-periodic, periodic,
3245  *           or both)
3246  *
3247  * Must be called with interrupt disabled and spinlock held
3248  */
3249 void dwc2_hcd_queue_transactions(struct dwc2_hsotg *hsotg,
3250                                  enum dwc2_transaction_type tr_type)
3251 {
3252 #ifdef DWC2_DEBUG_SOF
3253         dev_vdbg(hsotg->dev, "Queue Transactions\n");
3254 #endif
3255         /* Process host channels associated with periodic transfers */
3256         if (tr_type == DWC2_TRANSACTION_PERIODIC ||
3257             tr_type == DWC2_TRANSACTION_ALL)
3258                 dwc2_process_periodic_channels(hsotg);
3259
3260         /* Process host channels associated with non-periodic transfers */
3261         if (tr_type == DWC2_TRANSACTION_NON_PERIODIC ||
3262             tr_type == DWC2_TRANSACTION_ALL) {
3263                 if (!list_empty(&hsotg->non_periodic_sched_active)) {
3264                         dwc2_process_non_periodic_channels(hsotg);
3265                 } else {
3266                         /*
3267                          * Ensure NP Tx FIFO empty interrupt is disabled when
3268                          * there are no non-periodic transfers to process
3269                          */
3270                         u32 gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
3271
3272                         gintmsk &= ~GINTSTS_NPTXFEMP;
3273                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
3274                 }
3275         }
3276 }
3277
3278 static void dwc2_conn_id_status_change(struct work_struct *work)
3279 {
3280         struct dwc2_hsotg *hsotg = container_of(work, struct dwc2_hsotg,
3281                                                 wf_otg);
3282         u32 count = 0;
3283         u32 gotgctl;
3284         unsigned long flags;
3285
3286         dev_dbg(hsotg->dev, "%s()\n", __func__);
3287
3288         gotgctl = dwc2_readl(hsotg->regs + GOTGCTL);
3289         dev_dbg(hsotg->dev, "gotgctl=%0x\n", gotgctl);
3290         dev_dbg(hsotg->dev, "gotgctl.b.conidsts=%d\n",
3291                 !!(gotgctl & GOTGCTL_CONID_B));
3292
3293         /* B-Device connector (Device Mode) */
3294         if (gotgctl & GOTGCTL_CONID_B) {
3295                 dwc2_vbus_supply_exit(hsotg);
3296                 /* Wait for switch to device mode */
3297                 dev_dbg(hsotg->dev, "connId B\n");
3298                 if (hsotg->bus_suspended) {
3299                         dev_info(hsotg->dev,
3300                                  "Do port resume before switching to device mode\n");
3301                         dwc2_port_resume(hsotg);
3302                 }
3303                 while (!dwc2_is_device_mode(hsotg)) {
3304                         dev_info(hsotg->dev,
3305                                  "Waiting for Peripheral Mode, Mode=%s\n",
3306                                  dwc2_is_host_mode(hsotg) ? "Host" :
3307                                  "Peripheral");
3308                         msleep(20);
3309                         /*
3310                          * Sometimes the initial GOTGCTRL read is wrong, so
3311                          * check it again and jump to host mode if that was
3312                          * the case.
3313                          */
3314                         gotgctl = dwc2_readl(hsotg->regs + GOTGCTL);
3315                         if (!(gotgctl & GOTGCTL_CONID_B))
3316                                 goto host;
3317                         if (++count > 250)
3318                                 break;
3319                 }
3320                 if (count > 250)
3321                         dev_err(hsotg->dev,
3322                                 "Connection id status change timed out\n");
3323                 hsotg->op_state = OTG_STATE_B_PERIPHERAL;
3324                 dwc2_core_init(hsotg, false);
3325                 dwc2_enable_global_interrupts(hsotg);
3326                 spin_lock_irqsave(&hsotg->lock, flags);
3327                 dwc2_hsotg_core_init_disconnected(hsotg, false);
3328                 spin_unlock_irqrestore(&hsotg->lock, flags);
3329                 /* Enable ACG feature in device mode,if supported */
3330                 dwc2_enable_acg(hsotg);
3331                 dwc2_hsotg_core_connect(hsotg);
3332         } else {
3333 host:
3334                 /* A-Device connector (Host Mode) */
3335                 dev_dbg(hsotg->dev, "connId A\n");
3336                 while (!dwc2_is_host_mode(hsotg)) {
3337                         dev_info(hsotg->dev, "Waiting for Host Mode, Mode=%s\n",
3338                                  dwc2_is_host_mode(hsotg) ?
3339                                  "Host" : "Peripheral");
3340                         msleep(20);
3341                         if (++count > 250)
3342                                 break;
3343                 }
3344                 if (count > 250)
3345                         dev_err(hsotg->dev,
3346                                 "Connection id status change timed out\n");
3347
3348                 spin_lock_irqsave(&hsotg->lock, flags);
3349                 dwc2_hsotg_disconnect(hsotg);
3350                 spin_unlock_irqrestore(&hsotg->lock, flags);
3351
3352                 hsotg->op_state = OTG_STATE_A_HOST;
3353                 /* Initialize the Core for Host mode */
3354                 dwc2_core_init(hsotg, false);
3355                 dwc2_enable_global_interrupts(hsotg);
3356                 dwc2_hcd_start(hsotg);
3357         }
3358 }
3359
3360 static void dwc2_wakeup_detected(struct timer_list *t)
3361 {
3362         struct dwc2_hsotg *hsotg = from_timer(hsotg, t, wkp_timer);
3363         u32 hprt0;
3364
3365         dev_dbg(hsotg->dev, "%s()\n", __func__);
3366
3367         /*
3368          * Clear the Resume after 70ms. (Need 20 ms minimum. Use 70 ms
3369          * so that OPT tests pass with all PHYs.)
3370          */
3371         hprt0 = dwc2_read_hprt0(hsotg);
3372         dev_dbg(hsotg->dev, "Resume: HPRT0=%0x\n", hprt0);
3373         hprt0 &= ~HPRT0_RES;
3374         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3375         dev_dbg(hsotg->dev, "Clear Resume: HPRT0=%0x\n",
3376                 dwc2_readl(hsotg->regs + HPRT0));
3377
3378         dwc2_hcd_rem_wakeup(hsotg);
3379         hsotg->bus_suspended = false;
3380
3381         /* Change to L0 state */
3382         hsotg->lx_state = DWC2_L0;
3383 }
3384
3385 static int dwc2_host_is_b_hnp_enabled(struct dwc2_hsotg *hsotg)
3386 {
3387         struct usb_hcd *hcd = dwc2_hsotg_to_hcd(hsotg);
3388
3389         return hcd->self.b_hnp_enable;
3390 }
3391
3392 /* Must NOT be called with interrupt disabled or spinlock held */
3393 static void dwc2_port_suspend(struct dwc2_hsotg *hsotg, u16 windex)
3394 {
3395         unsigned long flags;
3396         u32 hprt0;
3397         u32 pcgctl;
3398         u32 gotgctl;
3399
3400         dev_dbg(hsotg->dev, "%s()\n", __func__);
3401
3402         spin_lock_irqsave(&hsotg->lock, flags);
3403
3404         if (windex == hsotg->otg_port && dwc2_host_is_b_hnp_enabled(hsotg)) {
3405                 gotgctl = dwc2_readl(hsotg->regs + GOTGCTL);
3406                 gotgctl |= GOTGCTL_HSTSETHNPEN;
3407                 dwc2_writel(gotgctl, hsotg->regs + GOTGCTL);
3408                 hsotg->op_state = OTG_STATE_A_SUSPEND;
3409         }
3410
3411         hprt0 = dwc2_read_hprt0(hsotg);
3412         hprt0 |= HPRT0_SUSP;
3413         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3414
3415         hsotg->bus_suspended = true;
3416
3417         /*
3418          * If power_down is supported, Phy clock will be suspended
3419          * after registers are backuped.
3420          */
3421         if (!hsotg->params.power_down) {
3422                 /* Suspend the Phy Clock */
3423                 pcgctl = dwc2_readl(hsotg->regs + PCGCTL);
3424                 pcgctl |= PCGCTL_STOPPCLK;
3425                 dwc2_writel(pcgctl, hsotg->regs + PCGCTL);
3426                 udelay(10);
3427         }
3428
3429         /* For HNP the bus must be suspended for at least 200ms */
3430         if (dwc2_host_is_b_hnp_enabled(hsotg)) {
3431                 pcgctl = dwc2_readl(hsotg->regs + PCGCTL);
3432                 pcgctl &= ~PCGCTL_STOPPCLK;
3433                 dwc2_writel(pcgctl, hsotg->regs + PCGCTL);
3434
3435                 spin_unlock_irqrestore(&hsotg->lock, flags);
3436
3437                 msleep(200);
3438         } else {
3439                 spin_unlock_irqrestore(&hsotg->lock, flags);
3440         }
3441 }
3442
3443 /* Must NOT be called with interrupt disabled or spinlock held */
3444 static void dwc2_port_resume(struct dwc2_hsotg *hsotg)
3445 {
3446         unsigned long flags;
3447         u32 hprt0;
3448         u32 pcgctl;
3449
3450         spin_lock_irqsave(&hsotg->lock, flags);
3451
3452         /*
3453          * If power_down is supported, Phy clock is already resumed
3454          * after registers restore.
3455          */
3456         if (!hsotg->params.power_down) {
3457                 pcgctl = dwc2_readl(hsotg->regs + PCGCTL);
3458                 pcgctl &= ~PCGCTL_STOPPCLK;
3459                 dwc2_writel(pcgctl, hsotg->regs + PCGCTL);
3460                 spin_unlock_irqrestore(&hsotg->lock, flags);
3461                 msleep(20);
3462                 spin_lock_irqsave(&hsotg->lock, flags);
3463         }
3464
3465         hprt0 = dwc2_read_hprt0(hsotg);
3466         hprt0 |= HPRT0_RES;
3467         hprt0 &= ~HPRT0_SUSP;
3468         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3469         spin_unlock_irqrestore(&hsotg->lock, flags);
3470
3471         msleep(USB_RESUME_TIMEOUT);
3472
3473         spin_lock_irqsave(&hsotg->lock, flags);
3474         hprt0 = dwc2_read_hprt0(hsotg);
3475         hprt0 &= ~(HPRT0_RES | HPRT0_SUSP);
3476         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3477         hsotg->bus_suspended = false;
3478         spin_unlock_irqrestore(&hsotg->lock, flags);
3479 }
3480
3481 /* Handles hub class-specific requests */
3482 static int dwc2_hcd_hub_control(struct dwc2_hsotg *hsotg, u16 typereq,
3483                                 u16 wvalue, u16 windex, char *buf, u16 wlength)
3484 {
3485         struct usb_hub_descriptor *hub_desc;
3486         int retval = 0;
3487         u32 hprt0;
3488         u32 port_status;
3489         u32 speed;
3490         u32 pcgctl;
3491
3492         switch (typereq) {
3493         case ClearHubFeature:
3494                 dev_dbg(hsotg->dev, "ClearHubFeature %1xh\n", wvalue);
3495
3496                 switch (wvalue) {
3497                 case C_HUB_LOCAL_POWER:
3498                 case C_HUB_OVER_CURRENT:
3499                         /* Nothing required here */
3500                         break;
3501
3502                 default:
3503                         retval = -EINVAL;
3504                         dev_err(hsotg->dev,
3505                                 "ClearHubFeature request %1xh unknown\n",
3506                                 wvalue);
3507                 }
3508                 break;
3509
3510         case ClearPortFeature:
3511                 if (wvalue != USB_PORT_FEAT_L1)
3512                         if (!windex || windex > 1)
3513                                 goto error;
3514                 switch (wvalue) {
3515                 case USB_PORT_FEAT_ENABLE:
3516                         dev_dbg(hsotg->dev,
3517                                 "ClearPortFeature USB_PORT_FEAT_ENABLE\n");
3518                         hprt0 = dwc2_read_hprt0(hsotg);
3519                         hprt0 |= HPRT0_ENA;
3520                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3521                         break;
3522
3523                 case USB_PORT_FEAT_SUSPEND:
3524                         dev_dbg(hsotg->dev,
3525                                 "ClearPortFeature USB_PORT_FEAT_SUSPEND\n");
3526
3527                         if (hsotg->bus_suspended) {
3528                                 if (hsotg->hibernated)
3529                                         dwc2_exit_hibernation(hsotg, 0, 0, 1);
3530                                 else
3531                                         dwc2_port_resume(hsotg);
3532                         }
3533                         break;
3534
3535                 case USB_PORT_FEAT_POWER:
3536                         dev_dbg(hsotg->dev,
3537                                 "ClearPortFeature USB_PORT_FEAT_POWER\n");
3538                         hprt0 = dwc2_read_hprt0(hsotg);
3539                         hprt0 &= ~HPRT0_PWR;
3540                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3541                         break;
3542
3543                 case USB_PORT_FEAT_INDICATOR:
3544                         dev_dbg(hsotg->dev,
3545                                 "ClearPortFeature USB_PORT_FEAT_INDICATOR\n");
3546                         /* Port indicator not supported */
3547                         break;
3548
3549                 case USB_PORT_FEAT_C_CONNECTION:
3550                         /*
3551                          * Clears driver's internal Connect Status Change flag
3552                          */
3553                         dev_dbg(hsotg->dev,
3554                                 "ClearPortFeature USB_PORT_FEAT_C_CONNECTION\n");
3555                         hsotg->flags.b.port_connect_status_change = 0;
3556                         break;
3557
3558                 case USB_PORT_FEAT_C_RESET:
3559                         /* Clears driver's internal Port Reset Change flag */
3560                         dev_dbg(hsotg->dev,
3561                                 "ClearPortFeature USB_PORT_FEAT_C_RESET\n");
3562                         hsotg->flags.b.port_reset_change = 0;
3563                         break;
3564
3565                 case USB_PORT_FEAT_C_ENABLE:
3566                         /*
3567                          * Clears the driver's internal Port Enable/Disable
3568                          * Change flag
3569                          */
3570                         dev_dbg(hsotg->dev,
3571                                 "ClearPortFeature USB_PORT_FEAT_C_ENABLE\n");
3572                         hsotg->flags.b.port_enable_change = 0;
3573                         break;
3574
3575                 case USB_PORT_FEAT_C_SUSPEND:
3576                         /*
3577                          * Clears the driver's internal Port Suspend Change
3578                          * flag, which is set when resume signaling on the host
3579                          * port is complete
3580                          */
3581                         dev_dbg(hsotg->dev,
3582                                 "ClearPortFeature USB_PORT_FEAT_C_SUSPEND\n");
3583                         hsotg->flags.b.port_suspend_change = 0;
3584                         break;
3585
3586                 case USB_PORT_FEAT_C_PORT_L1:
3587                         dev_dbg(hsotg->dev,
3588                                 "ClearPortFeature USB_PORT_FEAT_C_PORT_L1\n");
3589                         hsotg->flags.b.port_l1_change = 0;
3590                         break;
3591
3592                 case USB_PORT_FEAT_C_OVER_CURRENT:
3593                         dev_dbg(hsotg->dev,
3594                                 "ClearPortFeature USB_PORT_FEAT_C_OVER_CURRENT\n");
3595                         hsotg->flags.b.port_over_current_change = 0;
3596                         break;
3597
3598                 default:
3599                         retval = -EINVAL;
3600                         dev_err(hsotg->dev,
3601                                 "ClearPortFeature request %1xh unknown or unsupported\n",
3602                                 wvalue);
3603                 }
3604                 break;
3605
3606         case GetHubDescriptor:
3607                 dev_dbg(hsotg->dev, "GetHubDescriptor\n");
3608                 hub_desc = (struct usb_hub_descriptor *)buf;
3609                 hub_desc->bDescLength = 9;
3610                 hub_desc->bDescriptorType = USB_DT_HUB;
3611                 hub_desc->bNbrPorts = 1;
3612                 hub_desc->wHubCharacteristics =
3613                         cpu_to_le16(HUB_CHAR_COMMON_LPSM |
3614                                     HUB_CHAR_INDV_PORT_OCPM);
3615                 hub_desc->bPwrOn2PwrGood = 1;
3616                 hub_desc->bHubContrCurrent = 0;
3617                 hub_desc->u.hs.DeviceRemovable[0] = 0;
3618                 hub_desc->u.hs.DeviceRemovable[1] = 0xff;
3619                 break;
3620
3621         case GetHubStatus:
3622                 dev_dbg(hsotg->dev, "GetHubStatus\n");
3623                 memset(buf, 0, 4);
3624                 break;
3625
3626         case GetPortStatus:
3627                 dev_vdbg(hsotg->dev,
3628                          "GetPortStatus wIndex=0x%04x flags=0x%08x\n", windex,
3629                          hsotg->flags.d32);
3630                 if (!windex || windex > 1)
3631                         goto error;
3632
3633                 port_status = 0;
3634                 if (hsotg->flags.b.port_connect_status_change)
3635                         port_status |= USB_PORT_STAT_C_CONNECTION << 16;
3636                 if (hsotg->flags.b.port_enable_change)
3637                         port_status |= USB_PORT_STAT_C_ENABLE << 16;
3638                 if (hsotg->flags.b.port_suspend_change)
3639                         port_status |= USB_PORT_STAT_C_SUSPEND << 16;
3640                 if (hsotg->flags.b.port_l1_change)
3641                         port_status |= USB_PORT_STAT_C_L1 << 16;
3642                 if (hsotg->flags.b.port_reset_change)
3643                         port_status |= USB_PORT_STAT_C_RESET << 16;
3644                 if (hsotg->flags.b.port_over_current_change) {
3645                         dev_warn(hsotg->dev, "Overcurrent change detected\n");
3646                         port_status |= USB_PORT_STAT_C_OVERCURRENT << 16;
3647                 }
3648
3649                 if (!hsotg->flags.b.port_connect_status) {
3650                         /*
3651                          * The port is disconnected, which means the core is
3652                          * either in device mode or it soon will be. Just
3653                          * return 0's for the remainder of the port status
3654                          * since the port register can't be read if the core
3655                          * is in device mode.
3656                          */
3657                         *(__le32 *)buf = cpu_to_le32(port_status);
3658                         break;
3659                 }
3660
3661                 hprt0 = dwc2_readl(hsotg->regs + HPRT0);
3662                 dev_vdbg(hsotg->dev, "  HPRT0: 0x%08x\n", hprt0);
3663
3664                 if (hprt0 & HPRT0_CONNSTS)
3665                         port_status |= USB_PORT_STAT_CONNECTION;
3666                 if (hprt0 & HPRT0_ENA)
3667                         port_status |= USB_PORT_STAT_ENABLE;
3668                 if (hprt0 & HPRT0_SUSP)
3669                         port_status |= USB_PORT_STAT_SUSPEND;
3670                 if (hprt0 & HPRT0_OVRCURRACT)
3671                         port_status |= USB_PORT_STAT_OVERCURRENT;
3672                 if (hprt0 & HPRT0_RST)
3673                         port_status |= USB_PORT_STAT_RESET;
3674                 if (hprt0 & HPRT0_PWR)
3675                         port_status |= USB_PORT_STAT_POWER;
3676
3677                 speed = (hprt0 & HPRT0_SPD_MASK) >> HPRT0_SPD_SHIFT;
3678                 if (speed == HPRT0_SPD_HIGH_SPEED)
3679                         port_status |= USB_PORT_STAT_HIGH_SPEED;
3680                 else if (speed == HPRT0_SPD_LOW_SPEED)
3681                         port_status |= USB_PORT_STAT_LOW_SPEED;
3682
3683                 if (hprt0 & HPRT0_TSTCTL_MASK)
3684                         port_status |= USB_PORT_STAT_TEST;
3685                 /* USB_PORT_FEAT_INDICATOR unsupported always 0 */
3686
3687                 if (hsotg->params.dma_desc_fs_enable) {
3688                         /*
3689                          * Enable descriptor DMA only if a full speed
3690                          * device is connected.
3691                          */
3692                         if (hsotg->new_connection &&
3693                             ((port_status &
3694                               (USB_PORT_STAT_CONNECTION |
3695                                USB_PORT_STAT_HIGH_SPEED |
3696                                USB_PORT_STAT_LOW_SPEED)) ==
3697                                USB_PORT_STAT_CONNECTION)) {
3698                                 u32 hcfg;
3699
3700                                 dev_info(hsotg->dev, "Enabling descriptor DMA mode\n");
3701                                 hsotg->params.dma_desc_enable = true;
3702                                 hcfg = dwc2_readl(hsotg->regs + HCFG);
3703                                 hcfg |= HCFG_DESCDMA;
3704                                 dwc2_writel(hcfg, hsotg->regs + HCFG);
3705                                 hsotg->new_connection = false;
3706                         }
3707                 }
3708
3709                 dev_vdbg(hsotg->dev, "port_status=%08x\n", port_status);
3710                 *(__le32 *)buf = cpu_to_le32(port_status);
3711                 break;
3712
3713         case SetHubFeature:
3714                 dev_dbg(hsotg->dev, "SetHubFeature\n");
3715                 /* No HUB features supported */
3716                 break;
3717
3718         case SetPortFeature:
3719                 dev_dbg(hsotg->dev, "SetPortFeature\n");
3720                 if (wvalue != USB_PORT_FEAT_TEST && (!windex || windex > 1))
3721                         goto error;
3722
3723                 if (!hsotg->flags.b.port_connect_status) {
3724                         /*
3725                          * The port is disconnected, which means the core is
3726                          * either in device mode or it soon will be. Just
3727                          * return without doing anything since the port
3728                          * register can't be written if the core is in device
3729                          * mode.
3730                          */
3731                         break;
3732                 }
3733
3734                 switch (wvalue) {
3735                 case USB_PORT_FEAT_SUSPEND:
3736                         dev_dbg(hsotg->dev,
3737                                 "SetPortFeature - USB_PORT_FEAT_SUSPEND\n");
3738                         if (windex != hsotg->otg_port)
3739                                 goto error;
3740                         if (hsotg->params.power_down == 2)
3741                                 dwc2_enter_hibernation(hsotg, 1);
3742                         else
3743                                 dwc2_port_suspend(hsotg, windex);
3744                         break;
3745
3746                 case USB_PORT_FEAT_POWER:
3747                         dev_dbg(hsotg->dev,
3748                                 "SetPortFeature - USB_PORT_FEAT_POWER\n");
3749                         hprt0 = dwc2_read_hprt0(hsotg);
3750                         hprt0 |= HPRT0_PWR;
3751                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3752                         break;
3753
3754                 case USB_PORT_FEAT_RESET:
3755                         if (hsotg->params.power_down == 2 &&
3756                             hsotg->hibernated)
3757                                 dwc2_exit_hibernation(hsotg, 0, 1, 1);
3758                         hprt0 = dwc2_read_hprt0(hsotg);
3759                         dev_dbg(hsotg->dev,
3760                                 "SetPortFeature - USB_PORT_FEAT_RESET\n");
3761                         pcgctl = dwc2_readl(hsotg->regs + PCGCTL);
3762                         pcgctl &= ~(PCGCTL_ENBL_SLEEP_GATING | PCGCTL_STOPPCLK);
3763                         dwc2_writel(pcgctl, hsotg->regs + PCGCTL);
3764                         /* ??? Original driver does this */
3765                         dwc2_writel(0, hsotg->regs + PCGCTL);
3766
3767                         hprt0 = dwc2_read_hprt0(hsotg);
3768                         /* Clear suspend bit if resetting from suspend state */
3769                         hprt0 &= ~HPRT0_SUSP;
3770
3771                         /*
3772                          * When B-Host the Port reset bit is set in the Start
3773                          * HCD Callback function, so that the reset is started
3774                          * within 1ms of the HNP success interrupt
3775                          */
3776                         if (!dwc2_hcd_is_b_host(hsotg)) {
3777                                 hprt0 |= HPRT0_PWR | HPRT0_RST;
3778                                 dev_dbg(hsotg->dev,
3779                                         "In host mode, hprt0=%08x\n", hprt0);
3780                                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
3781                         }
3782
3783                         /* Clear reset bit in 10ms (FS/LS) or 50ms (HS) */
3784                         msleep(50);
3785                         hprt0 &= ~HPRT0_RST;
3786                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3787                         hsotg->lx_state = DWC2_L0; /* Now back to On state */
3788                         break;
3789
3790                 case USB_PORT_FEAT_INDICATOR:
3791                         dev_dbg(hsotg->dev,
3792                                 "SetPortFeature - USB_PORT_FEAT_INDICATOR\n");
3793                         /* Not supported */
3794                         break;
3795
3796                 case USB_PORT_FEAT_TEST:
3797                         hprt0 = dwc2_read_hprt0(hsotg);
3798                         dev_dbg(hsotg->dev,
3799                                 "SetPortFeature - USB_PORT_FEAT_TEST\n");
3800                         hprt0 &= ~HPRT0_TSTCTL_MASK;
3801                         hprt0 |= (windex >> 8) << HPRT0_TSTCTL_SHIFT;
3802                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3803                         break;
3804
3805                 default:
3806                         retval = -EINVAL;
3807                         dev_err(hsotg->dev,
3808                                 "SetPortFeature %1xh unknown or unsupported\n",
3809                                 wvalue);
3810                         break;
3811                 }
3812                 break;
3813
3814         default:
3815 error:
3816                 retval = -EINVAL;
3817                 dev_dbg(hsotg->dev,
3818                         "Unknown hub control request: %1xh wIndex: %1xh wValue: %1xh\n",
3819                         typereq, windex, wvalue);
3820                 break;
3821         }
3822
3823         return retval;
3824 }
3825
3826 static int dwc2_hcd_is_status_changed(struct dwc2_hsotg *hsotg, int port)
3827 {
3828         int retval;
3829
3830         if (port != 1)
3831                 return -EINVAL;
3832
3833         retval = (hsotg->flags.b.port_connect_status_change ||
3834                   hsotg->flags.b.port_reset_change ||
3835                   hsotg->flags.b.port_enable_change ||
3836                   hsotg->flags.b.port_suspend_change ||
3837                   hsotg->flags.b.port_over_current_change);
3838
3839         if (retval) {
3840                 dev_dbg(hsotg->dev,
3841                         "DWC OTG HCD HUB STATUS DATA: Root port status changed\n");
3842                 dev_dbg(hsotg->dev, "  port_connect_status_change: %d\n",
3843                         hsotg->flags.b.port_connect_status_change);
3844                 dev_dbg(hsotg->dev, "  port_reset_change: %d\n",
3845                         hsotg->flags.b.port_reset_change);
3846                 dev_dbg(hsotg->dev, "  port_enable_change: %d\n",
3847                         hsotg->flags.b.port_enable_change);
3848                 dev_dbg(hsotg->dev, "  port_suspend_change: %d\n",
3849                         hsotg->flags.b.port_suspend_change);
3850                 dev_dbg(hsotg->dev, "  port_over_current_change: %d\n",
3851                         hsotg->flags.b.port_over_current_change);
3852         }
3853
3854         return retval;
3855 }
3856
3857 int dwc2_hcd_get_frame_number(struct dwc2_hsotg *hsotg)
3858 {
3859         u32 hfnum = dwc2_readl(hsotg->regs + HFNUM);
3860
3861 #ifdef DWC2_DEBUG_SOF
3862         dev_vdbg(hsotg->dev, "DWC OTG HCD GET FRAME NUMBER %d\n",
3863                  (hfnum & HFNUM_FRNUM_MASK) >> HFNUM_FRNUM_SHIFT);
3864 #endif
3865         return (hfnum & HFNUM_FRNUM_MASK) >> HFNUM_FRNUM_SHIFT;
3866 }
3867
3868 int dwc2_hcd_get_future_frame_number(struct dwc2_hsotg *hsotg, int us)
3869 {
3870         u32 hprt = dwc2_readl(hsotg->regs + HPRT0);
3871         u32 hfir = dwc2_readl(hsotg->regs + HFIR);
3872         u32 hfnum = dwc2_readl(hsotg->regs + HFNUM);
3873         unsigned int us_per_frame;
3874         unsigned int frame_number;
3875         unsigned int remaining;
3876         unsigned int interval;
3877         unsigned int phy_clks;
3878
3879         /* High speed has 125 us per (micro) frame; others are 1 ms per */
3880         us_per_frame = (hprt & HPRT0_SPD_MASK) ? 1000 : 125;
3881
3882         /* Extract fields */
3883         frame_number = (hfnum & HFNUM_FRNUM_MASK) >> HFNUM_FRNUM_SHIFT;
3884         remaining = (hfnum & HFNUM_FRREM_MASK) >> HFNUM_FRREM_SHIFT;
3885         interval = (hfir & HFIR_FRINT_MASK) >> HFIR_FRINT_SHIFT;
3886
3887         /*
3888          * Number of phy clocks since the last tick of the frame number after
3889          * "us" has passed.
3890          */
3891         phy_clks = (interval - remaining) +
3892                    DIV_ROUND_UP(interval * us, us_per_frame);
3893
3894         return dwc2_frame_num_inc(frame_number, phy_clks / interval);
3895 }
3896
3897 int dwc2_hcd_is_b_host(struct dwc2_hsotg *hsotg)
3898 {
3899         return hsotg->op_state == OTG_STATE_B_HOST;
3900 }
3901
3902 static struct dwc2_hcd_urb *dwc2_hcd_urb_alloc(struct dwc2_hsotg *hsotg,
3903                                                int iso_desc_count,
3904                                                gfp_t mem_flags)
3905 {
3906         struct dwc2_hcd_urb *urb;
3907         u32 size = sizeof(*urb) + iso_desc_count *
3908                    sizeof(struct dwc2_hcd_iso_packet_desc);
3909
3910         urb = kzalloc(size, mem_flags);
3911         if (urb)
3912                 urb->packet_count = iso_desc_count;
3913         return urb;
3914 }
3915
3916 static void dwc2_hcd_urb_set_pipeinfo(struct dwc2_hsotg *hsotg,
3917                                       struct dwc2_hcd_urb *urb, u8 dev_addr,
3918                                       u8 ep_num, u8 ep_type, u8 ep_dir, u16 mps)
3919 {
3920         if (dbg_perio() ||
3921             ep_type == USB_ENDPOINT_XFER_BULK ||
3922             ep_type == USB_ENDPOINT_XFER_CONTROL)
3923                 dev_vdbg(hsotg->dev,
3924                          "addr=%d, ep_num=%d, ep_dir=%1x, ep_type=%1x, mps=%d\n",
3925                          dev_addr, ep_num, ep_dir, ep_type, mps);
3926         urb->pipe_info.dev_addr = dev_addr;
3927         urb->pipe_info.ep_num = ep_num;
3928         urb->pipe_info.pipe_type = ep_type;
3929         urb->pipe_info.pipe_dir = ep_dir;
3930         urb->pipe_info.mps = mps;
3931 }
3932
3933 /*
3934  * NOTE: This function will be removed once the peripheral controller code
3935  * is integrated and the driver is stable
3936  */
3937 void dwc2_hcd_dump_state(struct dwc2_hsotg *hsotg)
3938 {
3939 #ifdef DEBUG
3940         struct dwc2_host_chan *chan;
3941         struct dwc2_hcd_urb *urb;
3942         struct dwc2_qtd *qtd;
3943         int num_channels;
3944         u32 np_tx_status;
3945         u32 p_tx_status;
3946         int i;
3947
3948         num_channels = hsotg->params.host_channels;
3949         dev_dbg(hsotg->dev, "\n");
3950         dev_dbg(hsotg->dev,
3951                 "************************************************************\n");
3952         dev_dbg(hsotg->dev, "HCD State:\n");
3953         dev_dbg(hsotg->dev, "  Num channels: %d\n", num_channels);
3954
3955         for (i = 0; i < num_channels; i++) {
3956                 chan = hsotg->hc_ptr_array[i];
3957                 dev_dbg(hsotg->dev, "  Channel %d:\n", i);
3958                 dev_dbg(hsotg->dev,
3959                         "    dev_addr: %d, ep_num: %d, ep_is_in: %d\n",
3960                         chan->dev_addr, chan->ep_num, chan->ep_is_in);
3961                 dev_dbg(hsotg->dev, "    speed: %d\n", chan->speed);
3962                 dev_dbg(hsotg->dev, "    ep_type: %d\n", chan->ep_type);
3963                 dev_dbg(hsotg->dev, "    max_packet: %d\n", chan->max_packet);
3964                 dev_dbg(hsotg->dev, "    data_pid_start: %d\n",
3965                         chan->data_pid_start);
3966                 dev_dbg(hsotg->dev, "    multi_count: %d\n", chan->multi_count);
3967                 dev_dbg(hsotg->dev, "    xfer_started: %d\n",
3968                         chan->xfer_started);
3969                 dev_dbg(hsotg->dev, "    xfer_buf: %p\n", chan->xfer_buf);
3970                 dev_dbg(hsotg->dev, "    xfer_dma: %08lx\n",
3971                         (unsigned long)chan->xfer_dma);
3972                 dev_dbg(hsotg->dev, "    xfer_len: %d\n", chan->xfer_len);
3973                 dev_dbg(hsotg->dev, "    xfer_count: %d\n", chan->xfer_count);
3974                 dev_dbg(hsotg->dev, "    halt_on_queue: %d\n",
3975                         chan->halt_on_queue);
3976                 dev_dbg(hsotg->dev, "    halt_pending: %d\n",
3977                         chan->halt_pending);
3978                 dev_dbg(hsotg->dev, "    halt_status: %d\n", chan->halt_status);
3979                 dev_dbg(hsotg->dev, "    do_split: %d\n", chan->do_split);
3980                 dev_dbg(hsotg->dev, "    complete_split: %d\n",
3981                         chan->complete_split);
3982                 dev_dbg(hsotg->dev, "    hub_addr: %d\n", chan->hub_addr);
3983                 dev_dbg(hsotg->dev, "    hub_port: %d\n", chan->hub_port);
3984                 dev_dbg(hsotg->dev, "    xact_pos: %d\n", chan->xact_pos);
3985                 dev_dbg(hsotg->dev, "    requests: %d\n", chan->requests);
3986                 dev_dbg(hsotg->dev, "    qh: %p\n", chan->qh);
3987
3988                 if (chan->xfer_started) {
3989                         u32 hfnum, hcchar, hctsiz, hcint, hcintmsk;
3990
3991                         hfnum = dwc2_readl(hsotg->regs + HFNUM);
3992                         hcchar = dwc2_readl(hsotg->regs + HCCHAR(i));
3993                         hctsiz = dwc2_readl(hsotg->regs + HCTSIZ(i));
3994                         hcint = dwc2_readl(hsotg->regs + HCINT(i));
3995                         hcintmsk = dwc2_readl(hsotg->regs + HCINTMSK(i));
3996                         dev_dbg(hsotg->dev, "    hfnum: 0x%08x\n", hfnum);
3997                         dev_dbg(hsotg->dev, "    hcchar: 0x%08x\n", hcchar);
3998                         dev_dbg(hsotg->dev, "    hctsiz: 0x%08x\n", hctsiz);
3999                         dev_dbg(hsotg->dev, "    hcint: 0x%08x\n", hcint);
4000                         dev_dbg(hsotg->dev, "    hcintmsk: 0x%08x\n", hcintmsk);
4001                 }
4002
4003                 if (!(chan->xfer_started && chan->qh))
4004                         continue;
4005
4006                 list_for_each_entry(qtd, &chan->qh->qtd_list, qtd_list_entry) {
4007                         if (!qtd->in_process)
4008                                 break;
4009                         urb = qtd->urb;
4010                         dev_dbg(hsotg->dev, "    URB Info:\n");
4011                         dev_dbg(hsotg->dev, "      qtd: %p, urb: %p\n",
4012                                 qtd, urb);
4013                         if (urb) {
4014                                 dev_dbg(hsotg->dev,
4015                                         "      Dev: %d, EP: %d %s\n",
4016                                         dwc2_hcd_get_dev_addr(&urb->pipe_info),
4017                                         dwc2_hcd_get_ep_num(&urb->pipe_info),
4018                                         dwc2_hcd_is_pipe_in(&urb->pipe_info) ?
4019                                         "IN" : "OUT");
4020                                 dev_dbg(hsotg->dev,
4021                                         "      Max packet size: %d\n",
4022                                         dwc2_hcd_get_mps(&urb->pipe_info));
4023                                 dev_dbg(hsotg->dev,
4024                                         "      transfer_buffer: %p\n",
4025                                         urb->buf);
4026                                 dev_dbg(hsotg->dev,
4027                                         "      transfer_dma: %08lx\n",
4028                                         (unsigned long)urb->dma);
4029                                 dev_dbg(hsotg->dev,
4030                                         "      transfer_buffer_length: %d\n",
4031                                         urb->length);
4032                                 dev_dbg(hsotg->dev, "      actual_length: %d\n",
4033                                         urb->actual_length);
4034                         }
4035                 }
4036         }
4037
4038         dev_dbg(hsotg->dev, "  non_periodic_channels: %d\n",
4039                 hsotg->non_periodic_channels);
4040         dev_dbg(hsotg->dev, "  periodic_channels: %d\n",
4041                 hsotg->periodic_channels);
4042         dev_dbg(hsotg->dev, "  periodic_usecs: %d\n", hsotg->periodic_usecs);
4043         np_tx_status = dwc2_readl(hsotg->regs + GNPTXSTS);
4044         dev_dbg(hsotg->dev, "  NP Tx Req Queue Space Avail: %d\n",
4045                 (np_tx_status & TXSTS_QSPCAVAIL_MASK) >> TXSTS_QSPCAVAIL_SHIFT);
4046         dev_dbg(hsotg->dev, "  NP Tx FIFO Space Avail: %d\n",
4047                 (np_tx_status & TXSTS_FSPCAVAIL_MASK) >> TXSTS_FSPCAVAIL_SHIFT);
4048         p_tx_status = dwc2_readl(hsotg->regs + HPTXSTS);
4049         dev_dbg(hsotg->dev, "  P Tx Req Queue Space Avail: %d\n",
4050                 (p_tx_status & TXSTS_QSPCAVAIL_MASK) >> TXSTS_QSPCAVAIL_SHIFT);
4051         dev_dbg(hsotg->dev, "  P Tx FIFO Space Avail: %d\n",
4052                 (p_tx_status & TXSTS_FSPCAVAIL_MASK) >> TXSTS_FSPCAVAIL_SHIFT);
4053         dwc2_dump_global_registers(hsotg);
4054         dwc2_dump_host_registers(hsotg);
4055         dev_dbg(hsotg->dev,
4056                 "************************************************************\n");
4057         dev_dbg(hsotg->dev, "\n");
4058 #endif
4059 }
4060
4061 struct wrapper_priv_data {
4062         struct dwc2_hsotg *hsotg;
4063 };
4064
4065 /* Gets the dwc2_hsotg from a usb_hcd */
4066 static struct dwc2_hsotg *dwc2_hcd_to_hsotg(struct usb_hcd *hcd)
4067 {
4068         struct wrapper_priv_data *p;
4069
4070         p = (struct wrapper_priv_data *)&hcd->hcd_priv;
4071         return p->hsotg;
4072 }
4073
4074 /**
4075  * dwc2_host_get_tt_info() - Get the dwc2_tt associated with context
4076  *
4077  * This will get the dwc2_tt structure (and ttport) associated with the given
4078  * context (which is really just a struct urb pointer).
4079  *
4080  * The first time this is called for a given TT we allocate memory for our
4081  * structure.  When everyone is done and has called dwc2_host_put_tt_info()
4082  * then the refcount for the structure will go to 0 and we'll free it.
4083  *
4084  * @hsotg:     The HCD state structure for the DWC OTG controller.
4085  * @qh:        The QH structure.
4086  * @context:   The priv pointer from a struct dwc2_hcd_urb.
4087  * @mem_flags: Flags for allocating memory.
4088  * @ttport:    We'll return this device's port number here.  That's used to
4089  *             reference into the bitmap if we're on a multi_tt hub.
4090  *
4091  * Return: a pointer to a struct dwc2_tt.  Don't forget to call
4092  *         dwc2_host_put_tt_info()!  Returns NULL upon memory alloc failure.
4093  */
4094
4095 struct dwc2_tt *dwc2_host_get_tt_info(struct dwc2_hsotg *hsotg, void *context,
4096                                       gfp_t mem_flags, int *ttport)
4097 {
4098         struct urb *urb = context;
4099         struct dwc2_tt *dwc_tt = NULL;
4100
4101         if (urb->dev->tt) {
4102                 *ttport = urb->dev->ttport;
4103
4104                 dwc_tt = urb->dev->tt->hcpriv;
4105                 if (!dwc_tt) {
4106                         size_t bitmap_size;
4107
4108                         /*
4109                          * For single_tt we need one schedule.  For multi_tt
4110                          * we need one per port.
4111                          */
4112                         bitmap_size = DWC2_ELEMENTS_PER_LS_BITMAP *
4113                                       sizeof(dwc_tt->periodic_bitmaps[0]);
4114                         if (urb->dev->tt->multi)
4115                                 bitmap_size *= urb->dev->tt->hub->maxchild;
4116
4117                         dwc_tt = kzalloc(sizeof(*dwc_tt) + bitmap_size,
4118                                          mem_flags);
4119                         if (!dwc_tt)
4120                                 return NULL;
4121
4122                         dwc_tt->usb_tt = urb->dev->tt;
4123                         dwc_tt->usb_tt->hcpriv = dwc_tt;
4124                 }
4125
4126                 dwc_tt->refcount++;
4127         }
4128
4129         return dwc_tt;
4130 }
4131
4132 /**
4133  * dwc2_host_put_tt_info() - Put the dwc2_tt from dwc2_host_get_tt_info()
4134  *
4135  * Frees resources allocated by dwc2_host_get_tt_info() if all current holders
4136  * of the structure are done.
4137  *
4138  * It's OK to call this with NULL.
4139  *
4140  * @hsotg:     The HCD state structure for the DWC OTG controller.
4141  * @dwc_tt:    The pointer returned by dwc2_host_get_tt_info.
4142  */
4143 void dwc2_host_put_tt_info(struct dwc2_hsotg *hsotg, struct dwc2_tt *dwc_tt)
4144 {
4145         /* Model kfree and make put of NULL a no-op */
4146         if (!dwc_tt)
4147                 return;
4148
4149         WARN_ON(dwc_tt->refcount < 1);
4150
4151         dwc_tt->refcount--;
4152         if (!dwc_tt->refcount) {
4153                 dwc_tt->usb_tt->hcpriv = NULL;
4154                 kfree(dwc_tt);
4155         }
4156 }
4157
4158 int dwc2_host_get_speed(struct dwc2_hsotg *hsotg, void *context)
4159 {
4160         struct urb *urb = context;
4161
4162         return urb->dev->speed;
4163 }
4164
4165 static void dwc2_allocate_bus_bandwidth(struct usb_hcd *hcd, u16 bw,
4166                                         struct urb *urb)
4167 {
4168         struct usb_bus *bus = hcd_to_bus(hcd);
4169
4170         if (urb->interval)
4171                 bus->bandwidth_allocated += bw / urb->interval;
4172         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS)
4173                 bus->bandwidth_isoc_reqs++;
4174         else
4175                 bus->bandwidth_int_reqs++;
4176 }
4177
4178 static void dwc2_free_bus_bandwidth(struct usb_hcd *hcd, u16 bw,
4179                                     struct urb *urb)
4180 {
4181         struct usb_bus *bus = hcd_to_bus(hcd);
4182
4183         if (urb->interval)
4184                 bus->bandwidth_allocated -= bw / urb->interval;
4185         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS)
4186                 bus->bandwidth_isoc_reqs--;
4187         else
4188                 bus->bandwidth_int_reqs--;
4189 }
4190
4191 /*
4192  * Sets the final status of an URB and returns it to the upper layer. Any
4193  * required cleanup of the URB is performed.
4194  *
4195  * Must be called with interrupt disabled and spinlock held
4196  */
4197 void dwc2_host_complete(struct dwc2_hsotg *hsotg, struct dwc2_qtd *qtd,
4198                         int status)
4199 {
4200         struct urb *urb;
4201         int i;
4202
4203         if (!qtd) {
4204                 dev_dbg(hsotg->dev, "## %s: qtd is NULL ##\n", __func__);
4205                 return;
4206         }
4207
4208         if (!qtd->urb) {
4209                 dev_dbg(hsotg->dev, "## %s: qtd->urb is NULL ##\n", __func__);
4210                 return;
4211         }
4212
4213         urb = qtd->urb->priv;
4214         if (!urb) {
4215                 dev_dbg(hsotg->dev, "## %s: urb->priv is NULL ##\n", __func__);
4216                 return;
4217         }
4218
4219         urb->actual_length = dwc2_hcd_urb_get_actual_length(qtd->urb);
4220
4221         if (dbg_urb(urb))
4222                 dev_vdbg(hsotg->dev,
4223                          "%s: urb %p device %d ep %d-%s status %d actual %d\n",
4224                          __func__, urb, usb_pipedevice(urb->pipe),
4225                          usb_pipeendpoint(urb->pipe),
4226                          usb_pipein(urb->pipe) ? "IN" : "OUT", status,
4227                          urb->actual_length);
4228
4229         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) {
4230                 urb->error_count = dwc2_hcd_urb_get_error_count(qtd->urb);
4231                 for (i = 0; i < urb->number_of_packets; ++i) {
4232                         urb->iso_frame_desc[i].actual_length =
4233                                 dwc2_hcd_urb_get_iso_desc_actual_length(
4234                                                 qtd->urb, i);
4235                         urb->iso_frame_desc[i].status =
4236                                 dwc2_hcd_urb_get_iso_desc_status(qtd->urb, i);
4237                 }
4238         }
4239
4240         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS && dbg_perio()) {
4241                 for (i = 0; i < urb->number_of_packets; i++)
4242                         dev_vdbg(hsotg->dev, " ISO Desc %d status %d\n",
4243                                  i, urb->iso_frame_desc[i].status);
4244         }
4245
4246         urb->status = status;
4247         if (!status) {
4248                 if ((urb->transfer_flags & URB_SHORT_NOT_OK) &&
4249                     urb->actual_length < urb->transfer_buffer_length)
4250                         urb->status = -EREMOTEIO;
4251         }
4252
4253         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS ||
4254             usb_pipetype(urb->pipe) == PIPE_INTERRUPT) {
4255                 struct usb_host_endpoint *ep = urb->ep;
4256
4257                 if (ep)
4258                         dwc2_free_bus_bandwidth(dwc2_hsotg_to_hcd(hsotg),
4259                                         dwc2_hcd_get_ep_bandwidth(hsotg, ep),
4260                                         urb);
4261         }
4262
4263         usb_hcd_unlink_urb_from_ep(dwc2_hsotg_to_hcd(hsotg), urb);
4264         urb->hcpriv = NULL;
4265         kfree(qtd->urb);
4266         qtd->urb = NULL;
4267
4268         usb_hcd_giveback_urb(dwc2_hsotg_to_hcd(hsotg), urb, status);
4269 }
4270
4271 /*
4272  * Work queue function for starting the HCD when A-Cable is connected
4273  */
4274 static void dwc2_hcd_start_func(struct work_struct *work)
4275 {
4276         struct dwc2_hsotg *hsotg = container_of(work, struct dwc2_hsotg,
4277                                                 start_work.work);
4278
4279         dev_dbg(hsotg->dev, "%s() %p\n", __func__, hsotg);
4280         dwc2_host_start(hsotg);
4281 }
4282
4283 /*
4284  * Reset work queue function
4285  */
4286 static void dwc2_hcd_reset_func(struct work_struct *work)
4287 {
4288         struct dwc2_hsotg *hsotg = container_of(work, struct dwc2_hsotg,
4289                                                 reset_work.work);
4290         unsigned long flags;
4291         u32 hprt0;
4292
4293         dev_dbg(hsotg->dev, "USB RESET function called\n");
4294
4295         spin_lock_irqsave(&hsotg->lock, flags);
4296
4297         hprt0 = dwc2_read_hprt0(hsotg);
4298         hprt0 &= ~HPRT0_RST;
4299         dwc2_writel(hprt0, hsotg->regs + HPRT0);
4300         hsotg->flags.b.port_reset_change = 1;
4301
4302         spin_unlock_irqrestore(&hsotg->lock, flags);
4303 }
4304
4305 /*
4306  * =========================================================================
4307  *  Linux HC Driver Functions
4308  * =========================================================================
4309  */
4310
4311 /*
4312  * Initializes the DWC_otg controller and its root hub and prepares it for host
4313  * mode operation. Activates the root port. Returns 0 on success and a negative
4314  * error code on failure.
4315  */
4316 static int _dwc2_hcd_start(struct usb_hcd *hcd)
4317 {
4318         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4319         struct usb_bus *bus = hcd_to_bus(hcd);
4320         unsigned long flags;
4321
4322         dev_dbg(hsotg->dev, "DWC OTG HCD START\n");
4323
4324         spin_lock_irqsave(&hsotg->lock, flags);
4325         hsotg->lx_state = DWC2_L0;
4326         hcd->state = HC_STATE_RUNNING;
4327         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
4328
4329         if (dwc2_is_device_mode(hsotg)) {
4330                 spin_unlock_irqrestore(&hsotg->lock, flags);
4331                 return 0;       /* why 0 ?? */
4332         }
4333
4334         dwc2_hcd_reinit(hsotg);
4335
4336         /* Initialize and connect root hub if one is not already attached */
4337         if (bus->root_hub) {
4338                 dev_dbg(hsotg->dev, "DWC OTG HCD Has Root Hub\n");
4339                 /* Inform the HUB driver to resume */
4340                 usb_hcd_resume_root_hub(hcd);
4341         }
4342
4343         spin_unlock_irqrestore(&hsotg->lock, flags);
4344
4345         dwc2_vbus_supply_init(hsotg);
4346
4347         return 0;
4348 }
4349
4350 /*
4351  * Halts the DWC_otg host mode operations in a clean manner. USB transfers are
4352  * stopped.
4353  */
4354 static void _dwc2_hcd_stop(struct usb_hcd *hcd)
4355 {
4356         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4357         unsigned long flags;
4358
4359         /* Turn off all host-specific interrupts */
4360         dwc2_disable_host_interrupts(hsotg);
4361
4362         /* Wait for interrupt processing to finish */
4363         synchronize_irq(hcd->irq);
4364
4365         spin_lock_irqsave(&hsotg->lock, flags);
4366         /* Ensure hcd is disconnected */
4367         dwc2_hcd_disconnect(hsotg, true);
4368         dwc2_hcd_stop(hsotg);
4369         hsotg->lx_state = DWC2_L3;
4370         hcd->state = HC_STATE_HALT;
4371         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
4372         spin_unlock_irqrestore(&hsotg->lock, flags);
4373
4374         dwc2_vbus_supply_exit(hsotg);
4375
4376         usleep_range(1000, 3000);
4377 }
4378
4379 static int _dwc2_hcd_suspend(struct usb_hcd *hcd)
4380 {
4381         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4382         unsigned long flags;
4383         int ret = 0;
4384         u32 hprt0;
4385
4386         spin_lock_irqsave(&hsotg->lock, flags);
4387
4388         if (dwc2_is_device_mode(hsotg))
4389                 goto unlock;
4390
4391         if (hsotg->lx_state != DWC2_L0)
4392                 goto unlock;
4393
4394         if (!HCD_HW_ACCESSIBLE(hcd))
4395                 goto unlock;
4396
4397         if (hsotg->op_state == OTG_STATE_B_PERIPHERAL)
4398                 goto unlock;
4399
4400         if (hsotg->params.power_down != DWC2_POWER_DOWN_PARAM_PARTIAL)
4401                 goto skip_power_saving;
4402
4403         /*
4404          * Drive USB suspend and disable port Power
4405          * if usb bus is not suspended.
4406          */
4407         if (!hsotg->bus_suspended) {
4408                 hprt0 = dwc2_read_hprt0(hsotg);
4409                 hprt0 |= HPRT0_SUSP;
4410                 hprt0 &= ~HPRT0_PWR;
4411                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
4412                 dwc2_vbus_supply_exit(hsotg);
4413         }
4414
4415         /* Enter partial_power_down */
4416         ret = dwc2_enter_partial_power_down(hsotg);
4417         if (ret) {
4418                 if (ret != -ENOTSUPP)
4419                         dev_err(hsotg->dev,
4420                                 "enter partial_power_down failed\n");
4421                 goto skip_power_saving;
4422         }
4423
4424         /* Ask phy to be suspended */
4425         if (!IS_ERR_OR_NULL(hsotg->uphy)) {
4426                 spin_unlock_irqrestore(&hsotg->lock, flags);
4427                 usb_phy_set_suspend(hsotg->uphy, true);
4428                 spin_lock_irqsave(&hsotg->lock, flags);
4429         }
4430
4431         /* After entering partial_power_down, hardware is no more accessible */
4432         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
4433
4434 skip_power_saving:
4435         hsotg->lx_state = DWC2_L2;
4436 unlock:
4437         spin_unlock_irqrestore(&hsotg->lock, flags);
4438
4439         return ret;
4440 }
4441
4442 static int _dwc2_hcd_resume(struct usb_hcd *hcd)
4443 {
4444         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4445         unsigned long flags;
4446         int ret = 0;
4447
4448         spin_lock_irqsave(&hsotg->lock, flags);
4449
4450         if (dwc2_is_device_mode(hsotg))
4451                 goto unlock;
4452
4453         if (hsotg->lx_state != DWC2_L2)
4454                 goto unlock;
4455
4456         if (hsotg->params.power_down != DWC2_POWER_DOWN_PARAM_PARTIAL) {
4457                 hsotg->lx_state = DWC2_L0;
4458                 goto unlock;
4459         }
4460
4461         /*
4462          * Set HW accessible bit before powering on the controller
4463          * since an interrupt may rise.
4464          */
4465         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
4466
4467         /*
4468          * Enable power if not already done.
4469          * This must not be spinlocked since duration
4470          * of this call is unknown.
4471          */
4472         if (!IS_ERR_OR_NULL(hsotg->uphy)) {
4473                 spin_unlock_irqrestore(&hsotg->lock, flags);
4474                 usb_phy_set_suspend(hsotg->uphy, false);
4475                 spin_lock_irqsave(&hsotg->lock, flags);
4476         }
4477
4478         /* Exit partial_power_down */
4479         ret = dwc2_exit_partial_power_down(hsotg, true);
4480         if (ret && (ret != -ENOTSUPP))
4481                 dev_err(hsotg->dev, "exit partial_power_down failed\n");
4482
4483         hsotg->lx_state = DWC2_L0;
4484
4485         spin_unlock_irqrestore(&hsotg->lock, flags);
4486
4487         if (hsotg->bus_suspended) {
4488                 spin_lock_irqsave(&hsotg->lock, flags);
4489                 hsotg->flags.b.port_suspend_change = 1;
4490                 spin_unlock_irqrestore(&hsotg->lock, flags);
4491                 dwc2_port_resume(hsotg);
4492         } else {
4493                 dwc2_vbus_supply_init(hsotg);
4494
4495                 /* Wait for controller to correctly update D+/D- level */
4496                 usleep_range(3000, 5000);
4497
4498                 /*
4499                  * Clear Port Enable and Port Status changes.
4500                  * Enable Port Power.
4501                  */
4502                 dwc2_writel(HPRT0_PWR | HPRT0_CONNDET |
4503                                 HPRT0_ENACHG, hsotg->regs + HPRT0);
4504                 /* Wait for controller to detect Port Connect */
4505                 usleep_range(5000, 7000);
4506         }
4507
4508         return ret;
4509 unlock:
4510         spin_unlock_irqrestore(&hsotg->lock, flags);
4511
4512         return ret;
4513 }
4514
4515 /* Returns the current frame number */
4516 static int _dwc2_hcd_get_frame_number(struct usb_hcd *hcd)
4517 {
4518         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4519
4520         return dwc2_hcd_get_frame_number(hsotg);
4521 }
4522
4523 static void dwc2_dump_urb_info(struct usb_hcd *hcd, struct urb *urb,
4524                                char *fn_name)
4525 {
4526 #ifdef VERBOSE_DEBUG
4527         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4528         char *pipetype = NULL;
4529         char *speed = NULL;
4530
4531         dev_vdbg(hsotg->dev, "%s, urb %p\n", fn_name, urb);
4532         dev_vdbg(hsotg->dev, "  Device address: %d\n",
4533                  usb_pipedevice(urb->pipe));
4534         dev_vdbg(hsotg->dev, "  Endpoint: %d, %s\n",
4535                  usb_pipeendpoint(urb->pipe),
4536                  usb_pipein(urb->pipe) ? "IN" : "OUT");
4537
4538         switch (usb_pipetype(urb->pipe)) {
4539         case PIPE_CONTROL:
4540                 pipetype = "CONTROL";
4541                 break;
4542         case PIPE_BULK:
4543                 pipetype = "BULK";
4544                 break;
4545         case PIPE_INTERRUPT:
4546                 pipetype = "INTERRUPT";
4547                 break;
4548         case PIPE_ISOCHRONOUS:
4549                 pipetype = "ISOCHRONOUS";
4550                 break;
4551         }
4552
4553         dev_vdbg(hsotg->dev, "  Endpoint type: %s %s (%s)\n", pipetype,
4554                  usb_urb_dir_in(urb) ? "IN" : "OUT", usb_pipein(urb->pipe) ?
4555                  "IN" : "OUT");
4556
4557         switch (urb->dev->speed) {
4558         case USB_SPEED_HIGH:
4559                 speed = "HIGH";
4560                 break;
4561         case USB_SPEED_FULL:
4562                 speed = "FULL";
4563                 break;
4564         case USB_SPEED_LOW:
4565                 speed = "LOW";
4566                 break;
4567         default:
4568                 speed = "UNKNOWN";
4569                 break;
4570         }
4571
4572         dev_vdbg(hsotg->dev, "  Speed: %s\n", speed);
4573         dev_vdbg(hsotg->dev, "  Max packet size: %d\n",
4574                  usb_maxpacket(urb->dev, urb->pipe, usb_pipeout(urb->pipe)));
4575         dev_vdbg(hsotg->dev, "  Data buffer length: %d\n",
4576                  urb->transfer_buffer_length);
4577         dev_vdbg(hsotg->dev, "  Transfer buffer: %p, Transfer DMA: %08lx\n",
4578                  urb->transfer_buffer, (unsigned long)urb->transfer_dma);
4579         dev_vdbg(hsotg->dev, "  Setup buffer: %p, Setup DMA: %08lx\n",
4580                  urb->setup_packet, (unsigned long)urb->setup_dma);
4581         dev_vdbg(hsotg->dev, "  Interval: %d\n", urb->interval);
4582
4583         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) {
4584                 int i;
4585
4586                 for (i = 0; i < urb->number_of_packets; i++) {
4587                         dev_vdbg(hsotg->dev, "  ISO Desc %d:\n", i);
4588                         dev_vdbg(hsotg->dev, "    offset: %d, length %d\n",
4589                                  urb->iso_frame_desc[i].offset,
4590                                  urb->iso_frame_desc[i].length);
4591                 }
4592         }
4593 #endif
4594 }
4595
4596 /*
4597  * Starts processing a USB transfer request specified by a USB Request Block
4598  * (URB). mem_flags indicates the type of memory allocation to use while
4599  * processing this URB.
4600  */
4601 static int _dwc2_hcd_urb_enqueue(struct usb_hcd *hcd, struct urb *urb,
4602                                  gfp_t mem_flags)
4603 {
4604         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4605         struct usb_host_endpoint *ep = urb->ep;
4606         struct dwc2_hcd_urb *dwc2_urb;
4607         int i;
4608         int retval;
4609         int alloc_bandwidth = 0;
4610         u8 ep_type = 0;
4611         u32 tflags = 0;
4612         void *buf;
4613         unsigned long flags;
4614         struct dwc2_qh *qh;
4615         bool qh_allocated = false;
4616         struct dwc2_qtd *qtd;
4617
4618         if (dbg_urb(urb)) {
4619                 dev_vdbg(hsotg->dev, "DWC OTG HCD URB Enqueue\n");
4620                 dwc2_dump_urb_info(hcd, urb, "urb_enqueue");
4621         }
4622
4623         if (!ep)
4624                 return -EINVAL;
4625
4626         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS ||
4627             usb_pipetype(urb->pipe) == PIPE_INTERRUPT) {
4628                 spin_lock_irqsave(&hsotg->lock, flags);
4629                 if (!dwc2_hcd_is_bandwidth_allocated(hsotg, ep))
4630                         alloc_bandwidth = 1;
4631                 spin_unlock_irqrestore(&hsotg->lock, flags);
4632         }
4633
4634         switch (usb_pipetype(urb->pipe)) {
4635         case PIPE_CONTROL:
4636                 ep_type = USB_ENDPOINT_XFER_CONTROL;
4637                 break;
4638         case PIPE_ISOCHRONOUS:
4639                 ep_type = USB_ENDPOINT_XFER_ISOC;
4640                 break;
4641         case PIPE_BULK:
4642                 ep_type = USB_ENDPOINT_XFER_BULK;
4643                 break;
4644         case PIPE_INTERRUPT:
4645                 ep_type = USB_ENDPOINT_XFER_INT;
4646                 break;
4647         }
4648
4649         dwc2_urb = dwc2_hcd_urb_alloc(hsotg, urb->number_of_packets,
4650                                       mem_flags);
4651         if (!dwc2_urb)
4652                 return -ENOMEM;
4653
4654         dwc2_hcd_urb_set_pipeinfo(hsotg, dwc2_urb, usb_pipedevice(urb->pipe),
4655                                   usb_pipeendpoint(urb->pipe), ep_type,
4656                                   usb_pipein(urb->pipe),
4657                                   usb_maxpacket(urb->dev, urb->pipe,
4658                                                 !(usb_pipein(urb->pipe))));
4659
4660         buf = urb->transfer_buffer;
4661
4662         if (hcd->self.uses_dma) {
4663                 if (!buf && (urb->transfer_dma & 3)) {
4664                         dev_err(hsotg->dev,
4665                                 "%s: unaligned transfer with no transfer_buffer",
4666                                 __func__);
4667                         retval = -EINVAL;
4668                         goto fail0;
4669                 }
4670         }
4671
4672         if (!(urb->transfer_flags & URB_NO_INTERRUPT))
4673                 tflags |= URB_GIVEBACK_ASAP;
4674         if (urb->transfer_flags & URB_ZERO_PACKET)
4675                 tflags |= URB_SEND_ZERO_PACKET;
4676
4677         dwc2_urb->priv = urb;
4678         dwc2_urb->buf = buf;
4679         dwc2_urb->dma = urb->transfer_dma;
4680         dwc2_urb->length = urb->transfer_buffer_length;
4681         dwc2_urb->setup_packet = urb->setup_packet;
4682         dwc2_urb->setup_dma = urb->setup_dma;
4683         dwc2_urb->flags = tflags;
4684         dwc2_urb->interval = urb->interval;
4685         dwc2_urb->status = -EINPROGRESS;
4686
4687         for (i = 0; i < urb->number_of_packets; ++i)
4688                 dwc2_hcd_urb_set_iso_desc_params(dwc2_urb, i,
4689                                                  urb->iso_frame_desc[i].offset,
4690                                                  urb->iso_frame_desc[i].length);
4691
4692         urb->hcpriv = dwc2_urb;
4693         qh = (struct dwc2_qh *)ep->hcpriv;
4694         /* Create QH for the endpoint if it doesn't exist */
4695         if (!qh) {
4696                 qh = dwc2_hcd_qh_create(hsotg, dwc2_urb, mem_flags);
4697                 if (!qh) {
4698                         retval = -ENOMEM;
4699                         goto fail0;
4700                 }
4701                 ep->hcpriv = qh;
4702                 qh_allocated = true;
4703         }
4704
4705         qtd = kzalloc(sizeof(*qtd), mem_flags);
4706         if (!qtd) {
4707                 retval = -ENOMEM;
4708                 goto fail1;
4709         }
4710
4711         spin_lock_irqsave(&hsotg->lock, flags);
4712         retval = usb_hcd_link_urb_to_ep(hcd, urb);
4713         if (retval)
4714                 goto fail2;
4715
4716         retval = dwc2_hcd_urb_enqueue(hsotg, dwc2_urb, qh, qtd);
4717         if (retval)
4718                 goto fail3;
4719
4720         if (alloc_bandwidth) {
4721                 dwc2_allocate_bus_bandwidth(hcd,
4722                                 dwc2_hcd_get_ep_bandwidth(hsotg, ep),
4723                                 urb);
4724         }
4725
4726         spin_unlock_irqrestore(&hsotg->lock, flags);
4727
4728         return 0;
4729
4730 fail3:
4731         dwc2_urb->priv = NULL;
4732         usb_hcd_unlink_urb_from_ep(hcd, urb);
4733         if (qh_allocated && qh->channel && qh->channel->qh == qh)
4734                 qh->channel->qh = NULL;
4735 fail2:
4736         spin_unlock_irqrestore(&hsotg->lock, flags);
4737         urb->hcpriv = NULL;
4738         kfree(qtd);
4739         qtd = NULL;
4740 fail1:
4741         if (qh_allocated) {
4742                 struct dwc2_qtd *qtd2, *qtd2_tmp;
4743
4744                 ep->hcpriv = NULL;
4745                 dwc2_hcd_qh_unlink(hsotg, qh);
4746                 /* Free each QTD in the QH's QTD list */
4747                 list_for_each_entry_safe(qtd2, qtd2_tmp, &qh->qtd_list,
4748                                          qtd_list_entry)
4749                         dwc2_hcd_qtd_unlink_and_free(hsotg, qtd2, qh);
4750                 dwc2_hcd_qh_free(hsotg, qh);
4751         }
4752 fail0:
4753         kfree(dwc2_urb);
4754
4755         return retval;
4756 }
4757
4758 /*
4759  * Aborts/cancels a USB transfer request. Always returns 0 to indicate success.
4760  */
4761 static int _dwc2_hcd_urb_dequeue(struct usb_hcd *hcd, struct urb *urb,
4762                                  int status)
4763 {
4764         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4765         int rc;
4766         unsigned long flags;
4767
4768         dev_dbg(hsotg->dev, "DWC OTG HCD URB Dequeue\n");
4769         dwc2_dump_urb_info(hcd, urb, "urb_dequeue");
4770
4771         spin_lock_irqsave(&hsotg->lock, flags);
4772
4773         rc = usb_hcd_check_unlink_urb(hcd, urb, status);
4774         if (rc)
4775                 goto out;
4776
4777         if (!urb->hcpriv) {
4778                 dev_dbg(hsotg->dev, "## urb->hcpriv is NULL ##\n");
4779                 goto out;
4780         }
4781
4782         rc = dwc2_hcd_urb_dequeue(hsotg, urb->hcpriv);
4783
4784         usb_hcd_unlink_urb_from_ep(hcd, urb);
4785
4786         kfree(urb->hcpriv);
4787         urb->hcpriv = NULL;
4788
4789         /* Higher layer software sets URB status */
4790         spin_unlock(&hsotg->lock);
4791         usb_hcd_giveback_urb(hcd, urb, status);
4792         spin_lock(&hsotg->lock);
4793
4794         dev_dbg(hsotg->dev, "Called usb_hcd_giveback_urb()\n");
4795         dev_dbg(hsotg->dev, "  urb->status = %d\n", urb->status);
4796 out:
4797         spin_unlock_irqrestore(&hsotg->lock, flags);
4798
4799         return rc;
4800 }
4801
4802 /*
4803  * Frees resources in the DWC_otg controller related to a given endpoint. Also
4804  * clears state in the HCD related to the endpoint. Any URBs for the endpoint
4805  * must already be dequeued.
4806  */
4807 static void _dwc2_hcd_endpoint_disable(struct usb_hcd *hcd,
4808                                        struct usb_host_endpoint *ep)
4809 {
4810         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4811
4812         dev_dbg(hsotg->dev,
4813                 "DWC OTG HCD EP DISABLE: bEndpointAddress=0x%02x, ep->hcpriv=%p\n",
4814                 ep->desc.bEndpointAddress, ep->hcpriv);
4815         dwc2_hcd_endpoint_disable(hsotg, ep, 250);
4816 }
4817
4818 /*
4819  * Resets endpoint specific parameter values, in current version used to reset
4820  * the data toggle (as a WA). This function can be called from usb_clear_halt
4821  * routine.
4822  */
4823 static void _dwc2_hcd_endpoint_reset(struct usb_hcd *hcd,
4824                                      struct usb_host_endpoint *ep)
4825 {
4826         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4827         unsigned long flags;
4828
4829         dev_dbg(hsotg->dev,
4830                 "DWC OTG HCD EP RESET: bEndpointAddress=0x%02x\n",
4831                 ep->desc.bEndpointAddress);
4832
4833         spin_lock_irqsave(&hsotg->lock, flags);
4834         dwc2_hcd_endpoint_reset(hsotg, ep);
4835         spin_unlock_irqrestore(&hsotg->lock, flags);
4836 }
4837
4838 /*
4839  * Handles host mode interrupts for the DWC_otg controller. Returns IRQ_NONE if
4840  * there was no interrupt to handle. Returns IRQ_HANDLED if there was a valid
4841  * interrupt.
4842  *
4843  * This function is called by the USB core when an interrupt occurs
4844  */
4845 static irqreturn_t _dwc2_hcd_irq(struct usb_hcd *hcd)
4846 {
4847         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4848
4849         return dwc2_handle_hcd_intr(hsotg);
4850 }
4851
4852 /*
4853  * Creates Status Change bitmap for the root hub and root port. The bitmap is
4854  * returned in buf. Bit 0 is the status change indicator for the root hub. Bit 1
4855  * is the status change indicator for the single root port. Returns 1 if either
4856  * change indicator is 1, otherwise returns 0.
4857  */
4858 static int _dwc2_hcd_hub_status_data(struct usb_hcd *hcd, char *buf)
4859 {
4860         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4861
4862         buf[0] = dwc2_hcd_is_status_changed(hsotg, 1) << 1;
4863         return buf[0] != 0;
4864 }
4865
4866 /* Handles hub class-specific requests */
4867 static int _dwc2_hcd_hub_control(struct usb_hcd *hcd, u16 typereq, u16 wvalue,
4868                                  u16 windex, char *buf, u16 wlength)
4869 {
4870         int retval = dwc2_hcd_hub_control(dwc2_hcd_to_hsotg(hcd), typereq,
4871                                           wvalue, windex, buf, wlength);
4872         return retval;
4873 }
4874
4875 /* Handles hub TT buffer clear completions */
4876 static void _dwc2_hcd_clear_tt_buffer_complete(struct usb_hcd *hcd,
4877                                                struct usb_host_endpoint *ep)
4878 {
4879         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4880         struct dwc2_qh *qh;
4881         unsigned long flags;
4882
4883         qh = ep->hcpriv;
4884         if (!qh)
4885                 return;
4886
4887         spin_lock_irqsave(&hsotg->lock, flags);
4888         qh->tt_buffer_dirty = 0;
4889
4890         if (hsotg->flags.b.port_connect_status)
4891                 dwc2_hcd_queue_transactions(hsotg, DWC2_TRANSACTION_ALL);
4892
4893         spin_unlock_irqrestore(&hsotg->lock, flags);
4894 }
4895
4896 /*
4897  * HPRT0_SPD_HIGH_SPEED: high speed
4898  * HPRT0_SPD_FULL_SPEED: full speed
4899  */
4900 static void dwc2_change_bus_speed(struct usb_hcd *hcd, int speed)
4901 {
4902         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4903
4904         if (hsotg->params.speed == speed)
4905                 return;
4906
4907         hsotg->params.speed = speed;
4908         queue_work(hsotg->wq_otg, &hsotg->wf_otg);
4909 }
4910
4911 static void dwc2_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
4912 {
4913         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4914
4915         if (!hsotg->params.change_speed_quirk)
4916                 return;
4917
4918         /*
4919          * On removal, set speed to default high-speed.
4920          */
4921         if (udev->parent && udev->parent->speed > USB_SPEED_UNKNOWN &&
4922             udev->parent->speed < USB_SPEED_HIGH) {
4923                 dev_info(hsotg->dev, "Set speed to default high-speed\n");
4924                 dwc2_change_bus_speed(hcd, HPRT0_SPD_HIGH_SPEED);
4925         }
4926 }
4927
4928 static int dwc2_reset_device(struct usb_hcd *hcd, struct usb_device *udev)
4929 {
4930         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4931
4932         if (!hsotg->params.change_speed_quirk)
4933                 return 0;
4934
4935         if (udev->speed == USB_SPEED_HIGH) {
4936                 dev_info(hsotg->dev, "Set speed to high-speed\n");
4937                 dwc2_change_bus_speed(hcd, HPRT0_SPD_HIGH_SPEED);
4938         } else if ((udev->speed == USB_SPEED_FULL ||
4939                                 udev->speed == USB_SPEED_LOW)) {
4940                 /*
4941                  * Change speed setting to full-speed if there's
4942                  * a full-speed or low-speed device plugged in.
4943                  */
4944                 dev_info(hsotg->dev, "Set speed to full-speed\n");
4945                 dwc2_change_bus_speed(hcd, HPRT0_SPD_FULL_SPEED);
4946         }
4947
4948         return 0;
4949 }
4950
4951 static struct hc_driver dwc2_hc_driver = {
4952         .description = "dwc2_hsotg",
4953         .product_desc = "DWC OTG Controller",
4954         .hcd_priv_size = sizeof(struct wrapper_priv_data),
4955
4956         .irq = _dwc2_hcd_irq,
4957         .flags = HCD_MEMORY | HCD_USB2 | HCD_BH,
4958
4959         .start = _dwc2_hcd_start,
4960         .stop = _dwc2_hcd_stop,
4961         .urb_enqueue = _dwc2_hcd_urb_enqueue,
4962         .urb_dequeue = _dwc2_hcd_urb_dequeue,
4963         .endpoint_disable = _dwc2_hcd_endpoint_disable,
4964         .endpoint_reset = _dwc2_hcd_endpoint_reset,
4965         .get_frame_number = _dwc2_hcd_get_frame_number,
4966
4967         .hub_status_data = _dwc2_hcd_hub_status_data,
4968         .hub_control = _dwc2_hcd_hub_control,
4969         .clear_tt_buffer_complete = _dwc2_hcd_clear_tt_buffer_complete,
4970
4971         .bus_suspend = _dwc2_hcd_suspend,
4972         .bus_resume = _dwc2_hcd_resume,
4973
4974         .map_urb_for_dma        = dwc2_map_urb_for_dma,
4975         .unmap_urb_for_dma      = dwc2_unmap_urb_for_dma,
4976 };
4977
4978 /*
4979  * Frees secondary storage associated with the dwc2_hsotg structure contained
4980  * in the struct usb_hcd field
4981  */
4982 static void dwc2_hcd_free(struct dwc2_hsotg *hsotg)
4983 {
4984         u32 ahbcfg;
4985         u32 dctl;
4986         int i;
4987
4988         dev_dbg(hsotg->dev, "DWC OTG HCD FREE\n");
4989
4990         /* Free memory for QH/QTD lists */
4991         dwc2_qh_list_free(hsotg, &hsotg->non_periodic_sched_inactive);
4992         dwc2_qh_list_free(hsotg, &hsotg->non_periodic_sched_waiting);
4993         dwc2_qh_list_free(hsotg, &hsotg->non_periodic_sched_active);
4994         dwc2_qh_list_free(hsotg, &hsotg->periodic_sched_inactive);
4995         dwc2_qh_list_free(hsotg, &hsotg->periodic_sched_ready);
4996         dwc2_qh_list_free(hsotg, &hsotg->periodic_sched_assigned);
4997         dwc2_qh_list_free(hsotg, &hsotg->periodic_sched_queued);
4998
4999         /* Free memory for the host channels */
5000         for (i = 0; i < MAX_EPS_CHANNELS; i++) {
5001                 struct dwc2_host_chan *chan = hsotg->hc_ptr_array[i];
5002
5003                 if (chan) {
5004                         dev_dbg(hsotg->dev, "HCD Free channel #%i, chan=%p\n",
5005                                 i, chan);
5006                         hsotg->hc_ptr_array[i] = NULL;
5007                         kfree(chan);
5008                 }
5009         }
5010
5011         if (hsotg->params.host_dma) {
5012                 if (hsotg->status_buf) {
5013                         dma_free_coherent(hsotg->dev, DWC2_HCD_STATUS_BUF_SIZE,
5014                                           hsotg->status_buf,
5015                                           hsotg->status_buf_dma);
5016                         hsotg->status_buf = NULL;
5017                 }
5018         } else {
5019                 kfree(hsotg->status_buf);
5020                 hsotg->status_buf = NULL;
5021         }
5022
5023         ahbcfg = dwc2_readl(hsotg->regs + GAHBCFG);
5024
5025         /* Disable all interrupts */
5026         ahbcfg &= ~GAHBCFG_GLBL_INTR_EN;
5027         dwc2_writel(ahbcfg, hsotg->regs + GAHBCFG);
5028         dwc2_writel(0, hsotg->regs + GINTMSK);
5029
5030         if (hsotg->hw_params.snpsid >= DWC2_CORE_REV_3_00a) {
5031                 dctl = dwc2_readl(hsotg->regs + DCTL);
5032                 dctl |= DCTL_SFTDISCON;
5033                 dwc2_writel(dctl, hsotg->regs + DCTL);
5034         }
5035
5036         if (hsotg->wq_otg) {
5037                 if (!cancel_work_sync(&hsotg->wf_otg))
5038                         flush_workqueue(hsotg->wq_otg);
5039                 destroy_workqueue(hsotg->wq_otg);
5040         }
5041
5042         del_timer(&hsotg->wkp_timer);
5043 }
5044
5045 static void dwc2_hcd_release(struct dwc2_hsotg *hsotg)
5046 {
5047         /* Turn off all host-specific interrupts */
5048         dwc2_disable_host_interrupts(hsotg);
5049
5050         dwc2_hcd_free(hsotg);
5051 }
5052
5053 /*
5054  * Initializes the HCD. This function allocates memory for and initializes the
5055  * static parts of the usb_hcd and dwc2_hsotg structures. It also registers the
5056  * USB bus with the core and calls the hc_driver->start() function. It returns
5057  * a negative error on failure.
5058  */
5059 int dwc2_hcd_init(struct dwc2_hsotg *hsotg)
5060 {
5061         struct platform_device *pdev = to_platform_device(hsotg->dev);
5062         struct resource *res;
5063         struct usb_hcd *hcd;
5064         struct dwc2_host_chan *channel;
5065         u32 hcfg;
5066         int i, num_channels;
5067         int retval;
5068
5069         if (usb_disabled())
5070                 return -ENODEV;
5071
5072         dev_dbg(hsotg->dev, "DWC OTG HCD INIT\n");
5073
5074         retval = -ENOMEM;
5075
5076         hcfg = dwc2_readl(hsotg->regs + HCFG);
5077         dev_dbg(hsotg->dev, "hcfg=%08x\n", hcfg);
5078
5079 #ifdef CONFIG_USB_DWC2_TRACK_MISSED_SOFS
5080         hsotg->frame_num_array = kzalloc(sizeof(*hsotg->frame_num_array) *
5081                                          FRAME_NUM_ARRAY_SIZE, GFP_KERNEL);
5082         if (!hsotg->frame_num_array)
5083                 goto error1;
5084         hsotg->last_frame_num_array = kzalloc(
5085                         sizeof(*hsotg->last_frame_num_array) *
5086                         FRAME_NUM_ARRAY_SIZE, GFP_KERNEL);
5087         if (!hsotg->last_frame_num_array)
5088                 goto error1;
5089 #endif
5090         hsotg->last_frame_num = HFNUM_MAX_FRNUM;
5091
5092         /* Check if the bus driver or platform code has setup a dma_mask */
5093         if (hsotg->params.host_dma &&
5094             !hsotg->dev->dma_mask) {
5095                 dev_warn(hsotg->dev,
5096                          "dma_mask not set, disabling DMA\n");
5097                 hsotg->params.host_dma = false;
5098                 hsotg->params.dma_desc_enable = false;
5099         }
5100
5101         /* Set device flags indicating whether the HCD supports DMA */
5102         if (hsotg->params.host_dma) {
5103                 if (dma_set_mask(hsotg->dev, DMA_BIT_MASK(32)) < 0)
5104                         dev_warn(hsotg->dev, "can't set DMA mask\n");
5105                 if (dma_set_coherent_mask(hsotg->dev, DMA_BIT_MASK(32)) < 0)
5106                         dev_warn(hsotg->dev, "can't set coherent DMA mask\n");
5107         }
5108
5109         if (hsotg->params.change_speed_quirk) {
5110                 dwc2_hc_driver.free_dev = dwc2_free_dev;
5111                 dwc2_hc_driver.reset_device = dwc2_reset_device;
5112         }
5113
5114         hcd = usb_create_hcd(&dwc2_hc_driver, hsotg->dev, dev_name(hsotg->dev));
5115         if (!hcd)
5116                 goto error1;
5117
5118         if (!hsotg->params.host_dma)
5119                 hcd->self.uses_dma = 0;
5120
5121         hcd->has_tt = 1;
5122
5123         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
5124         hcd->rsrc_start = res->start;
5125         hcd->rsrc_len = resource_size(res);
5126
5127         ((struct wrapper_priv_data *)&hcd->hcd_priv)->hsotg = hsotg;
5128         hsotg->priv = hcd;
5129
5130         /*
5131          * Disable the global interrupt until all the interrupt handlers are
5132          * installed
5133          */
5134         dwc2_disable_global_interrupts(hsotg);
5135
5136         /* Initialize the DWC_otg core, and select the Phy type */
5137         retval = dwc2_core_init(hsotg, true);
5138         if (retval)
5139                 goto error2;
5140
5141         /* Create new workqueue and init work */
5142         retval = -ENOMEM;
5143         hsotg->wq_otg = alloc_ordered_workqueue("dwc2", 0);
5144         if (!hsotg->wq_otg) {
5145                 dev_err(hsotg->dev, "Failed to create workqueue\n");
5146                 goto error2;
5147         }
5148         INIT_WORK(&hsotg->wf_otg, dwc2_conn_id_status_change);
5149
5150         timer_setup(&hsotg->wkp_timer, dwc2_wakeup_detected, 0);
5151
5152         /* Initialize the non-periodic schedule */
5153         INIT_LIST_HEAD(&hsotg->non_periodic_sched_inactive);
5154         INIT_LIST_HEAD(&hsotg->non_periodic_sched_waiting);
5155         INIT_LIST_HEAD(&hsotg->non_periodic_sched_active);
5156
5157         /* Initialize the periodic schedule */
5158         INIT_LIST_HEAD(&hsotg->periodic_sched_inactive);
5159         INIT_LIST_HEAD(&hsotg->periodic_sched_ready);
5160         INIT_LIST_HEAD(&hsotg->periodic_sched_assigned);
5161         INIT_LIST_HEAD(&hsotg->periodic_sched_queued);
5162
5163         INIT_LIST_HEAD(&hsotg->split_order);
5164
5165         /*
5166          * Create a host channel descriptor for each host channel implemented
5167          * in the controller. Initialize the channel descriptor array.
5168          */
5169         INIT_LIST_HEAD(&hsotg->free_hc_list);
5170         num_channels = hsotg->params.host_channels;
5171         memset(&hsotg->hc_ptr_array[0], 0, sizeof(hsotg->hc_ptr_array));
5172
5173         for (i = 0; i < num_channels; i++) {
5174                 channel = kzalloc(sizeof(*channel), GFP_KERNEL);
5175                 if (!channel)
5176                         goto error3;
5177                 channel->hc_num = i;
5178                 INIT_LIST_HEAD(&channel->split_order_list_entry);
5179                 hsotg->hc_ptr_array[i] = channel;
5180         }
5181
5182         /* Initialize hsotg start work */
5183         INIT_DELAYED_WORK(&hsotg->start_work, dwc2_hcd_start_func);
5184
5185         /* Initialize port reset work */
5186         INIT_DELAYED_WORK(&hsotg->reset_work, dwc2_hcd_reset_func);
5187
5188         /*
5189          * Allocate space for storing data on status transactions. Normally no
5190          * data is sent, but this space acts as a bit bucket. This must be
5191          * done after usb_add_hcd since that function allocates the DMA buffer
5192          * pool.
5193          */
5194         if (hsotg->params.host_dma)
5195                 hsotg->status_buf = dma_alloc_coherent(hsotg->dev,
5196                                         DWC2_HCD_STATUS_BUF_SIZE,
5197                                         &hsotg->status_buf_dma, GFP_KERNEL);
5198         else
5199                 hsotg->status_buf = kzalloc(DWC2_HCD_STATUS_BUF_SIZE,
5200                                           GFP_KERNEL);
5201
5202         if (!hsotg->status_buf)
5203                 goto error3;
5204
5205         /*
5206          * Create kmem caches to handle descriptor buffers in descriptor
5207          * DMA mode.
5208          * Alignment must be set to 512 bytes.
5209          */
5210         if (hsotg->params.dma_desc_enable ||
5211             hsotg->params.dma_desc_fs_enable) {
5212                 hsotg->desc_gen_cache = kmem_cache_create("dwc2-gen-desc",
5213                                 sizeof(struct dwc2_dma_desc) *
5214                                 MAX_DMA_DESC_NUM_GENERIC, 512, SLAB_CACHE_DMA,
5215                                 NULL);
5216                 if (!hsotg->desc_gen_cache) {
5217                         dev_err(hsotg->dev,
5218                                 "unable to create dwc2 generic desc cache\n");
5219
5220                         /*
5221                          * Disable descriptor dma mode since it will not be
5222                          * usable.
5223                          */
5224                         hsotg->params.dma_desc_enable = false;
5225                         hsotg->params.dma_desc_fs_enable = false;
5226                 }
5227
5228                 hsotg->desc_hsisoc_cache = kmem_cache_create("dwc2-hsisoc-desc",
5229                                 sizeof(struct dwc2_dma_desc) *
5230                                 MAX_DMA_DESC_NUM_HS_ISOC, 512, 0, NULL);
5231                 if (!hsotg->desc_hsisoc_cache) {
5232                         dev_err(hsotg->dev,
5233                                 "unable to create dwc2 hs isoc desc cache\n");
5234
5235                         kmem_cache_destroy(hsotg->desc_gen_cache);
5236
5237                         /*
5238                          * Disable descriptor dma mode since it will not be
5239                          * usable.
5240                          */
5241                         hsotg->params.dma_desc_enable = false;
5242                         hsotg->params.dma_desc_fs_enable = false;
5243                 }
5244         }
5245
5246         hsotg->otg_port = 1;
5247         hsotg->frame_list = NULL;
5248         hsotg->frame_list_dma = 0;
5249         hsotg->periodic_qh_count = 0;
5250
5251         /* Initiate lx_state to L3 disconnected state */
5252         hsotg->lx_state = DWC2_L3;
5253
5254         hcd->self.otg_port = hsotg->otg_port;
5255
5256         /* Don't support SG list at this point */
5257         hcd->self.sg_tablesize = 0;
5258
5259         if (!IS_ERR_OR_NULL(hsotg->uphy))
5260                 otg_set_host(hsotg->uphy->otg, &hcd->self);
5261
5262         /*
5263          * Finish generic HCD initialization and start the HCD. This function
5264          * allocates the DMA buffer pool, registers the USB bus, requests the
5265          * IRQ line, and calls hcd_start method.
5266          */
5267         retval = usb_add_hcd(hcd, hsotg->irq, IRQF_SHARED);
5268         if (retval < 0)
5269                 goto error4;
5270
5271         device_wakeup_enable(hcd->self.controller);
5272
5273         dwc2_hcd_dump_state(hsotg);
5274
5275         dwc2_enable_global_interrupts(hsotg);
5276
5277         return 0;
5278
5279 error4:
5280         kmem_cache_destroy(hsotg->desc_gen_cache);
5281         kmem_cache_destroy(hsotg->desc_hsisoc_cache);
5282 error3:
5283         dwc2_hcd_release(hsotg);
5284 error2:
5285         usb_put_hcd(hcd);
5286 error1:
5287
5288 #ifdef CONFIG_USB_DWC2_TRACK_MISSED_SOFS
5289         kfree(hsotg->last_frame_num_array);
5290         kfree(hsotg->frame_num_array);
5291 #endif
5292
5293         dev_err(hsotg->dev, "%s() FAILED, returning %d\n", __func__, retval);
5294         return retval;
5295 }
5296
5297 /*
5298  * Removes the HCD.
5299  * Frees memory and resources associated with the HCD and deregisters the bus.
5300  */
5301 void dwc2_hcd_remove(struct dwc2_hsotg *hsotg)
5302 {
5303         struct usb_hcd *hcd;
5304
5305         dev_dbg(hsotg->dev, "DWC OTG HCD REMOVE\n");
5306
5307         hcd = dwc2_hsotg_to_hcd(hsotg);
5308         dev_dbg(hsotg->dev, "hsotg->hcd = %p\n", hcd);
5309
5310         if (!hcd) {
5311                 dev_dbg(hsotg->dev, "%s: dwc2_hsotg_to_hcd(hsotg) NULL!\n",
5312                         __func__);
5313                 return;
5314         }
5315
5316         if (!IS_ERR_OR_NULL(hsotg->uphy))
5317                 otg_set_host(hsotg->uphy->otg, NULL);
5318
5319         usb_remove_hcd(hcd);
5320         hsotg->priv = NULL;
5321
5322         kmem_cache_destroy(hsotg->desc_gen_cache);
5323         kmem_cache_destroy(hsotg->desc_hsisoc_cache);
5324
5325         dwc2_hcd_release(hsotg);
5326         usb_put_hcd(hcd);
5327
5328 #ifdef CONFIG_USB_DWC2_TRACK_MISSED_SOFS
5329         kfree(hsotg->last_frame_num_array);
5330         kfree(hsotg->frame_num_array);
5331 #endif
5332 }
5333
5334 /**
5335  * dwc2_backup_host_registers() - Backup controller host registers.
5336  * When suspending usb bus, registers needs to be backuped
5337  * if controller power is disabled once suspended.
5338  *
5339  * @hsotg: Programming view of the DWC_otg controller
5340  */
5341 int dwc2_backup_host_registers(struct dwc2_hsotg *hsotg)
5342 {
5343         struct dwc2_hregs_backup *hr;
5344         int i;
5345
5346         dev_dbg(hsotg->dev, "%s\n", __func__);
5347
5348         /* Backup Host regs */
5349         hr = &hsotg->hr_backup;
5350         hr->hcfg = dwc2_readl(hsotg->regs + HCFG);
5351         hr->haintmsk = dwc2_readl(hsotg->regs + HAINTMSK);
5352         for (i = 0; i < hsotg->params.host_channels; ++i)
5353                 hr->hcintmsk[i] = dwc2_readl(hsotg->regs + HCINTMSK(i));
5354
5355         hr->hprt0 = dwc2_read_hprt0(hsotg);
5356         hr->hfir = dwc2_readl(hsotg->regs + HFIR);
5357         hr->hptxfsiz = dwc2_readl(hsotg->regs + HPTXFSIZ);
5358         hr->valid = true;
5359
5360         return 0;
5361 }
5362
5363 /**
5364  * dwc2_restore_host_registers() - Restore controller host registers.
5365  * When resuming usb bus, device registers needs to be restored
5366  * if controller power were disabled.
5367  *
5368  * @hsotg: Programming view of the DWC_otg controller
5369  */
5370 int dwc2_restore_host_registers(struct dwc2_hsotg *hsotg)
5371 {
5372         struct dwc2_hregs_backup *hr;
5373         int i;
5374
5375         dev_dbg(hsotg->dev, "%s\n", __func__);
5376
5377         /* Restore host regs */
5378         hr = &hsotg->hr_backup;
5379         if (!hr->valid) {
5380                 dev_err(hsotg->dev, "%s: no host registers to restore\n",
5381                         __func__);
5382                 return -EINVAL;
5383         }
5384         hr->valid = false;
5385
5386         dwc2_writel(hr->hcfg, hsotg->regs + HCFG);
5387         dwc2_writel(hr->haintmsk, hsotg->regs + HAINTMSK);
5388
5389         for (i = 0; i < hsotg->params.host_channels; ++i)
5390                 dwc2_writel(hr->hcintmsk[i], hsotg->regs + HCINTMSK(i));
5391
5392         dwc2_writel(hr->hprt0, hsotg->regs + HPRT0);
5393         dwc2_writel(hr->hfir, hsotg->regs + HFIR);
5394         dwc2_writel(hr->hptxfsiz, hsotg->regs + HPTXFSIZ);
5395         hsotg->frame_number = 0;
5396
5397         return 0;
5398 }
5399
5400 /**
5401  * dwc2_host_enter_hibernation() - Put controller in Hibernation.
5402  *
5403  * @hsotg: Programming view of the DWC_otg controller
5404  */
5405 int dwc2_host_enter_hibernation(struct dwc2_hsotg *hsotg)
5406 {
5407         unsigned long flags;
5408         int ret = 0;
5409         u32 hprt0;
5410         u32 pcgcctl;
5411         u32 gusbcfg;
5412         u32 gpwrdn;
5413
5414         dev_dbg(hsotg->dev, "Preparing host for hibernation\n");
5415         ret = dwc2_backup_global_registers(hsotg);
5416         if (ret) {
5417                 dev_err(hsotg->dev, "%s: failed to backup global registers\n",
5418                         __func__);
5419                 return ret;
5420         }
5421         ret = dwc2_backup_host_registers(hsotg);
5422         if (ret) {
5423                 dev_err(hsotg->dev, "%s: failed to backup host registers\n",
5424                         __func__);
5425                 return ret;
5426         }
5427
5428         /* Enter USB Suspend Mode */
5429         hprt0 = dwc2_readl(hsotg->regs + HPRT0);
5430         hprt0 |= HPRT0_SUSP;
5431         hprt0 &= ~HPRT0_ENA;
5432         dwc2_writel(hprt0, hsotg->regs + HPRT0);
5433
5434         /* Wait for the HPRT0.PrtSusp register field to be set */
5435         if (dwc2_hsotg_wait_bit_set(hsotg, HPRT0, HPRT0_SUSP, 300))
5436                 dev_warn(hsotg->dev, "Suspend wasn't generated\n");
5437
5438         /*
5439          * We need to disable interrupts to prevent servicing of any IRQ
5440          * during going to hibernation
5441          */
5442         spin_lock_irqsave(&hsotg->lock, flags);
5443         hsotg->lx_state = DWC2_L2;
5444
5445         gusbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
5446         if (gusbcfg & GUSBCFG_ULPI_UTMI_SEL) {
5447                 /* ULPI interface */
5448                 /* Suspend the Phy Clock */
5449                 pcgcctl = dwc2_readl(hsotg->regs + PCGCTL);
5450                 pcgcctl |= PCGCTL_STOPPCLK;
5451                 dwc2_writel(pcgcctl, hsotg->regs + PCGCTL);
5452                 udelay(10);
5453
5454                 gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5455                 gpwrdn |= GPWRDN_PMUACTV;
5456                 dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5457                 udelay(10);
5458         } else {
5459                 /* UTMI+ Interface */
5460                 gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5461                 gpwrdn |= GPWRDN_PMUACTV;
5462                 dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5463                 udelay(10);
5464
5465                 pcgcctl = dwc2_readl(hsotg->regs + PCGCTL);
5466                 pcgcctl |= PCGCTL_STOPPCLK;
5467                 dwc2_writel(pcgcctl, hsotg->regs + PCGCTL);
5468                 udelay(10);
5469         }
5470
5471         /* Enable interrupts from wake up logic */
5472         gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5473         gpwrdn |= GPWRDN_PMUINTSEL;
5474         dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5475         udelay(10);
5476
5477         /* Unmask host mode interrupts in GPWRDN */
5478         gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5479         gpwrdn |= GPWRDN_DISCONN_DET_MSK;
5480         gpwrdn |= GPWRDN_LNSTSCHG_MSK;
5481         gpwrdn |= GPWRDN_STS_CHGINT_MSK;
5482         dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5483         udelay(10);
5484
5485         /* Enable Power Down Clamp */
5486         gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5487         gpwrdn |= GPWRDN_PWRDNCLMP;
5488         dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5489         udelay(10);
5490
5491         /* Switch off VDD */
5492         gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5493         gpwrdn |= GPWRDN_PWRDNSWTCH;
5494         dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5495
5496         hsotg->hibernated = 1;
5497         hsotg->bus_suspended = 1;
5498         dev_dbg(hsotg->dev, "Host hibernation completed\n");
5499         spin_unlock_irqrestore(&hsotg->lock, flags);
5500         return ret;
5501 }
5502
5503 /*
5504  * dwc2_host_exit_hibernation()
5505  *
5506  * @hsotg: Programming view of the DWC_otg controller
5507  * @rem_wakeup: indicates whether resume is initiated by Device or Host.
5508  * @param reset: indicates whether resume is initiated by Reset.
5509  *
5510  * Return: non-zero if failed to enter to hibernation.
5511  *
5512  * This function is for exiting from Host mode hibernation by
5513  * Host Initiated Resume/Reset and Device Initiated Remote-Wakeup.
5514  */
5515 int dwc2_host_exit_hibernation(struct dwc2_hsotg *hsotg, int rem_wakeup,
5516                                int reset)
5517 {
5518         u32 gpwrdn;
5519         u32 hprt0;
5520         int ret = 0;
5521         struct dwc2_gregs_backup *gr;
5522         struct dwc2_hregs_backup *hr;
5523
5524         gr = &hsotg->gr_backup;
5525         hr = &hsotg->hr_backup;
5526
5527         dev_dbg(hsotg->dev,
5528                 "%s: called with rem_wakeup = %d reset = %d\n",
5529                 __func__, rem_wakeup, reset);
5530
5531         dwc2_hib_restore_common(hsotg, rem_wakeup, 1);
5532         hsotg->hibernated = 0;
5533
5534         /*
5535          * This step is not described in functional spec but if not wait for
5536          * this delay, mismatch interrupts occurred because just after restore
5537          * core is in Device mode(gintsts.curmode == 0)
5538          */
5539         mdelay(100);
5540
5541         /* Clear all pending interupts */
5542         dwc2_writel(0xffffffff, hsotg->regs + GINTSTS);
5543
5544         /* De-assert Restore */
5545         gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5546         gpwrdn &= ~GPWRDN_RESTORE;
5547         dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5548         udelay(10);
5549
5550         /* Restore GUSBCFG, HCFG */
5551         dwc2_writel(gr->gusbcfg, hsotg->regs + GUSBCFG);
5552         dwc2_writel(hr->hcfg, hsotg->regs + HCFG);
5553
5554         /* De-assert Wakeup Logic */
5555         gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5556         gpwrdn &= ~GPWRDN_PMUACTV;
5557         dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5558         udelay(10);
5559
5560         hprt0 = hr->hprt0;
5561         hprt0 |= HPRT0_PWR;
5562         hprt0 &= ~HPRT0_ENA;
5563         hprt0 &= ~HPRT0_SUSP;
5564         dwc2_writel(hprt0, hsotg->regs + HPRT0);
5565
5566         hprt0 = hr->hprt0;
5567         hprt0 |= HPRT0_PWR;
5568         hprt0 &= ~HPRT0_ENA;
5569         hprt0 &= ~HPRT0_SUSP;
5570
5571         if (reset) {
5572                 hprt0 |= HPRT0_RST;
5573                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
5574
5575                 /* Wait for Resume time and then program HPRT again */
5576                 mdelay(60);
5577                 hprt0 &= ~HPRT0_RST;
5578                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
5579         } else {
5580                 hprt0 |= HPRT0_RES;
5581                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
5582
5583                 /* Wait for Resume time and then program HPRT again */
5584                 mdelay(100);
5585                 hprt0 &= ~HPRT0_RES;
5586                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
5587         }
5588         /* Clear all interrupt status */
5589         hprt0 = dwc2_readl(hsotg->regs + HPRT0);
5590         hprt0 |= HPRT0_CONNDET;
5591         hprt0 |= HPRT0_ENACHG;
5592         hprt0 &= ~HPRT0_ENA;
5593         dwc2_writel(hprt0, hsotg->regs + HPRT0);
5594
5595         hprt0 = dwc2_readl(hsotg->regs + HPRT0);
5596
5597         /* Clear all pending interupts */
5598         dwc2_writel(0xffffffff, hsotg->regs + GINTSTS);
5599
5600         /* Restore global registers */
5601         ret = dwc2_restore_global_registers(hsotg);
5602         if (ret) {
5603                 dev_err(hsotg->dev, "%s: failed to restore registers\n",
5604                         __func__);
5605                 return ret;
5606         }
5607
5608         /* Restore host registers */
5609         ret = dwc2_restore_host_registers(hsotg);
5610         if (ret) {
5611                 dev_err(hsotg->dev, "%s: failed to restore host registers\n",
5612                         __func__);
5613                 return ret;
5614         }
5615
5616         hsotg->hibernated = 0;
5617         hsotg->bus_suspended = 0;
5618         hsotg->lx_state = DWC2_L0;
5619         dev_dbg(hsotg->dev, "Host hibernation restore complete\n");
5620         return ret;
5621 }