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