Merge branch 'linux-4.18' of git://github.com/skeggsb/linux into drm-fixes
[sfrench/cifs-2.6.git] / drivers / usb / dwc2 / hcd.c
1 // SPDX-License-Identifier: (GPL-2.0+ OR BSD-3-Clause)
2 /*
3  * hcd.c - DesignWare HS OTG Controller host-mode routines
4  *
5  * Copyright (C) 2004-2013 Synopsys, Inc.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions, and the following disclaimer,
12  *    without modification.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The names of the above-listed copyright holders may not be used
17  *    to endorse or promote products derived from this software without
18  *    specific prior written permission.
19  *
20  * ALTERNATIVELY, this software may be distributed under the terms of the
21  * GNU General Public License ("GPL") as published by the Free Software
22  * Foundation; either version 2 of the License, or (at your option) any
23  * later version.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
26  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
27  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37
38 /*
39  * This file contains the core HCD code, and implements the Linux hc_driver
40  * API
41  */
42 #include <linux/kernel.h>
43 #include <linux/module.h>
44 #include <linux/spinlock.h>
45 #include <linux/interrupt.h>
46 #include <linux/platform_device.h>
47 #include <linux/dma-mapping.h>
48 #include <linux/delay.h>
49 #include <linux/io.h>
50 #include <linux/slab.h>
51 #include <linux/usb.h>
52
53 #include <linux/usb/hcd.h>
54 #include <linux/usb/ch11.h>
55
56 #include "core.h"
57 #include "hcd.h"
58
59 static void dwc2_port_resume(struct dwc2_hsotg *hsotg);
60
61 /*
62  * =========================================================================
63  *  Host Core Layer Functions
64  * =========================================================================
65  */
66
67 /**
68  * dwc2_enable_common_interrupts() - Initializes the commmon interrupts,
69  * used in both device and host modes
70  *
71  * @hsotg: Programming view of the DWC_otg controller
72  */
73 static void dwc2_enable_common_interrupts(struct dwc2_hsotg *hsotg)
74 {
75         u32 intmsk;
76
77         /* Clear any pending OTG Interrupts */
78         dwc2_writel(0xffffffff, hsotg->regs + GOTGINT);
79
80         /* Clear any pending interrupts */
81         dwc2_writel(0xffffffff, hsotg->regs + GINTSTS);
82
83         /* Enable the interrupts in the GINTMSK */
84         intmsk = GINTSTS_MODEMIS | GINTSTS_OTGINT;
85
86         if (!hsotg->params.host_dma)
87                 intmsk |= GINTSTS_RXFLVL;
88         if (!hsotg->params.external_id_pin_ctl)
89                 intmsk |= GINTSTS_CONIDSTSCHNG;
90
91         intmsk |= GINTSTS_WKUPINT | GINTSTS_USBSUSP |
92                   GINTSTS_SESSREQINT;
93
94         if (dwc2_is_device_mode(hsotg) && hsotg->params.lpm)
95                 intmsk |= GINTSTS_LPMTRANRCVD;
96
97         dwc2_writel(intmsk, hsotg->regs + GINTMSK);
98 }
99
100 /*
101  * Initializes the FSLSPClkSel field of the HCFG register depending on the
102  * PHY type
103  */
104 static void dwc2_init_fs_ls_pclk_sel(struct dwc2_hsotg *hsotg)
105 {
106         u32 hcfg, val;
107
108         if ((hsotg->hw_params.hs_phy_type == GHWCFG2_HS_PHY_TYPE_ULPI &&
109              hsotg->hw_params.fs_phy_type == GHWCFG2_FS_PHY_TYPE_DEDICATED &&
110              hsotg->params.ulpi_fs_ls) ||
111             hsotg->params.phy_type == DWC2_PHY_TYPE_PARAM_FS) {
112                 /* Full speed PHY */
113                 val = HCFG_FSLSPCLKSEL_48_MHZ;
114         } else {
115                 /* High speed PHY running at full speed or high speed */
116                 val = HCFG_FSLSPCLKSEL_30_60_MHZ;
117         }
118
119         dev_dbg(hsotg->dev, "Initializing HCFG.FSLSPClkSel to %08x\n", val);
120         hcfg = dwc2_readl(hsotg->regs + HCFG);
121         hcfg &= ~HCFG_FSLSPCLKSEL_MASK;
122         hcfg |= val << HCFG_FSLSPCLKSEL_SHIFT;
123         dwc2_writel(hcfg, hsotg->regs + HCFG);
124 }
125
126 static int dwc2_fs_phy_init(struct dwc2_hsotg *hsotg, bool select_phy)
127 {
128         u32 usbcfg, ggpio, i2cctl;
129         int retval = 0;
130
131         /*
132          * core_init() is now called on every switch so only call the
133          * following for the first time through
134          */
135         if (select_phy) {
136                 dev_dbg(hsotg->dev, "FS PHY selected\n");
137
138                 usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
139                 if (!(usbcfg & GUSBCFG_PHYSEL)) {
140                         usbcfg |= GUSBCFG_PHYSEL;
141                         dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
142
143                         /* Reset after a PHY select */
144                         retval = dwc2_core_reset(hsotg, false);
145
146                         if (retval) {
147                                 dev_err(hsotg->dev,
148                                         "%s: Reset failed, aborting", __func__);
149                                 return retval;
150                         }
151                 }
152
153                 if (hsotg->params.activate_stm_fs_transceiver) {
154                         ggpio = dwc2_readl(hsotg->regs + GGPIO);
155                         if (!(ggpio & GGPIO_STM32_OTG_GCCFG_PWRDWN)) {
156                                 dev_dbg(hsotg->dev, "Activating transceiver\n");
157                                 /*
158                                  * STM32F4x9 uses the GGPIO register as general
159                                  * core configuration register.
160                                  */
161                                 ggpio |= GGPIO_STM32_OTG_GCCFG_PWRDWN;
162                                 dwc2_writel(ggpio, hsotg->regs + GGPIO);
163                         }
164                 }
165         }
166
167         /*
168          * Program DCFG.DevSpd or HCFG.FSLSPclkSel to 48Mhz in FS. Also
169          * do this on HNP Dev/Host mode switches (done in dev_init and
170          * host_init).
171          */
172         if (dwc2_is_host_mode(hsotg))
173                 dwc2_init_fs_ls_pclk_sel(hsotg);
174
175         if (hsotg->params.i2c_enable) {
176                 dev_dbg(hsotg->dev, "FS PHY enabling I2C\n");
177
178                 /* Program GUSBCFG.OtgUtmiFsSel to I2C */
179                 usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
180                 usbcfg |= GUSBCFG_OTG_UTMI_FS_SEL;
181                 dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
182
183                 /* Program GI2CCTL.I2CEn */
184                 i2cctl = dwc2_readl(hsotg->regs + GI2CCTL);
185                 i2cctl &= ~GI2CCTL_I2CDEVADDR_MASK;
186                 i2cctl |= 1 << GI2CCTL_I2CDEVADDR_SHIFT;
187                 i2cctl &= ~GI2CCTL_I2CEN;
188                 dwc2_writel(i2cctl, hsotg->regs + GI2CCTL);
189                 i2cctl |= GI2CCTL_I2CEN;
190                 dwc2_writel(i2cctl, hsotg->regs + GI2CCTL);
191         }
192
193         return retval;
194 }
195
196 static int dwc2_hs_phy_init(struct dwc2_hsotg *hsotg, bool select_phy)
197 {
198         u32 usbcfg, usbcfg_old;
199         int retval = 0;
200
201         if (!select_phy)
202                 return 0;
203
204         usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
205         usbcfg_old = usbcfg;
206
207         /*
208          * HS PHY parameters. These parameters are preserved during soft reset
209          * so only program the first time. Do a soft reset immediately after
210          * setting phyif.
211          */
212         switch (hsotg->params.phy_type) {
213         case DWC2_PHY_TYPE_PARAM_ULPI:
214                 /* ULPI interface */
215                 dev_dbg(hsotg->dev, "HS ULPI PHY selected\n");
216                 usbcfg |= GUSBCFG_ULPI_UTMI_SEL;
217                 usbcfg &= ~(GUSBCFG_PHYIF16 | GUSBCFG_DDRSEL);
218                 if (hsotg->params.phy_ulpi_ddr)
219                         usbcfg |= GUSBCFG_DDRSEL;
220
221                 /* Set external VBUS indicator as needed. */
222                 if (hsotg->params.oc_disable)
223                         usbcfg |= (GUSBCFG_ULPI_INT_VBUS_IND |
224                                    GUSBCFG_INDICATORPASSTHROUGH);
225                 break;
226         case DWC2_PHY_TYPE_PARAM_UTMI:
227                 /* UTMI+ interface */
228                 dev_dbg(hsotg->dev, "HS UTMI+ PHY selected\n");
229                 usbcfg &= ~(GUSBCFG_ULPI_UTMI_SEL | GUSBCFG_PHYIF16);
230                 if (hsotg->params.phy_utmi_width == 16)
231                         usbcfg |= GUSBCFG_PHYIF16;
232                 break;
233         default:
234                 dev_err(hsotg->dev, "FS PHY selected at HS!\n");
235                 break;
236         }
237
238         if (usbcfg != usbcfg_old) {
239                 dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
240
241                 /* Reset after setting the PHY parameters */
242                 retval = dwc2_core_reset(hsotg, false);
243                 if (retval) {
244                         dev_err(hsotg->dev,
245                                 "%s: Reset failed, aborting", __func__);
246                         return retval;
247                 }
248         }
249
250         return retval;
251 }
252
253 static int dwc2_phy_init(struct dwc2_hsotg *hsotg, bool select_phy)
254 {
255         u32 usbcfg;
256         int retval = 0;
257
258         if ((hsotg->params.speed == DWC2_SPEED_PARAM_FULL ||
259              hsotg->params.speed == DWC2_SPEED_PARAM_LOW) &&
260             hsotg->params.phy_type == DWC2_PHY_TYPE_PARAM_FS) {
261                 /* If FS/LS mode with FS/LS PHY */
262                 retval = dwc2_fs_phy_init(hsotg, select_phy);
263                 if (retval)
264                         return retval;
265         } else {
266                 /* High speed PHY */
267                 retval = dwc2_hs_phy_init(hsotg, select_phy);
268                 if (retval)
269                         return retval;
270         }
271
272         if (hsotg->hw_params.hs_phy_type == GHWCFG2_HS_PHY_TYPE_ULPI &&
273             hsotg->hw_params.fs_phy_type == GHWCFG2_FS_PHY_TYPE_DEDICATED &&
274             hsotg->params.ulpi_fs_ls) {
275                 dev_dbg(hsotg->dev, "Setting ULPI FSLS\n");
276                 usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
277                 usbcfg |= GUSBCFG_ULPI_FS_LS;
278                 usbcfg |= GUSBCFG_ULPI_CLK_SUSP_M;
279                 dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
280         } else {
281                 usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
282                 usbcfg &= ~GUSBCFG_ULPI_FS_LS;
283                 usbcfg &= ~GUSBCFG_ULPI_CLK_SUSP_M;
284                 dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
285         }
286
287         return retval;
288 }
289
290 static int dwc2_gahbcfg_init(struct dwc2_hsotg *hsotg)
291 {
292         u32 ahbcfg = dwc2_readl(hsotg->regs + GAHBCFG);
293
294         switch (hsotg->hw_params.arch) {
295         case GHWCFG2_EXT_DMA_ARCH:
296                 dev_err(hsotg->dev, "External DMA Mode not supported\n");
297                 return -EINVAL;
298
299         case GHWCFG2_INT_DMA_ARCH:
300                 dev_dbg(hsotg->dev, "Internal DMA Mode\n");
301                 if (hsotg->params.ahbcfg != -1) {
302                         ahbcfg &= GAHBCFG_CTRL_MASK;
303                         ahbcfg |= hsotg->params.ahbcfg &
304                                   ~GAHBCFG_CTRL_MASK;
305                 }
306                 break;
307
308         case GHWCFG2_SLAVE_ONLY_ARCH:
309         default:
310                 dev_dbg(hsotg->dev, "Slave Only Mode\n");
311                 break;
312         }
313
314         if (hsotg->params.host_dma)
315                 ahbcfg |= GAHBCFG_DMA_EN;
316         else
317                 hsotg->params.dma_desc_enable = false;
318
319         dwc2_writel(ahbcfg, hsotg->regs + GAHBCFG);
320
321         return 0;
322 }
323
324 static void dwc2_gusbcfg_init(struct dwc2_hsotg *hsotg)
325 {
326         u32 usbcfg;
327
328         usbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
329         usbcfg &= ~(GUSBCFG_HNPCAP | GUSBCFG_SRPCAP);
330
331         switch (hsotg->hw_params.op_mode) {
332         case GHWCFG2_OP_MODE_HNP_SRP_CAPABLE:
333                 if (hsotg->params.otg_cap ==
334                                 DWC2_CAP_PARAM_HNP_SRP_CAPABLE)
335                         usbcfg |= GUSBCFG_HNPCAP;
336                 if (hsotg->params.otg_cap !=
337                                 DWC2_CAP_PARAM_NO_HNP_SRP_CAPABLE)
338                         usbcfg |= GUSBCFG_SRPCAP;
339                 break;
340
341         case GHWCFG2_OP_MODE_SRP_ONLY_CAPABLE:
342         case GHWCFG2_OP_MODE_SRP_CAPABLE_DEVICE:
343         case GHWCFG2_OP_MODE_SRP_CAPABLE_HOST:
344                 if (hsotg->params.otg_cap !=
345                                 DWC2_CAP_PARAM_NO_HNP_SRP_CAPABLE)
346                         usbcfg |= GUSBCFG_SRPCAP;
347                 break;
348
349         case GHWCFG2_OP_MODE_NO_HNP_SRP_CAPABLE:
350         case GHWCFG2_OP_MODE_NO_SRP_CAPABLE_DEVICE:
351         case GHWCFG2_OP_MODE_NO_SRP_CAPABLE_HOST:
352         default:
353                 break;
354         }
355
356         dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
357 }
358
359 static int dwc2_vbus_supply_init(struct dwc2_hsotg *hsotg)
360 {
361         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(0, hsotg->regs + GINTMSK);
394         dwc2_writel(0, hsotg->regs + 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->regs + GINTMSK);
401         intmsk |= GINTSTS_DISCONNINT | GINTSTS_PRTINT | GINTSTS_HCHINT;
402         dwc2_writel(intmsk, hsotg->regs + 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->regs + 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(intmsk, hsotg->regs + 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->regs + 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(grxfsiz, hsotg->regs + GRXFSIZ);
503         dev_dbg(hsotg->dev, "new grxfsiz=%08x\n",
504                 dwc2_readl(hsotg->regs + GRXFSIZ));
505
506         /* Non-periodic Tx FIFO */
507         dev_dbg(hsotg->dev, "initial gnptxfsiz=%08x\n",
508                 dwc2_readl(hsotg->regs + 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(nptxfsiz, hsotg->regs + GNPTXFSIZ);
514         dev_dbg(hsotg->dev, "new gnptxfsiz=%08x\n",
515                 dwc2_readl(hsotg->regs + GNPTXFSIZ));
516
517         /* Periodic Tx FIFO */
518         dev_dbg(hsotg->dev, "initial hptxfsiz=%08x\n",
519                 dwc2_readl(hsotg->regs + 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(hptxfsiz, hsotg->regs + HPTXFSIZ);
526         dev_dbg(hsotg->dev, "new hptxfsiz=%08x\n",
527                 dwc2_readl(hsotg->regs + 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->regs + 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(dfifocfg, hsotg->regs + 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->regs + GUSBCFG);
564         hprt0 = dwc2_readl(hsotg->regs + 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 __iomem *fifo = hsotg->regs + HCFIFO(0);
607         u32 *data_buf = (u32 *)dest;
608         int word_count = (bytes + 3) / 4;
609         int i;
610
611         /*
612          * Todo: Account for the case where dest is not dword aligned. This
613          * requires reading data from the FIFO into a u32 temp buffer, then
614          * moving it into the data buffer.
615          */
616
617         dev_vdbg(hsotg->dev, "%s(%p,%p,%d)\n", __func__, hsotg, dest, bytes);
618
619         for (i = 0; i < word_count; i++, data_buf++)
620                 *data_buf = dwc2_readl(fifo);
621 }
622
623 /**
624  * dwc2_dump_channel_info() - Prints the state of a host channel
625  *
626  * @hsotg: Programming view of DWC_otg controller
627  * @chan:  Pointer to the channel to dump
628  *
629  * Must be called with interrupt disabled and spinlock held
630  *
631  * NOTE: This function will be removed once the peripheral controller code
632  * is integrated and the driver is stable
633  */
634 static void dwc2_dump_channel_info(struct dwc2_hsotg *hsotg,
635                                    struct dwc2_host_chan *chan)
636 {
637 #ifdef VERBOSE_DEBUG
638         int num_channels = hsotg->params.host_channels;
639         struct dwc2_qh *qh;
640         u32 hcchar;
641         u32 hcsplt;
642         u32 hctsiz;
643         u32 hc_dma;
644         int i;
645
646         if (!chan)
647                 return;
648
649         hcchar = dwc2_readl(hsotg->regs + HCCHAR(chan->hc_num));
650         hcsplt = dwc2_readl(hsotg->regs + HCSPLT(chan->hc_num));
651         hctsiz = dwc2_readl(hsotg->regs + HCTSIZ(chan->hc_num));
652         hc_dma = dwc2_readl(hsotg->regs + HCDMA(chan->hc_num));
653
654         dev_dbg(hsotg->dev, "  Assigned to channel %p:\n", chan);
655         dev_dbg(hsotg->dev, "    hcchar 0x%08x, hcsplt 0x%08x\n",
656                 hcchar, hcsplt);
657         dev_dbg(hsotg->dev, "    hctsiz 0x%08x, hc_dma 0x%08x\n",
658                 hctsiz, hc_dma);
659         dev_dbg(hsotg->dev, "    dev_addr: %d, ep_num: %d, ep_is_in: %d\n",
660                 chan->dev_addr, chan->ep_num, chan->ep_is_in);
661         dev_dbg(hsotg->dev, "    ep_type: %d\n", chan->ep_type);
662         dev_dbg(hsotg->dev, "    max_packet: %d\n", chan->max_packet);
663         dev_dbg(hsotg->dev, "    data_pid_start: %d\n", chan->data_pid_start);
664         dev_dbg(hsotg->dev, "    xfer_started: %d\n", chan->xfer_started);
665         dev_dbg(hsotg->dev, "    halt_status: %d\n", chan->halt_status);
666         dev_dbg(hsotg->dev, "    xfer_buf: %p\n", chan->xfer_buf);
667         dev_dbg(hsotg->dev, "    xfer_dma: %08lx\n",
668                 (unsigned long)chan->xfer_dma);
669         dev_dbg(hsotg->dev, "    xfer_len: %d\n", chan->xfer_len);
670         dev_dbg(hsotg->dev, "    qh: %p\n", chan->qh);
671         dev_dbg(hsotg->dev, "  NP inactive sched:\n");
672         list_for_each_entry(qh, &hsotg->non_periodic_sched_inactive,
673                             qh_list_entry)
674                 dev_dbg(hsotg->dev, "    %p\n", qh);
675         dev_dbg(hsotg->dev, "  NP waiting sched:\n");
676         list_for_each_entry(qh, &hsotg->non_periodic_sched_waiting,
677                             qh_list_entry)
678                 dev_dbg(hsotg->dev, "    %p\n", qh);
679         dev_dbg(hsotg->dev, "  NP active sched:\n");
680         list_for_each_entry(qh, &hsotg->non_periodic_sched_active,
681                             qh_list_entry)
682                 dev_dbg(hsotg->dev, "    %p\n", qh);
683         dev_dbg(hsotg->dev, "  Channels:\n");
684         for (i = 0; i < num_channels; i++) {
685                 struct dwc2_host_chan *chan = hsotg->hc_ptr_array[i];
686
687                 dev_dbg(hsotg->dev, "    %2d: %p\n", i, chan);
688         }
689 #endif /* VERBOSE_DEBUG */
690 }
691
692 static int _dwc2_hcd_start(struct usb_hcd *hcd);
693
694 static void dwc2_host_start(struct dwc2_hsotg *hsotg)
695 {
696         struct usb_hcd *hcd = dwc2_hsotg_to_hcd(hsotg);
697
698         hcd->self.is_b_host = dwc2_hcd_is_b_host(hsotg);
699         _dwc2_hcd_start(hcd);
700 }
701
702 static void dwc2_host_disconnect(struct dwc2_hsotg *hsotg)
703 {
704         struct usb_hcd *hcd = dwc2_hsotg_to_hcd(hsotg);
705
706         hcd->self.is_b_host = 0;
707 }
708
709 static void dwc2_host_hub_info(struct dwc2_hsotg *hsotg, void *context,
710                                int *hub_addr, int *hub_port)
711 {
712         struct urb *urb = context;
713
714         if (urb->dev->tt)
715                 *hub_addr = urb->dev->tt->hub->devnum;
716         else
717                 *hub_addr = 0;
718         *hub_port = urb->dev->ttport;
719 }
720
721 /*
722  * =========================================================================
723  *  Low Level Host Channel Access Functions
724  * =========================================================================
725  */
726
727 static void dwc2_hc_enable_slave_ints(struct dwc2_hsotg *hsotg,
728                                       struct dwc2_host_chan *chan)
729 {
730         u32 hcintmsk = HCINTMSK_CHHLTD;
731
732         switch (chan->ep_type) {
733         case USB_ENDPOINT_XFER_CONTROL:
734         case USB_ENDPOINT_XFER_BULK:
735                 dev_vdbg(hsotg->dev, "control/bulk\n");
736                 hcintmsk |= HCINTMSK_XFERCOMPL;
737                 hcintmsk |= HCINTMSK_STALL;
738                 hcintmsk |= HCINTMSK_XACTERR;
739                 hcintmsk |= HCINTMSK_DATATGLERR;
740                 if (chan->ep_is_in) {
741                         hcintmsk |= HCINTMSK_BBLERR;
742                 } else {
743                         hcintmsk |= HCINTMSK_NAK;
744                         hcintmsk |= HCINTMSK_NYET;
745                         if (chan->do_ping)
746                                 hcintmsk |= HCINTMSK_ACK;
747                 }
748
749                 if (chan->do_split) {
750                         hcintmsk |= HCINTMSK_NAK;
751                         if (chan->complete_split)
752                                 hcintmsk |= HCINTMSK_NYET;
753                         else
754                                 hcintmsk |= HCINTMSK_ACK;
755                 }
756
757                 if (chan->error_state)
758                         hcintmsk |= HCINTMSK_ACK;
759                 break;
760
761         case USB_ENDPOINT_XFER_INT:
762                 if (dbg_perio())
763                         dev_vdbg(hsotg->dev, "intr\n");
764                 hcintmsk |= HCINTMSK_XFERCOMPL;
765                 hcintmsk |= HCINTMSK_NAK;
766                 hcintmsk |= HCINTMSK_STALL;
767                 hcintmsk |= HCINTMSK_XACTERR;
768                 hcintmsk |= HCINTMSK_DATATGLERR;
769                 hcintmsk |= HCINTMSK_FRMOVRUN;
770
771                 if (chan->ep_is_in)
772                         hcintmsk |= HCINTMSK_BBLERR;
773                 if (chan->error_state)
774                         hcintmsk |= HCINTMSK_ACK;
775                 if (chan->do_split) {
776                         if (chan->complete_split)
777                                 hcintmsk |= HCINTMSK_NYET;
778                         else
779                                 hcintmsk |= HCINTMSK_ACK;
780                 }
781                 break;
782
783         case USB_ENDPOINT_XFER_ISOC:
784                 if (dbg_perio())
785                         dev_vdbg(hsotg->dev, "isoc\n");
786                 hcintmsk |= HCINTMSK_XFERCOMPL;
787                 hcintmsk |= HCINTMSK_FRMOVRUN;
788                 hcintmsk |= HCINTMSK_ACK;
789
790                 if (chan->ep_is_in) {
791                         hcintmsk |= HCINTMSK_XACTERR;
792                         hcintmsk |= HCINTMSK_BBLERR;
793                 }
794                 break;
795         default:
796                 dev_err(hsotg->dev, "## Unknown EP type ##\n");
797                 break;
798         }
799
800         dwc2_writel(hcintmsk, hsotg->regs + HCINTMSK(chan->hc_num));
801         if (dbg_hc(chan))
802                 dev_vdbg(hsotg->dev, "set HCINTMSK to %08x\n", hcintmsk);
803 }
804
805 static void dwc2_hc_enable_dma_ints(struct dwc2_hsotg *hsotg,
806                                     struct dwc2_host_chan *chan)
807 {
808         u32 hcintmsk = HCINTMSK_CHHLTD;
809
810         /*
811          * For Descriptor DMA mode core halts the channel on AHB error.
812          * Interrupt is not required.
813          */
814         if (!hsotg->params.dma_desc_enable) {
815                 if (dbg_hc(chan))
816                         dev_vdbg(hsotg->dev, "desc DMA disabled\n");
817                 hcintmsk |= HCINTMSK_AHBERR;
818         } else {
819                 if (dbg_hc(chan))
820                         dev_vdbg(hsotg->dev, "desc DMA enabled\n");
821                 if (chan->ep_type == USB_ENDPOINT_XFER_ISOC)
822                         hcintmsk |= HCINTMSK_XFERCOMPL;
823         }
824
825         if (chan->error_state && !chan->do_split &&
826             chan->ep_type != USB_ENDPOINT_XFER_ISOC) {
827                 if (dbg_hc(chan))
828                         dev_vdbg(hsotg->dev, "setting ACK\n");
829                 hcintmsk |= HCINTMSK_ACK;
830                 if (chan->ep_is_in) {
831                         hcintmsk |= HCINTMSK_DATATGLERR;
832                         if (chan->ep_type != USB_ENDPOINT_XFER_INT)
833                                 hcintmsk |= HCINTMSK_NAK;
834                 }
835         }
836
837         dwc2_writel(hcintmsk, hsotg->regs + HCINTMSK(chan->hc_num));
838         if (dbg_hc(chan))
839                 dev_vdbg(hsotg->dev, "set HCINTMSK to %08x\n", hcintmsk);
840 }
841
842 static void dwc2_hc_enable_ints(struct dwc2_hsotg *hsotg,
843                                 struct dwc2_host_chan *chan)
844 {
845         u32 intmsk;
846
847         if (hsotg->params.host_dma) {
848                 if (dbg_hc(chan))
849                         dev_vdbg(hsotg->dev, "DMA enabled\n");
850                 dwc2_hc_enable_dma_ints(hsotg, chan);
851         } else {
852                 if (dbg_hc(chan))
853                         dev_vdbg(hsotg->dev, "DMA disabled\n");
854                 dwc2_hc_enable_slave_ints(hsotg, chan);
855         }
856
857         /* Enable the top level host channel interrupt */
858         intmsk = dwc2_readl(hsotg->regs + HAINTMSK);
859         intmsk |= 1 << chan->hc_num;
860         dwc2_writel(intmsk, hsotg->regs + HAINTMSK);
861         if (dbg_hc(chan))
862                 dev_vdbg(hsotg->dev, "set HAINTMSK to %08x\n", intmsk);
863
864         /* Make sure host channel interrupts are enabled */
865         intmsk = dwc2_readl(hsotg->regs + GINTMSK);
866         intmsk |= GINTSTS_HCHINT;
867         dwc2_writel(intmsk, hsotg->regs + GINTMSK);
868         if (dbg_hc(chan))
869                 dev_vdbg(hsotg->dev, "set GINTMSK to %08x\n", intmsk);
870 }
871
872 /**
873  * dwc2_hc_init() - Prepares a host channel for transferring packets to/from
874  * a specific endpoint
875  *
876  * @hsotg: Programming view of DWC_otg controller
877  * @chan:  Information needed to initialize the host channel
878  *
879  * The HCCHARn register is set up with the characteristics specified in chan.
880  * Host channel interrupts that may need to be serviced while this transfer is
881  * in progress are enabled.
882  */
883 static void dwc2_hc_init(struct dwc2_hsotg *hsotg, struct dwc2_host_chan *chan)
884 {
885         u8 hc_num = chan->hc_num;
886         u32 hcintmsk;
887         u32 hcchar;
888         u32 hcsplt = 0;
889
890         if (dbg_hc(chan))
891                 dev_vdbg(hsotg->dev, "%s()\n", __func__);
892
893         /* Clear old interrupt conditions for this host channel */
894         hcintmsk = 0xffffffff;
895         hcintmsk &= ~HCINTMSK_RESERVED14_31;
896         dwc2_writel(hcintmsk, hsotg->regs + HCINT(hc_num));
897
898         /* Enable channel interrupts required for this transfer */
899         dwc2_hc_enable_ints(hsotg, chan);
900
901         /*
902          * Program the HCCHARn register with the endpoint characteristics for
903          * the current transfer
904          */
905         hcchar = chan->dev_addr << HCCHAR_DEVADDR_SHIFT & HCCHAR_DEVADDR_MASK;
906         hcchar |= chan->ep_num << HCCHAR_EPNUM_SHIFT & HCCHAR_EPNUM_MASK;
907         if (chan->ep_is_in)
908                 hcchar |= HCCHAR_EPDIR;
909         if (chan->speed == USB_SPEED_LOW)
910                 hcchar |= HCCHAR_LSPDDEV;
911         hcchar |= chan->ep_type << HCCHAR_EPTYPE_SHIFT & HCCHAR_EPTYPE_MASK;
912         hcchar |= chan->max_packet << HCCHAR_MPS_SHIFT & HCCHAR_MPS_MASK;
913         dwc2_writel(hcchar, hsotg->regs + HCCHAR(hc_num));
914         if (dbg_hc(chan)) {
915                 dev_vdbg(hsotg->dev, "set HCCHAR(%d) to %08x\n",
916                          hc_num, hcchar);
917
918                 dev_vdbg(hsotg->dev, "%s: Channel %d\n",
919                          __func__, hc_num);
920                 dev_vdbg(hsotg->dev, "   Dev Addr: %d\n",
921                          chan->dev_addr);
922                 dev_vdbg(hsotg->dev, "   Ep Num: %d\n",
923                          chan->ep_num);
924                 dev_vdbg(hsotg->dev, "   Is In: %d\n",
925                          chan->ep_is_in);
926                 dev_vdbg(hsotg->dev, "   Is Low Speed: %d\n",
927                          chan->speed == USB_SPEED_LOW);
928                 dev_vdbg(hsotg->dev, "   Ep Type: %d\n",
929                          chan->ep_type);
930                 dev_vdbg(hsotg->dev, "   Max Pkt: %d\n",
931                          chan->max_packet);
932         }
933
934         /* Program the HCSPLT register for SPLITs */
935         if (chan->do_split) {
936                 if (dbg_hc(chan))
937                         dev_vdbg(hsotg->dev,
938                                  "Programming HC %d with split --> %s\n",
939                                  hc_num,
940                                  chan->complete_split ? "CSPLIT" : "SSPLIT");
941                 if (chan->complete_split)
942                         hcsplt |= HCSPLT_COMPSPLT;
943                 hcsplt |= chan->xact_pos << HCSPLT_XACTPOS_SHIFT &
944                           HCSPLT_XACTPOS_MASK;
945                 hcsplt |= chan->hub_addr << HCSPLT_HUBADDR_SHIFT &
946                           HCSPLT_HUBADDR_MASK;
947                 hcsplt |= chan->hub_port << HCSPLT_PRTADDR_SHIFT &
948                           HCSPLT_PRTADDR_MASK;
949                 if (dbg_hc(chan)) {
950                         dev_vdbg(hsotg->dev, "    comp split %d\n",
951                                  chan->complete_split);
952                         dev_vdbg(hsotg->dev, "    xact pos %d\n",
953                                  chan->xact_pos);
954                         dev_vdbg(hsotg->dev, "    hub addr %d\n",
955                                  chan->hub_addr);
956                         dev_vdbg(hsotg->dev, "    hub port %d\n",
957                                  chan->hub_port);
958                         dev_vdbg(hsotg->dev, "    is_in %d\n",
959                                  chan->ep_is_in);
960                         dev_vdbg(hsotg->dev, "    Max Pkt %d\n",
961                                  chan->max_packet);
962                         dev_vdbg(hsotg->dev, "    xferlen %d\n",
963                                  chan->xfer_len);
964                 }
965         }
966
967         dwc2_writel(hcsplt, hsotg->regs + HCSPLT(hc_num));
968 }
969
970 /**
971  * dwc2_hc_halt() - Attempts to halt a host channel
972  *
973  * @hsotg:       Controller register interface
974  * @chan:        Host channel to halt
975  * @halt_status: Reason for halting the channel
976  *
977  * This function should only be called in Slave mode or to abort a transfer in
978  * either Slave mode or DMA mode. Under normal circumstances in DMA mode, the
979  * controller halts the channel when the transfer is complete or a condition
980  * occurs that requires application intervention.
981  *
982  * In slave mode, checks for a free request queue entry, then sets the Channel
983  * Enable and Channel Disable bits of the Host Channel Characteristics
984  * register of the specified channel to intiate the halt. If there is no free
985  * request queue entry, sets only the Channel Disable bit of the HCCHARn
986  * register to flush requests for this channel. In the latter case, sets a
987  * flag to indicate that the host channel needs to be halted when a request
988  * queue slot is open.
989  *
990  * In DMA mode, always sets the Channel Enable and Channel Disable bits of the
991  * HCCHARn register. The controller ensures there is space in the request
992  * queue before submitting the halt request.
993  *
994  * Some time may elapse before the core flushes any posted requests for this
995  * host channel and halts. The Channel Halted interrupt handler completes the
996  * deactivation of the host channel.
997  */
998 void dwc2_hc_halt(struct dwc2_hsotg *hsotg, struct dwc2_host_chan *chan,
999                   enum dwc2_halt_status halt_status)
1000 {
1001         u32 nptxsts, hptxsts, hcchar;
1002
1003         if (dbg_hc(chan))
1004                 dev_vdbg(hsotg->dev, "%s()\n", __func__);
1005
1006         /*
1007          * In buffer DMA or external DMA mode channel can't be halted
1008          * for non-split periodic channels. At the end of the next
1009          * uframe/frame (in the worst case), the core generates a channel
1010          * halted and disables the channel automatically.
1011          */
1012         if ((hsotg->params.g_dma && !hsotg->params.g_dma_desc) ||
1013             hsotg->hw_params.arch == GHWCFG2_EXT_DMA_ARCH) {
1014                 if (!chan->do_split &&
1015                     (chan->ep_type == USB_ENDPOINT_XFER_ISOC ||
1016                      chan->ep_type == USB_ENDPOINT_XFER_INT)) {
1017                         dev_err(hsotg->dev, "%s() Channel can't be halted\n",
1018                                 __func__);
1019                         return;
1020                 }
1021         }
1022
1023         if (halt_status == DWC2_HC_XFER_NO_HALT_STATUS)
1024                 dev_err(hsotg->dev, "!!! halt_status = %d !!!\n", halt_status);
1025
1026         if (halt_status == DWC2_HC_XFER_URB_DEQUEUE ||
1027             halt_status == DWC2_HC_XFER_AHB_ERR) {
1028                 /*
1029                  * Disable all channel interrupts except Ch Halted. The QTD
1030                  * and QH state associated with this transfer has been cleared
1031                  * (in the case of URB_DEQUEUE), so the channel needs to be
1032                  * shut down carefully to prevent crashes.
1033                  */
1034                 u32 hcintmsk = HCINTMSK_CHHLTD;
1035
1036                 dev_vdbg(hsotg->dev, "dequeue/error\n");
1037                 dwc2_writel(hcintmsk, hsotg->regs + HCINTMSK(chan->hc_num));
1038
1039                 /*
1040                  * Make sure no other interrupts besides halt are currently
1041                  * pending. Handling another interrupt could cause a crash due
1042                  * to the QTD and QH state.
1043                  */
1044                 dwc2_writel(~hcintmsk, hsotg->regs + HCINT(chan->hc_num));
1045
1046                 /*
1047                  * Make sure the halt status is set to URB_DEQUEUE or AHB_ERR
1048                  * even if the channel was already halted for some other
1049                  * reason
1050                  */
1051                 chan->halt_status = halt_status;
1052
1053                 hcchar = dwc2_readl(hsotg->regs + HCCHAR(chan->hc_num));
1054                 if (!(hcchar & HCCHAR_CHENA)) {
1055                         /*
1056                          * The channel is either already halted or it hasn't
1057                          * started yet. In DMA mode, the transfer may halt if
1058                          * it finishes normally or a condition occurs that
1059                          * requires driver intervention. Don't want to halt
1060                          * the channel again. In either Slave or DMA mode,
1061                          * it's possible that the transfer has been assigned
1062                          * to a channel, but not started yet when an URB is
1063                          * dequeued. Don't want to halt a channel that hasn't
1064                          * started yet.
1065                          */
1066                         return;
1067                 }
1068         }
1069         if (chan->halt_pending) {
1070                 /*
1071                  * A halt has already been issued for this channel. This might
1072                  * happen when a transfer is aborted by a higher level in
1073                  * the stack.
1074                  */
1075                 dev_vdbg(hsotg->dev,
1076                          "*** %s: Channel %d, chan->halt_pending already set ***\n",
1077                          __func__, chan->hc_num);
1078                 return;
1079         }
1080
1081         hcchar = dwc2_readl(hsotg->regs + HCCHAR(chan->hc_num));
1082
1083         /* No need to set the bit in DDMA for disabling the channel */
1084         /* TODO check it everywhere channel is disabled */
1085         if (!hsotg->params.dma_desc_enable) {
1086                 if (dbg_hc(chan))
1087                         dev_vdbg(hsotg->dev, "desc DMA disabled\n");
1088                 hcchar |= HCCHAR_CHENA;
1089         } else {
1090                 if (dbg_hc(chan))
1091                         dev_dbg(hsotg->dev, "desc DMA enabled\n");
1092         }
1093         hcchar |= HCCHAR_CHDIS;
1094
1095         if (!hsotg->params.host_dma) {
1096                 if (dbg_hc(chan))
1097                         dev_vdbg(hsotg->dev, "DMA not enabled\n");
1098                 hcchar |= HCCHAR_CHENA;
1099
1100                 /* Check for space in the request queue to issue the halt */
1101                 if (chan->ep_type == USB_ENDPOINT_XFER_CONTROL ||
1102                     chan->ep_type == USB_ENDPOINT_XFER_BULK) {
1103                         dev_vdbg(hsotg->dev, "control/bulk\n");
1104                         nptxsts = dwc2_readl(hsotg->regs + GNPTXSTS);
1105                         if ((nptxsts & TXSTS_QSPCAVAIL_MASK) == 0) {
1106                                 dev_vdbg(hsotg->dev, "Disabling channel\n");
1107                                 hcchar &= ~HCCHAR_CHENA;
1108                         }
1109                 } else {
1110                         if (dbg_perio())
1111                                 dev_vdbg(hsotg->dev, "isoc/intr\n");
1112                         hptxsts = dwc2_readl(hsotg->regs + HPTXSTS);
1113                         if ((hptxsts & TXSTS_QSPCAVAIL_MASK) == 0 ||
1114                             hsotg->queuing_high_bandwidth) {
1115                                 if (dbg_perio())
1116                                         dev_vdbg(hsotg->dev, "Disabling channel\n");
1117                                 hcchar &= ~HCCHAR_CHENA;
1118                         }
1119                 }
1120         } else {
1121                 if (dbg_hc(chan))
1122                         dev_vdbg(hsotg->dev, "DMA enabled\n");
1123         }
1124
1125         dwc2_writel(hcchar, hsotg->regs + HCCHAR(chan->hc_num));
1126         chan->halt_status = halt_status;
1127
1128         if (hcchar & HCCHAR_CHENA) {
1129                 if (dbg_hc(chan))
1130                         dev_vdbg(hsotg->dev, "Channel enabled\n");
1131                 chan->halt_pending = 1;
1132                 chan->halt_on_queue = 0;
1133         } else {
1134                 if (dbg_hc(chan))
1135                         dev_vdbg(hsotg->dev, "Channel disabled\n");
1136                 chan->halt_on_queue = 1;
1137         }
1138
1139         if (dbg_hc(chan)) {
1140                 dev_vdbg(hsotg->dev, "%s: Channel %d\n", __func__,
1141                          chan->hc_num);
1142                 dev_vdbg(hsotg->dev, "   hcchar: 0x%08x\n",
1143                          hcchar);
1144                 dev_vdbg(hsotg->dev, "   halt_pending: %d\n",
1145                          chan->halt_pending);
1146                 dev_vdbg(hsotg->dev, "   halt_on_queue: %d\n",
1147                          chan->halt_on_queue);
1148                 dev_vdbg(hsotg->dev, "   halt_status: %d\n",
1149                          chan->halt_status);
1150         }
1151 }
1152
1153 /**
1154  * dwc2_hc_cleanup() - Clears the transfer state for a host channel
1155  *
1156  * @hsotg: Programming view of DWC_otg controller
1157  * @chan:  Identifies the host channel to clean up
1158  *
1159  * This function is normally called after a transfer is done and the host
1160  * channel is being released
1161  */
1162 void dwc2_hc_cleanup(struct dwc2_hsotg *hsotg, struct dwc2_host_chan *chan)
1163 {
1164         u32 hcintmsk;
1165
1166         chan->xfer_started = 0;
1167
1168         list_del_init(&chan->split_order_list_entry);
1169
1170         /*
1171          * Clear channel interrupt enables and any unhandled channel interrupt
1172          * conditions
1173          */
1174         dwc2_writel(0, hsotg->regs + HCINTMSK(chan->hc_num));
1175         hcintmsk = 0xffffffff;
1176         hcintmsk &= ~HCINTMSK_RESERVED14_31;
1177         dwc2_writel(hcintmsk, hsotg->regs + HCINT(chan->hc_num));
1178 }
1179
1180 /**
1181  * dwc2_hc_set_even_odd_frame() - Sets the channel property that indicates in
1182  * which frame a periodic transfer should occur
1183  *
1184  * @hsotg:  Programming view of DWC_otg controller
1185  * @chan:   Identifies the host channel to set up and its properties
1186  * @hcchar: Current value of the HCCHAR register for the specified host channel
1187  *
1188  * This function has no effect on non-periodic transfers
1189  */
1190 static void dwc2_hc_set_even_odd_frame(struct dwc2_hsotg *hsotg,
1191                                        struct dwc2_host_chan *chan, u32 *hcchar)
1192 {
1193         if (chan->ep_type == USB_ENDPOINT_XFER_INT ||
1194             chan->ep_type == USB_ENDPOINT_XFER_ISOC) {
1195                 int host_speed;
1196                 int xfer_ns;
1197                 int xfer_us;
1198                 int bytes_in_fifo;
1199                 u16 fifo_space;
1200                 u16 frame_number;
1201                 u16 wire_frame;
1202
1203                 /*
1204                  * Try to figure out if we're an even or odd frame. If we set
1205                  * even and the current frame number is even the the transfer
1206                  * will happen immediately.  Similar if both are odd. If one is
1207                  * even and the other is odd then the transfer will happen when
1208                  * the frame number ticks.
1209                  *
1210                  * There's a bit of a balancing act to get this right.
1211                  * Sometimes we may want to send data in the current frame (AK
1212                  * right away).  We might want to do this if the frame number
1213                  * _just_ ticked, but we might also want to do this in order
1214                  * to continue a split transaction that happened late in a
1215                  * microframe (so we didn't know to queue the next transfer
1216                  * until the frame number had ticked).  The problem is that we
1217                  * need a lot of knowledge to know if there's actually still
1218                  * time to send things or if it would be better to wait until
1219                  * the next frame.
1220                  *
1221                  * We can look at how much time is left in the current frame
1222                  * and make a guess about whether we'll have time to transfer.
1223                  * We'll do that.
1224                  */
1225
1226                 /* Get speed host is running at */
1227                 host_speed = (chan->speed != USB_SPEED_HIGH &&
1228                               !chan->do_split) ? chan->speed : USB_SPEED_HIGH;
1229
1230                 /* See how many bytes are in the periodic FIFO right now */
1231                 fifo_space = (dwc2_readl(hsotg->regs + HPTXSTS) &
1232                               TXSTS_FSPCAVAIL_MASK) >> TXSTS_FSPCAVAIL_SHIFT;
1233                 bytes_in_fifo = sizeof(u32) *
1234                                 (hsotg->params.host_perio_tx_fifo_size -
1235                                  fifo_space);
1236
1237                 /*
1238                  * Roughly estimate bus time for everything in the periodic
1239                  * queue + our new transfer.  This is "rough" because we're
1240                  * using a function that makes takes into account IN/OUT
1241                  * and INT/ISO and we're just slamming in one value for all
1242                  * transfers.  This should be an over-estimate and that should
1243                  * be OK, but we can probably tighten it.
1244                  */
1245                 xfer_ns = usb_calc_bus_time(host_speed, false, false,
1246                                             chan->xfer_len + bytes_in_fifo);
1247                 xfer_us = NS_TO_US(xfer_ns);
1248
1249                 /* See what frame number we'll be at by the time we finish */
1250                 frame_number = dwc2_hcd_get_future_frame_number(hsotg, xfer_us);
1251
1252                 /* This is when we were scheduled to be on the wire */
1253                 wire_frame = dwc2_frame_num_inc(chan->qh->next_active_frame, 1);
1254
1255                 /*
1256                  * If we'd finish _after_ the frame we're scheduled in then
1257                  * it's hopeless.  Just schedule right away and hope for the
1258                  * best.  Note that it _might_ be wise to call back into the
1259                  * scheduler to pick a better frame, but this is better than
1260                  * nothing.
1261                  */
1262                 if (dwc2_frame_num_gt(frame_number, wire_frame)) {
1263                         dwc2_sch_vdbg(hsotg,
1264                                       "QH=%p EO MISS fr=%04x=>%04x (%+d)\n",
1265                                       chan->qh, wire_frame, frame_number,
1266                                       dwc2_frame_num_dec(frame_number,
1267                                                          wire_frame));
1268                         wire_frame = frame_number;
1269
1270                         /*
1271                          * We picked a different frame number; communicate this
1272                          * back to the scheduler so it doesn't try to schedule
1273                          * another in the same frame.
1274                          *
1275                          * Remember that next_active_frame is 1 before the wire
1276                          * frame.
1277                          */
1278                         chan->qh->next_active_frame =
1279                                 dwc2_frame_num_dec(frame_number, 1);
1280                 }
1281
1282                 if (wire_frame & 1)
1283                         *hcchar |= HCCHAR_ODDFRM;
1284                 else
1285                         *hcchar &= ~HCCHAR_ODDFRM;
1286         }
1287 }
1288
1289 static void dwc2_set_pid_isoc(struct dwc2_host_chan *chan)
1290 {
1291         /* Set up the initial PID for the transfer */
1292         if (chan->speed == USB_SPEED_HIGH) {
1293                 if (chan->ep_is_in) {
1294                         if (chan->multi_count == 1)
1295                                 chan->data_pid_start = DWC2_HC_PID_DATA0;
1296                         else if (chan->multi_count == 2)
1297                                 chan->data_pid_start = DWC2_HC_PID_DATA1;
1298                         else
1299                                 chan->data_pid_start = DWC2_HC_PID_DATA2;
1300                 } else {
1301                         if (chan->multi_count == 1)
1302                                 chan->data_pid_start = DWC2_HC_PID_DATA0;
1303                         else
1304                                 chan->data_pid_start = DWC2_HC_PID_MDATA;
1305                 }
1306         } else {
1307                 chan->data_pid_start = DWC2_HC_PID_DATA0;
1308         }
1309 }
1310
1311 /**
1312  * dwc2_hc_write_packet() - Writes a packet into the Tx FIFO associated with
1313  * the Host Channel
1314  *
1315  * @hsotg: Programming view of DWC_otg controller
1316  * @chan:  Information needed to initialize the host channel
1317  *
1318  * This function should only be called in Slave mode. For a channel associated
1319  * with a non-periodic EP, the non-periodic Tx FIFO is written. For a channel
1320  * associated with a periodic EP, the periodic Tx FIFO is written.
1321  *
1322  * Upon return the xfer_buf and xfer_count fields in chan are incremented by
1323  * the number of bytes written to the Tx FIFO.
1324  */
1325 static void dwc2_hc_write_packet(struct dwc2_hsotg *hsotg,
1326                                  struct dwc2_host_chan *chan)
1327 {
1328         u32 i;
1329         u32 remaining_count;
1330         u32 byte_count;
1331         u32 dword_count;
1332         u32 __iomem *data_fifo;
1333         u32 *data_buf = (u32 *)chan->xfer_buf;
1334
1335         if (dbg_hc(chan))
1336                 dev_vdbg(hsotg->dev, "%s()\n", __func__);
1337
1338         data_fifo = (u32 __iomem *)(hsotg->regs + HCFIFO(chan->hc_num));
1339
1340         remaining_count = chan->xfer_len - chan->xfer_count;
1341         if (remaining_count > chan->max_packet)
1342                 byte_count = chan->max_packet;
1343         else
1344                 byte_count = remaining_count;
1345
1346         dword_count = (byte_count + 3) / 4;
1347
1348         if (((unsigned long)data_buf & 0x3) == 0) {
1349                 /* xfer_buf is DWORD aligned */
1350                 for (i = 0; i < dword_count; i++, data_buf++)
1351                         dwc2_writel(*data_buf, data_fifo);
1352         } else {
1353                 /* xfer_buf is not DWORD aligned */
1354                 for (i = 0; i < dword_count; i++, data_buf++) {
1355                         u32 data = data_buf[0] | data_buf[1] << 8 |
1356                                    data_buf[2] << 16 | data_buf[3] << 24;
1357                         dwc2_writel(data, data_fifo);
1358                 }
1359         }
1360
1361         chan->xfer_count += byte_count;
1362         chan->xfer_buf += byte_count;
1363 }
1364
1365 /**
1366  * dwc2_hc_do_ping() - Starts a PING transfer
1367  *
1368  * @hsotg: Programming view of DWC_otg controller
1369  * @chan:  Information needed to initialize the host channel
1370  *
1371  * This function should only be called in Slave mode. The Do Ping bit is set in
1372  * the HCTSIZ register, then the channel is enabled.
1373  */
1374 static void dwc2_hc_do_ping(struct dwc2_hsotg *hsotg,
1375                             struct dwc2_host_chan *chan)
1376 {
1377         u32 hcchar;
1378         u32 hctsiz;
1379
1380         if (dbg_hc(chan))
1381                 dev_vdbg(hsotg->dev, "%s: Channel %d\n", __func__,
1382                          chan->hc_num);
1383
1384         hctsiz = TSIZ_DOPNG;
1385         hctsiz |= 1 << TSIZ_PKTCNT_SHIFT;
1386         dwc2_writel(hctsiz, hsotg->regs + HCTSIZ(chan->hc_num));
1387
1388         hcchar = dwc2_readl(hsotg->regs + HCCHAR(chan->hc_num));
1389         hcchar |= HCCHAR_CHENA;
1390         hcchar &= ~HCCHAR_CHDIS;
1391         dwc2_writel(hcchar, hsotg->regs + HCCHAR(chan->hc_num));
1392 }
1393
1394 /**
1395  * dwc2_hc_start_transfer() - Does the setup for a data transfer for a host
1396  * channel and starts the transfer
1397  *
1398  * @hsotg: Programming view of DWC_otg controller
1399  * @chan:  Information needed to initialize the host channel. The xfer_len value
1400  *         may be reduced to accommodate the max widths of the XferSize and
1401  *         PktCnt fields in the HCTSIZn register. The multi_count value may be
1402  *         changed to reflect the final xfer_len value.
1403  *
1404  * This function may be called in either Slave mode or DMA mode. In Slave mode,
1405  * the caller must ensure that there is sufficient space in the request queue
1406  * and Tx Data FIFO.
1407  *
1408  * For an OUT transfer in Slave mode, it loads a data packet into the
1409  * appropriate FIFO. If necessary, additional data packets are loaded in the
1410  * Host ISR.
1411  *
1412  * For an IN transfer in Slave mode, a data packet is requested. The data
1413  * packets are unloaded from the Rx FIFO in the Host ISR. If necessary,
1414  * additional data packets are requested in the Host ISR.
1415  *
1416  * For a PING transfer in Slave mode, the Do Ping bit is set in the HCTSIZ
1417  * register along with a packet count of 1 and the channel is enabled. This
1418  * causes a single PING transaction to occur. Other fields in HCTSIZ are
1419  * simply set to 0 since no data transfer occurs in this case.
1420  *
1421  * For a PING transfer in DMA mode, the HCTSIZ register is initialized with
1422  * all the information required to perform the subsequent data transfer. In
1423  * addition, the Do Ping bit is set in the HCTSIZ register. In this case, the
1424  * controller performs the entire PING protocol, then starts the data
1425  * transfer.
1426  */
1427 static void dwc2_hc_start_transfer(struct dwc2_hsotg *hsotg,
1428                                    struct dwc2_host_chan *chan)
1429 {
1430         u32 max_hc_xfer_size = hsotg->params.max_transfer_size;
1431         u16 max_hc_pkt_count = hsotg->params.max_packet_count;
1432         u32 hcchar;
1433         u32 hctsiz = 0;
1434         u16 num_packets;
1435         u32 ec_mc;
1436
1437         if (dbg_hc(chan))
1438                 dev_vdbg(hsotg->dev, "%s()\n", __func__);
1439
1440         if (chan->do_ping) {
1441                 if (!hsotg->params.host_dma) {
1442                         if (dbg_hc(chan))
1443                                 dev_vdbg(hsotg->dev, "ping, no DMA\n");
1444                         dwc2_hc_do_ping(hsotg, chan);
1445                         chan->xfer_started = 1;
1446                         return;
1447                 }
1448
1449                 if (dbg_hc(chan))
1450                         dev_vdbg(hsotg->dev, "ping, DMA\n");
1451
1452                 hctsiz |= TSIZ_DOPNG;
1453         }
1454
1455         if (chan->do_split) {
1456                 if (dbg_hc(chan))
1457                         dev_vdbg(hsotg->dev, "split\n");
1458                 num_packets = 1;
1459
1460                 if (chan->complete_split && !chan->ep_is_in)
1461                         /*
1462                          * For CSPLIT OUT Transfer, set the size to 0 so the
1463                          * core doesn't expect any data written to the FIFO
1464                          */
1465                         chan->xfer_len = 0;
1466                 else if (chan->ep_is_in || chan->xfer_len > chan->max_packet)
1467                         chan->xfer_len = chan->max_packet;
1468                 else if (!chan->ep_is_in && chan->xfer_len > 188)
1469                         chan->xfer_len = 188;
1470
1471                 hctsiz |= chan->xfer_len << TSIZ_XFERSIZE_SHIFT &
1472                           TSIZ_XFERSIZE_MASK;
1473
1474                 /* For split set ec_mc for immediate retries */
1475                 if (chan->ep_type == USB_ENDPOINT_XFER_INT ||
1476                     chan->ep_type == USB_ENDPOINT_XFER_ISOC)
1477                         ec_mc = 3;
1478                 else
1479                         ec_mc = 1;
1480         } else {
1481                 if (dbg_hc(chan))
1482                         dev_vdbg(hsotg->dev, "no split\n");
1483                 /*
1484                  * Ensure that the transfer length and packet count will fit
1485                  * in the widths allocated for them in the HCTSIZn register
1486                  */
1487                 if (chan->ep_type == USB_ENDPOINT_XFER_INT ||
1488                     chan->ep_type == USB_ENDPOINT_XFER_ISOC) {
1489                         /*
1490                          * Make sure the transfer size is no larger than one
1491                          * (micro)frame's worth of data. (A check was done
1492                          * when the periodic transfer was accepted to ensure
1493                          * that a (micro)frame's worth of data can be
1494                          * programmed into a channel.)
1495                          */
1496                         u32 max_periodic_len =
1497                                 chan->multi_count * chan->max_packet;
1498
1499                         if (chan->xfer_len > max_periodic_len)
1500                                 chan->xfer_len = max_periodic_len;
1501                 } else if (chan->xfer_len > max_hc_xfer_size) {
1502                         /*
1503                          * Make sure that xfer_len is a multiple of max packet
1504                          * size
1505                          */
1506                         chan->xfer_len =
1507                                 max_hc_xfer_size - chan->max_packet + 1;
1508                 }
1509
1510                 if (chan->xfer_len > 0) {
1511                         num_packets = (chan->xfer_len + chan->max_packet - 1) /
1512                                         chan->max_packet;
1513                         if (num_packets > max_hc_pkt_count) {
1514                                 num_packets = max_hc_pkt_count;
1515                                 chan->xfer_len = num_packets * chan->max_packet;
1516                         }
1517                 } else {
1518                         /* Need 1 packet for transfer length of 0 */
1519                         num_packets = 1;
1520                 }
1521
1522                 if (chan->ep_is_in)
1523                         /*
1524                          * Always program an integral # of max packets for IN
1525                          * transfers
1526                          */
1527                         chan->xfer_len = num_packets * chan->max_packet;
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(hctsiz, hsotg->regs + 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((u32)dma_addr, hsotg->regs + 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->regs + HCSPLT(chan->hc_num));
1589
1590                 hcsplt |= HCSPLT_SPLTENA;
1591                 dwc2_writel(hcsplt, hsotg->regs + HCSPLT(chan->hc_num));
1592         }
1593
1594         hcchar = dwc2_readl(hsotg->regs + 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(hcchar, hsotg->regs + 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(hctsiz, hsotg->regs + 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(chan->desc_list_addr, hsotg->regs + 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->regs + 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(hcchar, hsotg->regs + 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->regs + 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(hcchar, hsotg->regs + 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->regs +
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(hprt0, hsotg->regs + 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->regs + HCCHAR(i));
1912                         if (hcchar & HCCHAR_CHENA) {
1913                                 hcchar &= ~(HCCHAR_CHENA | HCCHAR_EPDIR);
1914                                 hcchar |= HCCHAR_CHDIS;
1915                                 dwc2_writel(hcchar, hsotg->regs + 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->regs + HCCHAR(i));
1925                 if (hcchar & HCCHAR_CHENA) {
1926                         /* Halt the channel */
1927                         hcchar |= HCCHAR_CHDIS;
1928                         dwc2_writel(hcchar, hsotg->regs + 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->regs + GINTMSK);
1989         intr &= ~(GINTSTS_NPTXFEMP | GINTSTS_PTXFEMP | GINTSTS_HCHINT);
1990         dwc2_writel(intr, hsotg->regs + GINTMSK);
1991         intr = GINTSTS_NPTXFEMP | GINTSTS_PTXFEMP | GINTSTS_HCHINT;
1992         dwc2_writel(intr, hsotg->regs + 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(0, hsotg->regs + 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->regs + 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(0, hsotg->regs + 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->regs + 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->regs + 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->regs + 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(usbcfg, hsotg->regs + 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->regs + GOTGCTL);
2329         otgctl &= ~GOTGCTL_OTGVER;
2330         dwc2_writel(otgctl, hsotg->regs + 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->regs + GUSBCFG);
2378         usbcfg |= GUSBCFG_TOUTCAL(7);
2379         dwc2_writel(usbcfg, hsotg->regs + GUSBCFG);
2380
2381         /* Restart the Phy Clock */
2382         dwc2_writel(0, hsotg->regs + 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->regs + HCFG);
2389                 hcfg |= HCFG_FSLSSUPP;
2390                 dwc2_writel(hcfg, hsotg->regs + 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->regs + HFIR);
2400                 hfir |= HFIR_RLDCTRL;
2401                 dwc2_writel(hfir, hsotg->regs + 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->regs + HCFG);
2419                         hcfg |= HCFG_DESCDMA;
2420                         dwc2_writel(hcfg, hsotg->regs + 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->regs + GOTGCTL);
2430         otgctl &= ~GOTGCTL_HSTSETHNPEN;
2431         dwc2_writel(otgctl, hsotg->regs + 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->regs + GOTGCTL);
2439         otgctl &= ~GOTGCTL_HSTSETHNPEN;
2440         dwc2_writel(otgctl, hsotg->regs + 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->regs + HCCHAR(i));
2450                         hcchar &= ~HCCHAR_CHENA;
2451                         hcchar |= HCCHAR_CHDIS;
2452                         hcchar &= ~HCCHAR_EPDIR;
2453                         dwc2_writel(hcchar, hsotg->regs + 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->regs + HCCHAR(i));
2459                         hcchar |= HCCHAR_CHENA | HCCHAR_CHDIS;
2460                         hcchar &= ~HCCHAR_EPDIR;
2461                         dwc2_writel(hcchar, hsotg->regs + 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(hprt0, hsotg->regs + 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 struct dma_aligned_buffer {
2669         void *kmalloc_ptr;
2670         void *old_xfer_buffer;
2671         u8 data[0];
2672 };
2673
2674 static void dwc2_free_dma_aligned_buffer(struct urb *urb)
2675 {
2676         struct dma_aligned_buffer *temp;
2677
2678         if (!(urb->transfer_flags & URB_ALIGNED_TEMP_BUFFER))
2679                 return;
2680
2681         temp = container_of(urb->transfer_buffer,
2682                             struct dma_aligned_buffer, data);
2683
2684         if (usb_urb_dir_in(urb))
2685                 memcpy(temp->old_xfer_buffer, temp->data,
2686                        urb->transfer_buffer_length);
2687         urb->transfer_buffer = temp->old_xfer_buffer;
2688         kfree(temp->kmalloc_ptr);
2689
2690         urb->transfer_flags &= ~URB_ALIGNED_TEMP_BUFFER;
2691 }
2692
2693 static int dwc2_alloc_dma_aligned_buffer(struct urb *urb, gfp_t mem_flags)
2694 {
2695         struct dma_aligned_buffer *temp, *kmalloc_ptr;
2696         size_t kmalloc_size;
2697
2698         if (urb->num_sgs || urb->sg ||
2699             urb->transfer_buffer_length == 0 ||
2700             !((uintptr_t)urb->transfer_buffer & (DWC2_USB_DMA_ALIGN - 1)))
2701                 return 0;
2702
2703         /* Allocate a buffer with enough padding for alignment */
2704         kmalloc_size = urb->transfer_buffer_length +
2705                 sizeof(struct dma_aligned_buffer) + DWC2_USB_DMA_ALIGN - 1;
2706
2707         kmalloc_ptr = kmalloc(kmalloc_size, mem_flags);
2708         if (!kmalloc_ptr)
2709                 return -ENOMEM;
2710
2711         /* Position our struct dma_aligned_buffer such that data is aligned */
2712         temp = PTR_ALIGN(kmalloc_ptr + 1, DWC2_USB_DMA_ALIGN) - 1;
2713         temp->kmalloc_ptr = kmalloc_ptr;
2714         temp->old_xfer_buffer = urb->transfer_buffer;
2715         if (usb_urb_dir_out(urb))
2716                 memcpy(temp->data, urb->transfer_buffer,
2717                        urb->transfer_buffer_length);
2718         urb->transfer_buffer = temp->data;
2719
2720         urb->transfer_flags |= URB_ALIGNED_TEMP_BUFFER;
2721
2722         return 0;
2723 }
2724
2725 static int dwc2_map_urb_for_dma(struct usb_hcd *hcd, struct urb *urb,
2726                                 gfp_t mem_flags)
2727 {
2728         int ret;
2729
2730         /* We assume setup_dma is always aligned; warn if not */
2731         WARN_ON_ONCE(urb->setup_dma &&
2732                      (urb->setup_dma & (DWC2_USB_DMA_ALIGN - 1)));
2733
2734         ret = dwc2_alloc_dma_aligned_buffer(urb, mem_flags);
2735         if (ret)
2736                 return ret;
2737
2738         ret = usb_hcd_map_urb_for_dma(hcd, urb, mem_flags);
2739         if (ret)
2740                 dwc2_free_dma_aligned_buffer(urb);
2741
2742         return ret;
2743 }
2744
2745 static void dwc2_unmap_urb_for_dma(struct usb_hcd *hcd, struct urb *urb)
2746 {
2747         usb_hcd_unmap_urb_for_dma(hcd, urb);
2748         dwc2_free_dma_aligned_buffer(urb);
2749 }
2750
2751 /**
2752  * dwc2_assign_and_init_hc() - Assigns transactions from a QTD to a free host
2753  * channel and initializes the host channel to perform the transactions. The
2754  * host channel is removed from the free list.
2755  *
2756  * @hsotg: The HCD state structure
2757  * @qh:    Transactions from the first QTD for this QH are selected and assigned
2758  *         to a free host channel
2759  */
2760 static int dwc2_assign_and_init_hc(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh)
2761 {
2762         struct dwc2_host_chan *chan;
2763         struct dwc2_hcd_urb *urb;
2764         struct dwc2_qtd *qtd;
2765
2766         if (dbg_qh(qh))
2767                 dev_vdbg(hsotg->dev, "%s(%p,%p)\n", __func__, hsotg, qh);
2768
2769         if (list_empty(&qh->qtd_list)) {
2770                 dev_dbg(hsotg->dev, "No QTDs in QH list\n");
2771                 return -ENOMEM;
2772         }
2773
2774         if (list_empty(&hsotg->free_hc_list)) {
2775                 dev_dbg(hsotg->dev, "No free channel to assign\n");
2776                 return -ENOMEM;
2777         }
2778
2779         chan = list_first_entry(&hsotg->free_hc_list, struct dwc2_host_chan,
2780                                 hc_list_entry);
2781
2782         /* Remove host channel from free list */
2783         list_del_init(&chan->hc_list_entry);
2784
2785         qtd = list_first_entry(&qh->qtd_list, struct dwc2_qtd, qtd_list_entry);
2786         urb = qtd->urb;
2787         qh->channel = chan;
2788         qtd->in_process = 1;
2789
2790         /*
2791          * Use usb_pipedevice to determine device address. This address is
2792          * 0 before the SET_ADDRESS command and the correct address afterward.
2793          */
2794         chan->dev_addr = dwc2_hcd_get_dev_addr(&urb->pipe_info);
2795         chan->ep_num = dwc2_hcd_get_ep_num(&urb->pipe_info);
2796         chan->speed = qh->dev_speed;
2797         chan->max_packet = dwc2_max_packet(qh->maxp);
2798
2799         chan->xfer_started = 0;
2800         chan->halt_status = DWC2_HC_XFER_NO_HALT_STATUS;
2801         chan->error_state = (qtd->error_count > 0);
2802         chan->halt_on_queue = 0;
2803         chan->halt_pending = 0;
2804         chan->requests = 0;
2805
2806         /*
2807          * The following values may be modified in the transfer type section
2808          * below. The xfer_len value may be reduced when the transfer is
2809          * started to accommodate the max widths of the XferSize and PktCnt
2810          * fields in the HCTSIZn register.
2811          */
2812
2813         chan->ep_is_in = (dwc2_hcd_is_pipe_in(&urb->pipe_info) != 0);
2814         if (chan->ep_is_in)
2815                 chan->do_ping = 0;
2816         else
2817                 chan->do_ping = qh->ping_state;
2818
2819         chan->data_pid_start = qh->data_toggle;
2820         chan->multi_count = 1;
2821
2822         if (urb->actual_length > urb->length &&
2823             !dwc2_hcd_is_pipe_in(&urb->pipe_info))
2824                 urb->actual_length = urb->length;
2825
2826         if (hsotg->params.host_dma)
2827                 chan->xfer_dma = urb->dma + urb->actual_length;
2828         else
2829                 chan->xfer_buf = (u8 *)urb->buf + urb->actual_length;
2830
2831         chan->xfer_len = urb->length - urb->actual_length;
2832         chan->xfer_count = 0;
2833
2834         /* Set the split attributes if required */
2835         if (qh->do_split)
2836                 dwc2_hc_init_split(hsotg, chan, qtd, urb);
2837         else
2838                 chan->do_split = 0;
2839
2840         /* Set the transfer attributes */
2841         dwc2_hc_init_xfer(hsotg, chan, qtd);
2842
2843         /* For non-dword aligned buffers */
2844         if (hsotg->params.host_dma && qh->do_split &&
2845             chan->ep_is_in && (chan->xfer_dma & 0x3)) {
2846                 dev_vdbg(hsotg->dev, "Non-aligned buffer\n");
2847                 if (dwc2_alloc_split_dma_aligned_buf(hsotg, qh, chan)) {
2848                         dev_err(hsotg->dev,
2849                                 "Failed to allocate memory to handle non-aligned buffer\n");
2850                         /* Add channel back to free list */
2851                         chan->align_buf = 0;
2852                         chan->multi_count = 0;
2853                         list_add_tail(&chan->hc_list_entry,
2854                                       &hsotg->free_hc_list);
2855                         qtd->in_process = 0;
2856                         qh->channel = NULL;
2857                         return -ENOMEM;
2858                 }
2859         } else {
2860                 /*
2861                  * We assume that DMA is always aligned in non-split
2862                  * case or split out case. Warn if not.
2863                  */
2864                 WARN_ON_ONCE(hsotg->params.host_dma &&
2865                              (chan->xfer_dma & 0x3));
2866                 chan->align_buf = 0;
2867         }
2868
2869         if (chan->ep_type == USB_ENDPOINT_XFER_INT ||
2870             chan->ep_type == USB_ENDPOINT_XFER_ISOC)
2871                 /*
2872                  * This value may be modified when the transfer is started
2873                  * to reflect the actual transfer length
2874                  */
2875                 chan->multi_count = dwc2_hb_mult(qh->maxp);
2876
2877         if (hsotg->params.dma_desc_enable) {
2878                 chan->desc_list_addr = qh->desc_list_dma;
2879                 chan->desc_list_sz = qh->desc_list_sz;
2880         }
2881
2882         dwc2_hc_init(hsotg, chan);
2883         chan->qh = qh;
2884
2885         return 0;
2886 }
2887
2888 /**
2889  * dwc2_hcd_select_transactions() - Selects transactions from the HCD transfer
2890  * schedule and assigns them to available host channels. Called from the HCD
2891  * interrupt handler functions.
2892  *
2893  * @hsotg: The HCD state structure
2894  *
2895  * Return: The types of new transactions that were assigned to host channels
2896  */
2897 enum dwc2_transaction_type dwc2_hcd_select_transactions(
2898                 struct dwc2_hsotg *hsotg)
2899 {
2900         enum dwc2_transaction_type ret_val = DWC2_TRANSACTION_NONE;
2901         struct list_head *qh_ptr;
2902         struct dwc2_qh *qh;
2903         int num_channels;
2904
2905 #ifdef DWC2_DEBUG_SOF
2906         dev_vdbg(hsotg->dev, "  Select Transactions\n");
2907 #endif
2908
2909         /* Process entries in the periodic ready list */
2910         qh_ptr = hsotg->periodic_sched_ready.next;
2911         while (qh_ptr != &hsotg->periodic_sched_ready) {
2912                 if (list_empty(&hsotg->free_hc_list))
2913                         break;
2914                 if (hsotg->params.uframe_sched) {
2915                         if (hsotg->available_host_channels <= 1)
2916                                 break;
2917                         hsotg->available_host_channels--;
2918                 }
2919                 qh = list_entry(qh_ptr, struct dwc2_qh, qh_list_entry);
2920                 if (dwc2_assign_and_init_hc(hsotg, qh))
2921                         break;
2922
2923                 /*
2924                  * Move the QH from the periodic ready schedule to the
2925                  * periodic assigned schedule
2926                  */
2927                 qh_ptr = qh_ptr->next;
2928                 list_move_tail(&qh->qh_list_entry,
2929                                &hsotg->periodic_sched_assigned);
2930                 ret_val = DWC2_TRANSACTION_PERIODIC;
2931         }
2932
2933         /*
2934          * Process entries in the inactive portion of the non-periodic
2935          * schedule. Some free host channels may not be used if they are
2936          * reserved for periodic transfers.
2937          */
2938         num_channels = hsotg->params.host_channels;
2939         qh_ptr = hsotg->non_periodic_sched_inactive.next;
2940         while (qh_ptr != &hsotg->non_periodic_sched_inactive) {
2941                 if (!hsotg->params.uframe_sched &&
2942                     hsotg->non_periodic_channels >= num_channels -
2943                                                 hsotg->periodic_channels)
2944                         break;
2945                 if (list_empty(&hsotg->free_hc_list))
2946                         break;
2947                 qh = list_entry(qh_ptr, struct dwc2_qh, qh_list_entry);
2948                 if (hsotg->params.uframe_sched) {
2949                         if (hsotg->available_host_channels < 1)
2950                                 break;
2951                         hsotg->available_host_channels--;
2952                 }
2953
2954                 if (dwc2_assign_and_init_hc(hsotg, qh))
2955                         break;
2956
2957                 /*
2958                  * Move the QH from the non-periodic inactive schedule to the
2959                  * non-periodic active schedule
2960                  */
2961                 qh_ptr = qh_ptr->next;
2962                 list_move_tail(&qh->qh_list_entry,
2963                                &hsotg->non_periodic_sched_active);
2964
2965                 if (ret_val == DWC2_TRANSACTION_NONE)
2966                         ret_val = DWC2_TRANSACTION_NON_PERIODIC;
2967                 else
2968                         ret_val = DWC2_TRANSACTION_ALL;
2969
2970                 if (!hsotg->params.uframe_sched)
2971                         hsotg->non_periodic_channels++;
2972         }
2973
2974         return ret_val;
2975 }
2976
2977 /**
2978  * dwc2_queue_transaction() - Attempts to queue a single transaction request for
2979  * a host channel associated with either a periodic or non-periodic transfer
2980  *
2981  * @hsotg: The HCD state structure
2982  * @chan:  Host channel descriptor associated with either a periodic or
2983  *         non-periodic transfer
2984  * @fifo_dwords_avail: Number of DWORDs available in the periodic Tx FIFO
2985  *                     for periodic transfers or the non-periodic Tx FIFO
2986  *                     for non-periodic transfers
2987  *
2988  * Return: 1 if a request is queued and more requests may be needed to
2989  * complete the transfer, 0 if no more requests are required for this
2990  * transfer, -1 if there is insufficient space in the Tx FIFO
2991  *
2992  * This function assumes that there is space available in the appropriate
2993  * request queue. For an OUT transfer or SETUP transaction in Slave mode,
2994  * it checks whether space is available in the appropriate Tx FIFO.
2995  *
2996  * Must be called with interrupt disabled and spinlock held
2997  */
2998 static int dwc2_queue_transaction(struct dwc2_hsotg *hsotg,
2999                                   struct dwc2_host_chan *chan,
3000                                   u16 fifo_dwords_avail)
3001 {
3002         int retval = 0;
3003
3004         if (chan->do_split)
3005                 /* Put ourselves on the list to keep order straight */
3006                 list_move_tail(&chan->split_order_list_entry,
3007                                &hsotg->split_order);
3008
3009         if (hsotg->params.host_dma) {
3010                 if (hsotg->params.dma_desc_enable) {
3011                         if (!chan->xfer_started ||
3012                             chan->ep_type == USB_ENDPOINT_XFER_ISOC) {
3013                                 dwc2_hcd_start_xfer_ddma(hsotg, chan->qh);
3014                                 chan->qh->ping_state = 0;
3015                         }
3016                 } else if (!chan->xfer_started) {
3017                         dwc2_hc_start_transfer(hsotg, chan);
3018                         chan->qh->ping_state = 0;
3019                 }
3020         } else if (chan->halt_pending) {
3021                 /* Don't queue a request if the channel has been halted */
3022         } else if (chan->halt_on_queue) {
3023                 dwc2_hc_halt(hsotg, chan, chan->halt_status);
3024         } else if (chan->do_ping) {
3025                 if (!chan->xfer_started)
3026                         dwc2_hc_start_transfer(hsotg, chan);
3027         } else if (!chan->ep_is_in ||
3028                    chan->data_pid_start == DWC2_HC_PID_SETUP) {
3029                 if ((fifo_dwords_avail * 4) >= chan->max_packet) {
3030                         if (!chan->xfer_started) {
3031                                 dwc2_hc_start_transfer(hsotg, chan);
3032                                 retval = 1;
3033                         } else {
3034                                 retval = dwc2_hc_continue_transfer(hsotg, chan);
3035                         }
3036                 } else {
3037                         retval = -1;
3038                 }
3039         } else {
3040                 if (!chan->xfer_started) {
3041                         dwc2_hc_start_transfer(hsotg, chan);
3042                         retval = 1;
3043                 } else {
3044                         retval = dwc2_hc_continue_transfer(hsotg, chan);
3045                 }
3046         }
3047
3048         return retval;
3049 }
3050
3051 /*
3052  * Processes periodic channels for the next frame and queues transactions for
3053  * these channels to the DWC_otg controller. After queueing transactions, the
3054  * Periodic Tx FIFO Empty interrupt is enabled if there are more transactions
3055  * to queue as Periodic Tx FIFO or request queue space becomes available.
3056  * Otherwise, the Periodic Tx FIFO Empty interrupt is disabled.
3057  *
3058  * Must be called with interrupt disabled and spinlock held
3059  */
3060 static void dwc2_process_periodic_channels(struct dwc2_hsotg *hsotg)
3061 {
3062         struct list_head *qh_ptr;
3063         struct dwc2_qh *qh;
3064         u32 tx_status;
3065         u32 fspcavail;
3066         u32 gintmsk;
3067         int status;
3068         bool no_queue_space = false;
3069         bool no_fifo_space = false;
3070         u32 qspcavail;
3071
3072         /* If empty list then just adjust interrupt enables */
3073         if (list_empty(&hsotg->periodic_sched_assigned))
3074                 goto exit;
3075
3076         if (dbg_perio())
3077                 dev_vdbg(hsotg->dev, "Queue periodic transactions\n");
3078
3079         tx_status = dwc2_readl(hsotg->regs + HPTXSTS);
3080         qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
3081                     TXSTS_QSPCAVAIL_SHIFT;
3082         fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
3083                     TXSTS_FSPCAVAIL_SHIFT;
3084
3085         if (dbg_perio()) {
3086                 dev_vdbg(hsotg->dev, "  P Tx Req Queue Space Avail (before queue): %d\n",
3087                          qspcavail);
3088                 dev_vdbg(hsotg->dev, "  P Tx FIFO Space Avail (before queue): %d\n",
3089                          fspcavail);
3090         }
3091
3092         qh_ptr = hsotg->periodic_sched_assigned.next;
3093         while (qh_ptr != &hsotg->periodic_sched_assigned) {
3094                 tx_status = dwc2_readl(hsotg->regs + HPTXSTS);
3095                 qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
3096                             TXSTS_QSPCAVAIL_SHIFT;
3097                 if (qspcavail == 0) {
3098                         no_queue_space = true;
3099                         break;
3100                 }
3101
3102                 qh = list_entry(qh_ptr, struct dwc2_qh, qh_list_entry);
3103                 if (!qh->channel) {
3104                         qh_ptr = qh_ptr->next;
3105                         continue;
3106                 }
3107
3108                 /* Make sure EP's TT buffer is clean before queueing qtds */
3109                 if (qh->tt_buffer_dirty) {
3110                         qh_ptr = qh_ptr->next;
3111                         continue;
3112                 }
3113
3114                 /*
3115                  * Set a flag if we're queuing high-bandwidth in slave mode.
3116                  * The flag prevents any halts to get into the request queue in
3117                  * the middle of multiple high-bandwidth packets getting queued.
3118                  */
3119                 if (!hsotg->params.host_dma &&
3120                     qh->channel->multi_count > 1)
3121                         hsotg->queuing_high_bandwidth = 1;
3122
3123                 fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
3124                             TXSTS_FSPCAVAIL_SHIFT;
3125                 status = dwc2_queue_transaction(hsotg, qh->channel, fspcavail);
3126                 if (status < 0) {
3127                         no_fifo_space = true;
3128                         break;
3129                 }
3130
3131                 /*
3132                  * In Slave mode, stay on the current transfer until there is
3133                  * nothing more to do or the high-bandwidth request count is
3134                  * reached. In DMA mode, only need to queue one request. The
3135                  * controller automatically handles multiple packets for
3136                  * high-bandwidth transfers.
3137                  */
3138                 if (hsotg->params.host_dma || status == 0 ||
3139                     qh->channel->requests == qh->channel->multi_count) {
3140                         qh_ptr = qh_ptr->next;
3141                         /*
3142                          * Move the QH from the periodic assigned schedule to
3143                          * the periodic queued schedule
3144                          */
3145                         list_move_tail(&qh->qh_list_entry,
3146                                        &hsotg->periodic_sched_queued);
3147
3148                         /* done queuing high bandwidth */
3149                         hsotg->queuing_high_bandwidth = 0;
3150                 }
3151         }
3152
3153 exit:
3154         if (no_queue_space || no_fifo_space ||
3155             (!hsotg->params.host_dma &&
3156              !list_empty(&hsotg->periodic_sched_assigned))) {
3157                 /*
3158                  * May need to queue more transactions as the request
3159                  * queue or Tx FIFO empties. Enable the periodic Tx
3160                  * FIFO empty interrupt. (Always use the half-empty
3161                  * level to ensure that new requests are loaded as
3162                  * soon as possible.)
3163                  */
3164                 gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
3165                 if (!(gintmsk & GINTSTS_PTXFEMP)) {
3166                         gintmsk |= GINTSTS_PTXFEMP;
3167                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
3168                 }
3169         } else {
3170                 /*
3171                  * Disable the Tx FIFO empty interrupt since there are
3172                  * no more transactions that need to be queued right
3173                  * now. This function is called from interrupt
3174                  * handlers to queue more transactions as transfer
3175                  * states change.
3176                  */
3177                 gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
3178                 if (gintmsk & GINTSTS_PTXFEMP) {
3179                         gintmsk &= ~GINTSTS_PTXFEMP;
3180                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
3181                 }
3182         }
3183 }
3184
3185 /*
3186  * Processes active non-periodic channels and queues transactions for these
3187  * channels to the DWC_otg controller. After queueing transactions, the NP Tx
3188  * FIFO Empty interrupt is enabled if there are more transactions to queue as
3189  * NP Tx FIFO or request queue space becomes available. Otherwise, the NP Tx
3190  * FIFO Empty interrupt is disabled.
3191  *
3192  * Must be called with interrupt disabled and spinlock held
3193  */
3194 static void dwc2_process_non_periodic_channels(struct dwc2_hsotg *hsotg)
3195 {
3196         struct list_head *orig_qh_ptr;
3197         struct dwc2_qh *qh;
3198         u32 tx_status;
3199         u32 qspcavail;
3200         u32 fspcavail;
3201         u32 gintmsk;
3202         int status;
3203         int no_queue_space = 0;
3204         int no_fifo_space = 0;
3205         int more_to_do = 0;
3206
3207         dev_vdbg(hsotg->dev, "Queue non-periodic transactions\n");
3208
3209         tx_status = dwc2_readl(hsotg->regs + GNPTXSTS);
3210         qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
3211                     TXSTS_QSPCAVAIL_SHIFT;
3212         fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
3213                     TXSTS_FSPCAVAIL_SHIFT;
3214         dev_vdbg(hsotg->dev, "  NP Tx Req Queue Space Avail (before queue): %d\n",
3215                  qspcavail);
3216         dev_vdbg(hsotg->dev, "  NP Tx FIFO Space Avail (before queue): %d\n",
3217                  fspcavail);
3218
3219         /*
3220          * Keep track of the starting point. Skip over the start-of-list
3221          * entry.
3222          */
3223         if (hsotg->non_periodic_qh_ptr == &hsotg->non_periodic_sched_active)
3224                 hsotg->non_periodic_qh_ptr = hsotg->non_periodic_qh_ptr->next;
3225         orig_qh_ptr = hsotg->non_periodic_qh_ptr;
3226
3227         /*
3228          * Process once through the active list or until no more space is
3229          * available in the request queue or the Tx FIFO
3230          */
3231         do {
3232                 tx_status = dwc2_readl(hsotg->regs + GNPTXSTS);
3233                 qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
3234                             TXSTS_QSPCAVAIL_SHIFT;
3235                 if (!hsotg->params.host_dma && qspcavail == 0) {
3236                         no_queue_space = 1;
3237                         break;
3238                 }
3239
3240                 qh = list_entry(hsotg->non_periodic_qh_ptr, struct dwc2_qh,
3241                                 qh_list_entry);
3242                 if (!qh->channel)
3243                         goto next;
3244
3245                 /* Make sure EP's TT buffer is clean before queueing qtds */
3246                 if (qh->tt_buffer_dirty)
3247                         goto next;
3248
3249                 fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
3250                             TXSTS_FSPCAVAIL_SHIFT;
3251                 status = dwc2_queue_transaction(hsotg, qh->channel, fspcavail);
3252
3253                 if (status > 0) {
3254                         more_to_do = 1;
3255                 } else if (status < 0) {
3256                         no_fifo_space = 1;
3257                         break;
3258                 }
3259 next:
3260                 /* Advance to next QH, skipping start-of-list entry */
3261                 hsotg->non_periodic_qh_ptr = hsotg->non_periodic_qh_ptr->next;
3262                 if (hsotg->non_periodic_qh_ptr ==
3263                                 &hsotg->non_periodic_sched_active)
3264                         hsotg->non_periodic_qh_ptr =
3265                                         hsotg->non_periodic_qh_ptr->next;
3266         } while (hsotg->non_periodic_qh_ptr != orig_qh_ptr);
3267
3268         if (!hsotg->params.host_dma) {
3269                 tx_status = dwc2_readl(hsotg->regs + GNPTXSTS);
3270                 qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
3271                             TXSTS_QSPCAVAIL_SHIFT;
3272                 fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
3273                             TXSTS_FSPCAVAIL_SHIFT;
3274                 dev_vdbg(hsotg->dev,
3275                          "  NP Tx Req Queue Space Avail (after queue): %d\n",
3276                          qspcavail);
3277                 dev_vdbg(hsotg->dev,
3278                          "  NP Tx FIFO Space Avail (after queue): %d\n",
3279                          fspcavail);
3280
3281                 if (more_to_do || no_queue_space || no_fifo_space) {
3282                         /*
3283                          * May need to queue more transactions as the request
3284                          * queue or Tx FIFO empties. Enable the non-periodic
3285                          * Tx FIFO empty interrupt. (Always use the half-empty
3286                          * level to ensure that new requests are loaded as
3287                          * soon as possible.)
3288                          */
3289                         gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
3290                         gintmsk |= GINTSTS_NPTXFEMP;
3291                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
3292                 } else {
3293                         /*
3294                          * Disable the Tx FIFO empty interrupt since there are
3295                          * no more transactions that need to be queued right
3296                          * now. This function is called from interrupt
3297                          * handlers to queue more transactions as transfer
3298                          * states change.
3299                          */
3300                         gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
3301                         gintmsk &= ~GINTSTS_NPTXFEMP;
3302                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
3303                 }
3304         }
3305 }
3306
3307 /**
3308  * dwc2_hcd_queue_transactions() - Processes the currently active host channels
3309  * and queues transactions for these channels to the DWC_otg controller. Called
3310  * from the HCD interrupt handler functions.
3311  *
3312  * @hsotg:   The HCD state structure
3313  * @tr_type: The type(s) of transactions to queue (non-periodic, periodic,
3314  *           or both)
3315  *
3316  * Must be called with interrupt disabled and spinlock held
3317  */
3318 void dwc2_hcd_queue_transactions(struct dwc2_hsotg *hsotg,
3319                                  enum dwc2_transaction_type tr_type)
3320 {
3321 #ifdef DWC2_DEBUG_SOF
3322         dev_vdbg(hsotg->dev, "Queue Transactions\n");
3323 #endif
3324         /* Process host channels associated with periodic transfers */
3325         if (tr_type == DWC2_TRANSACTION_PERIODIC ||
3326             tr_type == DWC2_TRANSACTION_ALL)
3327                 dwc2_process_periodic_channels(hsotg);
3328
3329         /* Process host channels associated with non-periodic transfers */
3330         if (tr_type == DWC2_TRANSACTION_NON_PERIODIC ||
3331             tr_type == DWC2_TRANSACTION_ALL) {
3332                 if (!list_empty(&hsotg->non_periodic_sched_active)) {
3333                         dwc2_process_non_periodic_channels(hsotg);
3334                 } else {
3335                         /*
3336                          * Ensure NP Tx FIFO empty interrupt is disabled when
3337                          * there are no non-periodic transfers to process
3338                          */
3339                         u32 gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
3340
3341                         gintmsk &= ~GINTSTS_NPTXFEMP;
3342                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
3343                 }
3344         }
3345 }
3346
3347 static void dwc2_conn_id_status_change(struct work_struct *work)
3348 {
3349         struct dwc2_hsotg *hsotg = container_of(work, struct dwc2_hsotg,
3350                                                 wf_otg);
3351         u32 count = 0;
3352         u32 gotgctl;
3353         unsigned long flags;
3354
3355         dev_dbg(hsotg->dev, "%s()\n", __func__);
3356
3357         gotgctl = dwc2_readl(hsotg->regs + GOTGCTL);
3358         dev_dbg(hsotg->dev, "gotgctl=%0x\n", gotgctl);
3359         dev_dbg(hsotg->dev, "gotgctl.b.conidsts=%d\n",
3360                 !!(gotgctl & GOTGCTL_CONID_B));
3361
3362         /* B-Device connector (Device Mode) */
3363         if (gotgctl & GOTGCTL_CONID_B) {
3364                 dwc2_vbus_supply_exit(hsotg);
3365                 /* Wait for switch to device mode */
3366                 dev_dbg(hsotg->dev, "connId B\n");
3367                 if (hsotg->bus_suspended) {
3368                         dev_info(hsotg->dev,
3369                                  "Do port resume before switching to device mode\n");
3370                         dwc2_port_resume(hsotg);
3371                 }
3372                 while (!dwc2_is_device_mode(hsotg)) {
3373                         dev_info(hsotg->dev,
3374                                  "Waiting for Peripheral Mode, Mode=%s\n",
3375                                  dwc2_is_host_mode(hsotg) ? "Host" :
3376                                  "Peripheral");
3377                         msleep(20);
3378                         /*
3379                          * Sometimes the initial GOTGCTRL read is wrong, so
3380                          * check it again and jump to host mode if that was
3381                          * the case.
3382                          */
3383                         gotgctl = dwc2_readl(hsotg->regs + GOTGCTL);
3384                         if (!(gotgctl & GOTGCTL_CONID_B))
3385                                 goto host;
3386                         if (++count > 250)
3387                                 break;
3388                 }
3389                 if (count > 250)
3390                         dev_err(hsotg->dev,
3391                                 "Connection id status change timed out\n");
3392                 hsotg->op_state = OTG_STATE_B_PERIPHERAL;
3393                 dwc2_core_init(hsotg, false);
3394                 dwc2_enable_global_interrupts(hsotg);
3395                 spin_lock_irqsave(&hsotg->lock, flags);
3396                 dwc2_hsotg_core_init_disconnected(hsotg, false);
3397                 spin_unlock_irqrestore(&hsotg->lock, flags);
3398                 /* Enable ACG feature in device mode,if supported */
3399                 dwc2_enable_acg(hsotg);
3400                 dwc2_hsotg_core_connect(hsotg);
3401         } else {
3402 host:
3403                 /* A-Device connector (Host Mode) */
3404                 dev_dbg(hsotg->dev, "connId A\n");
3405                 while (!dwc2_is_host_mode(hsotg)) {
3406                         dev_info(hsotg->dev, "Waiting for Host Mode, Mode=%s\n",
3407                                  dwc2_is_host_mode(hsotg) ?
3408                                  "Host" : "Peripheral");
3409                         msleep(20);
3410                         if (++count > 250)
3411                                 break;
3412                 }
3413                 if (count > 250)
3414                         dev_err(hsotg->dev,
3415                                 "Connection id status change timed out\n");
3416
3417                 spin_lock_irqsave(&hsotg->lock, flags);
3418                 dwc2_hsotg_disconnect(hsotg);
3419                 spin_unlock_irqrestore(&hsotg->lock, flags);
3420
3421                 hsotg->op_state = OTG_STATE_A_HOST;
3422                 /* Initialize the Core for Host mode */
3423                 dwc2_core_init(hsotg, false);
3424                 dwc2_enable_global_interrupts(hsotg);
3425                 dwc2_hcd_start(hsotg);
3426         }
3427 }
3428
3429 static void dwc2_wakeup_detected(struct timer_list *t)
3430 {
3431         struct dwc2_hsotg *hsotg = from_timer(hsotg, t, wkp_timer);
3432         u32 hprt0;
3433
3434         dev_dbg(hsotg->dev, "%s()\n", __func__);
3435
3436         /*
3437          * Clear the Resume after 70ms. (Need 20 ms minimum. Use 70 ms
3438          * so that OPT tests pass with all PHYs.)
3439          */
3440         hprt0 = dwc2_read_hprt0(hsotg);
3441         dev_dbg(hsotg->dev, "Resume: HPRT0=%0x\n", hprt0);
3442         hprt0 &= ~HPRT0_RES;
3443         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3444         dev_dbg(hsotg->dev, "Clear Resume: HPRT0=%0x\n",
3445                 dwc2_readl(hsotg->regs + HPRT0));
3446
3447         dwc2_hcd_rem_wakeup(hsotg);
3448         hsotg->bus_suspended = false;
3449
3450         /* Change to L0 state */
3451         hsotg->lx_state = DWC2_L0;
3452 }
3453
3454 static int dwc2_host_is_b_hnp_enabled(struct dwc2_hsotg *hsotg)
3455 {
3456         struct usb_hcd *hcd = dwc2_hsotg_to_hcd(hsotg);
3457
3458         return hcd->self.b_hnp_enable;
3459 }
3460
3461 /* Must NOT be called with interrupt disabled or spinlock held */
3462 static void dwc2_port_suspend(struct dwc2_hsotg *hsotg, u16 windex)
3463 {
3464         unsigned long flags;
3465         u32 hprt0;
3466         u32 pcgctl;
3467         u32 gotgctl;
3468
3469         dev_dbg(hsotg->dev, "%s()\n", __func__);
3470
3471         spin_lock_irqsave(&hsotg->lock, flags);
3472
3473         if (windex == hsotg->otg_port && dwc2_host_is_b_hnp_enabled(hsotg)) {
3474                 gotgctl = dwc2_readl(hsotg->regs + GOTGCTL);
3475                 gotgctl |= GOTGCTL_HSTSETHNPEN;
3476                 dwc2_writel(gotgctl, hsotg->regs + GOTGCTL);
3477                 hsotg->op_state = OTG_STATE_A_SUSPEND;
3478         }
3479
3480         hprt0 = dwc2_read_hprt0(hsotg);
3481         hprt0 |= HPRT0_SUSP;
3482         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3483
3484         hsotg->bus_suspended = true;
3485
3486         /*
3487          * If power_down is supported, Phy clock will be suspended
3488          * after registers are backuped.
3489          */
3490         if (!hsotg->params.power_down) {
3491                 /* Suspend the Phy Clock */
3492                 pcgctl = dwc2_readl(hsotg->regs + PCGCTL);
3493                 pcgctl |= PCGCTL_STOPPCLK;
3494                 dwc2_writel(pcgctl, hsotg->regs + PCGCTL);
3495                 udelay(10);
3496         }
3497
3498         /* For HNP the bus must be suspended for at least 200ms */
3499         if (dwc2_host_is_b_hnp_enabled(hsotg)) {
3500                 pcgctl = dwc2_readl(hsotg->regs + PCGCTL);
3501                 pcgctl &= ~PCGCTL_STOPPCLK;
3502                 dwc2_writel(pcgctl, hsotg->regs + PCGCTL);
3503
3504                 spin_unlock_irqrestore(&hsotg->lock, flags);
3505
3506                 msleep(200);
3507         } else {
3508                 spin_unlock_irqrestore(&hsotg->lock, flags);
3509         }
3510 }
3511
3512 /* Must NOT be called with interrupt disabled or spinlock held */
3513 static void dwc2_port_resume(struct dwc2_hsotg *hsotg)
3514 {
3515         unsigned long flags;
3516         u32 hprt0;
3517         u32 pcgctl;
3518
3519         spin_lock_irqsave(&hsotg->lock, flags);
3520
3521         /*
3522          * If power_down is supported, Phy clock is already resumed
3523          * after registers restore.
3524          */
3525         if (!hsotg->params.power_down) {
3526                 pcgctl = dwc2_readl(hsotg->regs + PCGCTL);
3527                 pcgctl &= ~PCGCTL_STOPPCLK;
3528                 dwc2_writel(pcgctl, hsotg->regs + PCGCTL);
3529                 spin_unlock_irqrestore(&hsotg->lock, flags);
3530                 msleep(20);
3531                 spin_lock_irqsave(&hsotg->lock, flags);
3532         }
3533
3534         hprt0 = dwc2_read_hprt0(hsotg);
3535         hprt0 |= HPRT0_RES;
3536         hprt0 &= ~HPRT0_SUSP;
3537         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3538         spin_unlock_irqrestore(&hsotg->lock, flags);
3539
3540         msleep(USB_RESUME_TIMEOUT);
3541
3542         spin_lock_irqsave(&hsotg->lock, flags);
3543         hprt0 = dwc2_read_hprt0(hsotg);
3544         hprt0 &= ~(HPRT0_RES | HPRT0_SUSP);
3545         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3546         hsotg->bus_suspended = false;
3547         spin_unlock_irqrestore(&hsotg->lock, flags);
3548 }
3549
3550 /* Handles hub class-specific requests */
3551 static int dwc2_hcd_hub_control(struct dwc2_hsotg *hsotg, u16 typereq,
3552                                 u16 wvalue, u16 windex, char *buf, u16 wlength)
3553 {
3554         struct usb_hub_descriptor *hub_desc;
3555         int retval = 0;
3556         u32 hprt0;
3557         u32 port_status;
3558         u32 speed;
3559         u32 pcgctl;
3560
3561         switch (typereq) {
3562         case ClearHubFeature:
3563                 dev_dbg(hsotg->dev, "ClearHubFeature %1xh\n", wvalue);
3564
3565                 switch (wvalue) {
3566                 case C_HUB_LOCAL_POWER:
3567                 case C_HUB_OVER_CURRENT:
3568                         /* Nothing required here */
3569                         break;
3570
3571                 default:
3572                         retval = -EINVAL;
3573                         dev_err(hsotg->dev,
3574                                 "ClearHubFeature request %1xh unknown\n",
3575                                 wvalue);
3576                 }
3577                 break;
3578
3579         case ClearPortFeature:
3580                 if (wvalue != USB_PORT_FEAT_L1)
3581                         if (!windex || windex > 1)
3582                                 goto error;
3583                 switch (wvalue) {
3584                 case USB_PORT_FEAT_ENABLE:
3585                         dev_dbg(hsotg->dev,
3586                                 "ClearPortFeature USB_PORT_FEAT_ENABLE\n");
3587                         hprt0 = dwc2_read_hprt0(hsotg);
3588                         hprt0 |= HPRT0_ENA;
3589                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3590                         break;
3591
3592                 case USB_PORT_FEAT_SUSPEND:
3593                         dev_dbg(hsotg->dev,
3594                                 "ClearPortFeature USB_PORT_FEAT_SUSPEND\n");
3595
3596                         if (hsotg->bus_suspended) {
3597                                 if (hsotg->hibernated)
3598                                         dwc2_exit_hibernation(hsotg, 0, 0, 1);
3599                                 else
3600                                         dwc2_port_resume(hsotg);
3601                         }
3602                         break;
3603
3604                 case USB_PORT_FEAT_POWER:
3605                         dev_dbg(hsotg->dev,
3606                                 "ClearPortFeature USB_PORT_FEAT_POWER\n");
3607                         hprt0 = dwc2_read_hprt0(hsotg);
3608                         hprt0 &= ~HPRT0_PWR;
3609                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3610                         break;
3611
3612                 case USB_PORT_FEAT_INDICATOR:
3613                         dev_dbg(hsotg->dev,
3614                                 "ClearPortFeature USB_PORT_FEAT_INDICATOR\n");
3615                         /* Port indicator not supported */
3616                         break;
3617
3618                 case USB_PORT_FEAT_C_CONNECTION:
3619                         /*
3620                          * Clears driver's internal Connect Status Change flag
3621                          */
3622                         dev_dbg(hsotg->dev,
3623                                 "ClearPortFeature USB_PORT_FEAT_C_CONNECTION\n");
3624                         hsotg->flags.b.port_connect_status_change = 0;
3625                         break;
3626
3627                 case USB_PORT_FEAT_C_RESET:
3628                         /* Clears driver's internal Port Reset Change flag */
3629                         dev_dbg(hsotg->dev,
3630                                 "ClearPortFeature USB_PORT_FEAT_C_RESET\n");
3631                         hsotg->flags.b.port_reset_change = 0;
3632                         break;
3633
3634                 case USB_PORT_FEAT_C_ENABLE:
3635                         /*
3636                          * Clears the driver's internal Port Enable/Disable
3637                          * Change flag
3638                          */
3639                         dev_dbg(hsotg->dev,
3640                                 "ClearPortFeature USB_PORT_FEAT_C_ENABLE\n");
3641                         hsotg->flags.b.port_enable_change = 0;
3642                         break;
3643
3644                 case USB_PORT_FEAT_C_SUSPEND:
3645                         /*
3646                          * Clears the driver's internal Port Suspend Change
3647                          * flag, which is set when resume signaling on the host
3648                          * port is complete
3649                          */
3650                         dev_dbg(hsotg->dev,
3651                                 "ClearPortFeature USB_PORT_FEAT_C_SUSPEND\n");
3652                         hsotg->flags.b.port_suspend_change = 0;
3653                         break;
3654
3655                 case USB_PORT_FEAT_C_PORT_L1:
3656                         dev_dbg(hsotg->dev,
3657                                 "ClearPortFeature USB_PORT_FEAT_C_PORT_L1\n");
3658                         hsotg->flags.b.port_l1_change = 0;
3659                         break;
3660
3661                 case USB_PORT_FEAT_C_OVER_CURRENT:
3662                         dev_dbg(hsotg->dev,
3663                                 "ClearPortFeature USB_PORT_FEAT_C_OVER_CURRENT\n");
3664                         hsotg->flags.b.port_over_current_change = 0;
3665                         break;
3666
3667                 default:
3668                         retval = -EINVAL;
3669                         dev_err(hsotg->dev,
3670                                 "ClearPortFeature request %1xh unknown or unsupported\n",
3671                                 wvalue);
3672                 }
3673                 break;
3674
3675         case GetHubDescriptor:
3676                 dev_dbg(hsotg->dev, "GetHubDescriptor\n");
3677                 hub_desc = (struct usb_hub_descriptor *)buf;
3678                 hub_desc->bDescLength = 9;
3679                 hub_desc->bDescriptorType = USB_DT_HUB;
3680                 hub_desc->bNbrPorts = 1;
3681                 hub_desc->wHubCharacteristics =
3682                         cpu_to_le16(HUB_CHAR_COMMON_LPSM |
3683                                     HUB_CHAR_INDV_PORT_OCPM);
3684                 hub_desc->bPwrOn2PwrGood = 1;
3685                 hub_desc->bHubContrCurrent = 0;
3686                 hub_desc->u.hs.DeviceRemovable[0] = 0;
3687                 hub_desc->u.hs.DeviceRemovable[1] = 0xff;
3688                 break;
3689
3690         case GetHubStatus:
3691                 dev_dbg(hsotg->dev, "GetHubStatus\n");
3692                 memset(buf, 0, 4);
3693                 break;
3694
3695         case GetPortStatus:
3696                 dev_vdbg(hsotg->dev,
3697                          "GetPortStatus wIndex=0x%04x flags=0x%08x\n", windex,
3698                          hsotg->flags.d32);
3699                 if (!windex || windex > 1)
3700                         goto error;
3701
3702                 port_status = 0;
3703                 if (hsotg->flags.b.port_connect_status_change)
3704                         port_status |= USB_PORT_STAT_C_CONNECTION << 16;
3705                 if (hsotg->flags.b.port_enable_change)
3706                         port_status |= USB_PORT_STAT_C_ENABLE << 16;
3707                 if (hsotg->flags.b.port_suspend_change)
3708                         port_status |= USB_PORT_STAT_C_SUSPEND << 16;
3709                 if (hsotg->flags.b.port_l1_change)
3710                         port_status |= USB_PORT_STAT_C_L1 << 16;
3711                 if (hsotg->flags.b.port_reset_change)
3712                         port_status |= USB_PORT_STAT_C_RESET << 16;
3713                 if (hsotg->flags.b.port_over_current_change) {
3714                         dev_warn(hsotg->dev, "Overcurrent change detected\n");
3715                         port_status |= USB_PORT_STAT_C_OVERCURRENT << 16;
3716                 }
3717
3718                 if (!hsotg->flags.b.port_connect_status) {
3719                         /*
3720                          * The port is disconnected, which means the core is
3721                          * either in device mode or it soon will be. Just
3722                          * return 0's for the remainder of the port status
3723                          * since the port register can't be read if the core
3724                          * is in device mode.
3725                          */
3726                         *(__le32 *)buf = cpu_to_le32(port_status);
3727                         break;
3728                 }
3729
3730                 hprt0 = dwc2_readl(hsotg->regs + HPRT0);
3731                 dev_vdbg(hsotg->dev, "  HPRT0: 0x%08x\n", hprt0);
3732
3733                 if (hprt0 & HPRT0_CONNSTS)
3734                         port_status |= USB_PORT_STAT_CONNECTION;
3735                 if (hprt0 & HPRT0_ENA)
3736                         port_status |= USB_PORT_STAT_ENABLE;
3737                 if (hprt0 & HPRT0_SUSP)
3738                         port_status |= USB_PORT_STAT_SUSPEND;
3739                 if (hprt0 & HPRT0_OVRCURRACT)
3740                         port_status |= USB_PORT_STAT_OVERCURRENT;
3741                 if (hprt0 & HPRT0_RST)
3742                         port_status |= USB_PORT_STAT_RESET;
3743                 if (hprt0 & HPRT0_PWR)
3744                         port_status |= USB_PORT_STAT_POWER;
3745
3746                 speed = (hprt0 & HPRT0_SPD_MASK) >> HPRT0_SPD_SHIFT;
3747                 if (speed == HPRT0_SPD_HIGH_SPEED)
3748                         port_status |= USB_PORT_STAT_HIGH_SPEED;
3749                 else if (speed == HPRT0_SPD_LOW_SPEED)
3750                         port_status |= USB_PORT_STAT_LOW_SPEED;
3751
3752                 if (hprt0 & HPRT0_TSTCTL_MASK)
3753                         port_status |= USB_PORT_STAT_TEST;
3754                 /* USB_PORT_FEAT_INDICATOR unsupported always 0 */
3755
3756                 if (hsotg->params.dma_desc_fs_enable) {
3757                         /*
3758                          * Enable descriptor DMA only if a full speed
3759                          * device is connected.
3760                          */
3761                         if (hsotg->new_connection &&
3762                             ((port_status &
3763                               (USB_PORT_STAT_CONNECTION |
3764                                USB_PORT_STAT_HIGH_SPEED |
3765                                USB_PORT_STAT_LOW_SPEED)) ==
3766                                USB_PORT_STAT_CONNECTION)) {
3767                                 u32 hcfg;
3768
3769                                 dev_info(hsotg->dev, "Enabling descriptor DMA mode\n");
3770                                 hsotg->params.dma_desc_enable = true;
3771                                 hcfg = dwc2_readl(hsotg->regs + HCFG);
3772                                 hcfg |= HCFG_DESCDMA;
3773                                 dwc2_writel(hcfg, hsotg->regs + HCFG);
3774                                 hsotg->new_connection = false;
3775                         }
3776                 }
3777
3778                 dev_vdbg(hsotg->dev, "port_status=%08x\n", port_status);
3779                 *(__le32 *)buf = cpu_to_le32(port_status);
3780                 break;
3781
3782         case SetHubFeature:
3783                 dev_dbg(hsotg->dev, "SetHubFeature\n");
3784                 /* No HUB features supported */
3785                 break;
3786
3787         case SetPortFeature:
3788                 dev_dbg(hsotg->dev, "SetPortFeature\n");
3789                 if (wvalue != USB_PORT_FEAT_TEST && (!windex || windex > 1))
3790                         goto error;
3791
3792                 if (!hsotg->flags.b.port_connect_status) {
3793                         /*
3794                          * The port is disconnected, which means the core is
3795                          * either in device mode or it soon will be. Just
3796                          * return without doing anything since the port
3797                          * register can't be written if the core is in device
3798                          * mode.
3799                          */
3800                         break;
3801                 }
3802
3803                 switch (wvalue) {
3804                 case USB_PORT_FEAT_SUSPEND:
3805                         dev_dbg(hsotg->dev,
3806                                 "SetPortFeature - USB_PORT_FEAT_SUSPEND\n");
3807                         if (windex != hsotg->otg_port)
3808                                 goto error;
3809                         if (hsotg->params.power_down == 2)
3810                                 dwc2_enter_hibernation(hsotg, 1);
3811                         else
3812                                 dwc2_port_suspend(hsotg, windex);
3813                         break;
3814
3815                 case USB_PORT_FEAT_POWER:
3816                         dev_dbg(hsotg->dev,
3817                                 "SetPortFeature - USB_PORT_FEAT_POWER\n");
3818                         hprt0 = dwc2_read_hprt0(hsotg);
3819                         hprt0 |= HPRT0_PWR;
3820                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3821                         break;
3822
3823                 case USB_PORT_FEAT_RESET:
3824                         if (hsotg->params.power_down == 2 &&
3825                             hsotg->hibernated)
3826                                 dwc2_exit_hibernation(hsotg, 0, 1, 1);
3827                         hprt0 = dwc2_read_hprt0(hsotg);
3828                         dev_dbg(hsotg->dev,
3829                                 "SetPortFeature - USB_PORT_FEAT_RESET\n");
3830                         pcgctl = dwc2_readl(hsotg->regs + PCGCTL);
3831                         pcgctl &= ~(PCGCTL_ENBL_SLEEP_GATING | PCGCTL_STOPPCLK);
3832                         dwc2_writel(pcgctl, hsotg->regs + PCGCTL);
3833                         /* ??? Original driver does this */
3834                         dwc2_writel(0, hsotg->regs + PCGCTL);
3835
3836                         hprt0 = dwc2_read_hprt0(hsotg);
3837                         /* Clear suspend bit if resetting from suspend state */
3838                         hprt0 &= ~HPRT0_SUSP;
3839
3840                         /*
3841                          * When B-Host the Port reset bit is set in the Start
3842                          * HCD Callback function, so that the reset is started
3843                          * within 1ms of the HNP success interrupt
3844                          */
3845                         if (!dwc2_hcd_is_b_host(hsotg)) {
3846                                 hprt0 |= HPRT0_PWR | HPRT0_RST;
3847                                 dev_dbg(hsotg->dev,
3848                                         "In host mode, hprt0=%08x\n", hprt0);
3849                                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
3850                         }
3851
3852                         /* Clear reset bit in 10ms (FS/LS) or 50ms (HS) */
3853                         msleep(50);
3854                         hprt0 &= ~HPRT0_RST;
3855                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3856                         hsotg->lx_state = DWC2_L0; /* Now back to On state */
3857                         break;
3858
3859                 case USB_PORT_FEAT_INDICATOR:
3860                         dev_dbg(hsotg->dev,
3861                                 "SetPortFeature - USB_PORT_FEAT_INDICATOR\n");
3862                         /* Not supported */
3863                         break;
3864
3865                 case USB_PORT_FEAT_TEST:
3866                         hprt0 = dwc2_read_hprt0(hsotg);
3867                         dev_dbg(hsotg->dev,
3868                                 "SetPortFeature - USB_PORT_FEAT_TEST\n");
3869                         hprt0 &= ~HPRT0_TSTCTL_MASK;
3870                         hprt0 |= (windex >> 8) << HPRT0_TSTCTL_SHIFT;
3871                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
3872                         break;
3873
3874                 default:
3875                         retval = -EINVAL;
3876                         dev_err(hsotg->dev,
3877                                 "SetPortFeature %1xh unknown or unsupported\n",
3878                                 wvalue);
3879                         break;
3880                 }
3881                 break;
3882
3883         default:
3884 error:
3885                 retval = -EINVAL;
3886                 dev_dbg(hsotg->dev,
3887                         "Unknown hub control request: %1xh wIndex: %1xh wValue: %1xh\n",
3888                         typereq, windex, wvalue);
3889                 break;
3890         }
3891
3892         return retval;
3893 }
3894
3895 static int dwc2_hcd_is_status_changed(struct dwc2_hsotg *hsotg, int port)
3896 {
3897         int retval;
3898
3899         if (port != 1)
3900                 return -EINVAL;
3901
3902         retval = (hsotg->flags.b.port_connect_status_change ||
3903                   hsotg->flags.b.port_reset_change ||
3904                   hsotg->flags.b.port_enable_change ||
3905                   hsotg->flags.b.port_suspend_change ||
3906                   hsotg->flags.b.port_over_current_change);
3907
3908         if (retval) {
3909                 dev_dbg(hsotg->dev,
3910                         "DWC OTG HCD HUB STATUS DATA: Root port status changed\n");
3911                 dev_dbg(hsotg->dev, "  port_connect_status_change: %d\n",
3912                         hsotg->flags.b.port_connect_status_change);
3913                 dev_dbg(hsotg->dev, "  port_reset_change: %d\n",
3914                         hsotg->flags.b.port_reset_change);
3915                 dev_dbg(hsotg->dev, "  port_enable_change: %d\n",
3916                         hsotg->flags.b.port_enable_change);
3917                 dev_dbg(hsotg->dev, "  port_suspend_change: %d\n",
3918                         hsotg->flags.b.port_suspend_change);
3919                 dev_dbg(hsotg->dev, "  port_over_current_change: %d\n",
3920                         hsotg->flags.b.port_over_current_change);
3921         }
3922
3923         return retval;
3924 }
3925
3926 int dwc2_hcd_get_frame_number(struct dwc2_hsotg *hsotg)
3927 {
3928         u32 hfnum = dwc2_readl(hsotg->regs + HFNUM);
3929
3930 #ifdef DWC2_DEBUG_SOF
3931         dev_vdbg(hsotg->dev, "DWC OTG HCD GET FRAME NUMBER %d\n",
3932                  (hfnum & HFNUM_FRNUM_MASK) >> HFNUM_FRNUM_SHIFT);
3933 #endif
3934         return (hfnum & HFNUM_FRNUM_MASK) >> HFNUM_FRNUM_SHIFT;
3935 }
3936
3937 int dwc2_hcd_get_future_frame_number(struct dwc2_hsotg *hsotg, int us)
3938 {
3939         u32 hprt = dwc2_readl(hsotg->regs + HPRT0);
3940         u32 hfir = dwc2_readl(hsotg->regs + HFIR);
3941         u32 hfnum = dwc2_readl(hsotg->regs + HFNUM);
3942         unsigned int us_per_frame;
3943         unsigned int frame_number;
3944         unsigned int remaining;
3945         unsigned int interval;
3946         unsigned int phy_clks;
3947
3948         /* High speed has 125 us per (micro) frame; others are 1 ms per */
3949         us_per_frame = (hprt & HPRT0_SPD_MASK) ? 1000 : 125;
3950
3951         /* Extract fields */
3952         frame_number = (hfnum & HFNUM_FRNUM_MASK) >> HFNUM_FRNUM_SHIFT;
3953         remaining = (hfnum & HFNUM_FRREM_MASK) >> HFNUM_FRREM_SHIFT;
3954         interval = (hfir & HFIR_FRINT_MASK) >> HFIR_FRINT_SHIFT;
3955
3956         /*
3957          * Number of phy clocks since the last tick of the frame number after
3958          * "us" has passed.
3959          */
3960         phy_clks = (interval - remaining) +
3961                    DIV_ROUND_UP(interval * us, us_per_frame);
3962
3963         return dwc2_frame_num_inc(frame_number, phy_clks / interval);
3964 }
3965
3966 int dwc2_hcd_is_b_host(struct dwc2_hsotg *hsotg)
3967 {
3968         return hsotg->op_state == OTG_STATE_B_HOST;
3969 }
3970
3971 static struct dwc2_hcd_urb *dwc2_hcd_urb_alloc(struct dwc2_hsotg *hsotg,
3972                                                int iso_desc_count,
3973                                                gfp_t mem_flags)
3974 {
3975         struct dwc2_hcd_urb *urb;
3976         u32 size = sizeof(*urb) + iso_desc_count *
3977                    sizeof(struct dwc2_hcd_iso_packet_desc);
3978
3979         urb = kzalloc(size, mem_flags);
3980         if (urb)
3981                 urb->packet_count = iso_desc_count;
3982         return urb;
3983 }
3984
3985 static void dwc2_hcd_urb_set_pipeinfo(struct dwc2_hsotg *hsotg,
3986                                       struct dwc2_hcd_urb *urb, u8 dev_addr,
3987                                       u8 ep_num, u8 ep_type, u8 ep_dir, u16 mps)
3988 {
3989         if (dbg_perio() ||
3990             ep_type == USB_ENDPOINT_XFER_BULK ||
3991             ep_type == USB_ENDPOINT_XFER_CONTROL)
3992                 dev_vdbg(hsotg->dev,
3993                          "addr=%d, ep_num=%d, ep_dir=%1x, ep_type=%1x, mps=%d\n",
3994                          dev_addr, ep_num, ep_dir, ep_type, mps);
3995         urb->pipe_info.dev_addr = dev_addr;
3996         urb->pipe_info.ep_num = ep_num;
3997         urb->pipe_info.pipe_type = ep_type;
3998         urb->pipe_info.pipe_dir = ep_dir;
3999         urb->pipe_info.mps = mps;
4000 }
4001
4002 /*
4003  * NOTE: This function will be removed once the peripheral controller code
4004  * is integrated and the driver is stable
4005  */
4006 void dwc2_hcd_dump_state(struct dwc2_hsotg *hsotg)
4007 {
4008 #ifdef DEBUG
4009         struct dwc2_host_chan *chan;
4010         struct dwc2_hcd_urb *urb;
4011         struct dwc2_qtd *qtd;
4012         int num_channels;
4013         u32 np_tx_status;
4014         u32 p_tx_status;
4015         int i;
4016
4017         num_channels = hsotg->params.host_channels;
4018         dev_dbg(hsotg->dev, "\n");
4019         dev_dbg(hsotg->dev,
4020                 "************************************************************\n");
4021         dev_dbg(hsotg->dev, "HCD State:\n");
4022         dev_dbg(hsotg->dev, "  Num channels: %d\n", num_channels);
4023
4024         for (i = 0; i < num_channels; i++) {
4025                 chan = hsotg->hc_ptr_array[i];
4026                 dev_dbg(hsotg->dev, "  Channel %d:\n", i);
4027                 dev_dbg(hsotg->dev,
4028                         "    dev_addr: %d, ep_num: %d, ep_is_in: %d\n",
4029                         chan->dev_addr, chan->ep_num, chan->ep_is_in);
4030                 dev_dbg(hsotg->dev, "    speed: %d\n", chan->speed);
4031                 dev_dbg(hsotg->dev, "    ep_type: %d\n", chan->ep_type);
4032                 dev_dbg(hsotg->dev, "    max_packet: %d\n", chan->max_packet);
4033                 dev_dbg(hsotg->dev, "    data_pid_start: %d\n",
4034                         chan->data_pid_start);
4035                 dev_dbg(hsotg->dev, "    multi_count: %d\n", chan->multi_count);
4036                 dev_dbg(hsotg->dev, "    xfer_started: %d\n",
4037                         chan->xfer_started);
4038                 dev_dbg(hsotg->dev, "    xfer_buf: %p\n", chan->xfer_buf);
4039                 dev_dbg(hsotg->dev, "    xfer_dma: %08lx\n",
4040                         (unsigned long)chan->xfer_dma);
4041                 dev_dbg(hsotg->dev, "    xfer_len: %d\n", chan->xfer_len);
4042                 dev_dbg(hsotg->dev, "    xfer_count: %d\n", chan->xfer_count);
4043                 dev_dbg(hsotg->dev, "    halt_on_queue: %d\n",
4044                         chan->halt_on_queue);
4045                 dev_dbg(hsotg->dev, "    halt_pending: %d\n",
4046                         chan->halt_pending);
4047                 dev_dbg(hsotg->dev, "    halt_status: %d\n", chan->halt_status);
4048                 dev_dbg(hsotg->dev, "    do_split: %d\n", chan->do_split);
4049                 dev_dbg(hsotg->dev, "    complete_split: %d\n",
4050                         chan->complete_split);
4051                 dev_dbg(hsotg->dev, "    hub_addr: %d\n", chan->hub_addr);
4052                 dev_dbg(hsotg->dev, "    hub_port: %d\n", chan->hub_port);
4053                 dev_dbg(hsotg->dev, "    xact_pos: %d\n", chan->xact_pos);
4054                 dev_dbg(hsotg->dev, "    requests: %d\n", chan->requests);
4055                 dev_dbg(hsotg->dev, "    qh: %p\n", chan->qh);
4056
4057                 if (chan->xfer_started) {
4058                         u32 hfnum, hcchar, hctsiz, hcint, hcintmsk;
4059
4060                         hfnum = dwc2_readl(hsotg->regs + HFNUM);
4061                         hcchar = dwc2_readl(hsotg->regs + HCCHAR(i));
4062                         hctsiz = dwc2_readl(hsotg->regs + HCTSIZ(i));
4063                         hcint = dwc2_readl(hsotg->regs + HCINT(i));
4064                         hcintmsk = dwc2_readl(hsotg->regs + HCINTMSK(i));
4065                         dev_dbg(hsotg->dev, "    hfnum: 0x%08x\n", hfnum);
4066                         dev_dbg(hsotg->dev, "    hcchar: 0x%08x\n", hcchar);
4067                         dev_dbg(hsotg->dev, "    hctsiz: 0x%08x\n", hctsiz);
4068                         dev_dbg(hsotg->dev, "    hcint: 0x%08x\n", hcint);
4069                         dev_dbg(hsotg->dev, "    hcintmsk: 0x%08x\n", hcintmsk);
4070                 }
4071
4072                 if (!(chan->xfer_started && chan->qh))
4073                         continue;
4074
4075                 list_for_each_entry(qtd, &chan->qh->qtd_list, qtd_list_entry) {
4076                         if (!qtd->in_process)
4077                                 break;
4078                         urb = qtd->urb;
4079                         dev_dbg(hsotg->dev, "    URB Info:\n");
4080                         dev_dbg(hsotg->dev, "      qtd: %p, urb: %p\n",
4081                                 qtd, urb);
4082                         if (urb) {
4083                                 dev_dbg(hsotg->dev,
4084                                         "      Dev: %d, EP: %d %s\n",
4085                                         dwc2_hcd_get_dev_addr(&urb->pipe_info),
4086                                         dwc2_hcd_get_ep_num(&urb->pipe_info),
4087                                         dwc2_hcd_is_pipe_in(&urb->pipe_info) ?
4088                                         "IN" : "OUT");
4089                                 dev_dbg(hsotg->dev,
4090                                         "      Max packet size: %d\n",
4091                                         dwc2_hcd_get_mps(&urb->pipe_info));
4092                                 dev_dbg(hsotg->dev,
4093                                         "      transfer_buffer: %p\n",
4094                                         urb->buf);
4095                                 dev_dbg(hsotg->dev,
4096                                         "      transfer_dma: %08lx\n",
4097                                         (unsigned long)urb->dma);
4098                                 dev_dbg(hsotg->dev,
4099                                         "      transfer_buffer_length: %d\n",
4100                                         urb->length);
4101                                 dev_dbg(hsotg->dev, "      actual_length: %d\n",
4102                                         urb->actual_length);
4103                         }
4104                 }
4105         }
4106
4107         dev_dbg(hsotg->dev, "  non_periodic_channels: %d\n",
4108                 hsotg->non_periodic_channels);
4109         dev_dbg(hsotg->dev, "  periodic_channels: %d\n",
4110                 hsotg->periodic_channels);
4111         dev_dbg(hsotg->dev, "  periodic_usecs: %d\n", hsotg->periodic_usecs);
4112         np_tx_status = dwc2_readl(hsotg->regs + GNPTXSTS);
4113         dev_dbg(hsotg->dev, "  NP Tx Req Queue Space Avail: %d\n",
4114                 (np_tx_status & TXSTS_QSPCAVAIL_MASK) >> TXSTS_QSPCAVAIL_SHIFT);
4115         dev_dbg(hsotg->dev, "  NP Tx FIFO Space Avail: %d\n",
4116                 (np_tx_status & TXSTS_FSPCAVAIL_MASK) >> TXSTS_FSPCAVAIL_SHIFT);
4117         p_tx_status = dwc2_readl(hsotg->regs + HPTXSTS);
4118         dev_dbg(hsotg->dev, "  P Tx Req Queue Space Avail: %d\n",
4119                 (p_tx_status & TXSTS_QSPCAVAIL_MASK) >> TXSTS_QSPCAVAIL_SHIFT);
4120         dev_dbg(hsotg->dev, "  P Tx FIFO Space Avail: %d\n",
4121                 (p_tx_status & TXSTS_FSPCAVAIL_MASK) >> TXSTS_FSPCAVAIL_SHIFT);
4122         dwc2_dump_global_registers(hsotg);
4123         dwc2_dump_host_registers(hsotg);
4124         dev_dbg(hsotg->dev,
4125                 "************************************************************\n");
4126         dev_dbg(hsotg->dev, "\n");
4127 #endif
4128 }
4129
4130 struct wrapper_priv_data {
4131         struct dwc2_hsotg *hsotg;
4132 };
4133
4134 /* Gets the dwc2_hsotg from a usb_hcd */
4135 static struct dwc2_hsotg *dwc2_hcd_to_hsotg(struct usb_hcd *hcd)
4136 {
4137         struct wrapper_priv_data *p;
4138
4139         p = (struct wrapper_priv_data *)&hcd->hcd_priv;
4140         return p->hsotg;
4141 }
4142
4143 /**
4144  * dwc2_host_get_tt_info() - Get the dwc2_tt associated with context
4145  *
4146  * This will get the dwc2_tt structure (and ttport) associated with the given
4147  * context (which is really just a struct urb pointer).
4148  *
4149  * The first time this is called for a given TT we allocate memory for our
4150  * structure.  When everyone is done and has called dwc2_host_put_tt_info()
4151  * then the refcount for the structure will go to 0 and we'll free it.
4152  *
4153  * @hsotg:     The HCD state structure for the DWC OTG controller.
4154  * @context:   The priv pointer from a struct dwc2_hcd_urb.
4155  * @mem_flags: Flags for allocating memory.
4156  * @ttport:    We'll return this device's port number here.  That's used to
4157  *             reference into the bitmap if we're on a multi_tt hub.
4158  *
4159  * Return: a pointer to a struct dwc2_tt.  Don't forget to call
4160  *         dwc2_host_put_tt_info()!  Returns NULL upon memory alloc failure.
4161  */
4162
4163 struct dwc2_tt *dwc2_host_get_tt_info(struct dwc2_hsotg *hsotg, void *context,
4164                                       gfp_t mem_flags, int *ttport)
4165 {
4166         struct urb *urb = context;
4167         struct dwc2_tt *dwc_tt = NULL;
4168
4169         if (urb->dev->tt) {
4170                 *ttport = urb->dev->ttport;
4171
4172                 dwc_tt = urb->dev->tt->hcpriv;
4173                 if (!dwc_tt) {
4174                         size_t bitmap_size;
4175
4176                         /*
4177                          * For single_tt we need one schedule.  For multi_tt
4178                          * we need one per port.
4179                          */
4180                         bitmap_size = DWC2_ELEMENTS_PER_LS_BITMAP *
4181                                       sizeof(dwc_tt->periodic_bitmaps[0]);
4182                         if (urb->dev->tt->multi)
4183                                 bitmap_size *= urb->dev->tt->hub->maxchild;
4184
4185                         dwc_tt = kzalloc(sizeof(*dwc_tt) + bitmap_size,
4186                                          mem_flags);
4187                         if (!dwc_tt)
4188                                 return NULL;
4189
4190                         dwc_tt->usb_tt = urb->dev->tt;
4191                         dwc_tt->usb_tt->hcpriv = dwc_tt;
4192                 }
4193
4194                 dwc_tt->refcount++;
4195         }
4196
4197         return dwc_tt;
4198 }
4199
4200 /**
4201  * dwc2_host_put_tt_info() - Put the dwc2_tt from dwc2_host_get_tt_info()
4202  *
4203  * Frees resources allocated by dwc2_host_get_tt_info() if all current holders
4204  * of the structure are done.
4205  *
4206  * It's OK to call this with NULL.
4207  *
4208  * @hsotg:     The HCD state structure for the DWC OTG controller.
4209  * @dwc_tt:    The pointer returned by dwc2_host_get_tt_info.
4210  */
4211 void dwc2_host_put_tt_info(struct dwc2_hsotg *hsotg, struct dwc2_tt *dwc_tt)
4212 {
4213         /* Model kfree and make put of NULL a no-op */
4214         if (!dwc_tt)
4215                 return;
4216
4217         WARN_ON(dwc_tt->refcount < 1);
4218
4219         dwc_tt->refcount--;
4220         if (!dwc_tt->refcount) {
4221                 dwc_tt->usb_tt->hcpriv = NULL;
4222                 kfree(dwc_tt);
4223         }
4224 }
4225
4226 int dwc2_host_get_speed(struct dwc2_hsotg *hsotg, void *context)
4227 {
4228         struct urb *urb = context;
4229
4230         return urb->dev->speed;
4231 }
4232
4233 static void dwc2_allocate_bus_bandwidth(struct usb_hcd *hcd, u16 bw,
4234                                         struct urb *urb)
4235 {
4236         struct usb_bus *bus = hcd_to_bus(hcd);
4237
4238         if (urb->interval)
4239                 bus->bandwidth_allocated += bw / urb->interval;
4240         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS)
4241                 bus->bandwidth_isoc_reqs++;
4242         else
4243                 bus->bandwidth_int_reqs++;
4244 }
4245
4246 static void dwc2_free_bus_bandwidth(struct usb_hcd *hcd, u16 bw,
4247                                     struct urb *urb)
4248 {
4249         struct usb_bus *bus = hcd_to_bus(hcd);
4250
4251         if (urb->interval)
4252                 bus->bandwidth_allocated -= bw / urb->interval;
4253         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS)
4254                 bus->bandwidth_isoc_reqs--;
4255         else
4256                 bus->bandwidth_int_reqs--;
4257 }
4258
4259 /*
4260  * Sets the final status of an URB and returns it to the upper layer. Any
4261  * required cleanup of the URB is performed.
4262  *
4263  * Must be called with interrupt disabled and spinlock held
4264  */
4265 void dwc2_host_complete(struct dwc2_hsotg *hsotg, struct dwc2_qtd *qtd,
4266                         int status)
4267 {
4268         struct urb *urb;
4269         int i;
4270
4271         if (!qtd) {
4272                 dev_dbg(hsotg->dev, "## %s: qtd is NULL ##\n", __func__);
4273                 return;
4274         }
4275
4276         if (!qtd->urb) {
4277                 dev_dbg(hsotg->dev, "## %s: qtd->urb is NULL ##\n", __func__);
4278                 return;
4279         }
4280
4281         urb = qtd->urb->priv;
4282         if (!urb) {
4283                 dev_dbg(hsotg->dev, "## %s: urb->priv is NULL ##\n", __func__);
4284                 return;
4285         }
4286
4287         urb->actual_length = dwc2_hcd_urb_get_actual_length(qtd->urb);
4288
4289         if (dbg_urb(urb))
4290                 dev_vdbg(hsotg->dev,
4291                          "%s: urb %p device %d ep %d-%s status %d actual %d\n",
4292                          __func__, urb, usb_pipedevice(urb->pipe),
4293                          usb_pipeendpoint(urb->pipe),
4294                          usb_pipein(urb->pipe) ? "IN" : "OUT", status,
4295                          urb->actual_length);
4296
4297         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) {
4298                 urb->error_count = dwc2_hcd_urb_get_error_count(qtd->urb);
4299                 for (i = 0; i < urb->number_of_packets; ++i) {
4300                         urb->iso_frame_desc[i].actual_length =
4301                                 dwc2_hcd_urb_get_iso_desc_actual_length(
4302                                                 qtd->urb, i);
4303                         urb->iso_frame_desc[i].status =
4304                                 dwc2_hcd_urb_get_iso_desc_status(qtd->urb, i);
4305                 }
4306         }
4307
4308         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS && dbg_perio()) {
4309                 for (i = 0; i < urb->number_of_packets; i++)
4310                         dev_vdbg(hsotg->dev, " ISO Desc %d status %d\n",
4311                                  i, urb->iso_frame_desc[i].status);
4312         }
4313
4314         urb->status = status;
4315         if (!status) {
4316                 if ((urb->transfer_flags & URB_SHORT_NOT_OK) &&
4317                     urb->actual_length < urb->transfer_buffer_length)
4318                         urb->status = -EREMOTEIO;
4319         }
4320
4321         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS ||
4322             usb_pipetype(urb->pipe) == PIPE_INTERRUPT) {
4323                 struct usb_host_endpoint *ep = urb->ep;
4324
4325                 if (ep)
4326                         dwc2_free_bus_bandwidth(dwc2_hsotg_to_hcd(hsotg),
4327                                         dwc2_hcd_get_ep_bandwidth(hsotg, ep),
4328                                         urb);
4329         }
4330
4331         usb_hcd_unlink_urb_from_ep(dwc2_hsotg_to_hcd(hsotg), urb);
4332         urb->hcpriv = NULL;
4333         kfree(qtd->urb);
4334         qtd->urb = NULL;
4335
4336         usb_hcd_giveback_urb(dwc2_hsotg_to_hcd(hsotg), urb, status);
4337 }
4338
4339 /*
4340  * Work queue function for starting the HCD when A-Cable is connected
4341  */
4342 static void dwc2_hcd_start_func(struct work_struct *work)
4343 {
4344         struct dwc2_hsotg *hsotg = container_of(work, struct dwc2_hsotg,
4345                                                 start_work.work);
4346
4347         dev_dbg(hsotg->dev, "%s() %p\n", __func__, hsotg);
4348         dwc2_host_start(hsotg);
4349 }
4350
4351 /*
4352  * Reset work queue function
4353  */
4354 static void dwc2_hcd_reset_func(struct work_struct *work)
4355 {
4356         struct dwc2_hsotg *hsotg = container_of(work, struct dwc2_hsotg,
4357                                                 reset_work.work);
4358         unsigned long flags;
4359         u32 hprt0;
4360
4361         dev_dbg(hsotg->dev, "USB RESET function called\n");
4362
4363         spin_lock_irqsave(&hsotg->lock, flags);
4364
4365         hprt0 = dwc2_read_hprt0(hsotg);
4366         hprt0 &= ~HPRT0_RST;
4367         dwc2_writel(hprt0, hsotg->regs + HPRT0);
4368         hsotg->flags.b.port_reset_change = 1;
4369
4370         spin_unlock_irqrestore(&hsotg->lock, flags);
4371 }
4372
4373 /*
4374  * =========================================================================
4375  *  Linux HC Driver Functions
4376  * =========================================================================
4377  */
4378
4379 /*
4380  * Initializes the DWC_otg controller and its root hub and prepares it for host
4381  * mode operation. Activates the root port. Returns 0 on success and a negative
4382  * error code on failure.
4383  */
4384 static int _dwc2_hcd_start(struct usb_hcd *hcd)
4385 {
4386         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4387         struct usb_bus *bus = hcd_to_bus(hcd);
4388         unsigned long flags;
4389
4390         dev_dbg(hsotg->dev, "DWC OTG HCD START\n");
4391
4392         spin_lock_irqsave(&hsotg->lock, flags);
4393         hsotg->lx_state = DWC2_L0;
4394         hcd->state = HC_STATE_RUNNING;
4395         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
4396
4397         if (dwc2_is_device_mode(hsotg)) {
4398                 spin_unlock_irqrestore(&hsotg->lock, flags);
4399                 return 0;       /* why 0 ?? */
4400         }
4401
4402         dwc2_hcd_reinit(hsotg);
4403
4404         /* Initialize and connect root hub if one is not already attached */
4405         if (bus->root_hub) {
4406                 dev_dbg(hsotg->dev, "DWC OTG HCD Has Root Hub\n");
4407                 /* Inform the HUB driver to resume */
4408                 usb_hcd_resume_root_hub(hcd);
4409         }
4410
4411         spin_unlock_irqrestore(&hsotg->lock, flags);
4412
4413         return dwc2_vbus_supply_init(hsotg);
4414 }
4415
4416 /*
4417  * Halts the DWC_otg host mode operations in a clean manner. USB transfers are
4418  * stopped.
4419  */
4420 static void _dwc2_hcd_stop(struct usb_hcd *hcd)
4421 {
4422         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4423         unsigned long flags;
4424
4425         /* Turn off all host-specific interrupts */
4426         dwc2_disable_host_interrupts(hsotg);
4427
4428         /* Wait for interrupt processing to finish */
4429         synchronize_irq(hcd->irq);
4430
4431         spin_lock_irqsave(&hsotg->lock, flags);
4432         /* Ensure hcd is disconnected */
4433         dwc2_hcd_disconnect(hsotg, true);
4434         dwc2_hcd_stop(hsotg);
4435         hsotg->lx_state = DWC2_L3;
4436         hcd->state = HC_STATE_HALT;
4437         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
4438         spin_unlock_irqrestore(&hsotg->lock, flags);
4439
4440         dwc2_vbus_supply_exit(hsotg);
4441
4442         usleep_range(1000, 3000);
4443 }
4444
4445 static int _dwc2_hcd_suspend(struct usb_hcd *hcd)
4446 {
4447         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4448         unsigned long flags;
4449         int ret = 0;
4450         u32 hprt0;
4451
4452         spin_lock_irqsave(&hsotg->lock, flags);
4453
4454         if (dwc2_is_device_mode(hsotg))
4455                 goto unlock;
4456
4457         if (hsotg->lx_state != DWC2_L0)
4458                 goto unlock;
4459
4460         if (!HCD_HW_ACCESSIBLE(hcd))
4461                 goto unlock;
4462
4463         if (hsotg->op_state == OTG_STATE_B_PERIPHERAL)
4464                 goto unlock;
4465
4466         if (hsotg->params.power_down != DWC2_POWER_DOWN_PARAM_PARTIAL)
4467                 goto skip_power_saving;
4468
4469         /*
4470          * Drive USB suspend and disable port Power
4471          * if usb bus is not suspended.
4472          */
4473         if (!hsotg->bus_suspended) {
4474                 hprt0 = dwc2_read_hprt0(hsotg);
4475                 hprt0 |= HPRT0_SUSP;
4476                 hprt0 &= ~HPRT0_PWR;
4477                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
4478                 dwc2_vbus_supply_exit(hsotg);
4479         }
4480
4481         /* Enter partial_power_down */
4482         ret = dwc2_enter_partial_power_down(hsotg);
4483         if (ret) {
4484                 if (ret != -ENOTSUPP)
4485                         dev_err(hsotg->dev,
4486                                 "enter partial_power_down failed\n");
4487                 goto skip_power_saving;
4488         }
4489
4490         /* Ask phy to be suspended */
4491         if (!IS_ERR_OR_NULL(hsotg->uphy)) {
4492                 spin_unlock_irqrestore(&hsotg->lock, flags);
4493                 usb_phy_set_suspend(hsotg->uphy, true);
4494                 spin_lock_irqsave(&hsotg->lock, flags);
4495         }
4496
4497         /* After entering partial_power_down, hardware is no more accessible */
4498         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
4499
4500 skip_power_saving:
4501         hsotg->lx_state = DWC2_L2;
4502 unlock:
4503         spin_unlock_irqrestore(&hsotg->lock, flags);
4504
4505         return ret;
4506 }
4507
4508 static int _dwc2_hcd_resume(struct usb_hcd *hcd)
4509 {
4510         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4511         unsigned long flags;
4512         int ret = 0;
4513
4514         spin_lock_irqsave(&hsotg->lock, flags);
4515
4516         if (dwc2_is_device_mode(hsotg))
4517                 goto unlock;
4518
4519         if (hsotg->lx_state != DWC2_L2)
4520                 goto unlock;
4521
4522         if (hsotg->params.power_down != DWC2_POWER_DOWN_PARAM_PARTIAL) {
4523                 hsotg->lx_state = DWC2_L0;
4524                 goto unlock;
4525         }
4526
4527         /*
4528          * Set HW accessible bit before powering on the controller
4529          * since an interrupt may rise.
4530          */
4531         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
4532
4533         /*
4534          * Enable power if not already done.
4535          * This must not be spinlocked since duration
4536          * of this call is unknown.
4537          */
4538         if (!IS_ERR_OR_NULL(hsotg->uphy)) {
4539                 spin_unlock_irqrestore(&hsotg->lock, flags);
4540                 usb_phy_set_suspend(hsotg->uphy, false);
4541                 spin_lock_irqsave(&hsotg->lock, flags);
4542         }
4543
4544         /* Exit partial_power_down */
4545         ret = dwc2_exit_partial_power_down(hsotg, true);
4546         if (ret && (ret != -ENOTSUPP))
4547                 dev_err(hsotg->dev, "exit partial_power_down failed\n");
4548
4549         hsotg->lx_state = DWC2_L0;
4550
4551         spin_unlock_irqrestore(&hsotg->lock, flags);
4552
4553         if (hsotg->bus_suspended) {
4554                 spin_lock_irqsave(&hsotg->lock, flags);
4555                 hsotg->flags.b.port_suspend_change = 1;
4556                 spin_unlock_irqrestore(&hsotg->lock, flags);
4557                 dwc2_port_resume(hsotg);
4558         } else {
4559                 dwc2_vbus_supply_init(hsotg);
4560
4561                 /* Wait for controller to correctly update D+/D- level */
4562                 usleep_range(3000, 5000);
4563
4564                 /*
4565                  * Clear Port Enable and Port Status changes.
4566                  * Enable Port Power.
4567                  */
4568                 dwc2_writel(HPRT0_PWR | HPRT0_CONNDET |
4569                                 HPRT0_ENACHG, hsotg->regs + HPRT0);
4570                 /* Wait for controller to detect Port Connect */
4571                 usleep_range(5000, 7000);
4572         }
4573
4574         return ret;
4575 unlock:
4576         spin_unlock_irqrestore(&hsotg->lock, flags);
4577
4578         return ret;
4579 }
4580
4581 /* Returns the current frame number */
4582 static int _dwc2_hcd_get_frame_number(struct usb_hcd *hcd)
4583 {
4584         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4585
4586         return dwc2_hcd_get_frame_number(hsotg);
4587 }
4588
4589 static void dwc2_dump_urb_info(struct usb_hcd *hcd, struct urb *urb,
4590                                char *fn_name)
4591 {
4592 #ifdef VERBOSE_DEBUG
4593         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4594         char *pipetype = NULL;
4595         char *speed = NULL;
4596
4597         dev_vdbg(hsotg->dev, "%s, urb %p\n", fn_name, urb);
4598         dev_vdbg(hsotg->dev, "  Device address: %d\n",
4599                  usb_pipedevice(urb->pipe));
4600         dev_vdbg(hsotg->dev, "  Endpoint: %d, %s\n",
4601                  usb_pipeendpoint(urb->pipe),
4602                  usb_pipein(urb->pipe) ? "IN" : "OUT");
4603
4604         switch (usb_pipetype(urb->pipe)) {
4605         case PIPE_CONTROL:
4606                 pipetype = "CONTROL";
4607                 break;
4608         case PIPE_BULK:
4609                 pipetype = "BULK";
4610                 break;
4611         case PIPE_INTERRUPT:
4612                 pipetype = "INTERRUPT";
4613                 break;
4614         case PIPE_ISOCHRONOUS:
4615                 pipetype = "ISOCHRONOUS";
4616                 break;
4617         }
4618
4619         dev_vdbg(hsotg->dev, "  Endpoint type: %s %s (%s)\n", pipetype,
4620                  usb_urb_dir_in(urb) ? "IN" : "OUT", usb_pipein(urb->pipe) ?
4621                  "IN" : "OUT");
4622
4623         switch (urb->dev->speed) {
4624         case USB_SPEED_HIGH:
4625                 speed = "HIGH";
4626                 break;
4627         case USB_SPEED_FULL:
4628                 speed = "FULL";
4629                 break;
4630         case USB_SPEED_LOW:
4631                 speed = "LOW";
4632                 break;
4633         default:
4634                 speed = "UNKNOWN";
4635                 break;
4636         }
4637
4638         dev_vdbg(hsotg->dev, "  Speed: %s\n", speed);
4639         dev_vdbg(hsotg->dev, "  Max packet size: %d\n",
4640                  usb_maxpacket(urb->dev, urb->pipe, usb_pipeout(urb->pipe)));
4641         dev_vdbg(hsotg->dev, "  Data buffer length: %d\n",
4642                  urb->transfer_buffer_length);
4643         dev_vdbg(hsotg->dev, "  Transfer buffer: %p, Transfer DMA: %08lx\n",
4644                  urb->transfer_buffer, (unsigned long)urb->transfer_dma);
4645         dev_vdbg(hsotg->dev, "  Setup buffer: %p, Setup DMA: %08lx\n",
4646                  urb->setup_packet, (unsigned long)urb->setup_dma);
4647         dev_vdbg(hsotg->dev, "  Interval: %d\n", urb->interval);
4648
4649         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) {
4650                 int i;
4651
4652                 for (i = 0; i < urb->number_of_packets; i++) {
4653                         dev_vdbg(hsotg->dev, "  ISO Desc %d:\n", i);
4654                         dev_vdbg(hsotg->dev, "    offset: %d, length %d\n",
4655                                  urb->iso_frame_desc[i].offset,
4656                                  urb->iso_frame_desc[i].length);
4657                 }
4658         }
4659 #endif
4660 }
4661
4662 /*
4663  * Starts processing a USB transfer request specified by a USB Request Block
4664  * (URB). mem_flags indicates the type of memory allocation to use while
4665  * processing this URB.
4666  */
4667 static int _dwc2_hcd_urb_enqueue(struct usb_hcd *hcd, struct urb *urb,
4668                                  gfp_t mem_flags)
4669 {
4670         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4671         struct usb_host_endpoint *ep = urb->ep;
4672         struct dwc2_hcd_urb *dwc2_urb;
4673         int i;
4674         int retval;
4675         int alloc_bandwidth = 0;
4676         u8 ep_type = 0;
4677         u32 tflags = 0;
4678         void *buf;
4679         unsigned long flags;
4680         struct dwc2_qh *qh;
4681         bool qh_allocated = false;
4682         struct dwc2_qtd *qtd;
4683
4684         if (dbg_urb(urb)) {
4685                 dev_vdbg(hsotg->dev, "DWC OTG HCD URB Enqueue\n");
4686                 dwc2_dump_urb_info(hcd, urb, "urb_enqueue");
4687         }
4688
4689         if (!ep)
4690                 return -EINVAL;
4691
4692         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS ||
4693             usb_pipetype(urb->pipe) == PIPE_INTERRUPT) {
4694                 spin_lock_irqsave(&hsotg->lock, flags);
4695                 if (!dwc2_hcd_is_bandwidth_allocated(hsotg, ep))
4696                         alloc_bandwidth = 1;
4697                 spin_unlock_irqrestore(&hsotg->lock, flags);
4698         }
4699
4700         switch (usb_pipetype(urb->pipe)) {
4701         case PIPE_CONTROL:
4702                 ep_type = USB_ENDPOINT_XFER_CONTROL;
4703                 break;
4704         case PIPE_ISOCHRONOUS:
4705                 ep_type = USB_ENDPOINT_XFER_ISOC;
4706                 break;
4707         case PIPE_BULK:
4708                 ep_type = USB_ENDPOINT_XFER_BULK;
4709                 break;
4710         case PIPE_INTERRUPT:
4711                 ep_type = USB_ENDPOINT_XFER_INT;
4712                 break;
4713         }
4714
4715         dwc2_urb = dwc2_hcd_urb_alloc(hsotg, urb->number_of_packets,
4716                                       mem_flags);
4717         if (!dwc2_urb)
4718                 return -ENOMEM;
4719
4720         dwc2_hcd_urb_set_pipeinfo(hsotg, dwc2_urb, usb_pipedevice(urb->pipe),
4721                                   usb_pipeendpoint(urb->pipe), ep_type,
4722                                   usb_pipein(urb->pipe),
4723                                   usb_maxpacket(urb->dev, urb->pipe,
4724                                                 !(usb_pipein(urb->pipe))));
4725
4726         buf = urb->transfer_buffer;
4727
4728         if (hcd->self.uses_dma) {
4729                 if (!buf && (urb->transfer_dma & 3)) {
4730                         dev_err(hsotg->dev,
4731                                 "%s: unaligned transfer with no transfer_buffer",
4732                                 __func__);
4733                         retval = -EINVAL;
4734                         goto fail0;
4735                 }
4736         }
4737
4738         if (!(urb->transfer_flags & URB_NO_INTERRUPT))
4739                 tflags |= URB_GIVEBACK_ASAP;
4740         if (urb->transfer_flags & URB_ZERO_PACKET)
4741                 tflags |= URB_SEND_ZERO_PACKET;
4742
4743         dwc2_urb->priv = urb;
4744         dwc2_urb->buf = buf;
4745         dwc2_urb->dma = urb->transfer_dma;
4746         dwc2_urb->length = urb->transfer_buffer_length;
4747         dwc2_urb->setup_packet = urb->setup_packet;
4748         dwc2_urb->setup_dma = urb->setup_dma;
4749         dwc2_urb->flags = tflags;
4750         dwc2_urb->interval = urb->interval;
4751         dwc2_urb->status = -EINPROGRESS;
4752
4753         for (i = 0; i < urb->number_of_packets; ++i)
4754                 dwc2_hcd_urb_set_iso_desc_params(dwc2_urb, i,
4755                                                  urb->iso_frame_desc[i].offset,
4756                                                  urb->iso_frame_desc[i].length);
4757
4758         urb->hcpriv = dwc2_urb;
4759         qh = (struct dwc2_qh *)ep->hcpriv;
4760         /* Create QH for the endpoint if it doesn't exist */
4761         if (!qh) {
4762                 qh = dwc2_hcd_qh_create(hsotg, dwc2_urb, mem_flags);
4763                 if (!qh) {
4764                         retval = -ENOMEM;
4765                         goto fail0;
4766                 }
4767                 ep->hcpriv = qh;
4768                 qh_allocated = true;
4769         }
4770
4771         qtd = kzalloc(sizeof(*qtd), mem_flags);
4772         if (!qtd) {
4773                 retval = -ENOMEM;
4774                 goto fail1;
4775         }
4776
4777         spin_lock_irqsave(&hsotg->lock, flags);
4778         retval = usb_hcd_link_urb_to_ep(hcd, urb);
4779         if (retval)
4780                 goto fail2;
4781
4782         retval = dwc2_hcd_urb_enqueue(hsotg, dwc2_urb, qh, qtd);
4783         if (retval)
4784                 goto fail3;
4785
4786         if (alloc_bandwidth) {
4787                 dwc2_allocate_bus_bandwidth(hcd,
4788                                 dwc2_hcd_get_ep_bandwidth(hsotg, ep),
4789                                 urb);
4790         }
4791
4792         spin_unlock_irqrestore(&hsotg->lock, flags);
4793
4794         return 0;
4795
4796 fail3:
4797         dwc2_urb->priv = NULL;
4798         usb_hcd_unlink_urb_from_ep(hcd, urb);
4799         if (qh_allocated && qh->channel && qh->channel->qh == qh)
4800                 qh->channel->qh = NULL;
4801 fail2:
4802         spin_unlock_irqrestore(&hsotg->lock, flags);
4803         urb->hcpriv = NULL;
4804         kfree(qtd);
4805         qtd = NULL;
4806 fail1:
4807         if (qh_allocated) {
4808                 struct dwc2_qtd *qtd2, *qtd2_tmp;
4809
4810                 ep->hcpriv = NULL;
4811                 dwc2_hcd_qh_unlink(hsotg, qh);
4812                 /* Free each QTD in the QH's QTD list */
4813                 list_for_each_entry_safe(qtd2, qtd2_tmp, &qh->qtd_list,
4814                                          qtd_list_entry)
4815                         dwc2_hcd_qtd_unlink_and_free(hsotg, qtd2, qh);
4816                 dwc2_hcd_qh_free(hsotg, qh);
4817         }
4818 fail0:
4819         kfree(dwc2_urb);
4820
4821         return retval;
4822 }
4823
4824 /*
4825  * Aborts/cancels a USB transfer request. Always returns 0 to indicate success.
4826  */
4827 static int _dwc2_hcd_urb_dequeue(struct usb_hcd *hcd, struct urb *urb,
4828                                  int status)
4829 {
4830         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4831         int rc;
4832         unsigned long flags;
4833
4834         dev_dbg(hsotg->dev, "DWC OTG HCD URB Dequeue\n");
4835         dwc2_dump_urb_info(hcd, urb, "urb_dequeue");
4836
4837         spin_lock_irqsave(&hsotg->lock, flags);
4838
4839         rc = usb_hcd_check_unlink_urb(hcd, urb, status);
4840         if (rc)
4841                 goto out;
4842
4843         if (!urb->hcpriv) {
4844                 dev_dbg(hsotg->dev, "## urb->hcpriv is NULL ##\n");
4845                 goto out;
4846         }
4847
4848         rc = dwc2_hcd_urb_dequeue(hsotg, urb->hcpriv);
4849
4850         usb_hcd_unlink_urb_from_ep(hcd, urb);
4851
4852         kfree(urb->hcpriv);
4853         urb->hcpriv = NULL;
4854
4855         /* Higher layer software sets URB status */
4856         spin_unlock(&hsotg->lock);
4857         usb_hcd_giveback_urb(hcd, urb, status);
4858         spin_lock(&hsotg->lock);
4859
4860         dev_dbg(hsotg->dev, "Called usb_hcd_giveback_urb()\n");
4861         dev_dbg(hsotg->dev, "  urb->status = %d\n", urb->status);
4862 out:
4863         spin_unlock_irqrestore(&hsotg->lock, flags);
4864
4865         return rc;
4866 }
4867
4868 /*
4869  * Frees resources in the DWC_otg controller related to a given endpoint. Also
4870  * clears state in the HCD related to the endpoint. Any URBs for the endpoint
4871  * must already be dequeued.
4872  */
4873 static void _dwc2_hcd_endpoint_disable(struct usb_hcd *hcd,
4874                                        struct usb_host_endpoint *ep)
4875 {
4876         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4877
4878         dev_dbg(hsotg->dev,
4879                 "DWC OTG HCD EP DISABLE: bEndpointAddress=0x%02x, ep->hcpriv=%p\n",
4880                 ep->desc.bEndpointAddress, ep->hcpriv);
4881         dwc2_hcd_endpoint_disable(hsotg, ep, 250);
4882 }
4883
4884 /*
4885  * Resets endpoint specific parameter values, in current version used to reset
4886  * the data toggle (as a WA). This function can be called from usb_clear_halt
4887  * routine.
4888  */
4889 static void _dwc2_hcd_endpoint_reset(struct usb_hcd *hcd,
4890                                      struct usb_host_endpoint *ep)
4891 {
4892         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4893         unsigned long flags;
4894
4895         dev_dbg(hsotg->dev,
4896                 "DWC OTG HCD EP RESET: bEndpointAddress=0x%02x\n",
4897                 ep->desc.bEndpointAddress);
4898
4899         spin_lock_irqsave(&hsotg->lock, flags);
4900         dwc2_hcd_endpoint_reset(hsotg, ep);
4901         spin_unlock_irqrestore(&hsotg->lock, flags);
4902 }
4903
4904 /*
4905  * Handles host mode interrupts for the DWC_otg controller. Returns IRQ_NONE if
4906  * there was no interrupt to handle. Returns IRQ_HANDLED if there was a valid
4907  * interrupt.
4908  *
4909  * This function is called by the USB core when an interrupt occurs
4910  */
4911 static irqreturn_t _dwc2_hcd_irq(struct usb_hcd *hcd)
4912 {
4913         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4914
4915         return dwc2_handle_hcd_intr(hsotg);
4916 }
4917
4918 /*
4919  * Creates Status Change bitmap for the root hub and root port. The bitmap is
4920  * returned in buf. Bit 0 is the status change indicator for the root hub. Bit 1
4921  * is the status change indicator for the single root port. Returns 1 if either
4922  * change indicator is 1, otherwise returns 0.
4923  */
4924 static int _dwc2_hcd_hub_status_data(struct usb_hcd *hcd, char *buf)
4925 {
4926         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4927
4928         buf[0] = dwc2_hcd_is_status_changed(hsotg, 1) << 1;
4929         return buf[0] != 0;
4930 }
4931
4932 /* Handles hub class-specific requests */
4933 static int _dwc2_hcd_hub_control(struct usb_hcd *hcd, u16 typereq, u16 wvalue,
4934                                  u16 windex, char *buf, u16 wlength)
4935 {
4936         int retval = dwc2_hcd_hub_control(dwc2_hcd_to_hsotg(hcd), typereq,
4937                                           wvalue, windex, buf, wlength);
4938         return retval;
4939 }
4940
4941 /* Handles hub TT buffer clear completions */
4942 static void _dwc2_hcd_clear_tt_buffer_complete(struct usb_hcd *hcd,
4943                                                struct usb_host_endpoint *ep)
4944 {
4945         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4946         struct dwc2_qh *qh;
4947         unsigned long flags;
4948
4949         qh = ep->hcpriv;
4950         if (!qh)
4951                 return;
4952
4953         spin_lock_irqsave(&hsotg->lock, flags);
4954         qh->tt_buffer_dirty = 0;
4955
4956         if (hsotg->flags.b.port_connect_status)
4957                 dwc2_hcd_queue_transactions(hsotg, DWC2_TRANSACTION_ALL);
4958
4959         spin_unlock_irqrestore(&hsotg->lock, flags);
4960 }
4961
4962 /*
4963  * HPRT0_SPD_HIGH_SPEED: high speed
4964  * HPRT0_SPD_FULL_SPEED: full speed
4965  */
4966 static void dwc2_change_bus_speed(struct usb_hcd *hcd, int speed)
4967 {
4968         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4969
4970         if (hsotg->params.speed == speed)
4971                 return;
4972
4973         hsotg->params.speed = speed;
4974         queue_work(hsotg->wq_otg, &hsotg->wf_otg);
4975 }
4976
4977 static void dwc2_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
4978 {
4979         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4980
4981         if (!hsotg->params.change_speed_quirk)
4982                 return;
4983
4984         /*
4985          * On removal, set speed to default high-speed.
4986          */
4987         if (udev->parent && udev->parent->speed > USB_SPEED_UNKNOWN &&
4988             udev->parent->speed < USB_SPEED_HIGH) {
4989                 dev_info(hsotg->dev, "Set speed to default high-speed\n");
4990                 dwc2_change_bus_speed(hcd, HPRT0_SPD_HIGH_SPEED);
4991         }
4992 }
4993
4994 static int dwc2_reset_device(struct usb_hcd *hcd, struct usb_device *udev)
4995 {
4996         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
4997
4998         if (!hsotg->params.change_speed_quirk)
4999                 return 0;
5000
5001         if (udev->speed == USB_SPEED_HIGH) {
5002                 dev_info(hsotg->dev, "Set speed to high-speed\n");
5003                 dwc2_change_bus_speed(hcd, HPRT0_SPD_HIGH_SPEED);
5004         } else if ((udev->speed == USB_SPEED_FULL ||
5005                                 udev->speed == USB_SPEED_LOW)) {
5006                 /*
5007                  * Change speed setting to full-speed if there's
5008                  * a full-speed or low-speed device plugged in.
5009                  */
5010                 dev_info(hsotg->dev, "Set speed to full-speed\n");
5011                 dwc2_change_bus_speed(hcd, HPRT0_SPD_FULL_SPEED);
5012         }
5013
5014         return 0;
5015 }
5016
5017 static struct hc_driver dwc2_hc_driver = {
5018         .description = "dwc2_hsotg",
5019         .product_desc = "DWC OTG Controller",
5020         .hcd_priv_size = sizeof(struct wrapper_priv_data),
5021
5022         .irq = _dwc2_hcd_irq,
5023         .flags = HCD_MEMORY | HCD_USB2 | HCD_BH,
5024
5025         .start = _dwc2_hcd_start,
5026         .stop = _dwc2_hcd_stop,
5027         .urb_enqueue = _dwc2_hcd_urb_enqueue,
5028         .urb_dequeue = _dwc2_hcd_urb_dequeue,
5029         .endpoint_disable = _dwc2_hcd_endpoint_disable,
5030         .endpoint_reset = _dwc2_hcd_endpoint_reset,
5031         .get_frame_number = _dwc2_hcd_get_frame_number,
5032
5033         .hub_status_data = _dwc2_hcd_hub_status_data,
5034         .hub_control = _dwc2_hcd_hub_control,
5035         .clear_tt_buffer_complete = _dwc2_hcd_clear_tt_buffer_complete,
5036
5037         .bus_suspend = _dwc2_hcd_suspend,
5038         .bus_resume = _dwc2_hcd_resume,
5039
5040         .map_urb_for_dma        = dwc2_map_urb_for_dma,
5041         .unmap_urb_for_dma      = dwc2_unmap_urb_for_dma,
5042 };
5043
5044 /*
5045  * Frees secondary storage associated with the dwc2_hsotg structure contained
5046  * in the struct usb_hcd field
5047  */
5048 static void dwc2_hcd_free(struct dwc2_hsotg *hsotg)
5049 {
5050         u32 ahbcfg;
5051         u32 dctl;
5052         int i;
5053
5054         dev_dbg(hsotg->dev, "DWC OTG HCD FREE\n");
5055
5056         /* Free memory for QH/QTD lists */
5057         dwc2_qh_list_free(hsotg, &hsotg->non_periodic_sched_inactive);
5058         dwc2_qh_list_free(hsotg, &hsotg->non_periodic_sched_waiting);
5059         dwc2_qh_list_free(hsotg, &hsotg->non_periodic_sched_active);
5060         dwc2_qh_list_free(hsotg, &hsotg->periodic_sched_inactive);
5061         dwc2_qh_list_free(hsotg, &hsotg->periodic_sched_ready);
5062         dwc2_qh_list_free(hsotg, &hsotg->periodic_sched_assigned);
5063         dwc2_qh_list_free(hsotg, &hsotg->periodic_sched_queued);
5064
5065         /* Free memory for the host channels */
5066         for (i = 0; i < MAX_EPS_CHANNELS; i++) {
5067                 struct dwc2_host_chan *chan = hsotg->hc_ptr_array[i];
5068
5069                 if (chan) {
5070                         dev_dbg(hsotg->dev, "HCD Free channel #%i, chan=%p\n",
5071                                 i, chan);
5072                         hsotg->hc_ptr_array[i] = NULL;
5073                         kfree(chan);
5074                 }
5075         }
5076
5077         if (hsotg->params.host_dma) {
5078                 if (hsotg->status_buf) {
5079                         dma_free_coherent(hsotg->dev, DWC2_HCD_STATUS_BUF_SIZE,
5080                                           hsotg->status_buf,
5081                                           hsotg->status_buf_dma);
5082                         hsotg->status_buf = NULL;
5083                 }
5084         } else {
5085                 kfree(hsotg->status_buf);
5086                 hsotg->status_buf = NULL;
5087         }
5088
5089         ahbcfg = dwc2_readl(hsotg->regs + GAHBCFG);
5090
5091         /* Disable all interrupts */
5092         ahbcfg &= ~GAHBCFG_GLBL_INTR_EN;
5093         dwc2_writel(ahbcfg, hsotg->regs + GAHBCFG);
5094         dwc2_writel(0, hsotg->regs + GINTMSK);
5095
5096         if (hsotg->hw_params.snpsid >= DWC2_CORE_REV_3_00a) {
5097                 dctl = dwc2_readl(hsotg->regs + DCTL);
5098                 dctl |= DCTL_SFTDISCON;
5099                 dwc2_writel(dctl, hsotg->regs + DCTL);
5100         }
5101
5102         if (hsotg->wq_otg) {
5103                 if (!cancel_work_sync(&hsotg->wf_otg))
5104                         flush_workqueue(hsotg->wq_otg);
5105                 destroy_workqueue(hsotg->wq_otg);
5106         }
5107
5108         del_timer(&hsotg->wkp_timer);
5109 }
5110
5111 static void dwc2_hcd_release(struct dwc2_hsotg *hsotg)
5112 {
5113         /* Turn off all host-specific interrupts */
5114         dwc2_disable_host_interrupts(hsotg);
5115
5116         dwc2_hcd_free(hsotg);
5117 }
5118
5119 /*
5120  * Initializes the HCD. This function allocates memory for and initializes the
5121  * static parts of the usb_hcd and dwc2_hsotg structures. It also registers the
5122  * USB bus with the core and calls the hc_driver->start() function. It returns
5123  * a negative error on failure.
5124  */
5125 int dwc2_hcd_init(struct dwc2_hsotg *hsotg)
5126 {
5127         struct platform_device *pdev = to_platform_device(hsotg->dev);
5128         struct resource *res;
5129         struct usb_hcd *hcd;
5130         struct dwc2_host_chan *channel;
5131         u32 hcfg;
5132         int i, num_channels;
5133         int retval;
5134
5135         if (usb_disabled())
5136                 return -ENODEV;
5137
5138         dev_dbg(hsotg->dev, "DWC OTG HCD INIT\n");
5139
5140         retval = -ENOMEM;
5141
5142         hcfg = dwc2_readl(hsotg->regs + HCFG);
5143         dev_dbg(hsotg->dev, "hcfg=%08x\n", hcfg);
5144
5145 #ifdef CONFIG_USB_DWC2_TRACK_MISSED_SOFS
5146         hsotg->frame_num_array = kcalloc(FRAME_NUM_ARRAY_SIZE,
5147                                          sizeof(*hsotg->frame_num_array),
5148                                          GFP_KERNEL);
5149         if (!hsotg->frame_num_array)
5150                 goto error1;
5151         hsotg->last_frame_num_array =
5152                 kcalloc(FRAME_NUM_ARRAY_SIZE,
5153                         sizeof(*hsotg->last_frame_num_array), GFP_KERNEL);
5154         if (!hsotg->last_frame_num_array)
5155                 goto error1;
5156 #endif
5157         hsotg->last_frame_num = HFNUM_MAX_FRNUM;
5158
5159         /* Check if the bus driver or platform code has setup a dma_mask */
5160         if (hsotg->params.host_dma &&
5161             !hsotg->dev->dma_mask) {
5162                 dev_warn(hsotg->dev,
5163                          "dma_mask not set, disabling DMA\n");
5164                 hsotg->params.host_dma = false;
5165                 hsotg->params.dma_desc_enable = false;
5166         }
5167
5168         /* Set device flags indicating whether the HCD supports DMA */
5169         if (hsotg->params.host_dma) {
5170                 if (dma_set_mask(hsotg->dev, DMA_BIT_MASK(32)) < 0)
5171                         dev_warn(hsotg->dev, "can't set DMA mask\n");
5172                 if (dma_set_coherent_mask(hsotg->dev, DMA_BIT_MASK(32)) < 0)
5173                         dev_warn(hsotg->dev, "can't set coherent DMA mask\n");
5174         }
5175
5176         if (hsotg->params.change_speed_quirk) {
5177                 dwc2_hc_driver.free_dev = dwc2_free_dev;
5178                 dwc2_hc_driver.reset_device = dwc2_reset_device;
5179         }
5180
5181         hcd = usb_create_hcd(&dwc2_hc_driver, hsotg->dev, dev_name(hsotg->dev));
5182         if (!hcd)
5183                 goto error1;
5184
5185         if (!hsotg->params.host_dma)
5186                 hcd->self.uses_dma = 0;
5187
5188         hcd->has_tt = 1;
5189
5190         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
5191         hcd->rsrc_start = res->start;
5192         hcd->rsrc_len = resource_size(res);
5193
5194         ((struct wrapper_priv_data *)&hcd->hcd_priv)->hsotg = hsotg;
5195         hsotg->priv = hcd;
5196
5197         /*
5198          * Disable the global interrupt until all the interrupt handlers are
5199          * installed
5200          */
5201         dwc2_disable_global_interrupts(hsotg);
5202
5203         /* Initialize the DWC_otg core, and select the Phy type */
5204         retval = dwc2_core_init(hsotg, true);
5205         if (retval)
5206                 goto error2;
5207
5208         /* Create new workqueue and init work */
5209         retval = -ENOMEM;
5210         hsotg->wq_otg = alloc_ordered_workqueue("dwc2", 0);
5211         if (!hsotg->wq_otg) {
5212                 dev_err(hsotg->dev, "Failed to create workqueue\n");
5213                 goto error2;
5214         }
5215         INIT_WORK(&hsotg->wf_otg, dwc2_conn_id_status_change);
5216
5217         timer_setup(&hsotg->wkp_timer, dwc2_wakeup_detected, 0);
5218
5219         /* Initialize the non-periodic schedule */
5220         INIT_LIST_HEAD(&hsotg->non_periodic_sched_inactive);
5221         INIT_LIST_HEAD(&hsotg->non_periodic_sched_waiting);
5222         INIT_LIST_HEAD(&hsotg->non_periodic_sched_active);
5223
5224         /* Initialize the periodic schedule */
5225         INIT_LIST_HEAD(&hsotg->periodic_sched_inactive);
5226         INIT_LIST_HEAD(&hsotg->periodic_sched_ready);
5227         INIT_LIST_HEAD(&hsotg->periodic_sched_assigned);
5228         INIT_LIST_HEAD(&hsotg->periodic_sched_queued);
5229
5230         INIT_LIST_HEAD(&hsotg->split_order);
5231
5232         /*
5233          * Create a host channel descriptor for each host channel implemented
5234          * in the controller. Initialize the channel descriptor array.
5235          */
5236         INIT_LIST_HEAD(&hsotg->free_hc_list);
5237         num_channels = hsotg->params.host_channels;
5238         memset(&hsotg->hc_ptr_array[0], 0, sizeof(hsotg->hc_ptr_array));
5239
5240         for (i = 0; i < num_channels; i++) {
5241                 channel = kzalloc(sizeof(*channel), GFP_KERNEL);
5242                 if (!channel)
5243                         goto error3;
5244                 channel->hc_num = i;
5245                 INIT_LIST_HEAD(&channel->split_order_list_entry);
5246                 hsotg->hc_ptr_array[i] = channel;
5247         }
5248
5249         /* Initialize hsotg start work */
5250         INIT_DELAYED_WORK(&hsotg->start_work, dwc2_hcd_start_func);
5251
5252         /* Initialize port reset work */
5253         INIT_DELAYED_WORK(&hsotg->reset_work, dwc2_hcd_reset_func);
5254
5255         /*
5256          * Allocate space for storing data on status transactions. Normally no
5257          * data is sent, but this space acts as a bit bucket. This must be
5258          * done after usb_add_hcd since that function allocates the DMA buffer
5259          * pool.
5260          */
5261         if (hsotg->params.host_dma)
5262                 hsotg->status_buf = dma_alloc_coherent(hsotg->dev,
5263                                         DWC2_HCD_STATUS_BUF_SIZE,
5264                                         &hsotg->status_buf_dma, GFP_KERNEL);
5265         else
5266                 hsotg->status_buf = kzalloc(DWC2_HCD_STATUS_BUF_SIZE,
5267                                           GFP_KERNEL);
5268
5269         if (!hsotg->status_buf)
5270                 goto error3;
5271
5272         /*
5273          * Create kmem caches to handle descriptor buffers in descriptor
5274          * DMA mode.
5275          * Alignment must be set to 512 bytes.
5276          */
5277         if (hsotg->params.dma_desc_enable ||
5278             hsotg->params.dma_desc_fs_enable) {
5279                 hsotg->desc_gen_cache = kmem_cache_create("dwc2-gen-desc",
5280                                 sizeof(struct dwc2_dma_desc) *
5281                                 MAX_DMA_DESC_NUM_GENERIC, 512, SLAB_CACHE_DMA,
5282                                 NULL);
5283                 if (!hsotg->desc_gen_cache) {
5284                         dev_err(hsotg->dev,
5285                                 "unable to create dwc2 generic desc cache\n");
5286
5287                         /*
5288                          * Disable descriptor dma mode since it will not be
5289                          * usable.
5290                          */
5291                         hsotg->params.dma_desc_enable = false;
5292                         hsotg->params.dma_desc_fs_enable = false;
5293                 }
5294
5295                 hsotg->desc_hsisoc_cache = kmem_cache_create("dwc2-hsisoc-desc",
5296                                 sizeof(struct dwc2_dma_desc) *
5297                                 MAX_DMA_DESC_NUM_HS_ISOC, 512, 0, NULL);
5298                 if (!hsotg->desc_hsisoc_cache) {
5299                         dev_err(hsotg->dev,
5300                                 "unable to create dwc2 hs isoc desc cache\n");
5301
5302                         kmem_cache_destroy(hsotg->desc_gen_cache);
5303
5304                         /*
5305                          * Disable descriptor dma mode since it will not be
5306                          * usable.
5307                          */
5308                         hsotg->params.dma_desc_enable = false;
5309                         hsotg->params.dma_desc_fs_enable = false;
5310                 }
5311         }
5312
5313         if (hsotg->params.host_dma) {
5314                 /*
5315                  * Create kmem caches to handle non-aligned buffer
5316                  * in Buffer DMA mode.
5317                  */
5318                 hsotg->unaligned_cache = kmem_cache_create("dwc2-unaligned-dma",
5319                                                 DWC2_KMEM_UNALIGNED_BUF_SIZE, 4,
5320                                                 SLAB_CACHE_DMA, NULL);
5321                 if (!hsotg->unaligned_cache)
5322                         dev_err(hsotg->dev,
5323                                 "unable to create dwc2 unaligned cache\n");
5324         }
5325
5326         hsotg->otg_port = 1;
5327         hsotg->frame_list = NULL;
5328         hsotg->frame_list_dma = 0;
5329         hsotg->periodic_qh_count = 0;
5330
5331         /* Initiate lx_state to L3 disconnected state */
5332         hsotg->lx_state = DWC2_L3;
5333
5334         hcd->self.otg_port = hsotg->otg_port;
5335
5336         /* Don't support SG list at this point */
5337         hcd->self.sg_tablesize = 0;
5338
5339         if (!IS_ERR_OR_NULL(hsotg->uphy))
5340                 otg_set_host(hsotg->uphy->otg, &hcd->self);
5341
5342         /*
5343          * Finish generic HCD initialization and start the HCD. This function
5344          * allocates the DMA buffer pool, registers the USB bus, requests the
5345          * IRQ line, and calls hcd_start method.
5346          */
5347         retval = usb_add_hcd(hcd, hsotg->irq, IRQF_SHARED);
5348         if (retval < 0)
5349                 goto error4;
5350
5351         device_wakeup_enable(hcd->self.controller);
5352
5353         dwc2_hcd_dump_state(hsotg);
5354
5355         dwc2_enable_global_interrupts(hsotg);
5356
5357         return 0;
5358
5359 error4:
5360         kmem_cache_destroy(hsotg->unaligned_cache);
5361         kmem_cache_destroy(hsotg->desc_hsisoc_cache);
5362         kmem_cache_destroy(hsotg->desc_gen_cache);
5363 error3:
5364         dwc2_hcd_release(hsotg);
5365 error2:
5366         usb_put_hcd(hcd);
5367 error1:
5368
5369 #ifdef CONFIG_USB_DWC2_TRACK_MISSED_SOFS
5370         kfree(hsotg->last_frame_num_array);
5371         kfree(hsotg->frame_num_array);
5372 #endif
5373
5374         dev_err(hsotg->dev, "%s() FAILED, returning %d\n", __func__, retval);
5375         return retval;
5376 }
5377
5378 /*
5379  * Removes the HCD.
5380  * Frees memory and resources associated with the HCD and deregisters the bus.
5381  */
5382 void dwc2_hcd_remove(struct dwc2_hsotg *hsotg)
5383 {
5384         struct usb_hcd *hcd;
5385
5386         dev_dbg(hsotg->dev, "DWC OTG HCD REMOVE\n");
5387
5388         hcd = dwc2_hsotg_to_hcd(hsotg);
5389         dev_dbg(hsotg->dev, "hsotg->hcd = %p\n", hcd);
5390
5391         if (!hcd) {
5392                 dev_dbg(hsotg->dev, "%s: dwc2_hsotg_to_hcd(hsotg) NULL!\n",
5393                         __func__);
5394                 return;
5395         }
5396
5397         if (!IS_ERR_OR_NULL(hsotg->uphy))
5398                 otg_set_host(hsotg->uphy->otg, NULL);
5399
5400         usb_remove_hcd(hcd);
5401         hsotg->priv = NULL;
5402
5403         kmem_cache_destroy(hsotg->unaligned_cache);
5404         kmem_cache_destroy(hsotg->desc_hsisoc_cache);
5405         kmem_cache_destroy(hsotg->desc_gen_cache);
5406
5407         dwc2_hcd_release(hsotg);
5408         usb_put_hcd(hcd);
5409
5410 #ifdef CONFIG_USB_DWC2_TRACK_MISSED_SOFS
5411         kfree(hsotg->last_frame_num_array);
5412         kfree(hsotg->frame_num_array);
5413 #endif
5414 }
5415
5416 /**
5417  * dwc2_backup_host_registers() - Backup controller host registers.
5418  * When suspending usb bus, registers needs to be backuped
5419  * if controller power is disabled once suspended.
5420  *
5421  * @hsotg: Programming view of the DWC_otg controller
5422  */
5423 int dwc2_backup_host_registers(struct dwc2_hsotg *hsotg)
5424 {
5425         struct dwc2_hregs_backup *hr;
5426         int i;
5427
5428         dev_dbg(hsotg->dev, "%s\n", __func__);
5429
5430         /* Backup Host regs */
5431         hr = &hsotg->hr_backup;
5432         hr->hcfg = dwc2_readl(hsotg->regs + HCFG);
5433         hr->haintmsk = dwc2_readl(hsotg->regs + HAINTMSK);
5434         for (i = 0; i < hsotg->params.host_channels; ++i)
5435                 hr->hcintmsk[i] = dwc2_readl(hsotg->regs + HCINTMSK(i));
5436
5437         hr->hprt0 = dwc2_read_hprt0(hsotg);
5438         hr->hfir = dwc2_readl(hsotg->regs + HFIR);
5439         hr->hptxfsiz = dwc2_readl(hsotg->regs + HPTXFSIZ);
5440         hr->valid = true;
5441
5442         return 0;
5443 }
5444
5445 /**
5446  * dwc2_restore_host_registers() - Restore controller host registers.
5447  * When resuming usb bus, device registers needs to be restored
5448  * if controller power were disabled.
5449  *
5450  * @hsotg: Programming view of the DWC_otg controller
5451  */
5452 int dwc2_restore_host_registers(struct dwc2_hsotg *hsotg)
5453 {
5454         struct dwc2_hregs_backup *hr;
5455         int i;
5456
5457         dev_dbg(hsotg->dev, "%s\n", __func__);
5458
5459         /* Restore host regs */
5460         hr = &hsotg->hr_backup;
5461         if (!hr->valid) {
5462                 dev_err(hsotg->dev, "%s: no host registers to restore\n",
5463                         __func__);
5464                 return -EINVAL;
5465         }
5466         hr->valid = false;
5467
5468         dwc2_writel(hr->hcfg, hsotg->regs + HCFG);
5469         dwc2_writel(hr->haintmsk, hsotg->regs + HAINTMSK);
5470
5471         for (i = 0; i < hsotg->params.host_channels; ++i)
5472                 dwc2_writel(hr->hcintmsk[i], hsotg->regs + HCINTMSK(i));
5473
5474         dwc2_writel(hr->hprt0, hsotg->regs + HPRT0);
5475         dwc2_writel(hr->hfir, hsotg->regs + HFIR);
5476         dwc2_writel(hr->hptxfsiz, hsotg->regs + HPTXFSIZ);
5477         hsotg->frame_number = 0;
5478
5479         return 0;
5480 }
5481
5482 /**
5483  * dwc2_host_enter_hibernation() - Put controller in Hibernation.
5484  *
5485  * @hsotg: Programming view of the DWC_otg controller
5486  */
5487 int dwc2_host_enter_hibernation(struct dwc2_hsotg *hsotg)
5488 {
5489         unsigned long flags;
5490         int ret = 0;
5491         u32 hprt0;
5492         u32 pcgcctl;
5493         u32 gusbcfg;
5494         u32 gpwrdn;
5495
5496         dev_dbg(hsotg->dev, "Preparing host for hibernation\n");
5497         ret = dwc2_backup_global_registers(hsotg);
5498         if (ret) {
5499                 dev_err(hsotg->dev, "%s: failed to backup global registers\n",
5500                         __func__);
5501                 return ret;
5502         }
5503         ret = dwc2_backup_host_registers(hsotg);
5504         if (ret) {
5505                 dev_err(hsotg->dev, "%s: failed to backup host registers\n",
5506                         __func__);
5507                 return ret;
5508         }
5509
5510         /* Enter USB Suspend Mode */
5511         hprt0 = dwc2_readl(hsotg->regs + HPRT0);
5512         hprt0 |= HPRT0_SUSP;
5513         hprt0 &= ~HPRT0_ENA;
5514         dwc2_writel(hprt0, hsotg->regs + HPRT0);
5515
5516         /* Wait for the HPRT0.PrtSusp register field to be set */
5517         if (dwc2_hsotg_wait_bit_set(hsotg, HPRT0, HPRT0_SUSP, 3000))
5518                 dev_warn(hsotg->dev, "Suspend wasn't generated\n");
5519
5520         /*
5521          * We need to disable interrupts to prevent servicing of any IRQ
5522          * during going to hibernation
5523          */
5524         spin_lock_irqsave(&hsotg->lock, flags);
5525         hsotg->lx_state = DWC2_L2;
5526
5527         gusbcfg = dwc2_readl(hsotg->regs + GUSBCFG);
5528         if (gusbcfg & GUSBCFG_ULPI_UTMI_SEL) {
5529                 /* ULPI interface */
5530                 /* Suspend the Phy Clock */
5531                 pcgcctl = dwc2_readl(hsotg->regs + PCGCTL);
5532                 pcgcctl |= PCGCTL_STOPPCLK;
5533                 dwc2_writel(pcgcctl, hsotg->regs + PCGCTL);
5534                 udelay(10);
5535
5536                 gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5537                 gpwrdn |= GPWRDN_PMUACTV;
5538                 dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5539                 udelay(10);
5540         } else {
5541                 /* UTMI+ Interface */
5542                 gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5543                 gpwrdn |= GPWRDN_PMUACTV;
5544                 dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5545                 udelay(10);
5546
5547                 pcgcctl = dwc2_readl(hsotg->regs + PCGCTL);
5548                 pcgcctl |= PCGCTL_STOPPCLK;
5549                 dwc2_writel(pcgcctl, hsotg->regs + PCGCTL);
5550                 udelay(10);
5551         }
5552
5553         /* Enable interrupts from wake up logic */
5554         gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5555         gpwrdn |= GPWRDN_PMUINTSEL;
5556         dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5557         udelay(10);
5558
5559         /* Unmask host mode interrupts in GPWRDN */
5560         gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5561         gpwrdn |= GPWRDN_DISCONN_DET_MSK;
5562         gpwrdn |= GPWRDN_LNSTSCHG_MSK;
5563         gpwrdn |= GPWRDN_STS_CHGINT_MSK;
5564         dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5565         udelay(10);
5566
5567         /* Enable Power Down Clamp */
5568         gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5569         gpwrdn |= GPWRDN_PWRDNCLMP;
5570         dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5571         udelay(10);
5572
5573         /* Switch off VDD */
5574         gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5575         gpwrdn |= GPWRDN_PWRDNSWTCH;
5576         dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5577
5578         hsotg->hibernated = 1;
5579         hsotg->bus_suspended = 1;
5580         dev_dbg(hsotg->dev, "Host hibernation completed\n");
5581         spin_unlock_irqrestore(&hsotg->lock, flags);
5582         return ret;
5583 }
5584
5585 /*
5586  * dwc2_host_exit_hibernation()
5587  *
5588  * @hsotg: Programming view of the DWC_otg controller
5589  * @rem_wakeup: indicates whether resume is initiated by Device or Host.
5590  * @param reset: indicates whether resume is initiated by Reset.
5591  *
5592  * Return: non-zero if failed to enter to hibernation.
5593  *
5594  * This function is for exiting from Host mode hibernation by
5595  * Host Initiated Resume/Reset and Device Initiated Remote-Wakeup.
5596  */
5597 int dwc2_host_exit_hibernation(struct dwc2_hsotg *hsotg, int rem_wakeup,
5598                                int reset)
5599 {
5600         u32 gpwrdn;
5601         u32 hprt0;
5602         int ret = 0;
5603         struct dwc2_gregs_backup *gr;
5604         struct dwc2_hregs_backup *hr;
5605
5606         gr = &hsotg->gr_backup;
5607         hr = &hsotg->hr_backup;
5608
5609         dev_dbg(hsotg->dev,
5610                 "%s: called with rem_wakeup = %d reset = %d\n",
5611                 __func__, rem_wakeup, reset);
5612
5613         dwc2_hib_restore_common(hsotg, rem_wakeup, 1);
5614         hsotg->hibernated = 0;
5615
5616         /*
5617          * This step is not described in functional spec but if not wait for
5618          * this delay, mismatch interrupts occurred because just after restore
5619          * core is in Device mode(gintsts.curmode == 0)
5620          */
5621         mdelay(100);
5622
5623         /* Clear all pending interupts */
5624         dwc2_writel(0xffffffff, hsotg->regs + GINTSTS);
5625
5626         /* De-assert Restore */
5627         gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5628         gpwrdn &= ~GPWRDN_RESTORE;
5629         dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5630         udelay(10);
5631
5632         /* Restore GUSBCFG, HCFG */
5633         dwc2_writel(gr->gusbcfg, hsotg->regs + GUSBCFG);
5634         dwc2_writel(hr->hcfg, hsotg->regs + HCFG);
5635
5636         /* De-assert Wakeup Logic */
5637         gpwrdn = dwc2_readl(hsotg->regs + GPWRDN);
5638         gpwrdn &= ~GPWRDN_PMUACTV;
5639         dwc2_writel(gpwrdn, hsotg->regs + GPWRDN);
5640         udelay(10);
5641
5642         hprt0 = hr->hprt0;
5643         hprt0 |= HPRT0_PWR;
5644         hprt0 &= ~HPRT0_ENA;
5645         hprt0 &= ~HPRT0_SUSP;
5646         dwc2_writel(hprt0, hsotg->regs + HPRT0);
5647
5648         hprt0 = hr->hprt0;
5649         hprt0 |= HPRT0_PWR;
5650         hprt0 &= ~HPRT0_ENA;
5651         hprt0 &= ~HPRT0_SUSP;
5652
5653         if (reset) {
5654                 hprt0 |= HPRT0_RST;
5655                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
5656
5657                 /* Wait for Resume time and then program HPRT again */
5658                 mdelay(60);
5659                 hprt0 &= ~HPRT0_RST;
5660                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
5661         } else {
5662                 hprt0 |= HPRT0_RES;
5663                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
5664
5665                 /* Wait for Resume time and then program HPRT again */
5666                 mdelay(100);
5667                 hprt0 &= ~HPRT0_RES;
5668                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
5669         }
5670         /* Clear all interrupt status */
5671         hprt0 = dwc2_readl(hsotg->regs + HPRT0);
5672         hprt0 |= HPRT0_CONNDET;
5673         hprt0 |= HPRT0_ENACHG;
5674         hprt0 &= ~HPRT0_ENA;
5675         dwc2_writel(hprt0, hsotg->regs + HPRT0);
5676
5677         hprt0 = dwc2_readl(hsotg->regs + HPRT0);
5678
5679         /* Clear all pending interupts */
5680         dwc2_writel(0xffffffff, hsotg->regs + GINTSTS);
5681
5682         /* Restore global registers */
5683         ret = dwc2_restore_global_registers(hsotg);
5684         if (ret) {
5685                 dev_err(hsotg->dev, "%s: failed to restore registers\n",
5686                         __func__);
5687                 return ret;
5688         }
5689
5690         /* Restore host registers */
5691         ret = dwc2_restore_host_registers(hsotg);
5692         if (ret) {
5693                 dev_err(hsotg->dev, "%s: failed to restore host registers\n",
5694                         __func__);
5695                 return ret;
5696         }
5697
5698         dwc2_hcd_rem_wakeup(hsotg);
5699
5700         hsotg->hibernated = 0;
5701         hsotg->bus_suspended = 0;
5702         hsotg->lx_state = DWC2_L0;
5703         dev_dbg(hsotg->dev, "Host hibernation restore complete\n");
5704         return ret;
5705 }