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