1 /*
2  * Copyright (C) 2001-2004 by David Brownell
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License as published by the
6  * Free Software Foundation; either version 2 of the License, or (at your
7  * option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18 
19 /* this file is part of ehci-hcd.c */
20 
21 /*-------------------------------------------------------------------------*/
22 
23 /*
24  * EHCI hardware queue manipulation ... the core.  QH/QTD manipulation.
25  *
26  * Control, bulk, and interrupt traffic all use "qh" lists.  They list "qtd"
27  * entries describing USB transactions, max 16-20kB/entry (with 4kB-aligned
28  * buffers needed for the larger number).  We use one QH per endpoint, queue
29  * multiple urbs (all three types) per endpoint.  URBs may need several qtds.
30  *
31  * ISO traffic uses "ISO TD" (itd, and sitd) records, and (along with
32  * interrupts) needs careful scheduling.  Performance improvements can be
33  * an ongoing challenge.  That's in "ehci-sched.c".
34  *
35  * USB 1.1 devices are handled (a) by "companion" OHCI or UHCI root hubs,
36  * or otherwise through transaction translators (TTs) in USB 2.0 hubs using
37  * (b) special fields in qh entries or (c) split iso entries.  TTs will
38  * buffer low/full speed data so the host collects it at high speed.
39  */
40 
41 /*-------------------------------------------------------------------------*/
42 
43 /* fill a qtd, returning how much of the buffer we were able to queue up */
44 // 该函数用于填充qtd结构,并返回当前qtd所承载的数据长度,
45 // 每个qtd有5个pionter,每个pionter最大索引范围4k,因此,每个qtd最大索引5*4k
46 // 该函数填充pionter,把指针与要指向的物理地址关联起来
47 // #include "sunxi_hal_timer.h"
48 
49 static int
qtd_fill(struct ehci_hcd * ehci,struct ehci_qtd * qtd,dma_addr_t buf,size_t len,int token,int maxpacket)50 qtd_fill(struct ehci_hcd *ehci, struct ehci_qtd *qtd, dma_addr_t buf,
51           size_t len, int token, int maxpacket)
52 {
53     int i, count;
54     u64 addr = buf;
55 
56     /* one buffer entry per 4K ... first might be short or unaligned */
57     qtd->hw_buf[0] = cpu_to_hc32(ehci, (u32)addr);
58     qtd->hw_buf_hi[0] = cpu_to_hc32(ehci, (u32)(addr >> 32));
59     count = 0x1000 - (buf & 0x0fff);    /* rest of that page */
60     if (len < count)        /* ... iff needed */
61         count = len;
62     else {
63         buf +=  0x1000;
64         buf &= ~0x0fff;
65 
66         /* per-qtd limit: from 16K to 20K (best alignment) */
67         for (i = 1; count < len && i < 5; i++) {
68             addr = buf;
69             qtd->hw_buf[i] = cpu_to_hc32(ehci, (u32)addr);
70             qtd->hw_buf_hi[i] = cpu_to_hc32(ehci,
71                     (u32)(addr >> 32));
72             buf += 0x1000;
73             if ((count + 0x1000) < len)
74                 count += 0x1000;
75             else
76                 count = len;
77         }
78 
79         /* short packets may only terminate transfers */
80         if (count != len)
81             count -= (count % maxpacket);
82     }
83     qtd->hw_token = cpu_to_hc32(ehci, (count << 16) | token);
84     qtd->length = count;
85 
86     EHCI_DEBUG_PRINTF("qtd->hw_token = 0x%lx, qtd->length = 0x%x",
87                         qtd->hw_token, qtd->length);
88 
89     return count;
90 }
91 
92 /*-------------------------------------------------------------------------*/
93 
94 static inline void
qh_update(struct ehci_hcd * ehci,struct ehci_qh * qh,struct ehci_qtd * qtd)95 qh_update (struct ehci_hcd *ehci, struct ehci_qh *qh, struct ehci_qtd *qtd)
96 {
97     struct ehci_qh_hw *hw = qh->hw;
98 
99     /* writes to an active overlay are unsafe */
100     //WARN_ON(qh->qh_state != QH_STATE_IDLE);
101 
102     hw->hw_qtd_next = QTD_NEXT(ehci, qtd->qtd_dma);
103     hw->hw_alt_next = EHCI_LIST_END(ehci);
104 
105     /* Except for control endpoints, we make hardware maintain data
106      * toggle (like OHCI) ... here (re)initialize the toggle in the QH,
107      * and set the pseudo-toggle in udev. Only usb_clear_halt() will
108      * ever clear it.
109      */
110     if (!(hw->hw_info1 & cpu_to_hc32(ehci, QH_TOGGLE_CTL))) {
111         unsigned    is_out, epnum;
112 
113         is_out = qh->is_out;
114         epnum = (hc32_to_cpup(ehci, &hw->hw_info1) >> 8) & 0x0f;
115         if (!usb_gettoggle(qh->ps.udev, epnum, is_out)) {
116             hw->hw_token &= ~cpu_to_hc32(ehci, QTD_TOGGLE);
117             usb_settoggle(qh->ps.udev, epnum, is_out, 1);
118         }
119     }
120 
121     hw->hw_token &= cpu_to_hc32(ehci, QTD_TOGGLE | QTD_STS_PING);
122 }
123 
124 /* if it weren't for a common silicon quirk (writing the dummy into the qh
125  * overlay, so qh->hw_token wrongly becomes inactive/halted), only fault
126  * recovery (including urb dequeue) would need software changes to a QH...
127  */
128 static void
qh_refresh(struct ehci_hcd * ehci,struct ehci_qh * qh)129 qh_refresh (struct ehci_hcd *ehci, struct ehci_qh *qh)
130 {
131     struct ehci_qtd *qtd;
132 
133     qtd = list_entry(qh->qtd_list.next, struct ehci_qtd, qtd_list);
134 
135     /*
136      * first qtd may already be partially processed.
137      * If we come here during unlink, the QH overlay region
138      * might have reference to the just unlinked qtd. The
139      * qtd is updated in qh_completions(). Update the QH
140      * overlay here.
141      */
142     if (qh->hw->hw_token & ACTIVE_BIT(ehci)) {
143         qh->hw->hw_qtd_next = qtd->hw_next;
144         if (qh->should_be_inactive)
145             ehci_warn("qh %p should be inactive!\n", qh);
146     } else {
147         qh_update(ehci, qh, qtd);
148     }
149     qh->should_be_inactive = 0;
150 }
151 
152 /*-------------------------------------------------------------------------*/
153 
154 static void qh_link_async(struct ehci_hcd *ehci, struct ehci_qh *qh);
155 
156 //static void ehci_clear_tt_buffer_complete(struct usb_hcd *hcd,
ehci_clear_tt_buffer_complete(struct hc_gen_dev * hcd,struct usb_host_virt_endpoint * ep)157 static void ehci_clear_tt_buffer_complete(struct hc_gen_dev *hcd,
158         struct usb_host_virt_endpoint *ep)
159 {
160     struct ehci_hcd     *ehci = hcd_to_ehci(hcd);
161     struct ehci_qh      *qh = ep->hcpriv;
162     unsigned long       flags;
163 
164     flags = hal_spin_lock_irqsave(&ehci->lock);
165     qh->clearing_tt = 0;
166     if (qh->qh_state == QH_STATE_IDLE && !list_empty(&qh->qtd_list)
167             && ehci->rh_state == EHCI_RH_RUNNING)
168         qh_link_async(ehci, qh);
169     hal_spin_unlock_irqrestore(&ehci->lock, flags);
170 }
171 
172 //static void ehci_clear_tt_buffer(struct ehci_hcd *ehci, struct ehci_qh *qh,
173 //      struct urb *urb, u32 token)
174 //{
175 //
176 //  /* If an async split transaction gets an error or is unlinked,
177 //   * the TT buffer may be left in an indeterminate state.  We
178 //   * have to clear the TT buffer.
179 //   *
180 //   * Note: this routine is never called for Isochronous transfers.
181 //   */
182 //  if (urb->dev->tt && !usb_pipeint(urb->pipe) && !qh->clearing_tt) {
183 ////#ifdef CONFIG_DYNAMIC_DEBUG
184 ////        struct usb_device *tt = urb->dev->tt->hub;
185 ////        dev_dbg(&tt->dev,
186 ////            "clear tt buffer port %d, a%d ep%d t%08x\n",
187 ////            urb->dev->ttport, urb->dev->devnum,
188 ////            usb_pipeendpoint(urb->pipe), token);
189 ////#endif /* CONFIG_DYNAMIC_DEBUG */
190 //      if (!ehci_is_TDI(ehci)
191 //              || urb->dev->tt->hub !=
192 //                 ehci_to_hcd(ehci)->self.root_hub) {
193 //          if (usb_hub_clear_tt_buffer(urb) == 0)
194 //              qh->clearing_tt = 1;
195 //      } else {
196 //
197 //          /* REVISIT ARC-derived cores don't clear the root
198 //           * hub TT buffer in this way...
199 //           */
200 //      }
201 //  }
202 //}
203 
qtd_copy_status(struct ehci_hcd * ehci,struct urb * urb,size_t length,u32 token)204 static int qtd_copy_status (
205     struct ehci_hcd *ehci,
206     struct urb *urb,
207     size_t length,
208     u32 token
209 )
210 {
211     int status = -EINPROGRESS;
212 
213     /* count IN/OUT bytes, not SETUP (even short packets) */
214     if (QTD_PID (token) != 2)
215         urb->actual_length += length - QTD_LENGTH (token);
216 
217     /* don't modify error codes */
218     //if (unlikely(urb->unlinked))
219     //  return status;
220 
221     /* force cleanup after short read; not always an error */
222     //if (unlikely (IS_SHORT_READ (token)))
223     //  status = -EREMOTEIO;
224 
225     /* serious "can't proceed" faults reported by the hardware */
226     if (token & QTD_STS_HALT) {
227         if (token & QTD_STS_BABBLE) {
228             /* FIXME "must" disable babbling device's port too */
229             status = -EOVERFLOW;
230         /* CERR nonzero + halt --> stall */
231         } else if (QTD_CERR(token)) {
232             status = -EPIPE;
233 
234         /* In theory, more than one of the following bits can be set
235          * since they are sticky and the transaction is retried.
236          * Which to test first is rather arbitrary.
237          */
238         } else if (token & QTD_STS_MMF) {
239             /* fs/ls interrupt xfer missed the complete-split */
240             status = -EPROTO;
241         } else if (token & QTD_STS_DBE) {
242             status = (QTD_PID (token) == 1) /* IN ? */
243                 ? -ENOSR  /* hc couldn't read data */
244                 : -ECOMM; /* hc couldn't write data */
245         } else if (token & QTD_STS_XACT) {
246             /* timeout, bad CRC, wrong PID, etc */
247             //ehci_dbg("devpath %s ep%d%s 3strikes\n",
248             //  urb->dev->devpath,
249             //  usb_pipeendpoint(urb->pipe),
250             //  usb_pipein(urb->pipe) ? "in" : "out");
251             status = -EPROTO;
252         } else {    /* unknown */
253             status = -EPROTO;
254         }
255     }
256 
257     return status;
258 }
259 
260 static void
ehci_urb_done(struct ehci_hcd * ehci,struct urb * urb,int status)261 ehci_urb_done(struct ehci_hcd *ehci, struct urb *urb, int status)
262 {
263     if (usb_pipetype(urb->pipe) == PIPE_INTERRUPT) {
264         /* ... update hc-wide periodic stats */
265         ehci_to_hcd(ehci)->self.bandwidth_int_reqs--;
266     }
267 
268     if (unlikely(urb->unlinked)) {
269         COUNT(ehci->stats.unlink);
270     } else {
271         /* report non-error and short read status as zero */
272         if (status == -EINPROGRESS || status == -EREMOTEIO)
273             status = 0;
274         COUNT(ehci->stats.complete);
275     }
276 
277 //#ifdef EHCI_URB_TRACE
278 //  ehci_dbg (ehci,
279 //      "%s %s urb %p ep%d%s status %d len %d/%d\n",
280 //      __func__, urb->dev->devpath, urb,
281 //      usb_pipeendpoint (urb->pipe),
282 //      usb_pipein (urb->pipe) ? "in" : "out",
283 //      status,
284 //      urb->actual_length, urb->transfer_buffer_length);
285 //#endif
286 
287     // usb_hcd_unlink_urb_from_ep(ehci_to_hcd(ehci), urb);
288     //usb_hcd_giveback_urb(ehci_to_hcd(ehci), urb, status);
289 
290     if (urb->status == -EINPROGRESS)
291     {
292         urb->status = status;
293     }
294 
295     urb->hcpriv = NULL;
296 
297     usb_hcd_giveback_urb(ehci_to_hcd(ehci), urb);
298 }
299 
300 static int qh_schedule (struct ehci_hcd *ehci, struct ehci_qh *qh);
301 
302 /*
303  * Process and free completed qtds for a qh, returning URBs to drivers.
304  * Chases up to qh->hw_current.  Returns nonzero if the caller should
305  * unlink qh.
306  */
307 // qh_completions()中通过对qh下链接的qtd进行逐个遍历,来判断传输的情况
qh_completions(struct ehci_hcd * ehci,struct ehci_qh * qh)308 static unsigned qh_completions(struct ehci_hcd *ehci, struct ehci_qh *qh)
309 {
310     struct ehci_qtd *last, *end = qh->dummy;
311     struct list_head *entry, *tmp;
312     int last_status;
313     int stopped;
314     u8 state;
315     struct ehci_qh_hw *hw = qh->hw;
316 
317     /* completions (or tasks on other cpus) must never clobber HALT
318      * till we've gone through and cleaned everything up, even when
319      * they add urbs to this qh's queue or mark them for unlinking.
320      *
321      * NOTE:  unlinking expects to be done in queue order.
322      *
323      * It's a bug for qh->qh_state to be anything other than
324      * QH_STATE_IDLE, unless our caller is scan_async() or
325      * scan_intr().
326      */
327     state = qh->qh_state;
328     qh->qh_state = QH_STATE_COMPLETING;
329     stopped = (state == QH_STATE_IDLE);
330 
331 rescan:
332     last = NULL;
333     last_status = -EINPROGRESS;
334     qh->dequeue_during_giveback = 0;
335 
336     /* remove de-activated QTDs from front of queue.
337      * after faults (including short reads), cleanup this urb
338      * then let the queue advance.
339      * if queue is stopped, handles unlinks.
340      */
341     // list_for_each_safe逐个的把qh上的qtd取出放在指针entry中,
342     // list_for_each_safe的特点是可以中途删除entry,通过指针tmp去找到下一个entry
343     //该语句实际上是一个for循环
344     list_for_each_safe (entry, tmp, &qh->qtd_list) {
345         struct ehci_qtd *qtd;
346         struct urb *urb;
347         u32 token = 0;
348 
349         //printf("\n");
350         // 找到对应的qtd内存地址
351         qtd = list_entry(entry, struct ehci_qtd, qtd_list);
352         urb = qtd->urb;
353 
354         /* clean up any state from previous QTD ...*/
355         //last初始值是NULL,第一次不执行,跳过if
356         // 当再一次执行到此处时,如果前一次的处理中有qtd是执行完传输的(包括传输出错),
357         // last此时就会指向了前一个qtd,并在if语句中的ehci_qtd_free()函数中把分配的qtd空间释放掉
358         if (last) {
359             // 一个qtd链表中的urb指针的指向都是相同的,除了最末这一个dummy qtd,
360             // 所以在遍历到最后的qtd时“last->urb != urb”满足
361             if (likely(last->urb != urb)) {
362                 // ehci_urb_done()要做的一件事是回调urb->complete()函数指针,
363                 // 从而使控制权回到USB device Driver中,这就是我们填充一个urb的回调函数的触发处
364                 ehci_urb_done(ehci, last->urb, last_status);
365                 last_status = -EINPROGRESS;
366             }
367             ehci_qtd_free (ehci, last);
368             // list_add_tail(&(last->qtd_list), &(ehci->wait_free_list));
369             // hal_log_info("\033[41m ADD : last = 0x%x \033[0m", last);
370             last = NULL;
371         }
372 
373         /* ignore urbs submitted during completions we reported */
374         // 判断遍历到最后的dummy qtd,就跳出循环,表明整个qtd链表已被处理完了
375         if (qtd == end) {
376             break;
377         }
378 
379         /* hardware copies qtd out of qh overlay */
380         //rmb ();
381         // HC在处理完一个qtd后,反映处理结果的值会回写到当前qtd的token字段中,
382         // HCD读取这个token的Status值后,可以获知HC的传输情况
383         hal_dcache_invalidate((unsigned long)&(((struct ehci_qtd *)(qtd->qtd_dma))->hw_token), sizeof(uint32_t));
384         token = hc32_to_cpu(ehci, qtd->hw_token);
385         EHCI_DEBUG_PRINTF("token = 0x%lx", token);
386 
387         /* always clean up qtds the hc de-activated */
388     retry_xacterr:
389         if ((token & QTD_STS_ACTIVE) == 0) {
390             // 传输完成
391 
392             /* Report Data Buffer Error: non-fatal but useful */
393             // 在EHCI SPEC里说,不被视作传输错误,会强制endpoint重发一次,所以代码也只是做了打印
394             if (token & QTD_STS_DBE)
395             {
396                 EHCI_DEBUG_PRINTF("detected DataBufferErr for urb %p ep%d%s len %d, qtd %p [qh %p]",
397                                   urb,
398                                   usb_endpoint_num(&urb->ep->desc),
399                                   usb_endpoint_dir_in(&urb->ep->desc) ? "in" : "out",
400                                   urb->transfer_buffer_length,
401                                   qtd,
402                                   qh);
403             }
404             /* on STALL, error, and short reads this urb must
405              * complete and all its qtds must be recycled.
406              */
407             if ((token & QTD_STS_HALT) != 0) {
408                 // 表明当前qtd的传输出现了错误,而且与该endpoint的传输都被停掉
409                 EHCI_DEBUG_PRINTF("error halt");
410                 /* retry transaction errors until we
411                  * reach the software xacterr limit
412                  */
413                 // QTD_STS_XACT代表HC没有收到device发回的有效应答包
414                 if ((token & QTD_STS_XACT) &&
415                         QTD_CERR(token) == 0 &&
416                         ++qh->xacterrs < QH_XACTERR_MAX &&
417                         !urb->unlinked) {
418                     EHCI_DEBUG_PRINTF("detected XactErr len %zu/%zu retry %d",
419                              qtd->length - QTD_LENGTH(token), qtd->length, qh->xacterrs);
420 
421                     /* reset the token in the qtd and the
422                      * qh overlay (which still contains
423                      * the qtd) so that we pick up from
424                      * where we left off
425                      */
426                     // 出现这样的错误HCD的处理方式是,
427                     // 由软件把Halted位清零,
428                     // token[11:10] CERR位设为0x3,
429                     // Active位置1再次使能该qtd,
430                     // 让HC重新传输这个qtd
431                     token &= ~QTD_STS_HALT;
432                     token |= QTD_STS_ACTIVE |
433                             (EHCI_TUNE_CERR << 10);
434                     qtd->hw_token = cpu_to_hc32(ehci, token);
435                     //wmb();
436                     hw->hw_token = cpu_to_hc32(ehci, token);
437 
438                     hal_dcache_clean_invalidate((unsigned long)&(((struct ehci_qtd *)(qtd->qtd_dma))->hw_token), sizeof(uint32_t));
439                     hal_dcache_clean_invalidate((unsigned long)&(((struct ehci_qh_hw *)(qh->qh_dma))->hw_token), sizeof(uint32_t));
440 
441                     // 重复以上动作,直到传输成功或超时为止
442                     goto retry_xacterr;
443                 }
444                 stopped = 1;
445                 qh->unlink_reason |= QH_UNLINK_HALTED;
446 
447             /* magic dummy for some short reads; qh won't advance.
448              * that silicon quirk can kick in with this dummy too.
449              *
450              * other short reads won't stop the queue, including
451              * control transfers (status stage handles that) or
452              * most other single-qtd reads ... the queue stops if
453              * URB_SHORT_NOT_OK was set so the driver submitting
454              * the urbs could clean it up.
455              */
456             } else if (IS_SHORT_READ (token)
457                     && !(qtd->hw_alt_next
458                         & EHCI_LIST_END(ehci))) {
459                 EHCI_DEBUG_PRINTF("short reads");
460                 stopped = 1;
461                 qh->unlink_reason |= QH_UNLINK_SHORT_READ;
462             }
463 
464         /* stop scanning when we reach qtds the hc is using */
465         } else if (!stopped
466                 && ehci->rh_state >= EHCI_RH_RUNNING) {
467             EHCI_DEBUG_PRINTF("stop scanning");
468             break;
469 
470         /* scan the whole queue for unlinks whenever it stops */
471         } else {
472             EHCI_DEBUG_PRINTF("stopped");
473             stopped = 1;
474 
475             /* cancel everything if we halt, suspend, etc */
476             if (ehci->rh_state < EHCI_RH_RUNNING) {
477                 last_status = -ESHUTDOWN;
478                 qh->unlink_reason |= QH_UNLINK_SHUTDOWN;
479             }
480 
481             /* this qtd is active; skip it unless a previous qtd
482              * for its urb faulted, or its urb was canceled.
483              */
484             else if (last_status == -EINPROGRESS && !urb->unlinked) {
485             // else if (last_status == -EINPROGRESS) {
486                 continue;
487             }
488 
489             /*
490              * If this was the active qtd when the qh was unlinked
491              * and the overlay's token is active, then the overlay
492              * hasn't been written back to the qtd yet so use its
493              * token instead of the qtd's.  After the qtd is
494              * processed and removed, the overlay won't be valid
495              * any more.
496              */
497             if (state == QH_STATE_IDLE &&
498                     qh->qtd_list.next == &qtd->qtd_list &&
499                     (hw->hw_token & ACTIVE_BIT(ehci))) {
500                 token = hc32_to_cpu(ehci, hw->hw_token);
501                 hw->hw_token &= ~ACTIVE_BIT(ehci);
502                 qh->should_be_inactive = 1;
503 
504                 /* An unlink may leave an incomplete
505                  * async transaction in the TT buffer.
506                  * We have to clear it.
507                  */
508                 //ehci_clear_tt_buffer(ehci, qh, urb, token);
509             }
510         }
511 
512         /* unless we already know the urb's status, collect qtd status
513          * and update count of bytes transferred.  in common short read
514          * cases with only one data qtd (including control transfers),
515          * queue processing won't halt.  but with two or more qtds (for
516          * example, with a 32 KB transfer), when the first qtd gets a
517          * short read the second must be removed by hand.
518          */
519         if (last_status == -EINPROGRESS) {
520             // 读取状态
521             last_status = qtd_copy_status(ehci, urb,
522                     qtd->length, token);
523             if (last_status == -EREMOTEIO
524                     && (qtd->hw_alt_next
525                         & EHCI_LIST_END(ehci))) {
526                 last_status = -EINPROGRESS;
527             }
528             /* As part of low/full-speed endpoint-halt processing
529              * we must clear the TT buffer (11.17.5).
530              */
531             //if (unlikely(last_status != -EINPROGRESS &&
532             //      last_status != -EREMOTEIO)) {
533             //  /* The TT's in some hubs malfunction when they
534             //   * receive this request following a STALL (they
535             //   * stop sending isochronous packets).  Since a
536             //   * STALL can't leave the TT buffer in a busy
537             //   * state (if you believe Figures 11-48 - 11-51
538             //   * in the USB 2.0 spec), we won't clear the TT
539             //   * buffer in this case.  Strictly speaking this
540             //   * is a violation of the spec.
541             //   */
542             //  if (last_status != -EPIPE)
543             //      ehci_clear_tt_buffer(ehci, qh, urb,
544             //              token);
545             //}
546         }
547 
548         /* if we're removing something not at the queue head,
549          * patch the hardware queue pointer.
550          */
551         //如果是qtd链表的首个元素,则qtd->qtd_list.prev == &qh->qtd_list
552         //如果不是首元素,则需要先解链再释放,如是首元素,则不必
553         if (stopped && qtd->qtd_list.prev != &qh->qtd_list) {
554             //找到上一个qtd的地址
555             last = list_entry (qtd->qtd_list.prev,
556                     struct ehci_qtd, qtd_list);
557             //将上一个qtd的next与本qtd的next链接,即,将本qtd从链表中解链
558             last->hw_next = qtd->hw_next;
559 
560             hal_dcache_clean_invalidate((unsigned long)&(((struct ehci_qtd *)(last->qtd_dma))->hw_next), sizeof(uint32_t));
561             hal_dcache_clean_invalidate((unsigned long)&(((struct ehci_qtd *)(qtd->qtd_dma))->hw_next), sizeof(uint32_t));
562         }
563 
564         /* remove qtd; it's recycled after possible urb completion */
565         //释放
566         list_del (&qtd->qtd_list);
567         //记录到last里,下一次循环时真正回收qtd
568         last = qtd;
569 
570         /* reinit the xacterr counter for the next qtd */
571         qh->xacterrs = 0;
572     }//end of list_for_each_safe(entry, tmp, &qh->qtd_list)
573 
574     /* last urb's completion might still need calling */
575     // 如果指针last非空,那么一定是指向一个qtd链表队列的末尾处(非dummy qtd)
576     if (last != NULL) {
577         ehci_urb_done(ehci, last->urb, last_status);
578         ehci_qtd_free(ehci, last);
579         // list_add_tail(&(last->qtd_list), &(ehci->wait_free_list));
580         // hal_log_info("\033[41m ADD : last = 0x%x \033[0m", last);
581     }
582 
583     /* Do we need to rescan for URBs dequeued during a giveback? */
584     if (unlikely(qh->dequeue_during_giveback)) {
585         /* If the QH is already unlinked, do the rescan now. */
586         if (state == QH_STATE_IDLE) {
587             EHCI_DEBUG_PRINTF("goto rescan");
588             goto rescan;
589         }
590 
591         /* Otherwise the caller must unlink the QH. */
592     }
593 
594     /* restore original state; caller must unlink or relink */
595     qh->qh_state = state;
596 
597     /* be sure the hardware's done with the qh before refreshing
598      * it after fault cleanup, or recovering from silicon wrongly
599      * overlaying the dummy qtd (which reduces DMA chatter).
600      *
601      * We won't refresh a QH that's linked (after the HC
602      * stopped the queue).  That avoids a race:
603      *  - HC reads first part of QH;
604      *  - CPU updates that first part and the token;
605      *  - HC reads rest of that QH, including token
606      * Result:  HC gets an inconsistent image, and then
607      * DMAs to/from the wrong memory (corrupting it).
608      *
609      * That should be rare for interrupt transfers,
610      * except maybe high bandwidth ...
611      */
612     if (stopped != 0 || hw->hw_qtd_next == EHCI_LIST_END(ehci)) {
613         qh->unlink_reason |= QH_UNLINK_DUMMY_OVERLAY;
614     }
615 
616     EHCI_DEBUG_PRINTF("qh->unlink_reason = %u\n", qh->unlink_reason);
617     /* Let the caller know if the QH needs to be unlinked. */
618     return qh->unlink_reason;
619 }
620 
621 /*-------------------------------------------------------------------------*/
622 
623 // high bandwidth multiplier, as encoded in highspeed endpoint descriptors
624 #define hb_mult(wMaxPacketSize) (1 + (((wMaxPacketSize) >> 11) & 0x03))
625 // ... and packet size, for any kind of endpoint descriptor
626 #define max_packet(wMaxPacketSize) ((wMaxPacketSize) & 0x07ff)
627 
628 /*
629  * reverse of qh_urb_transaction:  free a list of TDs.
630  * used for cleanup after errors, before HC sees an URB's TDs.
631  */
qtd_list_free(struct ehci_hcd * ehci,struct urb * urb,struct list_head * qtd_list)632 static void qtd_list_free (
633     struct ehci_hcd     *ehci,
634     struct urb      *urb,
635     struct list_head    *qtd_list
636 ) {
637     struct list_head    *entry, *temp;
638 
639     list_for_each_safe (entry, temp, qtd_list) {
640         struct ehci_qtd *qtd;
641 
642         qtd = list_entry (entry, struct ehci_qtd, qtd_list);
643         list_del (&qtd->qtd_list);
644         ehci_qtd_free (ehci, qtd);
645     }
646 }
647 
648 /*
649  * create a list of filled qtds for this URB; won't link into qh.
650  * 为URB创建并填充qtd列表,但是并未加到qh中
651  * 一次USB的传输请求是由usb_submit_urb()提交下来的,要传输相关的数据、地址等信息都放在URB中
652  * qh_urb_transaction()函数就是对URB携带的信息整合到EHCI能识别的数据结构中,即构造相应的qTD
653  */
654 static struct list_head *
qh_urb_transaction(struct ehci_hcd * ehci,struct urb * urb,struct list_head * head,gfp_t flags)655 qh_urb_transaction (
656     struct ehci_hcd     *ehci,
657     struct urb      *urb,
658     struct list_head    *head,
659     gfp_t           flags
660 ) {
661     struct ehci_qtd     *qtd, *qtd_prev;
662     dma_addr_t      buf;
663     int         len, this_sg_len, maxpacket;
664     int         is_input;
665     u32         token;
666     int         i = 0;
667     //struct scatterlist    *sg;
668 
669     /*
670      * URBs map to sequences of QTDs:  one logical transaction
671      */
672     qtd = ehci_qtd_alloc (ehci, flags);
673     if (!qtd)
674         return NULL;
675     list_add_tail (&qtd->qtd_list, head);
676     qtd->urb = urb;
677 
678     token = QTD_STS_ACTIVE;//使能该qtd
679     token |= (EHCI_TUNE_CERR << 10);
680     /* for split transactions, SplitXState initialized to zero */
681 
682     len = urb->transfer_buffer_length;
683     is_input = usb_pipein (urb->pipe);
684     if (usb_pipecontrol (urb->pipe)) {
685         /* SETUP pid */
686         // 在此处将urb对应的数据包地址信息分配到qtd的pointer中,并返回长度
687         qtd_fill(ehci, qtd, urb->setup_dma,
688                 sizeof (struct usb_ctrlrequest),
689                 token | (2 /* "setup" */ << 8), 8);
690 
691         /* ... and always at least one more pid */
692         token ^= QTD_TOGGLE;
693         //用qtd_prev指向填充过的qtd,再申请一个空的qtd
694         qtd_prev = qtd;
695         qtd = ehci_qtd_alloc (ehci, flags);
696         if (!qtd)
697             goto cleanup;
698         qtd->urb = urb;
699 
700         // 将新的qtd联入队列
701         qtd_prev->hw_next = QTD_NEXT(ehci, qtd->qtd_dma);
702         list_add_tail (&qtd->qtd_list, head);
703 
704         /* for zero length DATA stages, STATUS is always IN */
705         // 为0说明是仅用于control的命令传输,没有数据
706         if (len == 0)
707             token |= (1 /* "in" */ << 8);
708     }
709 
710     /*
711      * data transfer stage:  buffer setup
712      */
713     //i = urb->num_mapped_sgs;
714     //if (len > 0 && i > 0) {
715     //  sg = urb->sg;
716     //  buf = sg_dma_address(sg);
717 
718     //  /* urb->transfer_buffer_length may be smaller than the
719     //   * size of the scatterlist (or vice versa)
720     //   */
721     //  this_sg_len = min_t(int, sg_dma_len(sg), len);
722     //} else {
723         //sg = NULL;
724         buf = urb->transfer_dma;
725         this_sg_len = len;
726     //}
727 
728     if (is_input)
729         token |= (1 /* "in" */ << 8);
730     /* else it's already initted to "out" pid (0 << 8) */
731 
732     maxpacket = max_packet(usb_maxpacket(urb->dev, urb->pipe, !is_input));
733 
734     /*
735      * buffer gets wrapped in one or more qtds;
736      * last one may be "short" (including zero len)
737      * and may serve as a control status ack
738      */
739     for (;;) {
740         int this_qtd_len;
741 
742         this_qtd_len = qtd_fill(ehci, qtd, buf, this_sg_len, token,
743                 maxpacket);
744         this_sg_len -= this_qtd_len;
745         len -= this_qtd_len;
746         buf += this_qtd_len;
747 
748         /*
749          * short reads advance to a "magic" dummy instead of the next
750          * qtd ... that forces the queue to stop, for manual cleanup.
751          * (this will usually be overridden later.)
752          */
753         if (is_input)
754             qtd->hw_alt_next = ehci->async->hw->hw_alt_next;
755 
756         /* qh makes control packets use qtd toggle; maybe switch it */
757         if ((maxpacket & (this_qtd_len + (maxpacket - 1))) == 0)
758             token ^= QTD_TOGGLE;
759 
760         if (this_sg_len <= 0) {
761             if (--i <= 0 || len <= 0)
762                 break;
763         //  sg = sg_next(sg);
764         //  buf = sg_dma_address(sg);
765         //  this_sg_len = min_t(int, sg_dma_len(sg), len);
766         }
767 
768         qtd_prev = qtd;
769         qtd = ehci_qtd_alloc (ehci, flags);
770         if (!qtd)
771             goto cleanup;
772         qtd->urb = urb;
773         qtd_prev->hw_next = QTD_NEXT(ehci, qtd->qtd_dma);
774         list_add_tail (&qtd->qtd_list, head);
775     }
776 
777     /*
778      * unless the caller requires manual cleanup after short reads,
779      * have the alt_next mechanism keep the queue running after the
780      * last data qtd (the only one, for control and most other cases).
781      */
782     if ((urb->transfer_flags & URB_SHORT_NOT_OK) == 0
783                 || usb_pipecontrol (urb->pipe))
784         qtd->hw_alt_next = EHCI_LIST_END(ehci);
785 
786     /*
787      * control requests may need a terminating data "status" ack;
788      * other OUT ones may need a terminating short packet
789      * (zero length).
790      */
791     // 对urb中transfer_buffer_length非零,即涉及数据传输,且传输类型为Control或者是传输方向为OUT,就增加一个qtd作为结束,
792     // 该qtd要传输的数据长度为零。并把最后一个qtd的token中IOC位置1,表示在完成qtd的传输后,在下一个中断周期产生一个中断
793     if (urb->transfer_buffer_length != 0) {
794         int one_more = 0;
795 
796         if (usb_pipecontrol (urb->pipe)) {
797             one_more = 1;
798             token ^= 0x0100;    /* "in" <--> "out"  */
799             token |= QTD_TOGGLE;    /* force DATA1 */
800             //printf("[%s %d] token = 0x%lx\n", __func__, __LINE__, token);
801         } else if (usb_pipeout(urb->pipe)
802                 && (urb->transfer_flags & URB_ZERO_PACKET)
803                 && !(urb->transfer_buffer_length % maxpacket)) {
804             one_more = 1;
805         }
806         if (one_more) {
807             qtd_prev = qtd;
808             qtd = ehci_qtd_alloc (ehci, flags);
809             if (!qtd)
810                 goto cleanup;
811             qtd->urb = urb;
812             qtd_prev->hw_next = QTD_NEXT(ehci, qtd->qtd_dma);
813             list_add_tail (&qtd->qtd_list, head);
814 
815             /* never any data in such packets */
816             qtd_fill(ehci, qtd, 0, 0, token, 0);
817         }
818     }
819 
820     /* by default, enable interrupt on urb completion */
821     if (!(urb->transfer_flags & URB_NO_INTERRUPT))
822         qtd->hw_token |= cpu_to_hc32(ehci, QTD_IOC);
823     return head;
824 
825 cleanup:
826     qtd_list_free (ehci, urb, head);
827     return NULL;
828 }
829 
830 /*-------------------------------------------------------------------------*/
831 
832 // Would be best to create all qh's from config descriptors,
833 // when each interface/altsetting is established.  Unlink
834 // any previous qh and cancel its urbs first; endpoints are
835 // implicitly reset then (data toggle too).
836 // That'd mean updating how usbcore talks to HCDs. (2.7?)
837 
838 
839 /*
840  * Each QH holds a qtd list; a QH is used for everything except iso.
841  *
842  * For interrupt urbs, the scheduler must set the microframe scheduling
843  * mask(s) each time the QH gets scheduled.  For highspeed, that's
844  * just one microframe in the s-mask.  For split interrupt transactions
845  * there are additional complications: c-mask, maybe FSTNs.
846  */
847 static struct ehci_qh *
qh_make(struct ehci_hcd * ehci,struct urb * urb,gfp_t flags)848 qh_make (
849     struct ehci_hcd     *ehci,
850     struct urb      *urb,
851     gfp_t           flags
852 ) {
853     struct ehci_qh      *qh = ehci_qh_alloc (ehci);
854     u32         info1 = 0, info2 = 0;
855     int         is_input, type;
856     int         maxp = 0;
857     //struct usb_tt     *tt = urb->dev->tt;
858     struct ehci_qh_hw   *hw;
859 
860     if (!qh)
861         return qh;
862 
863     /*
864      * init endpoint/device data for this QH
865      */
866     info1 |= usb_pipeendpoint (urb->pipe) << 8;
867     info1 |= usb_pipedevice (urb->pipe) << 0;
868 
869     is_input = usb_pipein (urb->pipe);
870     type = usb_pipetype (urb->pipe);
871     maxp = usb_maxpacket (urb->dev, urb->pipe, !is_input);
872 
873     /* 1024 byte maxpacket is a hardware ceiling.  High bandwidth
874      * acts like up to 3KB, but is built from smaller packets.
875      */
876     if (max_packet(maxp) > 1024) {
877         ehci_dbg("bogus qh maxpacket %d\n", max_packet(maxp));
878         goto done;
879     }
880 
881     /* Compute interrupt scheduling parameters just once, and save.
882      * - allowing for high bandwidth, how many nsec/uframe are used?
883      * - split transactions need a second CSPLIT uframe; same question
884      * - splits also need a schedule gap (for full/low speed I/O)
885      * - qh has a polling interval
886      *
887      * For control/bulk requests, the HC or TT handles these.
888      */
889     if (type == PIPE_INTERRUPT) {
890         unsigned    tmp;
891 
892         //qh->ps.usecs = NS_TO_US(usb_calc_bus_time(USB_SPEED_HIGH,
893         //      is_input, 0,
894         //      hb_mult(maxp) * max_packet(maxp)));
895         qh->ps.phase = NO_FRAME;
896 
897         if (urb->dev->speed == USB_SPEED_HIGH) {
898             qh->ps.c_usecs = 0;
899             qh->gap_uf = 0;
900 
901             if (urb->interval > 1 && urb->interval < 8) {
902                 /* NOTE interval 2 or 4 uframes could work.
903                  * But interval 1 scheduling is simpler, and
904                  * includes high bandwidth.
905                  */
906                 urb->interval = 1;
907             } else if (urb->interval > ehci->periodic_size << 3) {
908                 urb->interval = ehci->periodic_size << 3;
909             }
910             qh->ps.period = urb->interval >> 3;
911 
912             /* period for bandwidth allocation */
913             tmp = min(EHCI_BANDWIDTH_SIZE,
914                 1 << (urb->ep->desc.bInterval - 1));
915 
916             /* Allow urb->interval to override */
917             qh->ps.bw_uperiod = min(tmp, (unsigned)urb->interval);
918             qh->ps.bw_period = qh->ps.bw_uperiod >> 3;
919         } else {
920             int     think_time;
921 
922             /* gap is f(FS/LS transfer times) */
923             //qh->gap_uf = 1 + usb_calc_bus_time (urb->dev->speed,
924             //      is_input, 0, maxp) / (125 * 1000);
925 
926             /* FIXME this just approximates SPLIT/CSPLIT times */
927             if (is_input) {     // SPLIT, gap, CSPLIT+DATA
928                 //qh->ps.c_usecs = qh->ps.usecs + HS_USECS(0);
929                 //qh->ps.usecs = HS_USECS(1);
930             } else {        // SPLIT+DATA, gap, CSPLIT
931                 //qh->ps.usecs += HS_USECS(1);
932                 //qh->ps.c_usecs = HS_USECS(0);
933             }
934 
935             //think_time = tt ? tt->think_time : 0;
936             //qh->ps.tt_usecs = NS_TO_US(think_time +
937             //      usb_calc_bus_time (urb->dev->speed,
938             //      is_input, 0, max_packet (maxp)));
939             if (urb->interval > ehci->periodic_size)
940                 urb->interval = ehci->periodic_size;
941             qh->ps.period = urb->interval;
942 
943             /* period for bandwidth allocation */
944             tmp = min(EHCI_BANDWIDTH_FRAMES,
945                     (unsigned)(urb->ep->desc.bInterval));
946             //tmp = rounddown_pow_of_two(tmp);
947 
948             /* Allow urb->interval to override */
949             qh->ps.bw_period = min((unsigned)tmp, (unsigned)(urb->interval));
950             qh->ps.bw_uperiod = qh->ps.bw_period << 3;
951         }
952     }
953 
954     /* support for tt scheduling, and access to toggles */
955     qh->ps.udev = urb->dev;
956     qh->ps.ep = urb->ep;
957 
958     /* using TT? */
959     switch (urb->dev->speed) {
960     case USB_SPEED_LOW:
961         info1 |= QH_LOW_SPEED;
962         /* FALL THROUGH */
963 
964     case USB_SPEED_FULL:
965         /* EPS 0 means "full" */
966         if (type != PIPE_INTERRUPT)
967             info1 |= (EHCI_TUNE_RL_TT << 28);
968         if (type == PIPE_CONTROL) {
969             info1 |= QH_CONTROL_EP;     /* for TT */
970             info1 |= QH_TOGGLE_CTL;     /* toggle from qtd */
971         }
972         info1 |= maxp << 16;
973 
974         info2 |= (EHCI_TUNE_MULT_TT << 30);
975 
976         /* Some Freescale processors have an erratum in which the
977          * port number in the queue head was 0..N-1 instead of 1..N.
978          */
979         if (ehci_has_fsl_portno_bug(ehci))
980             info2 |= (urb->dev->ttport-1) << 23;
981         else
982             info2 |= urb->dev->ttport << 23;
983 
984         /* set the address of the TT; for TDI's integrated
985          * root hub tt, leave it zeroed.
986          */
987         //if (tt && tt->hub != ehci_to_hcd(ehci)->self.root_hub)
988         //  info2 |= tt->hub->devnum << 16;
989 
990         /* NOTE:  if (PIPE_INTERRUPT) { scheduler sets c-mask } */
991 
992         break;
993 
994     case USB_SPEED_HIGH:        /* no TT involved */
995         info1 |= QH_HIGH_SPEED;
996         if (type == PIPE_CONTROL) {
997             info1 |= (EHCI_TUNE_RL_HS << 28);
998             info1 |= 64 << 16;  /* usb2 fixed maxpacket */
999             info1 |= QH_TOGGLE_CTL; /* toggle from qtd */
1000             info2 |= (EHCI_TUNE_MULT_HS << 30);
1001         } else if (type == PIPE_BULK) {
1002             info1 |= (EHCI_TUNE_RL_HS << 28);
1003             /* The USB spec says that high speed bulk endpoints
1004              * always use 512 byte maxpacket.  But some device
1005              * vendors decided to ignore that, and MSFT is happy
1006              * to help them do so.  So now people expect to use
1007              * such nonconformant devices with Linux too; sigh.
1008              */
1009             info1 |= max_packet(maxp) << 16;
1010             info2 |= (EHCI_TUNE_MULT_HS << 30);
1011         } else {        /* PIPE_INTERRUPT */
1012             info1 |= max_packet (maxp) << 16;
1013             info2 |= hb_mult (maxp) << 30;
1014         }
1015         break;
1016     default:
1017         ehci_dbg("bogus dev %p speed %d\n", urb->dev,
1018             urb->dev->speed);
1019 done:
1020         qh_destroy(ehci, qh);
1021         return NULL;
1022     }
1023 
1024     /* NOTE:  if (PIPE_INTERRUPT) { scheduler sets s-mask } */
1025 
1026     /* init as live, toggle clear */
1027     qh->qh_state = QH_STATE_IDLE;
1028     hw = qh->hw;
1029     hw->hw_info1 = cpu_to_hc32(ehci, info1);
1030     hw->hw_info2 = cpu_to_hc32(ehci, info2);
1031     qh->is_out = !is_input;
1032     usb_settoggle (urb->dev, usb_pipeendpoint (urb->pipe), !is_input, 1);
1033     return qh;
1034 }
1035 
1036 /*-------------------------------------------------------------------------*/
1037 
enable_async(struct ehci_hcd * ehci)1038 static void enable_async(struct ehci_hcd *ehci)
1039 {
1040 
1041     int cmd;
1042     int ret;
1043 
1044     if (ehci->async_count++)
1045         return;
1046 
1047     ///* Stop waiting to turn off the async schedule */
1048     ehci->enabled_hrtimer_events &= ~BIT(EHCI_HRTIMER_DISABLE_ASYNC);
1049 
1050     ///* Don't start the schedule until ASS is 0 */
1051     hal_dcache_clean_all();      //akira 20202020
1052     hal_dcache_invalidate_all(); //akira 20202020
1053     ehci_poll_ASS(ehci);
1054     turn_on_io_watchdog(ehci);
1055     /*scan??*/
1056 
1057     //akira???
1058     // /* need to flush Dcache? */
1059     // hal_dcache_clean_all();
1060 
1061     // /* Enable async. schedule. */
1062     // cmd = ehci_readl(ehci, &ehci->regs->command);
1063     // cmd |= CMD_ASE;
1064     // ehci_writel(ehci, cmd, &ehci->regs->command);
1065 
1066     // ret = ehci_handshake(ehci, (uint32_t *)&ehci->regs->status, STS_ASS, STS_ASS,
1067     //      100*1000);
1068     // if (ret < 0) {
1069     //  hal_log_err("EHCI fail timeout STS_ASS set.\n");
1070     //  return;
1071     // }
1072 
1073     // if (ehci->isoc_count > 0 || (ehci->async_count + ehci->intr_count > 0))
1074     //      ehci_work(ehci);
1075 }
1076 
disable_async(struct ehci_hcd * ehci)1077 static void disable_async(struct ehci_hcd *ehci)
1078 {
1079     int cmd;
1080     int ret;
1081 
1082     if (--ehci->async_count)
1083         return;
1084 
1085     /* The async schedule and unlink lists are supposed to be empty */
1086     //WARN_ON(ehci->async->qh_next.qh || !list_empty(&ehci->async_unlink) ||
1087     //      !list_empty(&ehci->async_idle));
1088 
1089     ///* Don't turn off the schedule until ASS is 1 */
1090     hal_dcache_clean_all();      //akira 20202020
1091     hal_dcache_invalidate_all(); //akira 20202020
1092 
1093     ehci_poll_ASS(ehci);
1094     // cmd = ehci_readl(ehci, &ehci->regs->command);
1095     // cmd &= ~CMD_ASE;
1096     // ehci_writel(ehci, cmd, &ehci->regs->command);
1097 
1098     // ret = ehci_handshake(ehci, (uint32_t *)&ehci->regs->status, STS_ASS, 0,
1099     //      100*1000);
1100     // if (ret < 0) {
1101     //  hal_log_err("EHCI fail timeout STS_ASS reset.\n");
1102     //  return;
1103     // }
1104 }
1105 
1106 /* move qh (and its qtds) onto async queue; maybe enable queue.  */
1107 
qh_link_async(struct ehci_hcd * ehci,struct ehci_qh * qh)1108 static void qh_link_async (struct ehci_hcd *ehci, struct ehci_qh *qh)
1109 {
1110     uint32_t        dma = QH_NEXT(ehci, qh->qh_dma);
1111     struct ehci_qh  *head;
1112 
1113     /* Don't link a QH if there's a Clear-TT-Buffer pending */
1114     //if (unlikely(qh->clearing_tt))
1115     //  return;
1116 
1117     //WARN_ON(qh->qh_state != QH_STATE_IDLE);
1118 
1119     /* clear halt and/or toggle; and maybe recover from silicon quirk */
1120     qh_refresh(ehci, qh);
1121 
1122     /* splice right after start */
1123     head = ehci->async;
1124     qh->qh_next = head->qh_next;
1125     qh->hw->hw_next = head->hw->hw_next;
1126 
1127     head->qh_next.qh = qh;
1128     head->hw->hw_next = dma;
1129 
1130     qh->qh_state = QH_STATE_LINKED;
1131     qh->xacterrs = 0;
1132     qh->unlink_reason = 0;
1133     /* qtd completions reported later by interrupt */
1134 
1135     enable_async(ehci);
1136 }
1137 
1138 /*-------------------------------------------------------------------------*/
1139 
1140 /*
1141  * For control/bulk/interrupt, return QH with these TDs appended.
1142  * Allocates and initializes the QH if necessary.
1143  * Returns null if it can't allocate a QH it needs to.
1144  * If the QH has TDs (urbs) already, that's great.
1145  */
qh_append_tds(struct ehci_hcd * ehci,struct urb * urb,struct list_head * qtd_list,int epnum,void ** ptr)1146 static struct ehci_qh *qh_append_tds (
1147     struct ehci_hcd     *ehci,
1148     struct urb      *urb,
1149     struct list_head    *qtd_list,
1150     int         epnum,
1151     void            **ptr
1152 )
1153 {
1154     struct ehci_qh      *qh = NULL;
1155     uint32_t        qh_addr_mask = cpu_to_hc32(ehci, 0x7f);
1156 
1157     qh = (struct ehci_qh *) *ptr;
1158     if (unlikely (qh == NULL)) {
1159         /* can't sleep here, we have ehci->lock... */
1160         qh = qh_make (ehci, urb, 0);
1161         *ptr = qh;
1162     }
1163     if (qh != NULL) {
1164         struct ehci_qtd *qtd;
1165 
1166         if (unlikely (list_empty (qtd_list)))
1167             qtd = NULL;
1168         else
1169             qtd = list_entry (qtd_list->next, struct ehci_qtd,
1170                     qtd_list);
1171 
1172         /* control qh may need patching ... */
1173         if (epnum == 0) {
1174 
1175                         /* usb_reset_device() briefly reverts to address 0 */
1176                         if (usb_pipedevice (urb->pipe) == 0)
1177                 qh->hw->hw_info1 &= ~qh_addr_mask;
1178         }
1179 
1180         /* just one way to queue requests: swap with the dummy qtd.
1181          * only hc or qh_refresh() ever modify the overlay.
1182          */
1183         if (qtd != NULL) {
1184             struct ehci_qtd     *dummy;
1185             dma_addr_t      dma;
1186             uint32_t        token;
1187 
1188             /* to avoid racing the HC, use the dummy td instead of
1189              * the first td of our list (becomes new dummy).  both
1190              * tds stay deactivated until we're done, when the
1191              * HC is allowed to fetch the old dummy (4.10.2).
1192              */
1193             token = qtd->hw_token;
1194             qtd->hw_token = HALT_BIT(ehci);
1195 
1196             dummy = qh->dummy;
1197 
1198             dma = dummy->qtd_dma;
1199             *dummy = *qtd;
1200             dummy->qtd_dma = dma;
1201 
1202             list_del (&qtd->qtd_list);
1203             list_add (&dummy->qtd_list, qtd_list);
1204             list_splice_tail(qtd_list, &qh->qtd_list);
1205 
1206             ehci_qtd_init(ehci, qtd, qtd->qtd_dma);
1207             qh->dummy = qtd;
1208 
1209             /* hc must see the new dummy at list end */
1210             dma = qtd->qtd_dma;
1211             qtd = list_entry (qh->qtd_list.prev,
1212                     struct ehci_qtd, qtd_list);
1213             qtd->hw_next = QTD_NEXT(ehci, dma);
1214 
1215             /* let the hc process these next qtds */
1216             dummy->hw_token = token;
1217 
1218             urb->hcpriv = qh;
1219         }
1220     }
1221     return qh;
1222 }
1223 
1224 /*-------------------------------------------------------------------------*/
1225 
1226 static int
submit_async(struct ehci_hcd * ehci,struct urb * urb,struct list_head * qtd_list,gfp_t mem_flags)1227 submit_async (
1228     struct ehci_hcd     *ehci,
1229     struct urb      *urb,
1230     struct list_head    *qtd_list,
1231     gfp_t           mem_flags
1232 ) {
1233     int         epnum;
1234     unsigned long       flags;
1235     struct ehci_qh      *qh = NULL;
1236     int         rc = 0;
1237 
1238     epnum = urb->ep->desc.bEndpointAddress;
1239 
1240     flags = hal_spin_lock_irqsave(&ehci->lock);
1241     //if (unlikely(!HCD_HW_ACCESSIBLE(ehci_to_hcd(ehci)))) {
1242     //  rc = -ESHUTDOWN;
1243     //  goto done;
1244     //}
1245     // rc = usb_hcd_link_urb_to_ep(ehci_to_hcd(ehci), urb);
1246     // if (rc)
1247     //  goto done;
1248 
1249     qh = qh_append_tds(ehci, urb, qtd_list, epnum, &urb->ep->hcpriv);
1250     if (qh == NULL) {
1251         usb_hcd_unlink_urb_from_ep(ehci_to_hcd(ehci), urb);
1252         rc = -ENOMEM;
1253         goto done;
1254     }
1255 
1256     /* Control/bulk operations through TTs don't need scheduling,
1257      * the HC and TT handle it when the TT has a buffer ready.
1258      */
1259     if (qh->qh_state == QH_STATE_IDLE) {
1260         qh_link_async(ehci, qh);
1261     }
1262 done:
1263     hal_spin_unlock_irqrestore(&ehci->lock, flags);
1264     // qtd_list_free (ehci, urb, &(ehci->wait_free_list));
1265 
1266     if (qh == NULL)
1267         qtd_list_free (ehci, urb, qtd_list);
1268     return rc;
1269 }
1270 
single_unlink_async(struct ehci_hcd * ehci,struct ehci_qh * qh)1271 static void single_unlink_async(struct ehci_hcd *ehci, struct ehci_qh *qh)
1272 {
1273     struct ehci_qh      *prev;
1274 
1275     /* Add to the end of the list of QHs waiting for the next IAAD */
1276     qh->qh_state = QH_STATE_UNLINK_WAIT;
1277     list_add_tail(&qh->unlink_node, &ehci->async_unlink);
1278 
1279     /* Unlink it from the schedule */
1280     prev = ehci->async;
1281     while (prev->qh_next.qh != qh)
1282         prev = prev->qh_next.qh;
1283 
1284     prev->hw->hw_next = qh->hw->hw_next;
1285     prev->qh_next = qh->qh_next;
1286     if (ehci->qh_scan_next == qh)
1287         ehci->qh_scan_next = qh->qh_next.qh;
1288 }
1289 
start_iaa_cycle(struct ehci_hcd * ehci)1290 static void start_iaa_cycle(struct ehci_hcd *ehci)
1291 {
1292     /* If the controller isn't running, we don't have to wait for it */
1293     if (unlikely(ehci->rh_state < EHCI_RH_RUNNING)) {
1294         end_unlink_async(ehci);
1295 
1296     /* Otherwise start a new IAA cycle if one isn't already running */
1297     } else if (ehci->rh_state == EHCI_RH_RUNNING &&
1298             !ehci->iaa_in_progress) {
1299 
1300         /* Make sure the unlinks are all visible to the hardware */
1301         //wmb();
1302 
1303         ehci_writel(ehci, ehci->command | CMD_IAAD,
1304                 &ehci->regs->command);
1305         ehci_readl(ehci, &ehci->regs->command);
1306         ehci->iaa_in_progress = true;
1307         // ehci_enable_event(ehci, EHCI_HRTIMER_IAA_WATCHDOG, true);
1308         ehci_iaa_watchdog(ehci);
1309     }
1310 }
1311 
end_iaa_cycle(struct ehci_hcd * ehci)1312 static void end_iaa_cycle(struct ehci_hcd *ehci)
1313 {
1314     if (ehci->has_synopsys_hc_bug)
1315         ehci_writel(ehci, (u32) ehci->async->qh_dma,
1316                 &ehci->regs->async_next);
1317 
1318     /* The current IAA cycle has ended */
1319     ehci->iaa_in_progress = false;
1320 
1321     end_unlink_async(ehci);
1322 }
1323 
1324 /* See if the async qh for the qtds being unlinked are now gone from the HC */
1325 
end_unlink_async(struct ehci_hcd * ehci)1326 static void end_unlink_async(struct ehci_hcd *ehci)
1327 {
1328     struct ehci_qh      *qh;
1329     bool            early_exit;
1330 
1331     if (list_empty(&ehci->async_unlink))
1332         return;
1333     qh = list_first_entry(&ehci->async_unlink, struct ehci_qh,
1334             unlink_node);   /* QH whose IAA cycle just ended */
1335 
1336     /*
1337      * If async_unlinking is set then this routine is already running,
1338      * either on the stack or on another CPU.
1339      */
1340     early_exit = ehci->async_unlinking;
1341 
1342     /* If the controller isn't running, process all the waiting QHs */
1343     if (ehci->rh_state < EHCI_RH_RUNNING)
1344         list_splice_tail_init(&ehci->async_unlink, &ehci->async_idle);
1345 
1346     /*
1347      * Intel (?) bug: The HC can write back the overlay region even
1348      * after the IAA interrupt occurs.  In self-defense, always go
1349      * through two IAA cycles for each QH.
1350      */
1351     else if (qh->qh_state == QH_STATE_UNLINK) {
1352         /*
1353          * Second IAA cycle has finished.  Process only the first
1354          * waiting QH (NVIDIA (?) bug).
1355          */
1356         list_move_tail(&qh->unlink_node, &ehci->async_idle);
1357     }
1358 
1359     /*
1360      * AMD/ATI (?) bug: The HC can continue to use an active QH long
1361      * after the IAA interrupt occurs.  To prevent problems, QHs that
1362      * may still be active will wait until 2 ms have passed with no
1363      * change to the hw_current and hw_token fields (this delay occurs
1364      * between the two IAA cycles).
1365      *
1366      * The EHCI spec (4.8.2) says that active QHs must not be removed
1367      * from the async schedule and recommends waiting until the QH
1368      * goes inactive.  This is ridiculous because the QH will _never_
1369      * become inactive if the endpoint NAKs indefinitely.
1370      */
1371 
1372     /* Some reasons for unlinking guarantee the QH can't be active */
1373     else if (qh->unlink_reason & (QH_UNLINK_HALTED |
1374             QH_UNLINK_SHORT_READ | QH_UNLINK_DUMMY_OVERLAY))
1375         goto DelayDone;
1376 
1377     /* The QH can't be active if the queue was and still is empty... */
1378     else if ((qh->unlink_reason & QH_UNLINK_QUEUE_EMPTY) &&
1379             list_empty(&qh->qtd_list))
1380         goto DelayDone;
1381 
1382     /* ... or if the QH has halted */
1383     else if (qh->hw->hw_token & cpu_to_hc32(ehci, QTD_STS_HALT))
1384         goto DelayDone;
1385 
1386     /* Otherwise we have to wait until the QH stops changing */
1387     else {
1388         uint32_t        qh_current, qh_token;
1389 
1390         qh_current = qh->hw->hw_current;
1391         qh_token = qh->hw->hw_token;
1392         if (qh_current != ehci->old_current ||
1393                 qh_token != ehci->old_token) {
1394             ehci->old_current = qh_current;
1395             ehci->old_token = qh_token;
1396             ehci_enable_event(ehci, EHCI_HRTIMER_ACTIVE_UNLINK, true);
1397             return;
1398         }
1399  DelayDone:
1400         qh->qh_state = QH_STATE_UNLINK;
1401         early_exit = true;
1402     }
1403     ehci->old_current = ~0;     /* Prepare for next QH */
1404 
1405     /* Start a new IAA cycle if any QHs are waiting for it */
1406     if (!list_empty(&ehci->async_unlink))
1407         start_iaa_cycle(ehci);
1408 
1409     /*
1410      * Don't allow nesting or concurrent calls,
1411      * or wait for the second IAA cycle for the next QH.
1412      */
1413     if (early_exit)
1414         return;
1415 
1416     /* Process the idle QHs */
1417     ehci->async_unlinking = true;
1418     while (!list_empty(&ehci->async_idle)) {
1419         qh = list_first_entry(&ehci->async_idle, struct ehci_qh,
1420                 unlink_node);
1421         list_del(&qh->unlink_node);
1422 
1423         qh->qh_state = QH_STATE_IDLE;
1424         qh->qh_next.qh = NULL;
1425 
1426         if (!list_empty(&qh->qtd_list))
1427             qh_completions(ehci, qh);
1428         if (!list_empty(&qh->qtd_list) &&
1429                 ehci->rh_state == EHCI_RH_RUNNING)
1430             qh_link_async(ehci, qh);
1431         disable_async(ehci);
1432     }
1433     ehci->async_unlinking = false;
1434 }
1435 
1436 static void start_unlink_async(struct ehci_hcd *ehci, struct ehci_qh *qh);
1437 
unlink_empty_async(struct ehci_hcd * ehci)1438 static void unlink_empty_async(struct ehci_hcd *ehci)
1439 {
1440     struct ehci_qh      *qh;
1441     struct ehci_qh      *qh_to_unlink = NULL;
1442     int         count = 0;
1443 
1444     /* Find the last async QH which has been empty for a timer cycle */
1445     for (qh = ehci->async->qh_next.qh; qh; qh = qh->qh_next.qh) {
1446         if (list_empty(&qh->qtd_list) &&
1447                 qh->qh_state == QH_STATE_LINKED) {
1448             ++count;
1449             if (qh->unlink_cycle != ehci->async_unlink_cycle)
1450                 qh_to_unlink = qh;
1451         }
1452     }
1453 
1454     /* If nothing else is being unlinked, unlink the last empty QH */
1455     if (list_empty(&ehci->async_unlink) && qh_to_unlink) {
1456         qh_to_unlink->unlink_reason |= QH_UNLINK_QUEUE_EMPTY;
1457         start_unlink_async(ehci, qh_to_unlink);
1458         --count;
1459     }
1460 
1461     /* Other QHs will be handled later */
1462     if (count > 0) {
1463         // ehci_enable_event(ehci, EHCI_HRTIMER_ASYNC_UNLINKS, true);
1464         ++ehci->async_unlink_cycle;
1465         unlink_empty_async(ehci);
1466     }
1467 }
1468 
1469 #ifdef  CONFIG_PM
1470 
1471 /* The root hub is suspended; unlink all the async QHs */
unlink_empty_async_suspended(struct ehci_hcd * ehci)1472 static void unlink_empty_async_suspended(struct ehci_hcd *ehci)
1473 {
1474     struct ehci_qh      *qh;
1475 
1476     while (ehci->async->qh_next.qh) {
1477         qh = ehci->async->qh_next.qh;
1478         WARN_ON(!list_empty(&qh->qtd_list));
1479         single_unlink_async(ehci, qh);
1480     }
1481 }
1482 
1483 #endif
1484 
1485 /* makes sure the async qh will become idle */
1486 /* caller must own ehci->lock */
1487 
start_unlink_async(struct ehci_hcd * ehci,struct ehci_qh * qh)1488 static void start_unlink_async(struct ehci_hcd *ehci, struct ehci_qh *qh)
1489 {
1490     /* If the QH isn't linked then there's nothing we can do. */
1491     if (qh->qh_state != QH_STATE_LINKED)
1492         return;
1493 
1494     single_unlink_async(ehci, qh);
1495     start_iaa_cycle(ehci);
1496 }
1497 
1498 /*-------------------------------------------------------------------------*/
1499 // scan_async()函数的工作就是去check传输的状况,并回收qtd
scan_async(struct ehci_hcd * ehci)1500 static void scan_async (struct ehci_hcd *ehci)
1501 {
1502     struct ehci_qh      *qh;
1503     bool            check_unlinks_later = false;
1504 
1505     ehci->qh_scan_next = ehci->async->qh_next.qh;
1506     while (ehci->qh_scan_next) {
1507         qh = ehci->qh_scan_next;
1508         ehci->qh_scan_next = qh->qh_next.qh;
1509 
1510         /* clean any finished work for this qh */
1511         if (!list_empty(&qh->qtd_list)) {
1512             int temp;
1513 
1514             /*
1515              * Unlinks could happen here; completion reporting
1516              * drops the lock.  That's why ehci->qh_scan_next
1517              * always holds the next qh to scan; if the next qh
1518              * gets unlinked then ehci->qh_scan_next is adjusted
1519              * in single_unlink_async().
1520              */
1521             temp = qh_completions(ehci, qh);
1522             if (temp) {
1523                 start_unlink_async(ehci, qh);
1524             } else if (list_empty(&qh->qtd_list)
1525                     && qh->qh_state == QH_STATE_LINKED) {
1526                 qh->unlink_cycle = ehci->async_unlink_cycle;
1527                 check_unlinks_later = true;
1528             }
1529         }
1530     }
1531 
1532     /*
1533      * Unlink empty entries, reducing DMA usage as well
1534      * as HCD schedule-scanning costs.  Delay for any qh
1535      * we just scanned, there's a not-unusual case that it
1536      * doesn't stay idle for long.
1537      */
1538     // if (check_unlinks_later && ehci->rh_state == EHCI_RH_RUNNING &&
1539     //      !(ehci->enabled_hrtimer_events &
1540     //          BIT(EHCI_HRTIMER_ASYNC_UNLINKS))) {
1541     //  ehci_enable_event(ehci, EHCI_HRTIMER_ASYNC_UNLINKS, true);
1542     //  ++ehci->async_unlink_cycle;
1543     // }
1544     if (check_unlinks_later && ehci->rh_state == EHCI_RH_RUNNING) {
1545         ++ehci->async_unlink_cycle;//akira 20202020
1546         unlink_empty_async(ehci);
1547     }
1548 }
1549