UPSTREAM: usb: dwc2: host: Giveback URB in tasklet context
[firefly-linux-kernel-4.4.55.git] / drivers / usb / dwc2 / hcd.c
1 /*
2  * hcd.c - DesignWare HS OTG Controller host-mode routines
3  *
4  * Copyright (C) 2004-2013 Synopsys, Inc.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions, and the following disclaimer,
11  *    without modification.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The names of the above-listed copyright holders may not be used
16  *    to endorse or promote products derived from this software without
17  *    specific prior written permission.
18  *
19  * ALTERNATIVELY, this software may be distributed under the terms of the
20  * GNU General Public License ("GPL") as published by the Free Software
21  * Foundation; either version 2 of the License, or (at your option) any
22  * later version.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
26  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  */
36
37 /*
38  * This file contains the core HCD code, and implements the Linux hc_driver
39  * API
40  */
41 #include <linux/kernel.h>
42 #include <linux/module.h>
43 #include <linux/spinlock.h>
44 #include <linux/interrupt.h>
45 #include <linux/dma-mapping.h>
46 #include <linux/delay.h>
47 #include <linux/io.h>
48 #include <linux/slab.h>
49 #include <linux/usb.h>
50
51 #include <linux/usb/hcd.h>
52 #include <linux/usb/ch11.h>
53
54 #include "core.h"
55 #include "hcd.h"
56
57 /**
58  * dwc2_dump_channel_info() - Prints the state of a host channel
59  *
60  * @hsotg: Programming view of DWC_otg controller
61  * @chan:  Pointer to the channel to dump
62  *
63  * Must be called with interrupt disabled and spinlock held
64  *
65  * NOTE: This function will be removed once the peripheral controller code
66  * is integrated and the driver is stable
67  */
68 static void dwc2_dump_channel_info(struct dwc2_hsotg *hsotg,
69                                    struct dwc2_host_chan *chan)
70 {
71 #ifdef VERBOSE_DEBUG
72         int num_channels = hsotg->core_params->host_channels;
73         struct dwc2_qh *qh;
74         u32 hcchar;
75         u32 hcsplt;
76         u32 hctsiz;
77         u32 hc_dma;
78         int i;
79
80         if (chan == NULL)
81                 return;
82
83         hcchar = dwc2_readl(hsotg->regs + HCCHAR(chan->hc_num));
84         hcsplt = dwc2_readl(hsotg->regs + HCSPLT(chan->hc_num));
85         hctsiz = dwc2_readl(hsotg->regs + HCTSIZ(chan->hc_num));
86         hc_dma = dwc2_readl(hsotg->regs + HCDMA(chan->hc_num));
87
88         dev_dbg(hsotg->dev, "  Assigned to channel %p:\n", chan);
89         dev_dbg(hsotg->dev, "    hcchar 0x%08x, hcsplt 0x%08x\n",
90                 hcchar, hcsplt);
91         dev_dbg(hsotg->dev, "    hctsiz 0x%08x, hc_dma 0x%08x\n",
92                 hctsiz, hc_dma);
93         dev_dbg(hsotg->dev, "    dev_addr: %d, ep_num: %d, ep_is_in: %d\n",
94                 chan->dev_addr, chan->ep_num, chan->ep_is_in);
95         dev_dbg(hsotg->dev, "    ep_type: %d\n", chan->ep_type);
96         dev_dbg(hsotg->dev, "    max_packet: %d\n", chan->max_packet);
97         dev_dbg(hsotg->dev, "    data_pid_start: %d\n", chan->data_pid_start);
98         dev_dbg(hsotg->dev, "    xfer_started: %d\n", chan->xfer_started);
99         dev_dbg(hsotg->dev, "    halt_status: %d\n", chan->halt_status);
100         dev_dbg(hsotg->dev, "    xfer_buf: %p\n", chan->xfer_buf);
101         dev_dbg(hsotg->dev, "    xfer_dma: %08lx\n",
102                 (unsigned long)chan->xfer_dma);
103         dev_dbg(hsotg->dev, "    xfer_len: %d\n", chan->xfer_len);
104         dev_dbg(hsotg->dev, "    qh: %p\n", chan->qh);
105         dev_dbg(hsotg->dev, "  NP inactive sched:\n");
106         list_for_each_entry(qh, &hsotg->non_periodic_sched_inactive,
107                             qh_list_entry)
108                 dev_dbg(hsotg->dev, "    %p\n", qh);
109         dev_dbg(hsotg->dev, "  NP active sched:\n");
110         list_for_each_entry(qh, &hsotg->non_periodic_sched_active,
111                             qh_list_entry)
112                 dev_dbg(hsotg->dev, "    %p\n", qh);
113         dev_dbg(hsotg->dev, "  Channels:\n");
114         for (i = 0; i < num_channels; i++) {
115                 struct dwc2_host_chan *chan = hsotg->hc_ptr_array[i];
116
117                 dev_dbg(hsotg->dev, "    %2d: %p\n", i, chan);
118         }
119 #endif /* VERBOSE_DEBUG */
120 }
121
122 /*
123  * Processes all the URBs in a single list of QHs. Completes them with
124  * -ETIMEDOUT and frees the QTD.
125  *
126  * Must be called with interrupt disabled and spinlock held
127  */
128 static void dwc2_kill_urbs_in_qh_list(struct dwc2_hsotg *hsotg,
129                                       struct list_head *qh_list)
130 {
131         struct dwc2_qh *qh, *qh_tmp;
132         struct dwc2_qtd *qtd, *qtd_tmp;
133
134         list_for_each_entry_safe(qh, qh_tmp, qh_list, qh_list_entry) {
135                 list_for_each_entry_safe(qtd, qtd_tmp, &qh->qtd_list,
136                                          qtd_list_entry) {
137                         dwc2_host_complete(hsotg, qtd, -ECONNRESET);
138                         dwc2_hcd_qtd_unlink_and_free(hsotg, qtd, qh);
139                 }
140         }
141 }
142
143 static void dwc2_qh_list_free(struct dwc2_hsotg *hsotg,
144                               struct list_head *qh_list)
145 {
146         struct dwc2_qtd *qtd, *qtd_tmp;
147         struct dwc2_qh *qh, *qh_tmp;
148         unsigned long flags;
149
150         if (!qh_list->next)
151                 /* The list hasn't been initialized yet */
152                 return;
153
154         spin_lock_irqsave(&hsotg->lock, flags);
155
156         /* Ensure there are no QTDs or URBs left */
157         dwc2_kill_urbs_in_qh_list(hsotg, qh_list);
158
159         list_for_each_entry_safe(qh, qh_tmp, qh_list, qh_list_entry) {
160                 dwc2_hcd_qh_unlink(hsotg, qh);
161
162                 /* Free each QTD in the QH's QTD list */
163                 list_for_each_entry_safe(qtd, qtd_tmp, &qh->qtd_list,
164                                          qtd_list_entry)
165                         dwc2_hcd_qtd_unlink_and_free(hsotg, qtd, qh);
166
167                 if (qh->channel && qh->channel->qh == qh)
168                         qh->channel->qh = NULL;
169
170                 spin_unlock_irqrestore(&hsotg->lock, flags);
171                 dwc2_hcd_qh_free(hsotg, qh);
172                 spin_lock_irqsave(&hsotg->lock, flags);
173         }
174
175         spin_unlock_irqrestore(&hsotg->lock, flags);
176 }
177
178 /*
179  * Responds with an error status of -ETIMEDOUT to all URBs in the non-periodic
180  * and periodic schedules. The QTD associated with each URB is removed from
181  * the schedule and freed. This function may be called when a disconnect is
182  * detected or when the HCD is being stopped.
183  *
184  * Must be called with interrupt disabled and spinlock held
185  */
186 static void dwc2_kill_all_urbs(struct dwc2_hsotg *hsotg)
187 {
188         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->non_periodic_sched_inactive);
189         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->non_periodic_sched_active);
190         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->periodic_sched_inactive);
191         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->periodic_sched_ready);
192         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->periodic_sched_assigned);
193         dwc2_kill_urbs_in_qh_list(hsotg, &hsotg->periodic_sched_queued);
194 }
195
196 /**
197  * dwc2_hcd_start() - Starts the HCD when switching to Host mode
198  *
199  * @hsotg: Pointer to struct dwc2_hsotg
200  */
201 void dwc2_hcd_start(struct dwc2_hsotg *hsotg)
202 {
203         u32 hprt0;
204
205         if (hsotg->op_state == OTG_STATE_B_HOST) {
206                 /*
207                  * Reset the port. During a HNP mode switch the reset
208                  * needs to occur within 1ms and have a duration of at
209                  * least 50ms.
210                  */
211                 hprt0 = dwc2_read_hprt0(hsotg);
212                 hprt0 |= HPRT0_RST;
213                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
214         }
215
216         queue_delayed_work(hsotg->wq_otg, &hsotg->start_work,
217                            msecs_to_jiffies(50));
218 }
219
220 /* Must be called with interrupt disabled and spinlock held */
221 static void dwc2_hcd_cleanup_channels(struct dwc2_hsotg *hsotg)
222 {
223         int num_channels = hsotg->core_params->host_channels;
224         struct dwc2_host_chan *channel;
225         u32 hcchar;
226         int i;
227
228         if (hsotg->core_params->dma_enable <= 0) {
229                 /* Flush out any channel requests in slave mode */
230                 for (i = 0; i < num_channels; i++) {
231                         channel = hsotg->hc_ptr_array[i];
232                         if (!list_empty(&channel->hc_list_entry))
233                                 continue;
234                         hcchar = dwc2_readl(hsotg->regs + HCCHAR(i));
235                         if (hcchar & HCCHAR_CHENA) {
236                                 hcchar &= ~(HCCHAR_CHENA | HCCHAR_EPDIR);
237                                 hcchar |= HCCHAR_CHDIS;
238                                 dwc2_writel(hcchar, hsotg->regs + HCCHAR(i));
239                         }
240                 }
241         }
242
243         for (i = 0; i < num_channels; i++) {
244                 channel = hsotg->hc_ptr_array[i];
245                 if (!list_empty(&channel->hc_list_entry))
246                         continue;
247                 hcchar = dwc2_readl(hsotg->regs + HCCHAR(i));
248                 if (hcchar & HCCHAR_CHENA) {
249                         /* Halt the channel */
250                         hcchar |= HCCHAR_CHDIS;
251                         dwc2_writel(hcchar, hsotg->regs + HCCHAR(i));
252                 }
253
254                 dwc2_hc_cleanup(hsotg, channel);
255                 list_add_tail(&channel->hc_list_entry, &hsotg->free_hc_list);
256                 /*
257                  * Added for Descriptor DMA to prevent channel double cleanup in
258                  * release_channel_ddma(), which is called from ep_disable when
259                  * device disconnects
260                  */
261                 channel->qh = NULL;
262         }
263         /* All channels have been freed, mark them available */
264         if (hsotg->core_params->uframe_sched > 0) {
265                 hsotg->available_host_channels =
266                         hsotg->core_params->host_channels;
267         } else {
268                 hsotg->non_periodic_channels = 0;
269                 hsotg->periodic_channels = 0;
270         }
271 }
272
273 /**
274  * dwc2_hcd_connect() - Handles connect of the HCD
275  *
276  * @hsotg: Pointer to struct dwc2_hsotg
277  *
278  * Must be called with interrupt disabled and spinlock held
279  */
280 void dwc2_hcd_connect(struct dwc2_hsotg *hsotg)
281 {
282         if (hsotg->lx_state != DWC2_L0)
283                 usb_hcd_resume_root_hub(hsotg->priv);
284
285         hsotg->flags.b.port_connect_status_change = 1;
286         hsotg->flags.b.port_connect_status = 1;
287 }
288
289 /**
290  * dwc2_hcd_disconnect() - Handles disconnect of the HCD
291  *
292  * @hsotg: Pointer to struct dwc2_hsotg
293  * @force: If true, we won't try to reconnect even if we see device connected.
294  *
295  * Must be called with interrupt disabled and spinlock held
296  */
297 void dwc2_hcd_disconnect(struct dwc2_hsotg *hsotg, bool force)
298 {
299         u32 intr;
300         u32 hprt0;
301
302         /* Set status flags for the hub driver */
303         hsotg->flags.b.port_connect_status_change = 1;
304         hsotg->flags.b.port_connect_status = 0;
305
306         /*
307          * Shutdown any transfers in process by clearing the Tx FIFO Empty
308          * interrupt mask and status bits and disabling subsequent host
309          * channel interrupts.
310          */
311         intr = dwc2_readl(hsotg->regs + GINTMSK);
312         intr &= ~(GINTSTS_NPTXFEMP | GINTSTS_PTXFEMP | GINTSTS_HCHINT);
313         dwc2_writel(intr, hsotg->regs + GINTMSK);
314         intr = GINTSTS_NPTXFEMP | GINTSTS_PTXFEMP | GINTSTS_HCHINT;
315         dwc2_writel(intr, hsotg->regs + GINTSTS);
316
317         /*
318          * Turn off the vbus power only if the core has transitioned to device
319          * mode. If still in host mode, need to keep power on to detect a
320          * reconnection.
321          */
322         if (dwc2_is_device_mode(hsotg)) {
323                 if (hsotg->op_state != OTG_STATE_A_SUSPEND) {
324                         dev_dbg(hsotg->dev, "Disconnect: PortPower off\n");
325                         dwc2_writel(0, hsotg->regs + HPRT0);
326                 }
327
328                 dwc2_disable_host_interrupts(hsotg);
329         }
330
331         /* Respond with an error status to all URBs in the schedule */
332         dwc2_kill_all_urbs(hsotg);
333
334         if (dwc2_is_host_mode(hsotg))
335                 /* Clean up any host channels that were in use */
336                 dwc2_hcd_cleanup_channels(hsotg);
337
338         dwc2_host_disconnect(hsotg);
339
340         /*
341          * Add an extra check here to see if we're actually connected but
342          * we don't have a detection interrupt pending.  This can happen if:
343          *   1. hardware sees connect
344          *   2. hardware sees disconnect
345          *   3. hardware sees connect
346          *   4. dwc2_port_intr() - clears connect interrupt
347          *   5. dwc2_handle_common_intr() - calls here
348          *
349          * Without the extra check here we will end calling disconnect
350          * and won't get any future interrupts to handle the connect.
351          */
352         if (!force) {
353                 hprt0 = dwc2_readl(hsotg->regs + HPRT0);
354                 if (!(hprt0 & HPRT0_CONNDET) && (hprt0 & HPRT0_CONNSTS))
355                         dwc2_hcd_connect(hsotg);
356         }
357 }
358
359 /**
360  * dwc2_hcd_rem_wakeup() - Handles Remote Wakeup
361  *
362  * @hsotg: Pointer to struct dwc2_hsotg
363  */
364 static void dwc2_hcd_rem_wakeup(struct dwc2_hsotg *hsotg)
365 {
366         if (hsotg->bus_suspended) {
367                 hsotg->flags.b.port_suspend_change = 1;
368                 usb_hcd_resume_root_hub(hsotg->priv);
369         }
370
371         if (hsotg->lx_state == DWC2_L1)
372                 hsotg->flags.b.port_l1_change = 1;
373 }
374
375 /**
376  * dwc2_hcd_stop() - Halts the DWC_otg host mode operations in a clean manner
377  *
378  * @hsotg: Pointer to struct dwc2_hsotg
379  *
380  * Must be called with interrupt disabled and spinlock held
381  */
382 void dwc2_hcd_stop(struct dwc2_hsotg *hsotg)
383 {
384         dev_dbg(hsotg->dev, "DWC OTG HCD STOP\n");
385
386         /*
387          * The root hub should be disconnected before this function is called.
388          * The disconnect will clear the QTD lists (via ..._hcd_urb_dequeue)
389          * and the QH lists (via ..._hcd_endpoint_disable).
390          */
391
392         /* Turn off all host-specific interrupts */
393         dwc2_disable_host_interrupts(hsotg);
394
395         /* Turn off the vbus power */
396         dev_dbg(hsotg->dev, "PortPower off\n");
397         dwc2_writel(0, hsotg->regs + HPRT0);
398 }
399
400 /* Caller must hold driver lock */
401 static int dwc2_hcd_urb_enqueue(struct dwc2_hsotg *hsotg,
402                                 struct dwc2_hcd_urb *urb, struct dwc2_qh *qh,
403                                 struct dwc2_qtd *qtd)
404 {
405         u32 intr_mask;
406         int retval;
407         int dev_speed;
408
409         if (!hsotg->flags.b.port_connect_status) {
410                 /* No longer connected */
411                 dev_err(hsotg->dev, "Not connected\n");
412                 return -ENODEV;
413         }
414
415         dev_speed = dwc2_host_get_speed(hsotg, urb->priv);
416
417         /* Some configurations cannot support LS traffic on a FS root port */
418         if ((dev_speed == USB_SPEED_LOW) &&
419             (hsotg->hw_params.fs_phy_type == GHWCFG2_FS_PHY_TYPE_DEDICATED) &&
420             (hsotg->hw_params.hs_phy_type == GHWCFG2_HS_PHY_TYPE_UTMI)) {
421                 u32 hprt0 = dwc2_readl(hsotg->regs + HPRT0);
422                 u32 prtspd = (hprt0 & HPRT0_SPD_MASK) >> HPRT0_SPD_SHIFT;
423
424                 if (prtspd == HPRT0_SPD_FULL_SPEED)
425                         return -ENODEV;
426         }
427
428         if (!qtd)
429                 return -EINVAL;
430
431         dwc2_hcd_qtd_init(qtd, urb);
432         retval = dwc2_hcd_qtd_add(hsotg, qtd, qh);
433         if (retval) {
434                 dev_err(hsotg->dev,
435                         "DWC OTG HCD URB Enqueue failed adding QTD. Error status %d\n",
436                         retval);
437                 return retval;
438         }
439
440         intr_mask = dwc2_readl(hsotg->regs + GINTMSK);
441         if (!(intr_mask & GINTSTS_SOF)) {
442                 enum dwc2_transaction_type tr_type;
443
444                 if (qtd->qh->ep_type == USB_ENDPOINT_XFER_BULK &&
445                     !(qtd->urb->flags & URB_GIVEBACK_ASAP))
446                         /*
447                          * Do not schedule SG transactions until qtd has
448                          * URB_GIVEBACK_ASAP set
449                          */
450                         return 0;
451
452                 tr_type = dwc2_hcd_select_transactions(hsotg);
453                 if (tr_type != DWC2_TRANSACTION_NONE)
454                         dwc2_hcd_queue_transactions(hsotg, tr_type);
455         }
456
457         return 0;
458 }
459
460 /* Must be called with interrupt disabled and spinlock held */
461 static int dwc2_hcd_urb_dequeue(struct dwc2_hsotg *hsotg,
462                                 struct dwc2_hcd_urb *urb)
463 {
464         struct dwc2_qh *qh;
465         struct dwc2_qtd *urb_qtd;
466
467         urb_qtd = urb->qtd;
468         if (!urb_qtd) {
469                 dev_dbg(hsotg->dev, "## Urb QTD is NULL ##\n");
470                 return -EINVAL;
471         }
472
473         qh = urb_qtd->qh;
474         if (!qh) {
475                 dev_dbg(hsotg->dev, "## Urb QTD QH is NULL ##\n");
476                 return -EINVAL;
477         }
478
479         urb->priv = NULL;
480
481         if (urb_qtd->in_process && qh->channel) {
482                 dwc2_dump_channel_info(hsotg, qh->channel);
483
484                 /* The QTD is in process (it has been assigned to a channel) */
485                 if (hsotg->flags.b.port_connect_status)
486                         /*
487                          * If still connected (i.e. in host mode), halt the
488                          * channel so it can be used for other transfers. If
489                          * no longer connected, the host registers can't be
490                          * written to halt the channel since the core is in
491                          * device mode.
492                          */
493                         dwc2_hc_halt(hsotg, qh->channel,
494                                      DWC2_HC_XFER_URB_DEQUEUE);
495         }
496
497         /*
498          * Free the QTD and clean up the associated QH. Leave the QH in the
499          * schedule if it has any remaining QTDs.
500          */
501         if (hsotg->core_params->dma_desc_enable <= 0) {
502                 u8 in_process = urb_qtd->in_process;
503
504                 dwc2_hcd_qtd_unlink_and_free(hsotg, urb_qtd, qh);
505                 if (in_process) {
506                         dwc2_hcd_qh_deactivate(hsotg, qh, 0);
507                         qh->channel = NULL;
508                 } else if (list_empty(&qh->qtd_list)) {
509                         dwc2_hcd_qh_unlink(hsotg, qh);
510                 }
511         } else {
512                 dwc2_hcd_qtd_unlink_and_free(hsotg, urb_qtd, qh);
513         }
514
515         return 0;
516 }
517
518 /* Must NOT be called with interrupt disabled or spinlock held */
519 static int dwc2_hcd_endpoint_disable(struct dwc2_hsotg *hsotg,
520                                      struct usb_host_endpoint *ep, int retry)
521 {
522         struct dwc2_qtd *qtd, *qtd_tmp;
523         struct dwc2_qh *qh;
524         unsigned long flags;
525         int rc;
526
527         spin_lock_irqsave(&hsotg->lock, flags);
528
529         qh = ep->hcpriv;
530         if (!qh) {
531                 rc = -EINVAL;
532                 goto err;
533         }
534
535         while (!list_empty(&qh->qtd_list) && retry--) {
536                 if (retry == 0) {
537                         dev_err(hsotg->dev,
538                                 "## timeout in dwc2_hcd_endpoint_disable() ##\n");
539                         rc = -EBUSY;
540                         goto err;
541                 }
542
543                 spin_unlock_irqrestore(&hsotg->lock, flags);
544                 usleep_range(20000, 40000);
545                 spin_lock_irqsave(&hsotg->lock, flags);
546                 qh = ep->hcpriv;
547                 if (!qh) {
548                         rc = -EINVAL;
549                         goto err;
550                 }
551         }
552
553         dwc2_hcd_qh_unlink(hsotg, qh);
554
555         /* Free each QTD in the QH's QTD list */
556         list_for_each_entry_safe(qtd, qtd_tmp, &qh->qtd_list, qtd_list_entry)
557                 dwc2_hcd_qtd_unlink_and_free(hsotg, qtd, qh);
558
559         ep->hcpriv = NULL;
560
561         if (qh->channel && qh->channel->qh == qh)
562                 qh->channel->qh = NULL;
563
564         spin_unlock_irqrestore(&hsotg->lock, flags);
565
566         dwc2_hcd_qh_free(hsotg, qh);
567
568         return 0;
569
570 err:
571         ep->hcpriv = NULL;
572         spin_unlock_irqrestore(&hsotg->lock, flags);
573
574         return rc;
575 }
576
577 /* Must be called with interrupt disabled and spinlock held */
578 static int dwc2_hcd_endpoint_reset(struct dwc2_hsotg *hsotg,
579                                    struct usb_host_endpoint *ep)
580 {
581         struct dwc2_qh *qh = ep->hcpriv;
582
583         if (!qh)
584                 return -EINVAL;
585
586         qh->data_toggle = DWC2_HC_PID_DATA0;
587
588         return 0;
589 }
590
591 /*
592  * Initializes dynamic portions of the DWC_otg HCD state
593  *
594  * Must be called with interrupt disabled and spinlock held
595  */
596 static void dwc2_hcd_reinit(struct dwc2_hsotg *hsotg)
597 {
598         struct dwc2_host_chan *chan, *chan_tmp;
599         int num_channels;
600         int i;
601
602         hsotg->flags.d32 = 0;
603         hsotg->non_periodic_qh_ptr = &hsotg->non_periodic_sched_active;
604
605         if (hsotg->core_params->uframe_sched > 0) {
606                 hsotg->available_host_channels =
607                         hsotg->core_params->host_channels;
608         } else {
609                 hsotg->non_periodic_channels = 0;
610                 hsotg->periodic_channels = 0;
611         }
612
613         /*
614          * Put all channels in the free channel list and clean up channel
615          * states
616          */
617         list_for_each_entry_safe(chan, chan_tmp, &hsotg->free_hc_list,
618                                  hc_list_entry)
619                 list_del_init(&chan->hc_list_entry);
620
621         num_channels = hsotg->core_params->host_channels;
622         for (i = 0; i < num_channels; i++) {
623                 chan = hsotg->hc_ptr_array[i];
624                 list_add_tail(&chan->hc_list_entry, &hsotg->free_hc_list);
625                 dwc2_hc_cleanup(hsotg, chan);
626         }
627
628         /* Initialize the DWC core for host mode operation */
629         dwc2_core_host_init(hsotg);
630 }
631
632 static void dwc2_hc_init_split(struct dwc2_hsotg *hsotg,
633                                struct dwc2_host_chan *chan,
634                                struct dwc2_qtd *qtd, struct dwc2_hcd_urb *urb)
635 {
636         int hub_addr, hub_port;
637
638         chan->do_split = 1;
639         chan->xact_pos = qtd->isoc_split_pos;
640         chan->complete_split = qtd->complete_split;
641         dwc2_host_hub_info(hsotg, urb->priv, &hub_addr, &hub_port);
642         chan->hub_addr = (u8)hub_addr;
643         chan->hub_port = (u8)hub_port;
644 }
645
646 static void dwc2_hc_init_xfer(struct dwc2_hsotg *hsotg,
647                               struct dwc2_host_chan *chan,
648                               struct dwc2_qtd *qtd)
649 {
650         struct dwc2_hcd_urb *urb = qtd->urb;
651         struct dwc2_hcd_iso_packet_desc *frame_desc;
652
653         switch (dwc2_hcd_get_pipe_type(&urb->pipe_info)) {
654         case USB_ENDPOINT_XFER_CONTROL:
655                 chan->ep_type = USB_ENDPOINT_XFER_CONTROL;
656
657                 switch (qtd->control_phase) {
658                 case DWC2_CONTROL_SETUP:
659                         dev_vdbg(hsotg->dev, "  Control setup transaction\n");
660                         chan->do_ping = 0;
661                         chan->ep_is_in = 0;
662                         chan->data_pid_start = DWC2_HC_PID_SETUP;
663                         if (hsotg->core_params->dma_enable > 0)
664                                 chan->xfer_dma = urb->setup_dma;
665                         else
666                                 chan->xfer_buf = urb->setup_packet;
667                         chan->xfer_len = 8;
668                         break;
669
670                 case DWC2_CONTROL_DATA:
671                         dev_vdbg(hsotg->dev, "  Control data transaction\n");
672                         chan->data_pid_start = qtd->data_toggle;
673                         break;
674
675                 case DWC2_CONTROL_STATUS:
676                         /*
677                          * Direction is opposite of data direction or IN if no
678                          * data
679                          */
680                         dev_vdbg(hsotg->dev, "  Control status transaction\n");
681                         if (urb->length == 0)
682                                 chan->ep_is_in = 1;
683                         else
684                                 chan->ep_is_in =
685                                         dwc2_hcd_is_pipe_out(&urb->pipe_info);
686                         if (chan->ep_is_in)
687                                 chan->do_ping = 0;
688                         chan->data_pid_start = DWC2_HC_PID_DATA1;
689                         chan->xfer_len = 0;
690                         if (hsotg->core_params->dma_enable > 0)
691                                 chan->xfer_dma = hsotg->status_buf_dma;
692                         else
693                                 chan->xfer_buf = hsotg->status_buf;
694                         break;
695                 }
696                 break;
697
698         case USB_ENDPOINT_XFER_BULK:
699                 chan->ep_type = USB_ENDPOINT_XFER_BULK;
700                 break;
701
702         case USB_ENDPOINT_XFER_INT:
703                 chan->ep_type = USB_ENDPOINT_XFER_INT;
704                 break;
705
706         case USB_ENDPOINT_XFER_ISOC:
707                 chan->ep_type = USB_ENDPOINT_XFER_ISOC;
708                 if (hsotg->core_params->dma_desc_enable > 0)
709                         break;
710
711                 frame_desc = &urb->iso_descs[qtd->isoc_frame_index];
712                 frame_desc->status = 0;
713
714                 if (hsotg->core_params->dma_enable > 0) {
715                         chan->xfer_dma = urb->dma;
716                         chan->xfer_dma += frame_desc->offset +
717                                         qtd->isoc_split_offset;
718                 } else {
719                         chan->xfer_buf = urb->buf;
720                         chan->xfer_buf += frame_desc->offset +
721                                         qtd->isoc_split_offset;
722                 }
723
724                 chan->xfer_len = frame_desc->length - qtd->isoc_split_offset;
725
726                 if (chan->xact_pos == DWC2_HCSPLT_XACTPOS_ALL) {
727                         if (chan->xfer_len <= 188)
728                                 chan->xact_pos = DWC2_HCSPLT_XACTPOS_ALL;
729                         else
730                                 chan->xact_pos = DWC2_HCSPLT_XACTPOS_BEGIN;
731                 }
732                 break;
733         }
734 }
735
736 #define DWC2_USB_DMA_ALIGN 4
737
738 struct dma_aligned_buffer {
739         void *kmalloc_ptr;
740         void *old_xfer_buffer;
741         u8 data[0];
742 };
743
744 static void dwc2_free_dma_aligned_buffer(struct urb *urb)
745 {
746         struct dma_aligned_buffer *temp;
747
748         if (!(urb->transfer_flags & URB_ALIGNED_TEMP_BUFFER))
749                 return;
750
751         temp = container_of(urb->transfer_buffer,
752                 struct dma_aligned_buffer, data);
753
754         if (usb_urb_dir_in(urb))
755                 memcpy(temp->old_xfer_buffer, temp->data,
756                        urb->transfer_buffer_length);
757         urb->transfer_buffer = temp->old_xfer_buffer;
758         kfree(temp->kmalloc_ptr);
759
760         urb->transfer_flags &= ~URB_ALIGNED_TEMP_BUFFER;
761 }
762
763 static int dwc2_alloc_dma_aligned_buffer(struct urb *urb, gfp_t mem_flags)
764 {
765         struct dma_aligned_buffer *temp, *kmalloc_ptr;
766         size_t kmalloc_size;
767
768         if (urb->num_sgs || urb->sg ||
769             urb->transfer_buffer_length == 0 ||
770             !((uintptr_t)urb->transfer_buffer & (DWC2_USB_DMA_ALIGN - 1)))
771                 return 0;
772
773         /* Allocate a buffer with enough padding for alignment */
774         kmalloc_size = urb->transfer_buffer_length +
775                 sizeof(struct dma_aligned_buffer) + DWC2_USB_DMA_ALIGN - 1;
776
777         kmalloc_ptr = kmalloc(kmalloc_size, mem_flags);
778         if (!kmalloc_ptr)
779                 return -ENOMEM;
780
781         /* Position our struct dma_aligned_buffer such that data is aligned */
782         temp = PTR_ALIGN(kmalloc_ptr + 1, DWC2_USB_DMA_ALIGN) - 1;
783         temp->kmalloc_ptr = kmalloc_ptr;
784         temp->old_xfer_buffer = urb->transfer_buffer;
785         if (usb_urb_dir_out(urb))
786                 memcpy(temp->data, urb->transfer_buffer,
787                        urb->transfer_buffer_length);
788         urb->transfer_buffer = temp->data;
789
790         urb->transfer_flags |= URB_ALIGNED_TEMP_BUFFER;
791
792         return 0;
793 }
794
795 static int dwc2_map_urb_for_dma(struct usb_hcd *hcd, struct urb *urb,
796                                       gfp_t mem_flags)
797 {
798         int ret;
799
800         /* We assume setup_dma is always aligned; warn if not */
801         WARN_ON_ONCE(urb->setup_dma &&
802                      (urb->setup_dma & (DWC2_USB_DMA_ALIGN - 1)));
803
804         ret = dwc2_alloc_dma_aligned_buffer(urb, mem_flags);
805         if (ret)
806                 return ret;
807
808         ret = usb_hcd_map_urb_for_dma(hcd, urb, mem_flags);
809         if (ret)
810                 dwc2_free_dma_aligned_buffer(urb);
811
812         return ret;
813 }
814
815 static void dwc2_unmap_urb_for_dma(struct usb_hcd *hcd, struct urb *urb)
816 {
817         usb_hcd_unmap_urb_for_dma(hcd, urb);
818         dwc2_free_dma_aligned_buffer(urb);
819 }
820
821 /**
822  * dwc2_assign_and_init_hc() - Assigns transactions from a QTD to a free host
823  * channel and initializes the host channel to perform the transactions. The
824  * host channel is removed from the free list.
825  *
826  * @hsotg: The HCD state structure
827  * @qh:    Transactions from the first QTD for this QH are selected and assigned
828  *         to a free host channel
829  */
830 static int dwc2_assign_and_init_hc(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh)
831 {
832         struct dwc2_host_chan *chan;
833         struct dwc2_hcd_urb *urb;
834         struct dwc2_qtd *qtd;
835
836         if (dbg_qh(qh))
837                 dev_vdbg(hsotg->dev, "%s(%p,%p)\n", __func__, hsotg, qh);
838
839         if (list_empty(&qh->qtd_list)) {
840                 dev_dbg(hsotg->dev, "No QTDs in QH list\n");
841                 return -ENOMEM;
842         }
843
844         if (list_empty(&hsotg->free_hc_list)) {
845                 dev_dbg(hsotg->dev, "No free channel to assign\n");
846                 return -ENOMEM;
847         }
848
849         chan = list_first_entry(&hsotg->free_hc_list, struct dwc2_host_chan,
850                                 hc_list_entry);
851
852         /* Remove host channel from free list */
853         list_del_init(&chan->hc_list_entry);
854
855         qtd = list_first_entry(&qh->qtd_list, struct dwc2_qtd, qtd_list_entry);
856         urb = qtd->urb;
857         qh->channel = chan;
858         qtd->in_process = 1;
859
860         /*
861          * Use usb_pipedevice to determine device address. This address is
862          * 0 before the SET_ADDRESS command and the correct address afterward.
863          */
864         chan->dev_addr = dwc2_hcd_get_dev_addr(&urb->pipe_info);
865         chan->ep_num = dwc2_hcd_get_ep_num(&urb->pipe_info);
866         chan->speed = qh->dev_speed;
867         chan->max_packet = dwc2_max_packet(qh->maxp);
868
869         chan->xfer_started = 0;
870         chan->halt_status = DWC2_HC_XFER_NO_HALT_STATUS;
871         chan->error_state = (qtd->error_count > 0);
872         chan->halt_on_queue = 0;
873         chan->halt_pending = 0;
874         chan->requests = 0;
875
876         /*
877          * The following values may be modified in the transfer type section
878          * below. The xfer_len value may be reduced when the transfer is
879          * started to accommodate the max widths of the XferSize and PktCnt
880          * fields in the HCTSIZn register.
881          */
882
883         chan->ep_is_in = (dwc2_hcd_is_pipe_in(&urb->pipe_info) != 0);
884         if (chan->ep_is_in)
885                 chan->do_ping = 0;
886         else
887                 chan->do_ping = qh->ping_state;
888
889         chan->data_pid_start = qh->data_toggle;
890         chan->multi_count = 1;
891
892         if (urb->actual_length > urb->length &&
893                 !dwc2_hcd_is_pipe_in(&urb->pipe_info))
894                 urb->actual_length = urb->length;
895
896         if (hsotg->core_params->dma_enable > 0)
897                 chan->xfer_dma = urb->dma + urb->actual_length;
898         else
899                 chan->xfer_buf = (u8 *)urb->buf + urb->actual_length;
900
901         chan->xfer_len = urb->length - urb->actual_length;
902         chan->xfer_count = 0;
903
904         /* Set the split attributes if required */
905         if (qh->do_split)
906                 dwc2_hc_init_split(hsotg, chan, qtd, urb);
907         else
908                 chan->do_split = 0;
909
910         /* Set the transfer attributes */
911         dwc2_hc_init_xfer(hsotg, chan, qtd);
912
913         if (chan->ep_type == USB_ENDPOINT_XFER_INT ||
914             chan->ep_type == USB_ENDPOINT_XFER_ISOC)
915                 /*
916                  * This value may be modified when the transfer is started
917                  * to reflect the actual transfer length
918                  */
919                 chan->multi_count = dwc2_hb_mult(qh->maxp);
920
921         if (hsotg->core_params->dma_desc_enable > 0) {
922                 chan->desc_list_addr = qh->desc_list_dma;
923                 chan->desc_list_sz = qh->desc_list_sz;
924         }
925
926         dwc2_hc_init(hsotg, chan);
927         chan->qh = qh;
928
929         return 0;
930 }
931
932 /**
933  * dwc2_hcd_select_transactions() - Selects transactions from the HCD transfer
934  * schedule and assigns them to available host channels. Called from the HCD
935  * interrupt handler functions.
936  *
937  * @hsotg: The HCD state structure
938  *
939  * Return: The types of new transactions that were assigned to host channels
940  */
941 enum dwc2_transaction_type dwc2_hcd_select_transactions(
942                 struct dwc2_hsotg *hsotg)
943 {
944         enum dwc2_transaction_type ret_val = DWC2_TRANSACTION_NONE;
945         struct list_head *qh_ptr;
946         struct dwc2_qh *qh;
947         int num_channels;
948
949 #ifdef DWC2_DEBUG_SOF
950         dev_vdbg(hsotg->dev, "  Select Transactions\n");
951 #endif
952
953         /* Process entries in the periodic ready list */
954         qh_ptr = hsotg->periodic_sched_ready.next;
955         while (qh_ptr != &hsotg->periodic_sched_ready) {
956                 if (list_empty(&hsotg->free_hc_list))
957                         break;
958                 if (hsotg->core_params->uframe_sched > 0) {
959                         if (hsotg->available_host_channels <= 1)
960                                 break;
961                         hsotg->available_host_channels--;
962                 }
963                 qh = list_entry(qh_ptr, struct dwc2_qh, qh_list_entry);
964                 if (dwc2_assign_and_init_hc(hsotg, qh))
965                         break;
966
967                 /*
968                  * Move the QH from the periodic ready schedule to the
969                  * periodic assigned schedule
970                  */
971                 qh_ptr = qh_ptr->next;
972                 list_move_tail(&qh->qh_list_entry,
973                                &hsotg->periodic_sched_assigned);
974                 ret_val = DWC2_TRANSACTION_PERIODIC;
975         }
976
977         /*
978          * Process entries in the inactive portion of the non-periodic
979          * schedule. Some free host channels may not be used if they are
980          * reserved for periodic transfers.
981          */
982         num_channels = hsotg->core_params->host_channels;
983         qh_ptr = hsotg->non_periodic_sched_inactive.next;
984         while (qh_ptr != &hsotg->non_periodic_sched_inactive) {
985                 if (hsotg->core_params->uframe_sched <= 0 &&
986                     hsotg->non_periodic_channels >= num_channels -
987                                                 hsotg->periodic_channels)
988                         break;
989                 if (list_empty(&hsotg->free_hc_list))
990                         break;
991                 qh = list_entry(qh_ptr, struct dwc2_qh, qh_list_entry);
992                 if (hsotg->core_params->uframe_sched > 0) {
993                         if (hsotg->available_host_channels < 1)
994                                 break;
995                         hsotg->available_host_channels--;
996                 }
997
998                 if (dwc2_assign_and_init_hc(hsotg, qh))
999                         break;
1000
1001                 /*
1002                  * Move the QH from the non-periodic inactive schedule to the
1003                  * non-periodic active schedule
1004                  */
1005                 qh_ptr = qh_ptr->next;
1006                 list_move_tail(&qh->qh_list_entry,
1007                                &hsotg->non_periodic_sched_active);
1008
1009                 if (ret_val == DWC2_TRANSACTION_NONE)
1010                         ret_val = DWC2_TRANSACTION_NON_PERIODIC;
1011                 else
1012                         ret_val = DWC2_TRANSACTION_ALL;
1013
1014                 if (hsotg->core_params->uframe_sched <= 0)
1015                         hsotg->non_periodic_channels++;
1016         }
1017
1018         return ret_val;
1019 }
1020
1021 /**
1022  * dwc2_queue_transaction() - Attempts to queue a single transaction request for
1023  * a host channel associated with either a periodic or non-periodic transfer
1024  *
1025  * @hsotg: The HCD state structure
1026  * @chan:  Host channel descriptor associated with either a periodic or
1027  *         non-periodic transfer
1028  * @fifo_dwords_avail: Number of DWORDs available in the periodic Tx FIFO
1029  *                     for periodic transfers or the non-periodic Tx FIFO
1030  *                     for non-periodic transfers
1031  *
1032  * Return: 1 if a request is queued and more requests may be needed to
1033  * complete the transfer, 0 if no more requests are required for this
1034  * transfer, -1 if there is insufficient space in the Tx FIFO
1035  *
1036  * This function assumes that there is space available in the appropriate
1037  * request queue. For an OUT transfer or SETUP transaction in Slave mode,
1038  * it checks whether space is available in the appropriate Tx FIFO.
1039  *
1040  * Must be called with interrupt disabled and spinlock held
1041  */
1042 static int dwc2_queue_transaction(struct dwc2_hsotg *hsotg,
1043                                   struct dwc2_host_chan *chan,
1044                                   u16 fifo_dwords_avail)
1045 {
1046         int retval = 0;
1047
1048         if (chan->do_split)
1049                 /* Put ourselves on the list to keep order straight */
1050                 list_move_tail(&chan->split_order_list_entry,
1051                                &hsotg->split_order);
1052
1053         if (hsotg->core_params->dma_enable > 0) {
1054                 if (hsotg->core_params->dma_desc_enable > 0) {
1055                         if (!chan->xfer_started ||
1056                             chan->ep_type == USB_ENDPOINT_XFER_ISOC) {
1057                                 dwc2_hcd_start_xfer_ddma(hsotg, chan->qh);
1058                                 chan->qh->ping_state = 0;
1059                         }
1060                 } else if (!chan->xfer_started) {
1061                         dwc2_hc_start_transfer(hsotg, chan);
1062                         chan->qh->ping_state = 0;
1063                 }
1064         } else if (chan->halt_pending) {
1065                 /* Don't queue a request if the channel has been halted */
1066         } else if (chan->halt_on_queue) {
1067                 dwc2_hc_halt(hsotg, chan, chan->halt_status);
1068         } else if (chan->do_ping) {
1069                 if (!chan->xfer_started)
1070                         dwc2_hc_start_transfer(hsotg, chan);
1071         } else if (!chan->ep_is_in ||
1072                    chan->data_pid_start == DWC2_HC_PID_SETUP) {
1073                 if ((fifo_dwords_avail * 4) >= chan->max_packet) {
1074                         if (!chan->xfer_started) {
1075                                 dwc2_hc_start_transfer(hsotg, chan);
1076                                 retval = 1;
1077                         } else {
1078                                 retval = dwc2_hc_continue_transfer(hsotg, chan);
1079                         }
1080                 } else {
1081                         retval = -1;
1082                 }
1083         } else {
1084                 if (!chan->xfer_started) {
1085                         dwc2_hc_start_transfer(hsotg, chan);
1086                         retval = 1;
1087                 } else {
1088                         retval = dwc2_hc_continue_transfer(hsotg, chan);
1089                 }
1090         }
1091
1092         return retval;
1093 }
1094
1095 /*
1096  * Processes periodic channels for the next frame and queues transactions for
1097  * these channels to the DWC_otg controller. After queueing transactions, the
1098  * Periodic Tx FIFO Empty interrupt is enabled if there are more transactions
1099  * to queue as Periodic Tx FIFO or request queue space becomes available.
1100  * Otherwise, the Periodic Tx FIFO Empty interrupt is disabled.
1101  *
1102  * Must be called with interrupt disabled and spinlock held
1103  */
1104 static void dwc2_process_periodic_channels(struct dwc2_hsotg *hsotg)
1105 {
1106         struct list_head *qh_ptr;
1107         struct dwc2_qh *qh;
1108         u32 tx_status;
1109         u32 fspcavail;
1110         u32 gintmsk;
1111         int status;
1112         int no_queue_space = 0;
1113         int no_fifo_space = 0;
1114         u32 qspcavail;
1115
1116         if (dbg_perio())
1117                 dev_vdbg(hsotg->dev, "Queue periodic transactions\n");
1118
1119         tx_status = dwc2_readl(hsotg->regs + HPTXSTS);
1120         qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
1121                     TXSTS_QSPCAVAIL_SHIFT;
1122         fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
1123                     TXSTS_FSPCAVAIL_SHIFT;
1124
1125         if (dbg_perio()) {
1126                 dev_vdbg(hsotg->dev, "  P Tx Req Queue Space Avail (before queue): %d\n",
1127                          qspcavail);
1128                 dev_vdbg(hsotg->dev, "  P Tx FIFO Space Avail (before queue): %d\n",
1129                          fspcavail);
1130         }
1131
1132         qh_ptr = hsotg->periodic_sched_assigned.next;
1133         while (qh_ptr != &hsotg->periodic_sched_assigned) {
1134                 tx_status = dwc2_readl(hsotg->regs + HPTXSTS);
1135                 qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
1136                             TXSTS_QSPCAVAIL_SHIFT;
1137                 if (qspcavail == 0) {
1138                         no_queue_space = 1;
1139                         break;
1140                 }
1141
1142                 qh = list_entry(qh_ptr, struct dwc2_qh, qh_list_entry);
1143                 if (!qh->channel) {
1144                         qh_ptr = qh_ptr->next;
1145                         continue;
1146                 }
1147
1148                 /* Make sure EP's TT buffer is clean before queueing qtds */
1149                 if (qh->tt_buffer_dirty) {
1150                         qh_ptr = qh_ptr->next;
1151                         continue;
1152                 }
1153
1154                 /*
1155                  * Set a flag if we're queuing high-bandwidth in slave mode.
1156                  * The flag prevents any halts to get into the request queue in
1157                  * the middle of multiple high-bandwidth packets getting queued.
1158                  */
1159                 if (hsotg->core_params->dma_enable <= 0 &&
1160                                 qh->channel->multi_count > 1)
1161                         hsotg->queuing_high_bandwidth = 1;
1162
1163                 fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
1164                             TXSTS_FSPCAVAIL_SHIFT;
1165                 status = dwc2_queue_transaction(hsotg, qh->channel, fspcavail);
1166                 if (status < 0) {
1167                         no_fifo_space = 1;
1168                         break;
1169                 }
1170
1171                 /*
1172                  * In Slave mode, stay on the current transfer until there is
1173                  * nothing more to do or the high-bandwidth request count is
1174                  * reached. In DMA mode, only need to queue one request. The
1175                  * controller automatically handles multiple packets for
1176                  * high-bandwidth transfers.
1177                  */
1178                 if (hsotg->core_params->dma_enable > 0 || status == 0 ||
1179                     qh->channel->requests == qh->channel->multi_count) {
1180                         qh_ptr = qh_ptr->next;
1181                         /*
1182                          * Move the QH from the periodic assigned schedule to
1183                          * the periodic queued schedule
1184                          */
1185                         list_move_tail(&qh->qh_list_entry,
1186                                        &hsotg->periodic_sched_queued);
1187
1188                         /* done queuing high bandwidth */
1189                         hsotg->queuing_high_bandwidth = 0;
1190                 }
1191         }
1192
1193         if (hsotg->core_params->dma_enable <= 0) {
1194                 tx_status = dwc2_readl(hsotg->regs + HPTXSTS);
1195                 qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
1196                             TXSTS_QSPCAVAIL_SHIFT;
1197                 fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
1198                             TXSTS_FSPCAVAIL_SHIFT;
1199                 if (dbg_perio()) {
1200                         dev_vdbg(hsotg->dev,
1201                                  "  P Tx Req Queue Space Avail (after queue): %d\n",
1202                                  qspcavail);
1203                         dev_vdbg(hsotg->dev,
1204                                  "  P Tx FIFO Space Avail (after queue): %d\n",
1205                                  fspcavail);
1206                 }
1207
1208                 if (!list_empty(&hsotg->periodic_sched_assigned) ||
1209                     no_queue_space || no_fifo_space) {
1210                         /*
1211                          * May need to queue more transactions as the request
1212                          * queue or Tx FIFO empties. Enable the periodic Tx
1213                          * FIFO empty interrupt. (Always use the half-empty
1214                          * level to ensure that new requests are loaded as
1215                          * soon as possible.)
1216                          */
1217                         gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
1218                         gintmsk |= GINTSTS_PTXFEMP;
1219                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
1220                 } else {
1221                         /*
1222                          * Disable the Tx FIFO empty interrupt since there are
1223                          * no more transactions that need to be queued right
1224                          * now. This function is called from interrupt
1225                          * handlers to queue more transactions as transfer
1226                          * states change.
1227                          */
1228                         gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
1229                         gintmsk &= ~GINTSTS_PTXFEMP;
1230                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
1231                 }
1232         }
1233 }
1234
1235 /*
1236  * Processes active non-periodic channels and queues transactions for these
1237  * channels to the DWC_otg controller. After queueing transactions, the NP Tx
1238  * FIFO Empty interrupt is enabled if there are more transactions to queue as
1239  * NP Tx FIFO or request queue space becomes available. Otherwise, the NP Tx
1240  * FIFO Empty interrupt is disabled.
1241  *
1242  * Must be called with interrupt disabled and spinlock held
1243  */
1244 static void dwc2_process_non_periodic_channels(struct dwc2_hsotg *hsotg)
1245 {
1246         struct list_head *orig_qh_ptr;
1247         struct dwc2_qh *qh;
1248         u32 tx_status;
1249         u32 qspcavail;
1250         u32 fspcavail;
1251         u32 gintmsk;
1252         int status;
1253         int no_queue_space = 0;
1254         int no_fifo_space = 0;
1255         int more_to_do = 0;
1256
1257         dev_vdbg(hsotg->dev, "Queue non-periodic transactions\n");
1258
1259         tx_status = dwc2_readl(hsotg->regs + GNPTXSTS);
1260         qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
1261                     TXSTS_QSPCAVAIL_SHIFT;
1262         fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
1263                     TXSTS_FSPCAVAIL_SHIFT;
1264         dev_vdbg(hsotg->dev, "  NP Tx Req Queue Space Avail (before queue): %d\n",
1265                  qspcavail);
1266         dev_vdbg(hsotg->dev, "  NP Tx FIFO Space Avail (before queue): %d\n",
1267                  fspcavail);
1268
1269         /*
1270          * Keep track of the starting point. Skip over the start-of-list
1271          * entry.
1272          */
1273         if (hsotg->non_periodic_qh_ptr == &hsotg->non_periodic_sched_active)
1274                 hsotg->non_periodic_qh_ptr = hsotg->non_periodic_qh_ptr->next;
1275         orig_qh_ptr = hsotg->non_periodic_qh_ptr;
1276
1277         /*
1278          * Process once through the active list or until no more space is
1279          * available in the request queue or the Tx FIFO
1280          */
1281         do {
1282                 tx_status = dwc2_readl(hsotg->regs + GNPTXSTS);
1283                 qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
1284                             TXSTS_QSPCAVAIL_SHIFT;
1285                 if (hsotg->core_params->dma_enable <= 0 && qspcavail == 0) {
1286                         no_queue_space = 1;
1287                         break;
1288                 }
1289
1290                 qh = list_entry(hsotg->non_periodic_qh_ptr, struct dwc2_qh,
1291                                 qh_list_entry);
1292                 if (!qh->channel)
1293                         goto next;
1294
1295                 /* Make sure EP's TT buffer is clean before queueing qtds */
1296                 if (qh->tt_buffer_dirty)
1297                         goto next;
1298
1299                 fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
1300                             TXSTS_FSPCAVAIL_SHIFT;
1301                 status = dwc2_queue_transaction(hsotg, qh->channel, fspcavail);
1302
1303                 if (status > 0) {
1304                         more_to_do = 1;
1305                 } else if (status < 0) {
1306                         no_fifo_space = 1;
1307                         break;
1308                 }
1309 next:
1310                 /* Advance to next QH, skipping start-of-list entry */
1311                 hsotg->non_periodic_qh_ptr = hsotg->non_periodic_qh_ptr->next;
1312                 if (hsotg->non_periodic_qh_ptr ==
1313                                 &hsotg->non_periodic_sched_active)
1314                         hsotg->non_periodic_qh_ptr =
1315                                         hsotg->non_periodic_qh_ptr->next;
1316         } while (hsotg->non_periodic_qh_ptr != orig_qh_ptr);
1317
1318         if (hsotg->core_params->dma_enable <= 0) {
1319                 tx_status = dwc2_readl(hsotg->regs + GNPTXSTS);
1320                 qspcavail = (tx_status & TXSTS_QSPCAVAIL_MASK) >>
1321                             TXSTS_QSPCAVAIL_SHIFT;
1322                 fspcavail = (tx_status & TXSTS_FSPCAVAIL_MASK) >>
1323                             TXSTS_FSPCAVAIL_SHIFT;
1324                 dev_vdbg(hsotg->dev,
1325                          "  NP Tx Req Queue Space Avail (after queue): %d\n",
1326                          qspcavail);
1327                 dev_vdbg(hsotg->dev,
1328                          "  NP Tx FIFO Space Avail (after queue): %d\n",
1329                          fspcavail);
1330
1331                 if (more_to_do || no_queue_space || no_fifo_space) {
1332                         /*
1333                          * May need to queue more transactions as the request
1334                          * queue or Tx FIFO empties. Enable the non-periodic
1335                          * Tx FIFO empty interrupt. (Always use the half-empty
1336                          * level to ensure that new requests are loaded as
1337                          * soon as possible.)
1338                          */
1339                         gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
1340                         gintmsk |= GINTSTS_NPTXFEMP;
1341                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
1342                 } else {
1343                         /*
1344                          * Disable the Tx FIFO empty interrupt since there are
1345                          * no more transactions that need to be queued right
1346                          * now. This function is called from interrupt
1347                          * handlers to queue more transactions as transfer
1348                          * states change.
1349                          */
1350                         gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
1351                         gintmsk &= ~GINTSTS_NPTXFEMP;
1352                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
1353                 }
1354         }
1355 }
1356
1357 /**
1358  * dwc2_hcd_queue_transactions() - Processes the currently active host channels
1359  * and queues transactions for these channels to the DWC_otg controller. Called
1360  * from the HCD interrupt handler functions.
1361  *
1362  * @hsotg:   The HCD state structure
1363  * @tr_type: The type(s) of transactions to queue (non-periodic, periodic,
1364  *           or both)
1365  *
1366  * Must be called with interrupt disabled and spinlock held
1367  */
1368 void dwc2_hcd_queue_transactions(struct dwc2_hsotg *hsotg,
1369                                  enum dwc2_transaction_type tr_type)
1370 {
1371 #ifdef DWC2_DEBUG_SOF
1372         dev_vdbg(hsotg->dev, "Queue Transactions\n");
1373 #endif
1374         /* Process host channels associated with periodic transfers */
1375         if ((tr_type == DWC2_TRANSACTION_PERIODIC ||
1376              tr_type == DWC2_TRANSACTION_ALL) &&
1377             !list_empty(&hsotg->periodic_sched_assigned))
1378                 dwc2_process_periodic_channels(hsotg);
1379
1380         /* Process host channels associated with non-periodic transfers */
1381         if (tr_type == DWC2_TRANSACTION_NON_PERIODIC ||
1382             tr_type == DWC2_TRANSACTION_ALL) {
1383                 if (!list_empty(&hsotg->non_periodic_sched_active)) {
1384                         dwc2_process_non_periodic_channels(hsotg);
1385                 } else {
1386                         /*
1387                          * Ensure NP Tx FIFO empty interrupt is disabled when
1388                          * there are no non-periodic transfers to process
1389                          */
1390                         u32 gintmsk = dwc2_readl(hsotg->regs + GINTMSK);
1391
1392                         gintmsk &= ~GINTSTS_NPTXFEMP;
1393                         dwc2_writel(gintmsk, hsotg->regs + GINTMSK);
1394                 }
1395         }
1396 }
1397
1398 static void dwc2_conn_id_status_change(struct work_struct *work)
1399 {
1400         struct dwc2_hsotg *hsotg = container_of(work, struct dwc2_hsotg,
1401                                                 wf_otg);
1402         u32 count = 0;
1403         u32 gotgctl;
1404         unsigned long flags;
1405
1406         dev_dbg(hsotg->dev, "%s()\n", __func__);
1407
1408         gotgctl = dwc2_readl(hsotg->regs + GOTGCTL);
1409         dev_dbg(hsotg->dev, "gotgctl=%0x\n", gotgctl);
1410         dev_dbg(hsotg->dev, "gotgctl.b.conidsts=%d\n",
1411                 !!(gotgctl & GOTGCTL_CONID_B));
1412
1413         /* B-Device connector (Device Mode) */
1414         if (gotgctl & GOTGCTL_CONID_B) {
1415                 /* Wait for switch to device mode */
1416                 dev_dbg(hsotg->dev, "connId B\n");
1417                 while (!dwc2_is_device_mode(hsotg)) {
1418                         dev_info(hsotg->dev,
1419                                  "Waiting for Peripheral Mode, Mode=%s\n",
1420                                  dwc2_is_host_mode(hsotg) ? "Host" :
1421                                  "Peripheral");
1422                         usleep_range(20000, 40000);
1423                         if (++count > 250)
1424                                 break;
1425                 }
1426                 if (count > 250)
1427                         dev_err(hsotg->dev,
1428                                 "Connection id status change timed out\n");
1429                 hsotg->op_state = OTG_STATE_B_PERIPHERAL;
1430                 dwc2_core_init(hsotg, false);
1431                 dwc2_enable_global_interrupts(hsotg);
1432                 spin_lock_irqsave(&hsotg->lock, flags);
1433                 dwc2_hsotg_core_init_disconnected(hsotg, false);
1434                 spin_unlock_irqrestore(&hsotg->lock, flags);
1435                 dwc2_hsotg_core_connect(hsotg);
1436         } else {
1437                 /* A-Device connector (Host Mode) */
1438                 dev_dbg(hsotg->dev, "connId A\n");
1439                 while (!dwc2_is_host_mode(hsotg)) {
1440                         dev_info(hsotg->dev, "Waiting for Host Mode, Mode=%s\n",
1441                                  dwc2_is_host_mode(hsotg) ?
1442                                  "Host" : "Peripheral");
1443                         usleep_range(20000, 40000);
1444                         if (++count > 250)
1445                                 break;
1446                 }
1447                 if (count > 250)
1448                         dev_err(hsotg->dev,
1449                                 "Connection id status change timed out\n");
1450                 hsotg->op_state = OTG_STATE_A_HOST;
1451
1452                 /* Initialize the Core for Host mode */
1453                 dwc2_core_init(hsotg, false);
1454                 dwc2_enable_global_interrupts(hsotg);
1455                 dwc2_hcd_start(hsotg);
1456         }
1457 }
1458
1459 static void dwc2_wakeup_detected(unsigned long data)
1460 {
1461         struct dwc2_hsotg *hsotg = (struct dwc2_hsotg *)data;
1462         u32 hprt0;
1463
1464         dev_dbg(hsotg->dev, "%s()\n", __func__);
1465
1466         /*
1467          * Clear the Resume after 70ms. (Need 20 ms minimum. Use 70 ms
1468          * so that OPT tests pass with all PHYs.)
1469          */
1470         hprt0 = dwc2_read_hprt0(hsotg);
1471         dev_dbg(hsotg->dev, "Resume: HPRT0=%0x\n", hprt0);
1472         hprt0 &= ~HPRT0_RES;
1473         dwc2_writel(hprt0, hsotg->regs + HPRT0);
1474         dev_dbg(hsotg->dev, "Clear Resume: HPRT0=%0x\n",
1475                 dwc2_readl(hsotg->regs + HPRT0));
1476
1477         dwc2_hcd_rem_wakeup(hsotg);
1478         hsotg->bus_suspended = 0;
1479
1480         /* Change to L0 state */
1481         hsotg->lx_state = DWC2_L0;
1482 }
1483
1484 static int dwc2_host_is_b_hnp_enabled(struct dwc2_hsotg *hsotg)
1485 {
1486         struct usb_hcd *hcd = dwc2_hsotg_to_hcd(hsotg);
1487
1488         return hcd->self.b_hnp_enable;
1489 }
1490
1491 /* Must NOT be called with interrupt disabled or spinlock held */
1492 static void dwc2_port_suspend(struct dwc2_hsotg *hsotg, u16 windex)
1493 {
1494         unsigned long flags;
1495         u32 hprt0;
1496         u32 pcgctl;
1497         u32 gotgctl;
1498
1499         dev_dbg(hsotg->dev, "%s()\n", __func__);
1500
1501         spin_lock_irqsave(&hsotg->lock, flags);
1502
1503         if (windex == hsotg->otg_port && dwc2_host_is_b_hnp_enabled(hsotg)) {
1504                 gotgctl = dwc2_readl(hsotg->regs + GOTGCTL);
1505                 gotgctl |= GOTGCTL_HSTSETHNPEN;
1506                 dwc2_writel(gotgctl, hsotg->regs + GOTGCTL);
1507                 hsotg->op_state = OTG_STATE_A_SUSPEND;
1508         }
1509
1510         hprt0 = dwc2_read_hprt0(hsotg);
1511         hprt0 |= HPRT0_SUSP;
1512         dwc2_writel(hprt0, hsotg->regs + HPRT0);
1513
1514         hsotg->bus_suspended = 1;
1515
1516         /*
1517          * If hibernation is supported, Phy clock will be suspended
1518          * after registers are backuped.
1519          */
1520         if (!hsotg->core_params->hibernation) {
1521                 /* Suspend the Phy Clock */
1522                 pcgctl = dwc2_readl(hsotg->regs + PCGCTL);
1523                 pcgctl |= PCGCTL_STOPPCLK;
1524                 dwc2_writel(pcgctl, hsotg->regs + PCGCTL);
1525                 udelay(10);
1526         }
1527
1528         /* For HNP the bus must be suspended for at least 200ms */
1529         if (dwc2_host_is_b_hnp_enabled(hsotg)) {
1530                 pcgctl = dwc2_readl(hsotg->regs + PCGCTL);
1531                 pcgctl &= ~PCGCTL_STOPPCLK;
1532                 dwc2_writel(pcgctl, hsotg->regs + PCGCTL);
1533
1534                 spin_unlock_irqrestore(&hsotg->lock, flags);
1535
1536                 usleep_range(200000, 250000);
1537         } else {
1538                 spin_unlock_irqrestore(&hsotg->lock, flags);
1539         }
1540 }
1541
1542 /* Must NOT be called with interrupt disabled or spinlock held */
1543 static void dwc2_port_resume(struct dwc2_hsotg *hsotg)
1544 {
1545         unsigned long flags;
1546         u32 hprt0;
1547         u32 pcgctl;
1548
1549         spin_lock_irqsave(&hsotg->lock, flags);
1550
1551         /*
1552          * If hibernation is supported, Phy clock is already resumed
1553          * after registers restore.
1554          */
1555         if (!hsotg->core_params->hibernation) {
1556                 pcgctl = dwc2_readl(hsotg->regs + PCGCTL);
1557                 pcgctl &= ~PCGCTL_STOPPCLK;
1558                 dwc2_writel(pcgctl, hsotg->regs + PCGCTL);
1559                 spin_unlock_irqrestore(&hsotg->lock, flags);
1560                 usleep_range(20000, 40000);
1561                 spin_lock_irqsave(&hsotg->lock, flags);
1562         }
1563
1564         hprt0 = dwc2_read_hprt0(hsotg);
1565         hprt0 |= HPRT0_RES;
1566         hprt0 &= ~HPRT0_SUSP;
1567         dwc2_writel(hprt0, hsotg->regs + HPRT0);
1568         spin_unlock_irqrestore(&hsotg->lock, flags);
1569
1570         msleep(USB_RESUME_TIMEOUT);
1571
1572         spin_lock_irqsave(&hsotg->lock, flags);
1573         hprt0 = dwc2_read_hprt0(hsotg);
1574         hprt0 &= ~(HPRT0_RES | HPRT0_SUSP);
1575         dwc2_writel(hprt0, hsotg->regs + HPRT0);
1576         hsotg->bus_suspended = 0;
1577         spin_unlock_irqrestore(&hsotg->lock, flags);
1578 }
1579
1580 /* Handles hub class-specific requests */
1581 static int dwc2_hcd_hub_control(struct dwc2_hsotg *hsotg, u16 typereq,
1582                                 u16 wvalue, u16 windex, char *buf, u16 wlength)
1583 {
1584         struct usb_hub_descriptor *hub_desc;
1585         int retval = 0;
1586         u32 hprt0;
1587         u32 port_status;
1588         u32 speed;
1589         u32 pcgctl;
1590
1591         switch (typereq) {
1592         case ClearHubFeature:
1593                 dev_dbg(hsotg->dev, "ClearHubFeature %1xh\n", wvalue);
1594
1595                 switch (wvalue) {
1596                 case C_HUB_LOCAL_POWER:
1597                 case C_HUB_OVER_CURRENT:
1598                         /* Nothing required here */
1599                         break;
1600
1601                 default:
1602                         retval = -EINVAL;
1603                         dev_err(hsotg->dev,
1604                                 "ClearHubFeature request %1xh unknown\n",
1605                                 wvalue);
1606                 }
1607                 break;
1608
1609         case ClearPortFeature:
1610                 if (wvalue != USB_PORT_FEAT_L1)
1611                         if (!windex || windex > 1)
1612                                 goto error;
1613                 switch (wvalue) {
1614                 case USB_PORT_FEAT_ENABLE:
1615                         dev_dbg(hsotg->dev,
1616                                 "ClearPortFeature USB_PORT_FEAT_ENABLE\n");
1617                         hprt0 = dwc2_read_hprt0(hsotg);
1618                         hprt0 |= HPRT0_ENA;
1619                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
1620                         break;
1621
1622                 case USB_PORT_FEAT_SUSPEND:
1623                         dev_dbg(hsotg->dev,
1624                                 "ClearPortFeature USB_PORT_FEAT_SUSPEND\n");
1625
1626                         if (hsotg->bus_suspended)
1627                                 dwc2_port_resume(hsotg);
1628                         break;
1629
1630                 case USB_PORT_FEAT_POWER:
1631                         dev_dbg(hsotg->dev,
1632                                 "ClearPortFeature USB_PORT_FEAT_POWER\n");
1633                         hprt0 = dwc2_read_hprt0(hsotg);
1634                         hprt0 &= ~HPRT0_PWR;
1635                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
1636                         break;
1637
1638                 case USB_PORT_FEAT_INDICATOR:
1639                         dev_dbg(hsotg->dev,
1640                                 "ClearPortFeature USB_PORT_FEAT_INDICATOR\n");
1641                         /* Port indicator not supported */
1642                         break;
1643
1644                 case USB_PORT_FEAT_C_CONNECTION:
1645                         /*
1646                          * Clears driver's internal Connect Status Change flag
1647                          */
1648                         dev_dbg(hsotg->dev,
1649                                 "ClearPortFeature USB_PORT_FEAT_C_CONNECTION\n");
1650                         hsotg->flags.b.port_connect_status_change = 0;
1651                         break;
1652
1653                 case USB_PORT_FEAT_C_RESET:
1654                         /* Clears driver's internal Port Reset Change flag */
1655                         dev_dbg(hsotg->dev,
1656                                 "ClearPortFeature USB_PORT_FEAT_C_RESET\n");
1657                         hsotg->flags.b.port_reset_change = 0;
1658                         break;
1659
1660                 case USB_PORT_FEAT_C_ENABLE:
1661                         /*
1662                          * Clears the driver's internal Port Enable/Disable
1663                          * Change flag
1664                          */
1665                         dev_dbg(hsotg->dev,
1666                                 "ClearPortFeature USB_PORT_FEAT_C_ENABLE\n");
1667                         hsotg->flags.b.port_enable_change = 0;
1668                         break;
1669
1670                 case USB_PORT_FEAT_C_SUSPEND:
1671                         /*
1672                          * Clears the driver's internal Port Suspend Change
1673                          * flag, which is set when resume signaling on the host
1674                          * port is complete
1675                          */
1676                         dev_dbg(hsotg->dev,
1677                                 "ClearPortFeature USB_PORT_FEAT_C_SUSPEND\n");
1678                         hsotg->flags.b.port_suspend_change = 0;
1679                         break;
1680
1681                 case USB_PORT_FEAT_C_PORT_L1:
1682                         dev_dbg(hsotg->dev,
1683                                 "ClearPortFeature USB_PORT_FEAT_C_PORT_L1\n");
1684                         hsotg->flags.b.port_l1_change = 0;
1685                         break;
1686
1687                 case USB_PORT_FEAT_C_OVER_CURRENT:
1688                         dev_dbg(hsotg->dev,
1689                                 "ClearPortFeature USB_PORT_FEAT_C_OVER_CURRENT\n");
1690                         hsotg->flags.b.port_over_current_change = 0;
1691                         break;
1692
1693                 default:
1694                         retval = -EINVAL;
1695                         dev_err(hsotg->dev,
1696                                 "ClearPortFeature request %1xh unknown or unsupported\n",
1697                                 wvalue);
1698                 }
1699                 break;
1700
1701         case GetHubDescriptor:
1702                 dev_dbg(hsotg->dev, "GetHubDescriptor\n");
1703                 hub_desc = (struct usb_hub_descriptor *)buf;
1704                 hub_desc->bDescLength = 9;
1705                 hub_desc->bDescriptorType = USB_DT_HUB;
1706                 hub_desc->bNbrPorts = 1;
1707                 hub_desc->wHubCharacteristics =
1708                         cpu_to_le16(HUB_CHAR_COMMON_LPSM |
1709                                     HUB_CHAR_INDV_PORT_OCPM);
1710                 hub_desc->bPwrOn2PwrGood = 1;
1711                 hub_desc->bHubContrCurrent = 0;
1712                 hub_desc->u.hs.DeviceRemovable[0] = 0;
1713                 hub_desc->u.hs.DeviceRemovable[1] = 0xff;
1714                 break;
1715
1716         case GetHubStatus:
1717                 dev_dbg(hsotg->dev, "GetHubStatus\n");
1718                 memset(buf, 0, 4);
1719                 break;
1720
1721         case GetPortStatus:
1722                 dev_vdbg(hsotg->dev,
1723                          "GetPortStatus wIndex=0x%04x flags=0x%08x\n", windex,
1724                          hsotg->flags.d32);
1725                 if (!windex || windex > 1)
1726                         goto error;
1727
1728                 port_status = 0;
1729                 if (hsotg->flags.b.port_connect_status_change)
1730                         port_status |= USB_PORT_STAT_C_CONNECTION << 16;
1731                 if (hsotg->flags.b.port_enable_change)
1732                         port_status |= USB_PORT_STAT_C_ENABLE << 16;
1733                 if (hsotg->flags.b.port_suspend_change)
1734                         port_status |= USB_PORT_STAT_C_SUSPEND << 16;
1735                 if (hsotg->flags.b.port_l1_change)
1736                         port_status |= USB_PORT_STAT_C_L1 << 16;
1737                 if (hsotg->flags.b.port_reset_change)
1738                         port_status |= USB_PORT_STAT_C_RESET << 16;
1739                 if (hsotg->flags.b.port_over_current_change) {
1740                         dev_warn(hsotg->dev, "Overcurrent change detected\n");
1741                         port_status |= USB_PORT_STAT_C_OVERCURRENT << 16;
1742                 }
1743
1744                 if (!hsotg->flags.b.port_connect_status) {
1745                         /*
1746                          * The port is disconnected, which means the core is
1747                          * either in device mode or it soon will be. Just
1748                          * return 0's for the remainder of the port status
1749                          * since the port register can't be read if the core
1750                          * is in device mode.
1751                          */
1752                         *(__le32 *)buf = cpu_to_le32(port_status);
1753                         break;
1754                 }
1755
1756                 hprt0 = dwc2_readl(hsotg->regs + HPRT0);
1757                 dev_vdbg(hsotg->dev, "  HPRT0: 0x%08x\n", hprt0);
1758
1759                 if (hprt0 & HPRT0_CONNSTS)
1760                         port_status |= USB_PORT_STAT_CONNECTION;
1761                 if (hprt0 & HPRT0_ENA)
1762                         port_status |= USB_PORT_STAT_ENABLE;
1763                 if (hprt0 & HPRT0_SUSP)
1764                         port_status |= USB_PORT_STAT_SUSPEND;
1765                 if (hprt0 & HPRT0_OVRCURRACT)
1766                         port_status |= USB_PORT_STAT_OVERCURRENT;
1767                 if (hprt0 & HPRT0_RST)
1768                         port_status |= USB_PORT_STAT_RESET;
1769                 if (hprt0 & HPRT0_PWR)
1770                         port_status |= USB_PORT_STAT_POWER;
1771
1772                 speed = (hprt0 & HPRT0_SPD_MASK) >> HPRT0_SPD_SHIFT;
1773                 if (speed == HPRT0_SPD_HIGH_SPEED)
1774                         port_status |= USB_PORT_STAT_HIGH_SPEED;
1775                 else if (speed == HPRT0_SPD_LOW_SPEED)
1776                         port_status |= USB_PORT_STAT_LOW_SPEED;
1777
1778                 if (hprt0 & HPRT0_TSTCTL_MASK)
1779                         port_status |= USB_PORT_STAT_TEST;
1780                 /* USB_PORT_FEAT_INDICATOR unsupported always 0 */
1781
1782                 if (hsotg->core_params->dma_desc_fs_enable) {
1783                         /*
1784                          * Enable descriptor DMA only if a full speed
1785                          * device is connected.
1786                          */
1787                         if (hsotg->new_connection &&
1788                             ((port_status &
1789                               (USB_PORT_STAT_CONNECTION |
1790                                USB_PORT_STAT_HIGH_SPEED |
1791                                USB_PORT_STAT_LOW_SPEED)) ==
1792                                USB_PORT_STAT_CONNECTION)) {
1793                                 u32 hcfg;
1794
1795                                 dev_info(hsotg->dev, "Enabling descriptor DMA mode\n");
1796                                 hsotg->core_params->dma_desc_enable = 1;
1797                                 hcfg = dwc2_readl(hsotg->regs + HCFG);
1798                                 hcfg |= HCFG_DESCDMA;
1799                                 dwc2_writel(hcfg, hsotg->regs + HCFG);
1800                                 hsotg->new_connection = false;
1801                         }
1802                 }
1803
1804                 dev_vdbg(hsotg->dev, "port_status=%08x\n", port_status);
1805                 *(__le32 *)buf = cpu_to_le32(port_status);
1806                 break;
1807
1808         case SetHubFeature:
1809                 dev_dbg(hsotg->dev, "SetHubFeature\n");
1810                 /* No HUB features supported */
1811                 break;
1812
1813         case SetPortFeature:
1814                 dev_dbg(hsotg->dev, "SetPortFeature\n");
1815                 if (wvalue != USB_PORT_FEAT_TEST && (!windex || windex > 1))
1816                         goto error;
1817
1818                 if (!hsotg->flags.b.port_connect_status) {
1819                         /*
1820                          * The port is disconnected, which means the core is
1821                          * either in device mode or it soon will be. Just
1822                          * return without doing anything since the port
1823                          * register can't be written if the core is in device
1824                          * mode.
1825                          */
1826                         break;
1827                 }
1828
1829                 switch (wvalue) {
1830                 case USB_PORT_FEAT_SUSPEND:
1831                         dev_dbg(hsotg->dev,
1832                                 "SetPortFeature - USB_PORT_FEAT_SUSPEND\n");
1833                         if (windex != hsotg->otg_port)
1834                                 goto error;
1835                         dwc2_port_suspend(hsotg, windex);
1836                         break;
1837
1838                 case USB_PORT_FEAT_POWER:
1839                         dev_dbg(hsotg->dev,
1840                                 "SetPortFeature - USB_PORT_FEAT_POWER\n");
1841                         hprt0 = dwc2_read_hprt0(hsotg);
1842                         hprt0 |= HPRT0_PWR;
1843                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
1844                         break;
1845
1846                 case USB_PORT_FEAT_RESET:
1847                         hprt0 = dwc2_read_hprt0(hsotg);
1848                         dev_dbg(hsotg->dev,
1849                                 "SetPortFeature - USB_PORT_FEAT_RESET\n");
1850                         pcgctl = dwc2_readl(hsotg->regs + PCGCTL);
1851                         pcgctl &= ~(PCGCTL_ENBL_SLEEP_GATING | PCGCTL_STOPPCLK);
1852                         dwc2_writel(pcgctl, hsotg->regs + PCGCTL);
1853                         /* ??? Original driver does this */
1854                         dwc2_writel(0, hsotg->regs + PCGCTL);
1855
1856                         hprt0 = dwc2_read_hprt0(hsotg);
1857                         /* Clear suspend bit if resetting from suspend state */
1858                         hprt0 &= ~HPRT0_SUSP;
1859
1860                         /*
1861                          * When B-Host the Port reset bit is set in the Start
1862                          * HCD Callback function, so that the reset is started
1863                          * within 1ms of the HNP success interrupt
1864                          */
1865                         if (!dwc2_hcd_is_b_host(hsotg)) {
1866                                 hprt0 |= HPRT0_PWR | HPRT0_RST;
1867                                 dev_dbg(hsotg->dev,
1868                                         "In host mode, hprt0=%08x\n", hprt0);
1869                                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
1870                         }
1871
1872                         /* Clear reset bit in 10ms (FS/LS) or 50ms (HS) */
1873                         usleep_range(50000, 70000);
1874                         hprt0 &= ~HPRT0_RST;
1875                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
1876                         hsotg->lx_state = DWC2_L0; /* Now back to On state */
1877                         break;
1878
1879                 case USB_PORT_FEAT_INDICATOR:
1880                         dev_dbg(hsotg->dev,
1881                                 "SetPortFeature - USB_PORT_FEAT_INDICATOR\n");
1882                         /* Not supported */
1883                         break;
1884
1885                 case USB_PORT_FEAT_TEST:
1886                         hprt0 = dwc2_read_hprt0(hsotg);
1887                         dev_dbg(hsotg->dev,
1888                                 "SetPortFeature - USB_PORT_FEAT_TEST\n");
1889                         hprt0 &= ~HPRT0_TSTCTL_MASK;
1890                         hprt0 |= (windex >> 8) << HPRT0_TSTCTL_SHIFT;
1891                         dwc2_writel(hprt0, hsotg->regs + HPRT0);
1892                         break;
1893
1894                 default:
1895                         retval = -EINVAL;
1896                         dev_err(hsotg->dev,
1897                                 "SetPortFeature %1xh unknown or unsupported\n",
1898                                 wvalue);
1899                         break;
1900                 }
1901                 break;
1902
1903         default:
1904 error:
1905                 retval = -EINVAL;
1906                 dev_dbg(hsotg->dev,
1907                         "Unknown hub control request: %1xh wIndex: %1xh wValue: %1xh\n",
1908                         typereq, windex, wvalue);
1909                 break;
1910         }
1911
1912         return retval;
1913 }
1914
1915 static int dwc2_hcd_is_status_changed(struct dwc2_hsotg *hsotg, int port)
1916 {
1917         int retval;
1918
1919         if (port != 1)
1920                 return -EINVAL;
1921
1922         retval = (hsotg->flags.b.port_connect_status_change ||
1923                   hsotg->flags.b.port_reset_change ||
1924                   hsotg->flags.b.port_enable_change ||
1925                   hsotg->flags.b.port_suspend_change ||
1926                   hsotg->flags.b.port_over_current_change);
1927
1928         if (retval) {
1929                 dev_dbg(hsotg->dev,
1930                         "DWC OTG HCD HUB STATUS DATA: Root port status changed\n");
1931                 dev_dbg(hsotg->dev, "  port_connect_status_change: %d\n",
1932                         hsotg->flags.b.port_connect_status_change);
1933                 dev_dbg(hsotg->dev, "  port_reset_change: %d\n",
1934                         hsotg->flags.b.port_reset_change);
1935                 dev_dbg(hsotg->dev, "  port_enable_change: %d\n",
1936                         hsotg->flags.b.port_enable_change);
1937                 dev_dbg(hsotg->dev, "  port_suspend_change: %d\n",
1938                         hsotg->flags.b.port_suspend_change);
1939                 dev_dbg(hsotg->dev, "  port_over_current_change: %d\n",
1940                         hsotg->flags.b.port_over_current_change);
1941         }
1942
1943         return retval;
1944 }
1945
1946 int dwc2_hcd_get_frame_number(struct dwc2_hsotg *hsotg)
1947 {
1948         u32 hfnum = dwc2_readl(hsotg->regs + HFNUM);
1949
1950 #ifdef DWC2_DEBUG_SOF
1951         dev_vdbg(hsotg->dev, "DWC OTG HCD GET FRAME NUMBER %d\n",
1952                  (hfnum & HFNUM_FRNUM_MASK) >> HFNUM_FRNUM_SHIFT);
1953 #endif
1954         return (hfnum & HFNUM_FRNUM_MASK) >> HFNUM_FRNUM_SHIFT;
1955 }
1956
1957 int dwc2_hcd_is_b_host(struct dwc2_hsotg *hsotg)
1958 {
1959         return hsotg->op_state == OTG_STATE_B_HOST;
1960 }
1961
1962 static struct dwc2_hcd_urb *dwc2_hcd_urb_alloc(struct dwc2_hsotg *hsotg,
1963                                                int iso_desc_count,
1964                                                gfp_t mem_flags)
1965 {
1966         struct dwc2_hcd_urb *urb;
1967         u32 size = sizeof(*urb) + iso_desc_count *
1968                    sizeof(struct dwc2_hcd_iso_packet_desc);
1969
1970         urb = kzalloc(size, mem_flags);
1971         if (urb)
1972                 urb->packet_count = iso_desc_count;
1973         return urb;
1974 }
1975
1976 static void dwc2_hcd_urb_set_pipeinfo(struct dwc2_hsotg *hsotg,
1977                                       struct dwc2_hcd_urb *urb, u8 dev_addr,
1978                                       u8 ep_num, u8 ep_type, u8 ep_dir, u16 mps)
1979 {
1980         if (dbg_perio() ||
1981             ep_type == USB_ENDPOINT_XFER_BULK ||
1982             ep_type == USB_ENDPOINT_XFER_CONTROL)
1983                 dev_vdbg(hsotg->dev,
1984                          "addr=%d, ep_num=%d, ep_dir=%1x, ep_type=%1x, mps=%d\n",
1985                          dev_addr, ep_num, ep_dir, ep_type, mps);
1986         urb->pipe_info.dev_addr = dev_addr;
1987         urb->pipe_info.ep_num = ep_num;
1988         urb->pipe_info.pipe_type = ep_type;
1989         urb->pipe_info.pipe_dir = ep_dir;
1990         urb->pipe_info.mps = mps;
1991 }
1992
1993 /*
1994  * NOTE: This function will be removed once the peripheral controller code
1995  * is integrated and the driver is stable
1996  */
1997 void dwc2_hcd_dump_state(struct dwc2_hsotg *hsotg)
1998 {
1999 #ifdef DEBUG
2000         struct dwc2_host_chan *chan;
2001         struct dwc2_hcd_urb *urb;
2002         struct dwc2_qtd *qtd;
2003         int num_channels;
2004         u32 np_tx_status;
2005         u32 p_tx_status;
2006         int i;
2007
2008         num_channels = hsotg->core_params->host_channels;
2009         dev_dbg(hsotg->dev, "\n");
2010         dev_dbg(hsotg->dev,
2011                 "************************************************************\n");
2012         dev_dbg(hsotg->dev, "HCD State:\n");
2013         dev_dbg(hsotg->dev, "  Num channels: %d\n", num_channels);
2014
2015         for (i = 0; i < num_channels; i++) {
2016                 chan = hsotg->hc_ptr_array[i];
2017                 dev_dbg(hsotg->dev, "  Channel %d:\n", i);
2018                 dev_dbg(hsotg->dev,
2019                         "    dev_addr: %d, ep_num: %d, ep_is_in: %d\n",
2020                         chan->dev_addr, chan->ep_num, chan->ep_is_in);
2021                 dev_dbg(hsotg->dev, "    speed: %d\n", chan->speed);
2022                 dev_dbg(hsotg->dev, "    ep_type: %d\n", chan->ep_type);
2023                 dev_dbg(hsotg->dev, "    max_packet: %d\n", chan->max_packet);
2024                 dev_dbg(hsotg->dev, "    data_pid_start: %d\n",
2025                         chan->data_pid_start);
2026                 dev_dbg(hsotg->dev, "    multi_count: %d\n", chan->multi_count);
2027                 dev_dbg(hsotg->dev, "    xfer_started: %d\n",
2028                         chan->xfer_started);
2029                 dev_dbg(hsotg->dev, "    xfer_buf: %p\n", chan->xfer_buf);
2030                 dev_dbg(hsotg->dev, "    xfer_dma: %08lx\n",
2031                         (unsigned long)chan->xfer_dma);
2032                 dev_dbg(hsotg->dev, "    xfer_len: %d\n", chan->xfer_len);
2033                 dev_dbg(hsotg->dev, "    xfer_count: %d\n", chan->xfer_count);
2034                 dev_dbg(hsotg->dev, "    halt_on_queue: %d\n",
2035                         chan->halt_on_queue);
2036                 dev_dbg(hsotg->dev, "    halt_pending: %d\n",
2037                         chan->halt_pending);
2038                 dev_dbg(hsotg->dev, "    halt_status: %d\n", chan->halt_status);
2039                 dev_dbg(hsotg->dev, "    do_split: %d\n", chan->do_split);
2040                 dev_dbg(hsotg->dev, "    complete_split: %d\n",
2041                         chan->complete_split);
2042                 dev_dbg(hsotg->dev, "    hub_addr: %d\n", chan->hub_addr);
2043                 dev_dbg(hsotg->dev, "    hub_port: %d\n", chan->hub_port);
2044                 dev_dbg(hsotg->dev, "    xact_pos: %d\n", chan->xact_pos);
2045                 dev_dbg(hsotg->dev, "    requests: %d\n", chan->requests);
2046                 dev_dbg(hsotg->dev, "    qh: %p\n", chan->qh);
2047
2048                 if (chan->xfer_started) {
2049                         u32 hfnum, hcchar, hctsiz, hcint, hcintmsk;
2050
2051                         hfnum = dwc2_readl(hsotg->regs + HFNUM);
2052                         hcchar = dwc2_readl(hsotg->regs + HCCHAR(i));
2053                         hctsiz = dwc2_readl(hsotg->regs + HCTSIZ(i));
2054                         hcint = dwc2_readl(hsotg->regs + HCINT(i));
2055                         hcintmsk = dwc2_readl(hsotg->regs + HCINTMSK(i));
2056                         dev_dbg(hsotg->dev, "    hfnum: 0x%08x\n", hfnum);
2057                         dev_dbg(hsotg->dev, "    hcchar: 0x%08x\n", hcchar);
2058                         dev_dbg(hsotg->dev, "    hctsiz: 0x%08x\n", hctsiz);
2059                         dev_dbg(hsotg->dev, "    hcint: 0x%08x\n", hcint);
2060                         dev_dbg(hsotg->dev, "    hcintmsk: 0x%08x\n", hcintmsk);
2061                 }
2062
2063                 if (!(chan->xfer_started && chan->qh))
2064                         continue;
2065
2066                 list_for_each_entry(qtd, &chan->qh->qtd_list, qtd_list_entry) {
2067                         if (!qtd->in_process)
2068                                 break;
2069                         urb = qtd->urb;
2070                         dev_dbg(hsotg->dev, "    URB Info:\n");
2071                         dev_dbg(hsotg->dev, "      qtd: %p, urb: %p\n",
2072                                 qtd, urb);
2073                         if (urb) {
2074                                 dev_dbg(hsotg->dev,
2075                                         "      Dev: %d, EP: %d %s\n",
2076                                         dwc2_hcd_get_dev_addr(&urb->pipe_info),
2077                                         dwc2_hcd_get_ep_num(&urb->pipe_info),
2078                                         dwc2_hcd_is_pipe_in(&urb->pipe_info) ?
2079                                         "IN" : "OUT");
2080                                 dev_dbg(hsotg->dev,
2081                                         "      Max packet size: %d\n",
2082                                         dwc2_hcd_get_mps(&urb->pipe_info));
2083                                 dev_dbg(hsotg->dev,
2084                                         "      transfer_buffer: %p\n",
2085                                         urb->buf);
2086                                 dev_dbg(hsotg->dev,
2087                                         "      transfer_dma: %08lx\n",
2088                                         (unsigned long)urb->dma);
2089                                 dev_dbg(hsotg->dev,
2090                                         "      transfer_buffer_length: %d\n",
2091                                         urb->length);
2092                                 dev_dbg(hsotg->dev, "      actual_length: %d\n",
2093                                         urb->actual_length);
2094                         }
2095                 }
2096         }
2097
2098         dev_dbg(hsotg->dev, "  non_periodic_channels: %d\n",
2099                 hsotg->non_periodic_channels);
2100         dev_dbg(hsotg->dev, "  periodic_channels: %d\n",
2101                 hsotg->periodic_channels);
2102         dev_dbg(hsotg->dev, "  periodic_usecs: %d\n", hsotg->periodic_usecs);
2103         np_tx_status = dwc2_readl(hsotg->regs + GNPTXSTS);
2104         dev_dbg(hsotg->dev, "  NP Tx Req Queue Space Avail: %d\n",
2105                 (np_tx_status & TXSTS_QSPCAVAIL_MASK) >> TXSTS_QSPCAVAIL_SHIFT);
2106         dev_dbg(hsotg->dev, "  NP Tx FIFO Space Avail: %d\n",
2107                 (np_tx_status & TXSTS_FSPCAVAIL_MASK) >> TXSTS_FSPCAVAIL_SHIFT);
2108         p_tx_status = dwc2_readl(hsotg->regs + HPTXSTS);
2109         dev_dbg(hsotg->dev, "  P Tx Req Queue Space Avail: %d\n",
2110                 (p_tx_status & TXSTS_QSPCAVAIL_MASK) >> TXSTS_QSPCAVAIL_SHIFT);
2111         dev_dbg(hsotg->dev, "  P Tx FIFO Space Avail: %d\n",
2112                 (p_tx_status & TXSTS_FSPCAVAIL_MASK) >> TXSTS_FSPCAVAIL_SHIFT);
2113         dwc2_hcd_dump_frrem(hsotg);
2114         dwc2_dump_global_registers(hsotg);
2115         dwc2_dump_host_registers(hsotg);
2116         dev_dbg(hsotg->dev,
2117                 "************************************************************\n");
2118         dev_dbg(hsotg->dev, "\n");
2119 #endif
2120 }
2121
2122 /*
2123  * NOTE: This function will be removed once the peripheral controller code
2124  * is integrated and the driver is stable
2125  */
2126 void dwc2_hcd_dump_frrem(struct dwc2_hsotg *hsotg)
2127 {
2128 #ifdef DWC2_DUMP_FRREM
2129         dev_dbg(hsotg->dev, "Frame remaining at SOF:\n");
2130         dev_dbg(hsotg->dev, "  samples %u, accum %llu, avg %llu\n",
2131                 hsotg->frrem_samples, hsotg->frrem_accum,
2132                 hsotg->frrem_samples > 0 ?
2133                 hsotg->frrem_accum / hsotg->frrem_samples : 0);
2134         dev_dbg(hsotg->dev, "\n");
2135         dev_dbg(hsotg->dev, "Frame remaining at start_transfer (uframe 7):\n");
2136         dev_dbg(hsotg->dev, "  samples %u, accum %llu, avg %llu\n",
2137                 hsotg->hfnum_7_samples,
2138                 hsotg->hfnum_7_frrem_accum,
2139                 hsotg->hfnum_7_samples > 0 ?
2140                 hsotg->hfnum_7_frrem_accum / hsotg->hfnum_7_samples : 0);
2141         dev_dbg(hsotg->dev, "Frame remaining at start_transfer (uframe 0):\n");
2142         dev_dbg(hsotg->dev, "  samples %u, accum %llu, avg %llu\n",
2143                 hsotg->hfnum_0_samples,
2144                 hsotg->hfnum_0_frrem_accum,
2145                 hsotg->hfnum_0_samples > 0 ?
2146                 hsotg->hfnum_0_frrem_accum / hsotg->hfnum_0_samples : 0);
2147         dev_dbg(hsotg->dev, "Frame remaining at start_transfer (uframe 1-6):\n");
2148         dev_dbg(hsotg->dev, "  samples %u, accum %llu, avg %llu\n",
2149                 hsotg->hfnum_other_samples,
2150                 hsotg->hfnum_other_frrem_accum,
2151                 hsotg->hfnum_other_samples > 0 ?
2152                 hsotg->hfnum_other_frrem_accum / hsotg->hfnum_other_samples :
2153                 0);
2154         dev_dbg(hsotg->dev, "\n");
2155         dev_dbg(hsotg->dev, "Frame remaining at sample point A (uframe 7):\n");
2156         dev_dbg(hsotg->dev, "  samples %u, accum %llu, avg %llu\n",
2157                 hsotg->hfnum_7_samples_a, hsotg->hfnum_7_frrem_accum_a,
2158                 hsotg->hfnum_7_samples_a > 0 ?
2159                 hsotg->hfnum_7_frrem_accum_a / hsotg->hfnum_7_samples_a : 0);
2160         dev_dbg(hsotg->dev, "Frame remaining at sample point A (uframe 0):\n");
2161         dev_dbg(hsotg->dev, "  samples %u, accum %llu, avg %llu\n",
2162                 hsotg->hfnum_0_samples_a, hsotg->hfnum_0_frrem_accum_a,
2163                 hsotg->hfnum_0_samples_a > 0 ?
2164                 hsotg->hfnum_0_frrem_accum_a / hsotg->hfnum_0_samples_a : 0);
2165         dev_dbg(hsotg->dev, "Frame remaining at sample point A (uframe 1-6):\n");
2166         dev_dbg(hsotg->dev, "  samples %u, accum %llu, avg %llu\n",
2167                 hsotg->hfnum_other_samples_a, hsotg->hfnum_other_frrem_accum_a,
2168                 hsotg->hfnum_other_samples_a > 0 ?
2169                 hsotg->hfnum_other_frrem_accum_a / hsotg->hfnum_other_samples_a
2170                 : 0);
2171         dev_dbg(hsotg->dev, "\n");
2172         dev_dbg(hsotg->dev, "Frame remaining at sample point B (uframe 7):\n");
2173         dev_dbg(hsotg->dev, "  samples %u, accum %llu, avg %llu\n",
2174                 hsotg->hfnum_7_samples_b, hsotg->hfnum_7_frrem_accum_b,
2175                 hsotg->hfnum_7_samples_b > 0 ?
2176                 hsotg->hfnum_7_frrem_accum_b / hsotg->hfnum_7_samples_b : 0);
2177         dev_dbg(hsotg->dev, "Frame remaining at sample point B (uframe 0):\n");
2178         dev_dbg(hsotg->dev, "  samples %u, accum %llu, avg %llu\n",
2179                 hsotg->hfnum_0_samples_b, hsotg->hfnum_0_frrem_accum_b,
2180                 (hsotg->hfnum_0_samples_b > 0) ?
2181                 hsotg->hfnum_0_frrem_accum_b / hsotg->hfnum_0_samples_b : 0);
2182         dev_dbg(hsotg->dev, "Frame remaining at sample point B (uframe 1-6):\n");
2183         dev_dbg(hsotg->dev, "  samples %u, accum %llu, avg %llu\n",
2184                 hsotg->hfnum_other_samples_b, hsotg->hfnum_other_frrem_accum_b,
2185                 (hsotg->hfnum_other_samples_b > 0) ?
2186                 hsotg->hfnum_other_frrem_accum_b / hsotg->hfnum_other_samples_b
2187                 : 0);
2188 #endif
2189 }
2190
2191 struct wrapper_priv_data {
2192         struct dwc2_hsotg *hsotg;
2193 };
2194
2195 /* Gets the dwc2_hsotg from a usb_hcd */
2196 static struct dwc2_hsotg *dwc2_hcd_to_hsotg(struct usb_hcd *hcd)
2197 {
2198         struct wrapper_priv_data *p;
2199
2200         p = (struct wrapper_priv_data *) &hcd->hcd_priv;
2201         return p->hsotg;
2202 }
2203
2204 static int _dwc2_hcd_start(struct usb_hcd *hcd);
2205
2206 void dwc2_host_start(struct dwc2_hsotg *hsotg)
2207 {
2208         struct usb_hcd *hcd = dwc2_hsotg_to_hcd(hsotg);
2209
2210         hcd->self.is_b_host = dwc2_hcd_is_b_host(hsotg);
2211         _dwc2_hcd_start(hcd);
2212 }
2213
2214 void dwc2_host_disconnect(struct dwc2_hsotg *hsotg)
2215 {
2216         struct usb_hcd *hcd = dwc2_hsotg_to_hcd(hsotg);
2217
2218         hcd->self.is_b_host = 0;
2219 }
2220
2221 void dwc2_host_hub_info(struct dwc2_hsotg *hsotg, void *context, int *hub_addr,
2222                         int *hub_port)
2223 {
2224         struct urb *urb = context;
2225
2226         if (urb->dev->tt)
2227                 *hub_addr = urb->dev->tt->hub->devnum;
2228         else
2229                 *hub_addr = 0;
2230         *hub_port = urb->dev->ttport;
2231 }
2232
2233 int dwc2_host_get_speed(struct dwc2_hsotg *hsotg, void *context)
2234 {
2235         struct urb *urb = context;
2236
2237         return urb->dev->speed;
2238 }
2239
2240 static void dwc2_allocate_bus_bandwidth(struct usb_hcd *hcd, u16 bw,
2241                                         struct urb *urb)
2242 {
2243         struct usb_bus *bus = hcd_to_bus(hcd);
2244
2245         if (urb->interval)
2246                 bus->bandwidth_allocated += bw / urb->interval;
2247         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS)
2248                 bus->bandwidth_isoc_reqs++;
2249         else
2250                 bus->bandwidth_int_reqs++;
2251 }
2252
2253 static void dwc2_free_bus_bandwidth(struct usb_hcd *hcd, u16 bw,
2254                                     struct urb *urb)
2255 {
2256         struct usb_bus *bus = hcd_to_bus(hcd);
2257
2258         if (urb->interval)
2259                 bus->bandwidth_allocated -= bw / urb->interval;
2260         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS)
2261                 bus->bandwidth_isoc_reqs--;
2262         else
2263                 bus->bandwidth_int_reqs--;
2264 }
2265
2266 /*
2267  * Sets the final status of an URB and returns it to the upper layer. Any
2268  * required cleanup of the URB is performed.
2269  *
2270  * Must be called with interrupt disabled and spinlock held
2271  */
2272 void dwc2_host_complete(struct dwc2_hsotg *hsotg, struct dwc2_qtd *qtd,
2273                         int status)
2274 {
2275         struct urb *urb;
2276         int i;
2277
2278         if (!qtd) {
2279                 dev_dbg(hsotg->dev, "## %s: qtd is NULL ##\n", __func__);
2280                 return;
2281         }
2282
2283         if (!qtd->urb) {
2284                 dev_dbg(hsotg->dev, "## %s: qtd->urb is NULL ##\n", __func__);
2285                 return;
2286         }
2287
2288         urb = qtd->urb->priv;
2289         if (!urb) {
2290                 dev_dbg(hsotg->dev, "## %s: urb->priv is NULL ##\n", __func__);
2291                 return;
2292         }
2293
2294         urb->actual_length = dwc2_hcd_urb_get_actual_length(qtd->urb);
2295
2296         if (dbg_urb(urb))
2297                 dev_vdbg(hsotg->dev,
2298                          "%s: urb %p device %d ep %d-%s status %d actual %d\n",
2299                          __func__, urb, usb_pipedevice(urb->pipe),
2300                          usb_pipeendpoint(urb->pipe),
2301                          usb_pipein(urb->pipe) ? "IN" : "OUT", status,
2302                          urb->actual_length);
2303
2304
2305         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) {
2306                 urb->error_count = dwc2_hcd_urb_get_error_count(qtd->urb);
2307                 for (i = 0; i < urb->number_of_packets; ++i) {
2308                         urb->iso_frame_desc[i].actual_length =
2309                                 dwc2_hcd_urb_get_iso_desc_actual_length(
2310                                                 qtd->urb, i);
2311                         urb->iso_frame_desc[i].status =
2312                                 dwc2_hcd_urb_get_iso_desc_status(qtd->urb, i);
2313                 }
2314         }
2315
2316         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS && dbg_perio()) {
2317                 for (i = 0; i < urb->number_of_packets; i++)
2318                         dev_vdbg(hsotg->dev, " ISO Desc %d status %d\n",
2319                                  i, urb->iso_frame_desc[i].status);
2320         }
2321
2322         urb->status = status;
2323         if (!status) {
2324                 if ((urb->transfer_flags & URB_SHORT_NOT_OK) &&
2325                     urb->actual_length < urb->transfer_buffer_length)
2326                         urb->status = -EREMOTEIO;
2327         }
2328
2329         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS ||
2330             usb_pipetype(urb->pipe) == PIPE_INTERRUPT) {
2331                 struct usb_host_endpoint *ep = urb->ep;
2332
2333                 if (ep)
2334                         dwc2_free_bus_bandwidth(dwc2_hsotg_to_hcd(hsotg),
2335                                         dwc2_hcd_get_ep_bandwidth(hsotg, ep),
2336                                         urb);
2337         }
2338
2339         usb_hcd_unlink_urb_from_ep(dwc2_hsotg_to_hcd(hsotg), urb);
2340         urb->hcpriv = NULL;
2341         kfree(qtd->urb);
2342         qtd->urb = NULL;
2343
2344         usb_hcd_giveback_urb(dwc2_hsotg_to_hcd(hsotg), urb, status);
2345 }
2346
2347 /*
2348  * Work queue function for starting the HCD when A-Cable is connected
2349  */
2350 static void dwc2_hcd_start_func(struct work_struct *work)
2351 {
2352         struct dwc2_hsotg *hsotg = container_of(work, struct dwc2_hsotg,
2353                                                 start_work.work);
2354
2355         dev_dbg(hsotg->dev, "%s() %p\n", __func__, hsotg);
2356         dwc2_host_start(hsotg);
2357 }
2358
2359 /*
2360  * Reset work queue function
2361  */
2362 static void dwc2_hcd_reset_func(struct work_struct *work)
2363 {
2364         struct dwc2_hsotg *hsotg = container_of(work, struct dwc2_hsotg,
2365                                                 reset_work.work);
2366         unsigned long flags;
2367         u32 hprt0;
2368
2369         dev_dbg(hsotg->dev, "USB RESET function called\n");
2370
2371         spin_lock_irqsave(&hsotg->lock, flags);
2372
2373         hprt0 = dwc2_read_hprt0(hsotg);
2374         hprt0 &= ~HPRT0_RST;
2375         dwc2_writel(hprt0, hsotg->regs + HPRT0);
2376         hsotg->flags.b.port_reset_change = 1;
2377
2378         spin_unlock_irqrestore(&hsotg->lock, flags);
2379 }
2380
2381 /*
2382  * =========================================================================
2383  *  Linux HC Driver Functions
2384  * =========================================================================
2385  */
2386
2387 /*
2388  * Initializes the DWC_otg controller and its root hub and prepares it for host
2389  * mode operation. Activates the root port. Returns 0 on success and a negative
2390  * error code on failure.
2391  */
2392 static int _dwc2_hcd_start(struct usb_hcd *hcd)
2393 {
2394         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2395         struct usb_bus *bus = hcd_to_bus(hcd);
2396         unsigned long flags;
2397
2398         dev_dbg(hsotg->dev, "DWC OTG HCD START\n");
2399
2400         spin_lock_irqsave(&hsotg->lock, flags);
2401         hsotg->lx_state = DWC2_L0;
2402         hcd->state = HC_STATE_RUNNING;
2403         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
2404
2405         if (dwc2_is_device_mode(hsotg)) {
2406                 spin_unlock_irqrestore(&hsotg->lock, flags);
2407                 return 0;       /* why 0 ?? */
2408         }
2409
2410         dwc2_hcd_reinit(hsotg);
2411
2412         /* Initialize and connect root hub if one is not already attached */
2413         if (bus->root_hub) {
2414                 dev_dbg(hsotg->dev, "DWC OTG HCD Has Root Hub\n");
2415                 /* Inform the HUB driver to resume */
2416                 usb_hcd_resume_root_hub(hcd);
2417         }
2418
2419         spin_unlock_irqrestore(&hsotg->lock, flags);
2420         return 0;
2421 }
2422
2423 /*
2424  * Halts the DWC_otg host mode operations in a clean manner. USB transfers are
2425  * stopped.
2426  */
2427 static void _dwc2_hcd_stop(struct usb_hcd *hcd)
2428 {
2429         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2430         unsigned long flags;
2431
2432         /* Turn off all host-specific interrupts */
2433         dwc2_disable_host_interrupts(hsotg);
2434
2435         /* Wait for interrupt processing to finish */
2436         synchronize_irq(hcd->irq);
2437
2438         spin_lock_irqsave(&hsotg->lock, flags);
2439         /* Ensure hcd is disconnected */
2440         dwc2_hcd_disconnect(hsotg, true);
2441         dwc2_hcd_stop(hsotg);
2442         hsotg->lx_state = DWC2_L3;
2443         hcd->state = HC_STATE_HALT;
2444         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
2445         spin_unlock_irqrestore(&hsotg->lock, flags);
2446
2447         usleep_range(1000, 3000);
2448 }
2449
2450 static int _dwc2_hcd_suspend(struct usb_hcd *hcd)
2451 {
2452         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2453         unsigned long flags;
2454         int ret = 0;
2455         u32 hprt0;
2456
2457         spin_lock_irqsave(&hsotg->lock, flags);
2458
2459         if (hsotg->lx_state != DWC2_L0)
2460                 goto unlock;
2461
2462         if (!HCD_HW_ACCESSIBLE(hcd))
2463                 goto unlock;
2464
2465         if (!hsotg->core_params->hibernation)
2466                 goto skip_power_saving;
2467
2468         /*
2469          * Drive USB suspend and disable port Power
2470          * if usb bus is not suspended.
2471          */
2472         if (!hsotg->bus_suspended) {
2473                 hprt0 = dwc2_read_hprt0(hsotg);
2474                 hprt0 |= HPRT0_SUSP;
2475                 hprt0 &= ~HPRT0_PWR;
2476                 dwc2_writel(hprt0, hsotg->regs + HPRT0);
2477         }
2478
2479         /* Enter hibernation */
2480         ret = dwc2_enter_hibernation(hsotg);
2481         if (ret) {
2482                 if (ret != -ENOTSUPP)
2483                         dev_err(hsotg->dev,
2484                                 "enter hibernation failed\n");
2485                 goto skip_power_saving;
2486         }
2487
2488         /* Ask phy to be suspended */
2489         if (!IS_ERR_OR_NULL(hsotg->uphy)) {
2490                 spin_unlock_irqrestore(&hsotg->lock, flags);
2491                 usb_phy_set_suspend(hsotg->uphy, true);
2492                 spin_lock_irqsave(&hsotg->lock, flags);
2493         }
2494
2495         /* After entering hibernation, hardware is no more accessible */
2496         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
2497
2498 skip_power_saving:
2499         hsotg->lx_state = DWC2_L2;
2500 unlock:
2501         spin_unlock_irqrestore(&hsotg->lock, flags);
2502
2503         return ret;
2504 }
2505
2506 static int _dwc2_hcd_resume(struct usb_hcd *hcd)
2507 {
2508         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2509         unsigned long flags;
2510         int ret = 0;
2511
2512         spin_lock_irqsave(&hsotg->lock, flags);
2513
2514         if (hsotg->lx_state != DWC2_L2)
2515                 goto unlock;
2516
2517         if (!hsotg->core_params->hibernation) {
2518                 hsotg->lx_state = DWC2_L0;
2519                 goto unlock;
2520         }
2521
2522         /*
2523          * Set HW accessible bit before powering on the controller
2524          * since an interrupt may rise.
2525          */
2526         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
2527
2528         /*
2529          * Enable power if not already done.
2530          * This must not be spinlocked since duration
2531          * of this call is unknown.
2532          */
2533         if (!IS_ERR_OR_NULL(hsotg->uphy)) {
2534                 spin_unlock_irqrestore(&hsotg->lock, flags);
2535                 usb_phy_set_suspend(hsotg->uphy, false);
2536                 spin_lock_irqsave(&hsotg->lock, flags);
2537         }
2538
2539         /* Exit hibernation */
2540         ret = dwc2_exit_hibernation(hsotg, true);
2541         if (ret && (ret != -ENOTSUPP))
2542                 dev_err(hsotg->dev, "exit hibernation failed\n");
2543
2544         hsotg->lx_state = DWC2_L0;
2545
2546         spin_unlock_irqrestore(&hsotg->lock, flags);
2547
2548         if (hsotg->bus_suspended) {
2549                 spin_lock_irqsave(&hsotg->lock, flags);
2550                 hsotg->flags.b.port_suspend_change = 1;
2551                 spin_unlock_irqrestore(&hsotg->lock, flags);
2552                 dwc2_port_resume(hsotg);
2553         } else {
2554                 /* Wait for controller to correctly update D+/D- level */
2555                 usleep_range(3000, 5000);
2556
2557                 /*
2558                  * Clear Port Enable and Port Status changes.
2559                  * Enable Port Power.
2560                  */
2561                 dwc2_writel(HPRT0_PWR | HPRT0_CONNDET |
2562                                 HPRT0_ENACHG, hsotg->regs + HPRT0);
2563                 /* Wait for controller to detect Port Connect */
2564                 usleep_range(5000, 7000);
2565         }
2566
2567         return ret;
2568 unlock:
2569         spin_unlock_irqrestore(&hsotg->lock, flags);
2570
2571         return ret;
2572 }
2573
2574 /* Returns the current frame number */
2575 static int _dwc2_hcd_get_frame_number(struct usb_hcd *hcd)
2576 {
2577         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2578
2579         return dwc2_hcd_get_frame_number(hsotg);
2580 }
2581
2582 static void dwc2_dump_urb_info(struct usb_hcd *hcd, struct urb *urb,
2583                                char *fn_name)
2584 {
2585 #ifdef VERBOSE_DEBUG
2586         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2587         char *pipetype;
2588         char *speed;
2589
2590         dev_vdbg(hsotg->dev, "%s, urb %p\n", fn_name, urb);
2591         dev_vdbg(hsotg->dev, "  Device address: %d\n",
2592                  usb_pipedevice(urb->pipe));
2593         dev_vdbg(hsotg->dev, "  Endpoint: %d, %s\n",
2594                  usb_pipeendpoint(urb->pipe),
2595                  usb_pipein(urb->pipe) ? "IN" : "OUT");
2596
2597         switch (usb_pipetype(urb->pipe)) {
2598         case PIPE_CONTROL:
2599                 pipetype = "CONTROL";
2600                 break;
2601         case PIPE_BULK:
2602                 pipetype = "BULK";
2603                 break;
2604         case PIPE_INTERRUPT:
2605                 pipetype = "INTERRUPT";
2606                 break;
2607         case PIPE_ISOCHRONOUS:
2608                 pipetype = "ISOCHRONOUS";
2609                 break;
2610         default:
2611                 pipetype = "UNKNOWN";
2612                 break;
2613         }
2614
2615         dev_vdbg(hsotg->dev, "  Endpoint type: %s %s (%s)\n", pipetype,
2616                  usb_urb_dir_in(urb) ? "IN" : "OUT", usb_pipein(urb->pipe) ?
2617                  "IN" : "OUT");
2618
2619         switch (urb->dev->speed) {
2620         case USB_SPEED_HIGH:
2621                 speed = "HIGH";
2622                 break;
2623         case USB_SPEED_FULL:
2624                 speed = "FULL";
2625                 break;
2626         case USB_SPEED_LOW:
2627                 speed = "LOW";
2628                 break;
2629         default:
2630                 speed = "UNKNOWN";
2631                 break;
2632         }
2633
2634         dev_vdbg(hsotg->dev, "  Speed: %s\n", speed);
2635         dev_vdbg(hsotg->dev, "  Max packet size: %d\n",
2636                  usb_maxpacket(urb->dev, urb->pipe, usb_pipeout(urb->pipe)));
2637         dev_vdbg(hsotg->dev, "  Data buffer length: %d\n",
2638                  urb->transfer_buffer_length);
2639         dev_vdbg(hsotg->dev, "  Transfer buffer: %p, Transfer DMA: %08lx\n",
2640                  urb->transfer_buffer, (unsigned long)urb->transfer_dma);
2641         dev_vdbg(hsotg->dev, "  Setup buffer: %p, Setup DMA: %08lx\n",
2642                  urb->setup_packet, (unsigned long)urb->setup_dma);
2643         dev_vdbg(hsotg->dev, "  Interval: %d\n", urb->interval);
2644
2645         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) {
2646                 int i;
2647
2648                 for (i = 0; i < urb->number_of_packets; i++) {
2649                         dev_vdbg(hsotg->dev, "  ISO Desc %d:\n", i);
2650                         dev_vdbg(hsotg->dev, "    offset: %d, length %d\n",
2651                                  urb->iso_frame_desc[i].offset,
2652                                  urb->iso_frame_desc[i].length);
2653                 }
2654         }
2655 #endif
2656 }
2657
2658 /*
2659  * Starts processing a USB transfer request specified by a USB Request Block
2660  * (URB). mem_flags indicates the type of memory allocation to use while
2661  * processing this URB.
2662  */
2663 static int _dwc2_hcd_urb_enqueue(struct usb_hcd *hcd, struct urb *urb,
2664                                  gfp_t mem_flags)
2665 {
2666         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2667         struct usb_host_endpoint *ep = urb->ep;
2668         struct dwc2_hcd_urb *dwc2_urb;
2669         int i;
2670         int retval;
2671         int alloc_bandwidth = 0;
2672         u8 ep_type = 0;
2673         u32 tflags = 0;
2674         void *buf;
2675         unsigned long flags;
2676         struct dwc2_qh *qh;
2677         bool qh_allocated = false;
2678         struct dwc2_qtd *qtd;
2679
2680         if (dbg_urb(urb)) {
2681                 dev_vdbg(hsotg->dev, "DWC OTG HCD URB Enqueue\n");
2682                 dwc2_dump_urb_info(hcd, urb, "urb_enqueue");
2683         }
2684
2685         if (ep == NULL)
2686                 return -EINVAL;
2687
2688         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS ||
2689             usb_pipetype(urb->pipe) == PIPE_INTERRUPT) {
2690                 spin_lock_irqsave(&hsotg->lock, flags);
2691                 if (!dwc2_hcd_is_bandwidth_allocated(hsotg, ep))
2692                         alloc_bandwidth = 1;
2693                 spin_unlock_irqrestore(&hsotg->lock, flags);
2694         }
2695
2696         switch (usb_pipetype(urb->pipe)) {
2697         case PIPE_CONTROL:
2698                 ep_type = USB_ENDPOINT_XFER_CONTROL;
2699                 break;
2700         case PIPE_ISOCHRONOUS:
2701                 ep_type = USB_ENDPOINT_XFER_ISOC;
2702                 break;
2703         case PIPE_BULK:
2704                 ep_type = USB_ENDPOINT_XFER_BULK;
2705                 break;
2706         case PIPE_INTERRUPT:
2707                 ep_type = USB_ENDPOINT_XFER_INT;
2708                 break;
2709         default:
2710                 dev_warn(hsotg->dev, "Wrong ep type\n");
2711         }
2712
2713         dwc2_urb = dwc2_hcd_urb_alloc(hsotg, urb->number_of_packets,
2714                                       mem_flags);
2715         if (!dwc2_urb)
2716                 return -ENOMEM;
2717
2718         dwc2_hcd_urb_set_pipeinfo(hsotg, dwc2_urb, usb_pipedevice(urb->pipe),
2719                                   usb_pipeendpoint(urb->pipe), ep_type,
2720                                   usb_pipein(urb->pipe),
2721                                   usb_maxpacket(urb->dev, urb->pipe,
2722                                                 !(usb_pipein(urb->pipe))));
2723
2724         buf = urb->transfer_buffer;
2725
2726         if (hcd->self.uses_dma) {
2727                 if (!buf && (urb->transfer_dma & 3)) {
2728                         dev_err(hsotg->dev,
2729                                 "%s: unaligned transfer with no transfer_buffer",
2730                                 __func__);
2731                         retval = -EINVAL;
2732                         goto fail0;
2733                 }
2734         }
2735
2736         if (!(urb->transfer_flags & URB_NO_INTERRUPT))
2737                 tflags |= URB_GIVEBACK_ASAP;
2738         if (urb->transfer_flags & URB_ZERO_PACKET)
2739                 tflags |= URB_SEND_ZERO_PACKET;
2740
2741         dwc2_urb->priv = urb;
2742         dwc2_urb->buf = buf;
2743         dwc2_urb->dma = urb->transfer_dma;
2744         dwc2_urb->length = urb->transfer_buffer_length;
2745         dwc2_urb->setup_packet = urb->setup_packet;
2746         dwc2_urb->setup_dma = urb->setup_dma;
2747         dwc2_urb->flags = tflags;
2748         dwc2_urb->interval = urb->interval;
2749         dwc2_urb->status = -EINPROGRESS;
2750
2751         for (i = 0; i < urb->number_of_packets; ++i)
2752                 dwc2_hcd_urb_set_iso_desc_params(dwc2_urb, i,
2753                                                  urb->iso_frame_desc[i].offset,
2754                                                  urb->iso_frame_desc[i].length);
2755
2756         urb->hcpriv = dwc2_urb;
2757         qh = (struct dwc2_qh *) ep->hcpriv;
2758         /* Create QH for the endpoint if it doesn't exist */
2759         if (!qh) {
2760                 qh = dwc2_hcd_qh_create(hsotg, dwc2_urb, mem_flags);
2761                 if (!qh) {
2762                         retval = -ENOMEM;
2763                         goto fail0;
2764                 }
2765                 ep->hcpriv = qh;
2766                 qh_allocated = true;
2767         }
2768
2769         qtd = kzalloc(sizeof(*qtd), mem_flags);
2770         if (!qtd) {
2771                 retval = -ENOMEM;
2772                 goto fail1;
2773         }
2774
2775         spin_lock_irqsave(&hsotg->lock, flags);
2776         retval = usb_hcd_link_urb_to_ep(hcd, urb);
2777         if (retval)
2778                 goto fail2;
2779
2780         retval = dwc2_hcd_urb_enqueue(hsotg, dwc2_urb, qh, qtd);
2781         if (retval)
2782                 goto fail3;
2783
2784         if (alloc_bandwidth) {
2785                 dwc2_allocate_bus_bandwidth(hcd,
2786                                 dwc2_hcd_get_ep_bandwidth(hsotg, ep),
2787                                 urb);
2788         }
2789
2790         spin_unlock_irqrestore(&hsotg->lock, flags);
2791
2792         return 0;
2793
2794 fail3:
2795         dwc2_urb->priv = NULL;
2796         usb_hcd_unlink_urb_from_ep(hcd, urb);
2797         if (qh_allocated && qh->channel && qh->channel->qh == qh)
2798                 qh->channel->qh = NULL;
2799 fail2:
2800         spin_unlock_irqrestore(&hsotg->lock, flags);
2801         urb->hcpriv = NULL;
2802         kfree(qtd);
2803 fail1:
2804         if (qh_allocated) {
2805                 struct dwc2_qtd *qtd2, *qtd2_tmp;
2806
2807                 ep->hcpriv = NULL;
2808                 dwc2_hcd_qh_unlink(hsotg, qh);
2809                 /* Free each QTD in the QH's QTD list */
2810                 list_for_each_entry_safe(qtd2, qtd2_tmp, &qh->qtd_list,
2811                                                          qtd_list_entry)
2812                         dwc2_hcd_qtd_unlink_and_free(hsotg, qtd2, qh);
2813                 dwc2_hcd_qh_free(hsotg, qh);
2814         }
2815 fail0:
2816         kfree(dwc2_urb);
2817
2818         return retval;
2819 }
2820
2821 /*
2822  * Aborts/cancels a USB transfer request. Always returns 0 to indicate success.
2823  */
2824 static int _dwc2_hcd_urb_dequeue(struct usb_hcd *hcd, struct urb *urb,
2825                                  int status)
2826 {
2827         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2828         int rc;
2829         unsigned long flags;
2830
2831         dev_dbg(hsotg->dev, "DWC OTG HCD URB Dequeue\n");
2832         dwc2_dump_urb_info(hcd, urb, "urb_dequeue");
2833
2834         spin_lock_irqsave(&hsotg->lock, flags);
2835
2836         rc = usb_hcd_check_unlink_urb(hcd, urb, status);
2837         if (rc)
2838                 goto out;
2839
2840         if (!urb->hcpriv) {
2841                 dev_dbg(hsotg->dev, "## urb->hcpriv is NULL ##\n");
2842                 goto out;
2843         }
2844
2845         rc = dwc2_hcd_urb_dequeue(hsotg, urb->hcpriv);
2846
2847         usb_hcd_unlink_urb_from_ep(hcd, urb);
2848
2849         kfree(urb->hcpriv);
2850         urb->hcpriv = NULL;
2851
2852         /* Higher layer software sets URB status */
2853         spin_unlock(&hsotg->lock);
2854         usb_hcd_giveback_urb(hcd, urb, status);
2855         spin_lock(&hsotg->lock);
2856
2857         dev_dbg(hsotg->dev, "Called usb_hcd_giveback_urb()\n");
2858         dev_dbg(hsotg->dev, "  urb->status = %d\n", urb->status);
2859 out:
2860         spin_unlock_irqrestore(&hsotg->lock, flags);
2861
2862         return rc;
2863 }
2864
2865 /*
2866  * Frees resources in the DWC_otg controller related to a given endpoint. Also
2867  * clears state in the HCD related to the endpoint. Any URBs for the endpoint
2868  * must already be dequeued.
2869  */
2870 static void _dwc2_hcd_endpoint_disable(struct usb_hcd *hcd,
2871                                        struct usb_host_endpoint *ep)
2872 {
2873         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2874
2875         dev_dbg(hsotg->dev,
2876                 "DWC OTG HCD EP DISABLE: bEndpointAddress=0x%02x, ep->hcpriv=%p\n",
2877                 ep->desc.bEndpointAddress, ep->hcpriv);
2878         dwc2_hcd_endpoint_disable(hsotg, ep, 250);
2879 }
2880
2881 /*
2882  * Resets endpoint specific parameter values, in current version used to reset
2883  * the data toggle (as a WA). This function can be called from usb_clear_halt
2884  * routine.
2885  */
2886 static void _dwc2_hcd_endpoint_reset(struct usb_hcd *hcd,
2887                                      struct usb_host_endpoint *ep)
2888 {
2889         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2890         unsigned long flags;
2891
2892         dev_dbg(hsotg->dev,
2893                 "DWC OTG HCD EP RESET: bEndpointAddress=0x%02x\n",
2894                 ep->desc.bEndpointAddress);
2895
2896         spin_lock_irqsave(&hsotg->lock, flags);
2897         dwc2_hcd_endpoint_reset(hsotg, ep);
2898         spin_unlock_irqrestore(&hsotg->lock, flags);
2899 }
2900
2901 /*
2902  * Handles host mode interrupts for the DWC_otg controller. Returns IRQ_NONE if
2903  * there was no interrupt to handle. Returns IRQ_HANDLED if there was a valid
2904  * interrupt.
2905  *
2906  * This function is called by the USB core when an interrupt occurs
2907  */
2908 static irqreturn_t _dwc2_hcd_irq(struct usb_hcd *hcd)
2909 {
2910         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2911
2912         return dwc2_handle_hcd_intr(hsotg);
2913 }
2914
2915 /*
2916  * Creates Status Change bitmap for the root hub and root port. The bitmap is
2917  * returned in buf. Bit 0 is the status change indicator for the root hub. Bit 1
2918  * is the status change indicator for the single root port. Returns 1 if either
2919  * change indicator is 1, otherwise returns 0.
2920  */
2921 static int _dwc2_hcd_hub_status_data(struct usb_hcd *hcd, char *buf)
2922 {
2923         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2924
2925         buf[0] = dwc2_hcd_is_status_changed(hsotg, 1) << 1;
2926         return buf[0] != 0;
2927 }
2928
2929 /* Handles hub class-specific requests */
2930 static int _dwc2_hcd_hub_control(struct usb_hcd *hcd, u16 typereq, u16 wvalue,
2931                                  u16 windex, char *buf, u16 wlength)
2932 {
2933         int retval = dwc2_hcd_hub_control(dwc2_hcd_to_hsotg(hcd), typereq,
2934                                           wvalue, windex, buf, wlength);
2935         return retval;
2936 }
2937
2938 /* Handles hub TT buffer clear completions */
2939 static void _dwc2_hcd_clear_tt_buffer_complete(struct usb_hcd *hcd,
2940                                                struct usb_host_endpoint *ep)
2941 {
2942         struct dwc2_hsotg *hsotg = dwc2_hcd_to_hsotg(hcd);
2943         struct dwc2_qh *qh;
2944         unsigned long flags;
2945
2946         qh = ep->hcpriv;
2947         if (!qh)
2948                 return;
2949
2950         spin_lock_irqsave(&hsotg->lock, flags);
2951         qh->tt_buffer_dirty = 0;
2952
2953         if (hsotg->flags.b.port_connect_status)
2954                 dwc2_hcd_queue_transactions(hsotg, DWC2_TRANSACTION_ALL);
2955
2956         spin_unlock_irqrestore(&hsotg->lock, flags);
2957 }
2958
2959 static struct hc_driver dwc2_hc_driver = {
2960         .description = "dwc2_hsotg",
2961         .product_desc = "DWC OTG Controller",
2962         .hcd_priv_size = sizeof(struct wrapper_priv_data),
2963
2964         .irq = _dwc2_hcd_irq,
2965         .flags = HCD_MEMORY | HCD_USB2 | HCD_BH,
2966
2967         .start = _dwc2_hcd_start,
2968         .stop = _dwc2_hcd_stop,
2969         .urb_enqueue = _dwc2_hcd_urb_enqueue,
2970         .urb_dequeue = _dwc2_hcd_urb_dequeue,
2971         .endpoint_disable = _dwc2_hcd_endpoint_disable,
2972         .endpoint_reset = _dwc2_hcd_endpoint_reset,
2973         .get_frame_number = _dwc2_hcd_get_frame_number,
2974
2975         .hub_status_data = _dwc2_hcd_hub_status_data,
2976         .hub_control = _dwc2_hcd_hub_control,
2977         .clear_tt_buffer_complete = _dwc2_hcd_clear_tt_buffer_complete,
2978
2979         .bus_suspend = _dwc2_hcd_suspend,
2980         .bus_resume = _dwc2_hcd_resume,
2981
2982         .map_urb_for_dma        = dwc2_map_urb_for_dma,
2983         .unmap_urb_for_dma      = dwc2_unmap_urb_for_dma,
2984 };
2985
2986 /*
2987  * Frees secondary storage associated with the dwc2_hsotg structure contained
2988  * in the struct usb_hcd field
2989  */
2990 static void dwc2_hcd_free(struct dwc2_hsotg *hsotg)
2991 {
2992         u32 ahbcfg;
2993         u32 dctl;
2994         int i;
2995
2996         dev_dbg(hsotg->dev, "DWC OTG HCD FREE\n");
2997
2998         /* Free memory for QH/QTD lists */
2999         dwc2_qh_list_free(hsotg, &hsotg->non_periodic_sched_inactive);
3000         dwc2_qh_list_free(hsotg, &hsotg->non_periodic_sched_active);
3001         dwc2_qh_list_free(hsotg, &hsotg->periodic_sched_inactive);
3002         dwc2_qh_list_free(hsotg, &hsotg->periodic_sched_ready);
3003         dwc2_qh_list_free(hsotg, &hsotg->periodic_sched_assigned);
3004         dwc2_qh_list_free(hsotg, &hsotg->periodic_sched_queued);
3005
3006         /* Free memory for the host channels */
3007         for (i = 0; i < MAX_EPS_CHANNELS; i++) {
3008                 struct dwc2_host_chan *chan = hsotg->hc_ptr_array[i];
3009
3010                 if (chan != NULL) {
3011                         dev_dbg(hsotg->dev, "HCD Free channel #%i, chan=%p\n",
3012                                 i, chan);
3013                         hsotg->hc_ptr_array[i] = NULL;
3014                         kfree(chan);
3015                 }
3016         }
3017
3018         if (hsotg->core_params->dma_enable > 0) {
3019                 if (hsotg->status_buf) {
3020                         dma_free_coherent(hsotg->dev, DWC2_HCD_STATUS_BUF_SIZE,
3021                                           hsotg->status_buf,
3022                                           hsotg->status_buf_dma);
3023                         hsotg->status_buf = NULL;
3024                 }
3025         } else {
3026                 kfree(hsotg->status_buf);
3027                 hsotg->status_buf = NULL;
3028         }
3029
3030         ahbcfg = dwc2_readl(hsotg->regs + GAHBCFG);
3031
3032         /* Disable all interrupts */
3033         ahbcfg &= ~GAHBCFG_GLBL_INTR_EN;
3034         dwc2_writel(ahbcfg, hsotg->regs + GAHBCFG);
3035         dwc2_writel(0, hsotg->regs + GINTMSK);
3036
3037         if (hsotg->hw_params.snpsid >= DWC2_CORE_REV_3_00a) {
3038                 dctl = dwc2_readl(hsotg->regs + DCTL);
3039                 dctl |= DCTL_SFTDISCON;
3040                 dwc2_writel(dctl, hsotg->regs + DCTL);
3041         }
3042
3043         if (hsotg->wq_otg) {
3044                 if (!cancel_work_sync(&hsotg->wf_otg))
3045                         flush_workqueue(hsotg->wq_otg);
3046                 destroy_workqueue(hsotg->wq_otg);
3047         }
3048
3049         del_timer(&hsotg->wkp_timer);
3050 }
3051
3052 static void dwc2_hcd_release(struct dwc2_hsotg *hsotg)
3053 {
3054         /* Turn off all host-specific interrupts */
3055         dwc2_disable_host_interrupts(hsotg);
3056
3057         dwc2_hcd_free(hsotg);
3058 }
3059
3060 /*
3061  * Initializes the HCD. This function allocates memory for and initializes the
3062  * static parts of the usb_hcd and dwc2_hsotg structures. It also registers the
3063  * USB bus with the core and calls the hc_driver->start() function. It returns
3064  * a negative error on failure.
3065  */
3066 int dwc2_hcd_init(struct dwc2_hsotg *hsotg, int irq)
3067 {
3068         struct usb_hcd *hcd;
3069         struct dwc2_host_chan *channel;
3070         u32 hcfg;
3071         int i, num_channels;
3072         int retval;
3073
3074         if (usb_disabled())
3075                 return -ENODEV;
3076
3077         dev_dbg(hsotg->dev, "DWC OTG HCD INIT\n");
3078
3079         retval = -ENOMEM;
3080
3081         hcfg = dwc2_readl(hsotg->regs + HCFG);
3082         dev_dbg(hsotg->dev, "hcfg=%08x\n", hcfg);
3083
3084 #ifdef CONFIG_USB_DWC2_TRACK_MISSED_SOFS
3085         hsotg->frame_num_array = kzalloc(sizeof(*hsotg->frame_num_array) *
3086                                          FRAME_NUM_ARRAY_SIZE, GFP_KERNEL);
3087         if (!hsotg->frame_num_array)
3088                 goto error1;
3089         hsotg->last_frame_num_array = kzalloc(
3090                         sizeof(*hsotg->last_frame_num_array) *
3091                         FRAME_NUM_ARRAY_SIZE, GFP_KERNEL);
3092         if (!hsotg->last_frame_num_array)
3093                 goto error1;
3094         hsotg->last_frame_num = HFNUM_MAX_FRNUM;
3095 #endif
3096
3097         /* Check if the bus driver or platform code has setup a dma_mask */
3098         if (hsotg->core_params->dma_enable > 0 &&
3099             hsotg->dev->dma_mask == NULL) {
3100                 dev_warn(hsotg->dev,
3101                          "dma_mask not set, disabling DMA\n");
3102                 hsotg->core_params->dma_enable = 0;
3103                 hsotg->core_params->dma_desc_enable = 0;
3104         }
3105
3106         /* Set device flags indicating whether the HCD supports DMA */
3107         if (hsotg->core_params->dma_enable > 0) {
3108                 if (dma_set_mask(hsotg->dev, DMA_BIT_MASK(32)) < 0)
3109                         dev_warn(hsotg->dev, "can't set DMA mask\n");
3110                 if (dma_set_coherent_mask(hsotg->dev, DMA_BIT_MASK(32)) < 0)
3111                         dev_warn(hsotg->dev, "can't set coherent DMA mask\n");
3112         }
3113
3114         hcd = usb_create_hcd(&dwc2_hc_driver, hsotg->dev, dev_name(hsotg->dev));
3115         if (!hcd)
3116                 goto error1;
3117
3118         if (hsotg->core_params->dma_enable <= 0)
3119                 hcd->self.uses_dma = 0;
3120
3121         hcd->has_tt = 1;
3122
3123         ((struct wrapper_priv_data *) &hcd->hcd_priv)->hsotg = hsotg;
3124         hsotg->priv = hcd;
3125
3126         /*
3127          * Disable the global interrupt until all the interrupt handlers are
3128          * installed
3129          */
3130         dwc2_disable_global_interrupts(hsotg);
3131
3132         /* Initialize the DWC_otg core, and select the Phy type */
3133         retval = dwc2_core_init(hsotg, true);
3134         if (retval)
3135                 goto error2;
3136
3137         /* Create new workqueue and init work */
3138         retval = -ENOMEM;
3139         hsotg->wq_otg = create_singlethread_workqueue("dwc2");
3140         if (!hsotg->wq_otg) {
3141                 dev_err(hsotg->dev, "Failed to create workqueue\n");
3142                 goto error2;
3143         }
3144         INIT_WORK(&hsotg->wf_otg, dwc2_conn_id_status_change);
3145
3146         setup_timer(&hsotg->wkp_timer, dwc2_wakeup_detected,
3147                     (unsigned long)hsotg);
3148
3149         /* Initialize the non-periodic schedule */
3150         INIT_LIST_HEAD(&hsotg->non_periodic_sched_inactive);
3151         INIT_LIST_HEAD(&hsotg->non_periodic_sched_active);
3152
3153         /* Initialize the periodic schedule */
3154         INIT_LIST_HEAD(&hsotg->periodic_sched_inactive);
3155         INIT_LIST_HEAD(&hsotg->periodic_sched_ready);
3156         INIT_LIST_HEAD(&hsotg->periodic_sched_assigned);
3157         INIT_LIST_HEAD(&hsotg->periodic_sched_queued);
3158
3159         INIT_LIST_HEAD(&hsotg->split_order);
3160
3161         /*
3162          * Create a host channel descriptor for each host channel implemented
3163          * in the controller. Initialize the channel descriptor array.
3164          */
3165         INIT_LIST_HEAD(&hsotg->free_hc_list);
3166         num_channels = hsotg->core_params->host_channels;
3167         memset(&hsotg->hc_ptr_array[0], 0, sizeof(hsotg->hc_ptr_array));
3168
3169         for (i = 0; i < num_channels; i++) {
3170                 channel = kzalloc(sizeof(*channel), GFP_KERNEL);
3171                 if (channel == NULL)
3172                         goto error3;
3173                 channel->hc_num = i;
3174                 INIT_LIST_HEAD(&channel->split_order_list_entry);
3175                 hsotg->hc_ptr_array[i] = channel;
3176         }
3177
3178         if (hsotg->core_params->uframe_sched > 0)
3179                 dwc2_hcd_init_usecs(hsotg);
3180
3181         /* Initialize hsotg start work */
3182         INIT_DELAYED_WORK(&hsotg->start_work, dwc2_hcd_start_func);
3183
3184         /* Initialize port reset work */
3185         INIT_DELAYED_WORK(&hsotg->reset_work, dwc2_hcd_reset_func);
3186
3187         /*
3188          * Allocate space for storing data on status transactions. Normally no
3189          * data is sent, but this space acts as a bit bucket. This must be
3190          * done after usb_add_hcd since that function allocates the DMA buffer
3191          * pool.
3192          */
3193         if (hsotg->core_params->dma_enable > 0)
3194                 hsotg->status_buf = dma_alloc_coherent(hsotg->dev,
3195                                         DWC2_HCD_STATUS_BUF_SIZE,
3196                                         &hsotg->status_buf_dma, GFP_KERNEL);
3197         else
3198                 hsotg->status_buf = kzalloc(DWC2_HCD_STATUS_BUF_SIZE,
3199                                           GFP_KERNEL);
3200
3201         if (!hsotg->status_buf)
3202                 goto error3;
3203
3204         /*
3205          * Create kmem caches to handle descriptor buffers in descriptor
3206          * DMA mode.
3207          * Alignment must be set to 512 bytes.
3208          */
3209         if (hsotg->core_params->dma_desc_enable ||
3210             hsotg->core_params->dma_desc_fs_enable) {
3211                 hsotg->desc_gen_cache = kmem_cache_create("dwc2-gen-desc",
3212                                 sizeof(struct dwc2_hcd_dma_desc) *
3213                                 MAX_DMA_DESC_NUM_GENERIC, 512, SLAB_CACHE_DMA,
3214                                 NULL);
3215                 if (!hsotg->desc_gen_cache) {
3216                         dev_err(hsotg->dev,
3217                                 "unable to create dwc2 generic desc cache\n");
3218
3219                         /*
3220                          * Disable descriptor dma mode since it will not be
3221                          * usable.
3222                          */
3223                         hsotg->core_params->dma_desc_enable = 0;
3224                         hsotg->core_params->dma_desc_fs_enable = 0;
3225                 }
3226
3227                 hsotg->desc_hsisoc_cache = kmem_cache_create("dwc2-hsisoc-desc",
3228                                 sizeof(struct dwc2_hcd_dma_desc) *
3229                                 MAX_DMA_DESC_NUM_HS_ISOC, 512, 0, NULL);
3230                 if (!hsotg->desc_hsisoc_cache) {
3231                         dev_err(hsotg->dev,
3232                                 "unable to create dwc2 hs isoc desc cache\n");
3233
3234                         kmem_cache_destroy(hsotg->desc_gen_cache);
3235
3236                         /*
3237                          * Disable descriptor dma mode since it will not be
3238                          * usable.
3239                          */
3240                         hsotg->core_params->dma_desc_enable = 0;
3241                         hsotg->core_params->dma_desc_fs_enable = 0;
3242                 }
3243         }
3244
3245         hsotg->otg_port = 1;
3246         hsotg->frame_list = NULL;
3247         hsotg->frame_list_dma = 0;
3248         hsotg->periodic_qh_count = 0;
3249
3250         /* Initiate lx_state to L3 disconnected state */
3251         hsotg->lx_state = DWC2_L3;
3252
3253         hcd->self.otg_port = hsotg->otg_port;
3254
3255         /* Don't support SG list at this point */
3256         hcd->self.sg_tablesize = 0;
3257
3258         if (!IS_ERR_OR_NULL(hsotg->uphy))
3259                 otg_set_host(hsotg->uphy->otg, &hcd->self);
3260
3261         /*
3262          * Finish generic HCD initialization and start the HCD. This function
3263          * allocates the DMA buffer pool, registers the USB bus, requests the
3264          * IRQ line, and calls hcd_start method.
3265          */
3266         retval = usb_add_hcd(hcd, irq, IRQF_SHARED);
3267         if (retval < 0)
3268                 goto error4;
3269
3270         device_wakeup_enable(hcd->self.controller);
3271
3272         dwc2_hcd_dump_state(hsotg);
3273
3274         dwc2_enable_global_interrupts(hsotg);
3275
3276         return 0;
3277
3278 error4:
3279         kmem_cache_destroy(hsotg->desc_gen_cache);
3280         kmem_cache_destroy(hsotg->desc_hsisoc_cache);
3281 error3:
3282         dwc2_hcd_release(hsotg);
3283 error2:
3284         usb_put_hcd(hcd);
3285 error1:
3286         kfree(hsotg->core_params);
3287
3288 #ifdef CONFIG_USB_DWC2_TRACK_MISSED_SOFS
3289         kfree(hsotg->last_frame_num_array);
3290         kfree(hsotg->frame_num_array);
3291 #endif
3292
3293         dev_err(hsotg->dev, "%s() FAILED, returning %d\n", __func__, retval);
3294         return retval;
3295 }
3296
3297 /*
3298  * Removes the HCD.
3299  * Frees memory and resources associated with the HCD and deregisters the bus.
3300  */
3301 void dwc2_hcd_remove(struct dwc2_hsotg *hsotg)
3302 {
3303         struct usb_hcd *hcd;
3304
3305         dev_dbg(hsotg->dev, "DWC OTG HCD REMOVE\n");
3306
3307         hcd = dwc2_hsotg_to_hcd(hsotg);
3308         dev_dbg(hsotg->dev, "hsotg->hcd = %p\n", hcd);
3309
3310         if (!hcd) {
3311                 dev_dbg(hsotg->dev, "%s: dwc2_hsotg_to_hcd(hsotg) NULL!\n",
3312                         __func__);
3313                 return;
3314         }
3315
3316         if (!IS_ERR_OR_NULL(hsotg->uphy))
3317                 otg_set_host(hsotg->uphy->otg, NULL);
3318
3319         usb_remove_hcd(hcd);
3320         hsotg->priv = NULL;
3321
3322         kmem_cache_destroy(hsotg->desc_gen_cache);
3323         kmem_cache_destroy(hsotg->desc_hsisoc_cache);
3324
3325         dwc2_hcd_release(hsotg);
3326         usb_put_hcd(hcd);
3327
3328 #ifdef CONFIG_USB_DWC2_TRACK_MISSED_SOFS
3329         kfree(hsotg->last_frame_num_array);
3330         kfree(hsotg->frame_num_array);
3331 #endif
3332 }