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