UPSTREAM: usb: dwc2: host: Reorder things in hcd_queue.c
[firefly-linux-kernel-4.4.55.git] / drivers / usb / dwc2 / hcd_queue.c
1 /*
2  * hcd_queue.c - DesignWare HS OTG Controller host queuing 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 functions to manage Queue Heads and Queue
39  * Transfer Descriptors for Host mode
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/io.h>
47 #include <linux/slab.h>
48 #include <linux/usb.h>
49
50 #include <linux/usb/hcd.h>
51 #include <linux/usb/ch11.h>
52
53 #include "core.h"
54 #include "hcd.h"
55
56 /* Wait this long before releasing periodic reservation */
57 #define DWC2_UNRESERVE_DELAY (msecs_to_jiffies(5))
58
59 /**
60  * dwc2_periodic_channel_available() - Checks that a channel is available for a
61  * periodic transfer
62  *
63  * @hsotg: The HCD state structure for the DWC OTG controller
64  *
65  * Return: 0 if successful, negative error code otherwise
66  */
67 static int dwc2_periodic_channel_available(struct dwc2_hsotg *hsotg)
68 {
69         /*
70          * Currently assuming that there is a dedicated host channel for
71          * each periodic transaction plus at least one host channel for
72          * non-periodic transactions
73          */
74         int status;
75         int num_channels;
76
77         num_channels = hsotg->core_params->host_channels;
78         if (hsotg->periodic_channels + hsotg->non_periodic_channels <
79                                                                 num_channels
80             && hsotg->periodic_channels < num_channels - 1) {
81                 status = 0;
82         } else {
83                 dev_dbg(hsotg->dev,
84                         "%s: Total channels: %d, Periodic: %d, "
85                         "Non-periodic: %d\n", __func__, num_channels,
86                         hsotg->periodic_channels, hsotg->non_periodic_channels);
87                 status = -ENOSPC;
88         }
89
90         return status;
91 }
92
93 /**
94  * dwc2_check_periodic_bandwidth() - Checks that there is sufficient bandwidth
95  * for the specified QH in the periodic schedule
96  *
97  * @hsotg: The HCD state structure for the DWC OTG controller
98  * @qh:    QH containing periodic bandwidth required
99  *
100  * Return: 0 if successful, negative error code otherwise
101  *
102  * For simplicity, this calculation assumes that all the transfers in the
103  * periodic schedule may occur in the same (micro)frame
104  */
105 static int dwc2_check_periodic_bandwidth(struct dwc2_hsotg *hsotg,
106                                          struct dwc2_qh *qh)
107 {
108         int status;
109         s16 max_claimed_usecs;
110
111         status = 0;
112
113         if (qh->dev_speed == USB_SPEED_HIGH || qh->do_split) {
114                 /*
115                  * High speed mode
116                  * Max periodic usecs is 80% x 125 usec = 100 usec
117                  */
118                 max_claimed_usecs = 100 - qh->host_us;
119         } else {
120                 /*
121                  * Full speed mode
122                  * Max periodic usecs is 90% x 1000 usec = 900 usec
123                  */
124                 max_claimed_usecs = 900 - qh->host_us;
125         }
126
127         if (hsotg->periodic_usecs > max_claimed_usecs) {
128                 dev_err(hsotg->dev,
129                         "%s: already claimed usecs %d, required usecs %d\n",
130                         __func__, hsotg->periodic_usecs, qh->host_us);
131                 status = -ENOSPC;
132         }
133
134         return status;
135 }
136
137 /**
138  * Microframe scheduler
139  * track the total use in hsotg->frame_usecs
140  * keep each qh use in qh->frame_usecs
141  * when surrendering the qh then donate the time back
142  */
143 static const unsigned short max_uframe_usecs[] = {
144         100, 100, 100, 100, 100, 100, 30, 0
145 };
146
147 void dwc2_hcd_init_usecs(struct dwc2_hsotg *hsotg)
148 {
149         int i;
150
151         for (i = 0; i < 8; i++)
152                 hsotg->frame_usecs[i] = max_uframe_usecs[i];
153 }
154
155 static int dwc2_find_single_uframe(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh)
156 {
157         unsigned short utime = qh->host_us;
158         int i;
159
160         for (i = 0; i < 8; i++) {
161                 /* At the start hsotg->frame_usecs[i] = max_uframe_usecs[i] */
162                 if (utime <= hsotg->frame_usecs[i]) {
163                         hsotg->frame_usecs[i] -= utime;
164                         qh->frame_usecs[i] += utime;
165                         return i;
166                 }
167         }
168         return -ENOSPC;
169 }
170
171 /*
172  * use this for FS apps that can span multiple uframes
173  */
174 static int dwc2_find_multi_uframe(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh)
175 {
176         unsigned short utime = qh->host_us;
177         unsigned short xtime;
178         int t_left;
179         int i;
180         int j;
181         int k;
182
183         for (i = 0; i < 8; i++) {
184                 if (hsotg->frame_usecs[i] <= 0)
185                         continue;
186
187                 /*
188                  * we need n consecutive slots so use j as a start slot
189                  * j plus j+1 must be enough time (for now)
190                  */
191                 xtime = hsotg->frame_usecs[i];
192                 for (j = i + 1; j < 8; j++) {
193                         /*
194                          * if we add this frame remaining time to xtime we may
195                          * be OK, if not we need to test j for a complete frame
196                          */
197                         if (xtime + hsotg->frame_usecs[j] < utime) {
198                                 if (hsotg->frame_usecs[j] <
199                                                         max_uframe_usecs[j])
200                                         continue;
201                         }
202                         if (xtime >= utime) {
203                                 t_left = utime;
204                                 for (k = i; k < 8; k++) {
205                                         t_left -= hsotg->frame_usecs[k];
206                                         if (t_left <= 0) {
207                                                 qh->frame_usecs[k] +=
208                                                         hsotg->frame_usecs[k]
209                                                                 + t_left;
210                                                 hsotg->frame_usecs[k] = -t_left;
211                                                 return i;
212                                         } else {
213                                                 qh->frame_usecs[k] +=
214                                                         hsotg->frame_usecs[k];
215                                                 hsotg->frame_usecs[k] = 0;
216                                         }
217                                 }
218                         }
219                         /* add the frame time to x time */
220                         xtime += hsotg->frame_usecs[j];
221                         /* we must have a fully available next frame or break */
222                         if (xtime < utime &&
223                            hsotg->frame_usecs[j] == max_uframe_usecs[j])
224                                 continue;
225                 }
226         }
227         return -ENOSPC;
228 }
229
230 static int dwc2_find_uframe(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh)
231 {
232         int ret;
233
234         if (qh->dev_speed == USB_SPEED_HIGH) {
235                 /* if this is a hs transaction we need a full frame */
236                 ret = dwc2_find_single_uframe(hsotg, qh);
237         } else {
238                 /*
239                  * if this is a fs transaction we may need a sequence
240                  * of frames
241                  */
242                 ret = dwc2_find_multi_uframe(hsotg, qh);
243         }
244         return ret;
245 }
246
247 /**
248  * dwc2_do_unreserve() - Actually release the periodic reservation
249  *
250  * This function actually releases the periodic bandwidth that was reserved
251  * by the given qh.
252  *
253  * @hsotg: The HCD state structure for the DWC OTG controller
254  * @qh:    QH for the periodic transfer.
255  */
256 static void dwc2_do_unreserve(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh)
257 {
258         assert_spin_locked(&hsotg->lock);
259
260         WARN_ON(!qh->unreserve_pending);
261
262         /* No more unreserve pending--we're doing it */
263         qh->unreserve_pending = false;
264
265         if (WARN_ON(!list_empty(&qh->qh_list_entry)))
266                 list_del_init(&qh->qh_list_entry);
267
268         /* Update claimed usecs per (micro)frame */
269         hsotg->periodic_usecs -= qh->host_us;
270
271         if (hsotg->core_params->uframe_sched > 0) {
272                 int i;
273
274                 for (i = 0; i < 8; i++) {
275                         hsotg->frame_usecs[i] += qh->frame_usecs[i];
276                         qh->frame_usecs[i] = 0;
277                 }
278         } else {
279                 /* Release periodic channel reservation */
280                 hsotg->periodic_channels--;
281         }
282 }
283
284 /**
285  * dwc2_unreserve_timer_fn() - Timer function to release periodic reservation
286  *
287  * According to the kernel doc for usb_submit_urb() (specifically the part about
288  * "Reserved Bandwidth Transfers"), we need to keep a reservation active as
289  * long as a device driver keeps submitting.  Since we're using HCD_BH to give
290  * back the URB we need to give the driver a little bit of time before we
291  * release the reservation.  This worker is called after the appropriate
292  * delay.
293  *
294  * @work: Pointer to a qh unreserve_work.
295  */
296 static void dwc2_unreserve_timer_fn(unsigned long data)
297 {
298         struct dwc2_qh *qh = (struct dwc2_qh *)data;
299         struct dwc2_hsotg *hsotg = qh->hsotg;
300         unsigned long flags;
301
302         /*
303          * Wait for the lock, or for us to be scheduled again.  We
304          * could be scheduled again if:
305          * - We started executing but didn't get the lock yet.
306          * - A new reservation came in, but cancel didn't take effect
307          *   because we already started executing.
308          * - The timer has been kicked again.
309          * In that case cancel and wait for the next call.
310          */
311         while (!spin_trylock_irqsave(&hsotg->lock, flags)) {
312                 if (timer_pending(&qh->unreserve_timer))
313                         return;
314         }
315
316         /*
317          * Might be no more unreserve pending if:
318          * - We started executing but didn't get the lock yet.
319          * - A new reservation came in, but cancel didn't take effect
320          *   because we already started executing.
321          *
322          * We can't put this in the loop above because unreserve_pending needs
323          * to be accessed under lock, so we can only check it once we got the
324          * lock.
325          */
326         if (qh->unreserve_pending)
327                 dwc2_do_unreserve(hsotg, qh);
328
329         spin_unlock_irqrestore(&hsotg->lock, flags);
330 }
331
332 /**
333  * dwc2_check_max_xfer_size() - Checks that the max transfer size allowed in a
334  * host channel is large enough to handle the maximum data transfer in a single
335  * (micro)frame for a periodic transfer
336  *
337  * @hsotg: The HCD state structure for the DWC OTG controller
338  * @qh:    QH for a periodic endpoint
339  *
340  * Return: 0 if successful, negative error code otherwise
341  */
342 static int dwc2_check_max_xfer_size(struct dwc2_hsotg *hsotg,
343                                     struct dwc2_qh *qh)
344 {
345         u32 max_xfer_size;
346         u32 max_channel_xfer_size;
347         int status = 0;
348
349         max_xfer_size = dwc2_max_packet(qh->maxp) * dwc2_hb_mult(qh->maxp);
350         max_channel_xfer_size = hsotg->core_params->max_transfer_size;
351
352         if (max_xfer_size > max_channel_xfer_size) {
353                 dev_err(hsotg->dev,
354                         "%s: Periodic xfer length %d > max xfer length for channel %d\n",
355                         __func__, max_xfer_size, max_channel_xfer_size);
356                 status = -ENOSPC;
357         }
358
359         return status;
360 }
361
362 /**
363  * dwc2_schedule_periodic() - Schedules an interrupt or isochronous transfer in
364  * the periodic schedule
365  *
366  * @hsotg: The HCD state structure for the DWC OTG controller
367  * @qh:    QH for the periodic transfer. The QH should already contain the
368  *         scheduling information.
369  *
370  * Return: 0 if successful, negative error code otherwise
371  */
372 static int dwc2_schedule_periodic(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh)
373 {
374         int status;
375
376         status = dwc2_check_max_xfer_size(hsotg, qh);
377         if (status) {
378                 dev_dbg(hsotg->dev,
379                         "%s: Channel max transfer size too small for periodic transfer\n",
380                         __func__);
381                 return status;
382         }
383
384         /* Cancel pending unreserve; if canceled OK, unreserve was pending */
385         if (del_timer(&qh->unreserve_timer))
386                 WARN_ON(!qh->unreserve_pending);
387
388         /*
389          * Only need to reserve if there's not an unreserve pending, since if an
390          * unreserve is pending then by definition our old reservation is still
391          * valid.  Unreserve might still be pending even if we didn't cancel if
392          * dwc2_unreserve_timer_fn() already started.  Code in the timer handles
393          * that case.
394          */
395         if (!qh->unreserve_pending) {
396                 if (hsotg->core_params->uframe_sched > 0) {
397                         int frame = -1;
398
399                         status = dwc2_find_uframe(hsotg, qh);
400                         if (status == 0)
401                                 frame = 7;
402                         else if (status > 0)
403                                 frame = status - 1;
404
405                         /* Set the new frame up */
406                         if (frame >= 0) {
407                                 qh->next_active_frame &= ~0x7;
408                                 qh->next_active_frame |= (frame & 7);
409                                 dwc2_sch_dbg(hsotg,
410                                              "QH=%p sched_p nxt=%04x, uf=%d\n",
411                                              qh, qh->next_active_frame, frame);
412                         }
413
414                         if (status > 0)
415                                 status = 0;
416                 } else {
417                         status = dwc2_periodic_channel_available(hsotg);
418                         if (status) {
419                                 dev_info(hsotg->dev,
420                                         "%s: No host channel available for periodic transfer\n",
421                                         __func__);
422                                 return status;
423                         }
424
425                         status = dwc2_check_periodic_bandwidth(hsotg, qh);
426                 }
427
428                 if (status) {
429                         dev_dbg(hsotg->dev,
430                                 "%s: Insufficient periodic bandwidth for periodic transfer\n",
431                                 __func__);
432                         return status;
433                 }
434
435                 if (hsotg->core_params->uframe_sched <= 0)
436                         /* Reserve periodic channel */
437                         hsotg->periodic_channels++;
438
439                 /* Update claimed usecs per (micro)frame */
440                 hsotg->periodic_usecs += qh->host_us;
441         }
442
443         qh->unreserve_pending = 0;
444
445         if (hsotg->core_params->dma_desc_enable > 0)
446                 /* Don't rely on SOF and start in ready schedule */
447                 list_add_tail(&qh->qh_list_entry, &hsotg->periodic_sched_ready);
448         else
449                 /* Always start in inactive schedule */
450                 list_add_tail(&qh->qh_list_entry,
451                               &hsotg->periodic_sched_inactive);
452
453         return status;
454 }
455
456 /**
457  * dwc2_deschedule_periodic() - Removes an interrupt or isochronous transfer
458  * from the periodic schedule
459  *
460  * @hsotg: The HCD state structure for the DWC OTG controller
461  * @qh:    QH for the periodic transfer
462  */
463 static void dwc2_deschedule_periodic(struct dwc2_hsotg *hsotg,
464                                      struct dwc2_qh *qh)
465 {
466         bool did_modify;
467
468         assert_spin_locked(&hsotg->lock);
469
470         /*
471          * Schedule the unreserve to happen in a little bit.  Cases here:
472          * - Unreserve worker might be sitting there waiting to grab the lock.
473          *   In this case it will notice it's been schedule again and will
474          *   quit.
475          * - Unreserve worker might not be scheduled.
476          *
477          * We should never already be scheduled since dwc2_schedule_periodic()
478          * should have canceled the scheduled unreserve timer (hence the
479          * warning on did_modify).
480          *
481          * We add + 1 to the timer to guarantee that at least 1 jiffy has
482          * passed (otherwise if the jiffy counter might tick right after we
483          * read it and we'll get no delay).
484          */
485         did_modify = mod_timer(&qh->unreserve_timer,
486                                jiffies + DWC2_UNRESERVE_DELAY + 1);
487         WARN_ON(did_modify);
488         qh->unreserve_pending = 1;
489
490         list_del_init(&qh->qh_list_entry);
491 }
492
493 /**
494  * dwc2_qh_init() - Initializes a QH structure
495  *
496  * @hsotg: The HCD state structure for the DWC OTG controller
497  * @qh:    The QH to init
498  * @urb:   Holds the information about the device/endpoint needed to initialize
499  *         the QH
500  */
501 #define SCHEDULE_SLOP 10
502 static void dwc2_qh_init(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh,
503                          struct dwc2_hcd_urb *urb)
504 {
505         int dev_speed, hub_addr, hub_port;
506         char *speed, *type;
507
508         dev_vdbg(hsotg->dev, "%s()\n", __func__);
509
510         /* Initialize QH */
511         qh->hsotg = hsotg;
512         setup_timer(&qh->unreserve_timer, dwc2_unreserve_timer_fn,
513                     (unsigned long)qh);
514         qh->ep_type = dwc2_hcd_get_pipe_type(&urb->pipe_info);
515         qh->ep_is_in = dwc2_hcd_is_pipe_in(&urb->pipe_info) ? 1 : 0;
516
517         qh->data_toggle = DWC2_HC_PID_DATA0;
518         qh->maxp = dwc2_hcd_get_mps(&urb->pipe_info);
519         INIT_LIST_HEAD(&qh->qtd_list);
520         INIT_LIST_HEAD(&qh->qh_list_entry);
521
522         /* FS/LS Endpoint on HS Hub, NOT virtual root hub */
523         dev_speed = dwc2_host_get_speed(hsotg, urb->priv);
524
525         dwc2_host_hub_info(hsotg, urb->priv, &hub_addr, &hub_port);
526
527         if ((dev_speed == USB_SPEED_LOW || dev_speed == USB_SPEED_FULL) &&
528             hub_addr != 0 && hub_addr != 1) {
529                 dev_vdbg(hsotg->dev,
530                          "QH init: EP %d: TT found at hub addr %d, for port %d\n",
531                          dwc2_hcd_get_ep_num(&urb->pipe_info), hub_addr,
532                          hub_port);
533                 qh->do_split = 1;
534         }
535
536         if (qh->ep_type == USB_ENDPOINT_XFER_INT ||
537             qh->ep_type == USB_ENDPOINT_XFER_ISOC) {
538                 /* Compute scheduling parameters once and save them */
539                 u32 hprt, prtspd;
540
541                 /* Todo: Account for split transfers in the bus time */
542                 int bytecount =
543                         dwc2_hb_mult(qh->maxp) * dwc2_max_packet(qh->maxp);
544
545                 qh->host_us = NS_TO_US(usb_calc_bus_time(qh->do_split ?
546                               USB_SPEED_HIGH : dev_speed, qh->ep_is_in,
547                               qh->ep_type == USB_ENDPOINT_XFER_ISOC,
548                               bytecount));
549
550                 /* Ensure frame_number corresponds to the reality */
551                 hsotg->frame_number = dwc2_hcd_get_frame_number(hsotg);
552                 /* Start in a slightly future (micro)frame */
553                 qh->next_active_frame = dwc2_frame_num_inc(hsotg->frame_number,
554                                                      SCHEDULE_SLOP);
555                 qh->host_interval = urb->interval;
556                 dwc2_sch_dbg(hsotg, "QH=%p init nxt=%04x, fn=%04x, int=%#x\n",
557                              qh, qh->next_active_frame, hsotg->frame_number,
558                              qh->host_interval);
559 #if 0
560                 /* Increase interrupt polling rate for debugging */
561                 if (qh->ep_type == USB_ENDPOINT_XFER_INT)
562                         qh->host_interval = 8;
563 #endif
564                 hprt = dwc2_readl(hsotg->regs + HPRT0);
565                 prtspd = (hprt & HPRT0_SPD_MASK) >> HPRT0_SPD_SHIFT;
566                 if (prtspd == HPRT0_SPD_HIGH_SPEED &&
567                     (dev_speed == USB_SPEED_LOW ||
568                      dev_speed == USB_SPEED_FULL)) {
569                         qh->host_interval *= 8;
570                         qh->next_active_frame |= 0x7;
571                         qh->start_split_frame = qh->next_active_frame;
572                         dwc2_sch_dbg(hsotg,
573                                      "QH=%p init*8 nxt=%04x, fn=%04x, int=%#x\n",
574                                      qh, qh->next_active_frame,
575                                      hsotg->frame_number, qh->host_interval);
576
577                 }
578                 dev_dbg(hsotg->dev, "interval=%d\n", qh->host_interval);
579         }
580
581         dev_vdbg(hsotg->dev, "DWC OTG HCD QH Initialized\n");
582         dev_vdbg(hsotg->dev, "DWC OTG HCD QH - qh = %p\n", qh);
583         dev_vdbg(hsotg->dev, "DWC OTG HCD QH - Device Address = %d\n",
584                  dwc2_hcd_get_dev_addr(&urb->pipe_info));
585         dev_vdbg(hsotg->dev, "DWC OTG HCD QH - Endpoint %d, %s\n",
586                  dwc2_hcd_get_ep_num(&urb->pipe_info),
587                  dwc2_hcd_is_pipe_in(&urb->pipe_info) ? "IN" : "OUT");
588
589         qh->dev_speed = dev_speed;
590
591         switch (dev_speed) {
592         case USB_SPEED_LOW:
593                 speed = "low";
594                 break;
595         case USB_SPEED_FULL:
596                 speed = "full";
597                 break;
598         case USB_SPEED_HIGH:
599                 speed = "high";
600                 break;
601         default:
602                 speed = "?";
603                 break;
604         }
605         dev_vdbg(hsotg->dev, "DWC OTG HCD QH - Speed = %s\n", speed);
606
607         switch (qh->ep_type) {
608         case USB_ENDPOINT_XFER_ISOC:
609                 type = "isochronous";
610                 break;
611         case USB_ENDPOINT_XFER_INT:
612                 type = "interrupt";
613                 break;
614         case USB_ENDPOINT_XFER_CONTROL:
615                 type = "control";
616                 break;
617         case USB_ENDPOINT_XFER_BULK:
618                 type = "bulk";
619                 break;
620         default:
621                 type = "?";
622                 break;
623         }
624
625         dev_vdbg(hsotg->dev, "DWC OTG HCD QH - Type = %s\n", type);
626
627         if (qh->ep_type == USB_ENDPOINT_XFER_INT) {
628                 dev_vdbg(hsotg->dev, "DWC OTG HCD QH - usecs = %d\n",
629                          qh->host_us);
630                 dev_vdbg(hsotg->dev, "DWC OTG HCD QH - interval = %d\n",
631                          qh->host_interval);
632         }
633 }
634
635 /**
636  * dwc2_hcd_qh_create() - Allocates and initializes a QH
637  *
638  * @hsotg:        The HCD state structure for the DWC OTG controller
639  * @urb:          Holds the information about the device/endpoint needed
640  *                to initialize the QH
641  * @atomic_alloc: Flag to do atomic allocation if needed
642  *
643  * Return: Pointer to the newly allocated QH, or NULL on error
644  */
645 struct dwc2_qh *dwc2_hcd_qh_create(struct dwc2_hsotg *hsotg,
646                                           struct dwc2_hcd_urb *urb,
647                                           gfp_t mem_flags)
648 {
649         struct dwc2_qh *qh;
650
651         if (!urb->priv)
652                 return NULL;
653
654         /* Allocate memory */
655         qh = kzalloc(sizeof(*qh), mem_flags);
656         if (!qh)
657                 return NULL;
658
659         dwc2_qh_init(hsotg, qh, urb);
660
661         if (hsotg->core_params->dma_desc_enable > 0 &&
662             dwc2_hcd_qh_init_ddma(hsotg, qh, mem_flags) < 0) {
663                 dwc2_hcd_qh_free(hsotg, qh);
664                 return NULL;
665         }
666
667         return qh;
668 }
669
670 /**
671  * dwc2_hcd_qh_free() - Frees the QH
672  *
673  * @hsotg: HCD instance
674  * @qh:    The QH to free
675  *
676  * QH should already be removed from the list. QTD list should already be empty
677  * if called from URB Dequeue.
678  *
679  * Must NOT be called with interrupt disabled or spinlock held
680  */
681 void dwc2_hcd_qh_free(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh)
682 {
683         /* Make sure any unreserve work is finished. */
684         if (del_timer_sync(&qh->unreserve_timer)) {
685                 unsigned long flags;
686
687                 spin_lock_irqsave(&hsotg->lock, flags);
688                 dwc2_do_unreserve(hsotg, qh);
689                 spin_unlock_irqrestore(&hsotg->lock, flags);
690         }
691
692         if (qh->desc_list)
693                 dwc2_hcd_qh_free_ddma(hsotg, qh);
694         kfree(qh);
695 }
696
697 /**
698  * dwc2_hcd_qh_add() - Adds a QH to either the non periodic or periodic
699  * schedule if it is not already in the schedule. If the QH is already in
700  * the schedule, no action is taken.
701  *
702  * @hsotg: The HCD state structure for the DWC OTG controller
703  * @qh:    The QH to add
704  *
705  * Return: 0 if successful, negative error code otherwise
706  */
707 int dwc2_hcd_qh_add(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh)
708 {
709         int status;
710         u32 intr_mask;
711
712         if (dbg_qh(qh))
713                 dev_vdbg(hsotg->dev, "%s()\n", __func__);
714
715         if (!list_empty(&qh->qh_list_entry))
716                 /* QH already in a schedule */
717                 return 0;
718
719         if (!dwc2_frame_num_le(qh->next_active_frame, hsotg->frame_number) &&
720                         !hsotg->frame_number) {
721                 u16 new_frame;
722
723                 dev_dbg(hsotg->dev,
724                                 "reset frame number counter\n");
725                 new_frame = dwc2_frame_num_inc(hsotg->frame_number,
726                                 SCHEDULE_SLOP);
727
728                 dwc2_sch_vdbg(hsotg, "QH=%p reset nxt=%04x=>%04x\n",
729                               qh, qh->next_active_frame, new_frame);
730                 qh->next_active_frame = new_frame;
731         }
732
733         /* Add the new QH to the appropriate schedule */
734         if (dwc2_qh_is_non_per(qh)) {
735                 /* Always start in inactive schedule */
736                 list_add_tail(&qh->qh_list_entry,
737                               &hsotg->non_periodic_sched_inactive);
738                 return 0;
739         }
740
741         status = dwc2_schedule_periodic(hsotg, qh);
742         if (status)
743                 return status;
744         if (!hsotg->periodic_qh_count) {
745                 intr_mask = dwc2_readl(hsotg->regs + GINTMSK);
746                 intr_mask |= GINTSTS_SOF;
747                 dwc2_writel(intr_mask, hsotg->regs + GINTMSK);
748         }
749         hsotg->periodic_qh_count++;
750
751         return 0;
752 }
753
754 /**
755  * dwc2_hcd_qh_unlink() - Removes a QH from either the non-periodic or periodic
756  * schedule. Memory is not freed.
757  *
758  * @hsotg: The HCD state structure
759  * @qh:    QH to remove from schedule
760  */
761 void dwc2_hcd_qh_unlink(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh)
762 {
763         u32 intr_mask;
764
765         dev_vdbg(hsotg->dev, "%s()\n", __func__);
766
767         if (list_empty(&qh->qh_list_entry))
768                 /* QH is not in a schedule */
769                 return;
770
771         if (dwc2_qh_is_non_per(qh)) {
772                 if (hsotg->non_periodic_qh_ptr == &qh->qh_list_entry)
773                         hsotg->non_periodic_qh_ptr =
774                                         hsotg->non_periodic_qh_ptr->next;
775                 list_del_init(&qh->qh_list_entry);
776                 return;
777         }
778
779         dwc2_deschedule_periodic(hsotg, qh);
780         hsotg->periodic_qh_count--;
781         if (!hsotg->periodic_qh_count) {
782                 intr_mask = dwc2_readl(hsotg->regs + GINTMSK);
783                 intr_mask &= ~GINTSTS_SOF;
784                 dwc2_writel(intr_mask, hsotg->regs + GINTMSK);
785         }
786 }
787
788 /*
789  * Schedule the next continuing periodic split transfer
790  */
791 static void dwc2_sched_periodic_split(struct dwc2_hsotg *hsotg,
792                                       struct dwc2_qh *qh, u16 frame_number,
793                                       int sched_next_periodic_split)
794 {
795         u16 incr;
796         u16 old_frame = qh->next_active_frame;
797
798         if (sched_next_periodic_split) {
799                 qh->next_active_frame = frame_number;
800                 incr = dwc2_frame_num_inc(qh->start_split_frame, 1);
801                 if (dwc2_frame_num_le(frame_number, incr)) {
802                         /*
803                          * Allow one frame to elapse after start split
804                          * microframe before scheduling complete split, but
805                          * DON'T if we are doing the next start split in the
806                          * same frame for an ISOC out
807                          */
808                         if (qh->ep_type != USB_ENDPOINT_XFER_ISOC ||
809                             qh->ep_is_in != 0) {
810                                 qh->next_active_frame = dwc2_frame_num_inc(
811                                         qh->next_active_frame, 1);
812                         }
813                 }
814         } else {
815                 qh->next_active_frame =
816                         dwc2_frame_num_inc(qh->start_split_frame,
817                                            qh->host_interval);
818                 if (dwc2_frame_num_le(qh->next_active_frame, frame_number))
819                         qh->next_active_frame = frame_number;
820                 qh->next_active_frame |= 0x7;
821                 qh->start_split_frame = qh->next_active_frame;
822         }
823
824         dwc2_sch_vdbg(hsotg, "QH=%p next(%d) fn=%04x, nxt=%04x=>%04x (%+d)\n",
825                       qh, sched_next_periodic_split, frame_number, old_frame,
826                       qh->next_active_frame,
827                       dwc2_frame_num_dec(qh->next_active_frame, old_frame));
828 }
829
830 /*
831  * Deactivates a QH. For non-periodic QHs, removes the QH from the active
832  * non-periodic schedule. The QH is added to the inactive non-periodic
833  * schedule if any QTDs are still attached to the QH.
834  *
835  * For periodic QHs, the QH is removed from the periodic queued schedule. If
836  * there are any QTDs still attached to the QH, the QH is added to either the
837  * periodic inactive schedule or the periodic ready schedule and its next
838  * scheduled frame is calculated. The QH is placed in the ready schedule if
839  * the scheduled frame has been reached already. Otherwise it's placed in the
840  * inactive schedule. If there are no QTDs attached to the QH, the QH is
841  * completely removed from the periodic schedule.
842  */
843 void dwc2_hcd_qh_deactivate(struct dwc2_hsotg *hsotg, struct dwc2_qh *qh,
844                             int sched_next_periodic_split)
845 {
846         u16 frame_number;
847
848         if (dbg_qh(qh))
849                 dev_vdbg(hsotg->dev, "%s()\n", __func__);
850
851         if (dwc2_qh_is_non_per(qh)) {
852                 dwc2_hcd_qh_unlink(hsotg, qh);
853                 if (!list_empty(&qh->qtd_list))
854                         /* Add back to inactive non-periodic schedule */
855                         dwc2_hcd_qh_add(hsotg, qh);
856                 return;
857         }
858
859         frame_number = dwc2_hcd_get_frame_number(hsotg);
860
861         if (qh->do_split) {
862                 dwc2_sched_periodic_split(hsotg, qh, frame_number,
863                                           sched_next_periodic_split);
864         } else {
865                 qh->next_active_frame = dwc2_frame_num_inc(
866                         qh->next_active_frame, qh->host_interval);
867                 if (dwc2_frame_num_le(qh->next_active_frame, frame_number))
868                         qh->next_active_frame = frame_number;
869         }
870
871         if (list_empty(&qh->qtd_list)) {
872                 dwc2_hcd_qh_unlink(hsotg, qh);
873                 return;
874         }
875         /*
876          * Remove from periodic_sched_queued and move to
877          * appropriate queue
878          */
879         if ((hsotg->core_params->uframe_sched > 0 &&
880              dwc2_frame_num_le(qh->next_active_frame, frame_number)) ||
881             (hsotg->core_params->uframe_sched <= 0 &&
882              qh->next_active_frame == frame_number))
883                 list_move_tail(&qh->qh_list_entry,
884                                &hsotg->periodic_sched_ready);
885         else
886                 list_move_tail(&qh->qh_list_entry,
887                                &hsotg->periodic_sched_inactive);
888 }
889
890 /**
891  * dwc2_hcd_qtd_init() - Initializes a QTD structure
892  *
893  * @qtd: The QTD to initialize
894  * @urb: The associated URB
895  */
896 void dwc2_hcd_qtd_init(struct dwc2_qtd *qtd, struct dwc2_hcd_urb *urb)
897 {
898         qtd->urb = urb;
899         if (dwc2_hcd_get_pipe_type(&urb->pipe_info) ==
900                         USB_ENDPOINT_XFER_CONTROL) {
901                 /*
902                  * The only time the QTD data toggle is used is on the data
903                  * phase of control transfers. This phase always starts with
904                  * DATA1.
905                  */
906                 qtd->data_toggle = DWC2_HC_PID_DATA1;
907                 qtd->control_phase = DWC2_CONTROL_SETUP;
908         }
909
910         /* Start split */
911         qtd->complete_split = 0;
912         qtd->isoc_split_pos = DWC2_HCSPLT_XACTPOS_ALL;
913         qtd->isoc_split_offset = 0;
914         qtd->in_process = 0;
915
916         /* Store the qtd ptr in the urb to reference the QTD */
917         urb->qtd = qtd;
918 }
919
920 /**
921  * dwc2_hcd_qtd_add() - Adds a QTD to the QTD-list of a QH
922  *                      Caller must hold driver lock.
923  *
924  * @hsotg:        The DWC HCD structure
925  * @qtd:          The QTD to add
926  * @qh:           Queue head to add qtd to
927  *
928  * Return: 0 if successful, negative error code otherwise
929  *
930  * If the QH to which the QTD is added is not currently scheduled, it is placed
931  * into the proper schedule based on its EP type.
932  */
933 int dwc2_hcd_qtd_add(struct dwc2_hsotg *hsotg, struct dwc2_qtd *qtd,
934                      struct dwc2_qh *qh)
935 {
936         int retval;
937
938         if (unlikely(!qh)) {
939                 dev_err(hsotg->dev, "%s: Invalid QH\n", __func__);
940                 retval = -EINVAL;
941                 goto fail;
942         }
943
944         retval = dwc2_hcd_qh_add(hsotg, qh);
945         if (retval)
946                 goto fail;
947
948         qtd->qh = qh;
949         list_add_tail(&qtd->qtd_list_entry, &qh->qtd_list);
950
951         return 0;
952 fail:
953         return retval;
954 }