]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/usb/controller/uhci.c
Merge bmake-20201117
[FreeBSD/FreeBSD.git] / sys / dev / usb / controller / uhci.c
1 /* $FreeBSD$ */
2 /*-
3  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4  *
5  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
6  * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved.
7  * Copyright (c) 1998 Lennart Augustsson. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30
31 /*
32  * USB Universal Host Controller driver.
33  * Handles e.g. PIIX3 and PIIX4.
34  *
35  * UHCI spec: http://developer.intel.com/design/USB/UHCI11D.htm
36  * USB spec:  http://www.usb.org/developers/docs/usbspec.zip
37  * PIIXn spec: ftp://download.intel.com/design/intarch/datashts/29055002.pdf
38  *             ftp://download.intel.com/design/intarch/datashts/29056201.pdf
39  */
40
41 #ifdef USB_GLOBAL_INCLUDE_FILE
42 #include USB_GLOBAL_INCLUDE_FILE
43 #else
44 #include <sys/stdint.h>
45 #include <sys/stddef.h>
46 #include <sys/param.h>
47 #include <sys/queue.h>
48 #include <sys/types.h>
49 #include <sys/systm.h>
50 #include <sys/kernel.h>
51 #include <sys/bus.h>
52 #include <sys/module.h>
53 #include <sys/lock.h>
54 #include <sys/mutex.h>
55 #include <sys/condvar.h>
56 #include <sys/sysctl.h>
57 #include <sys/sx.h>
58 #include <sys/unistd.h>
59 #include <sys/callout.h>
60 #include <sys/malloc.h>
61 #include <sys/priv.h>
62
63 #include <dev/usb/usb.h>
64 #include <dev/usb/usbdi.h>
65
66 #define USB_DEBUG_VAR uhcidebug
67
68 #include <dev/usb/usb_core.h>
69 #include <dev/usb/usb_debug.h>
70 #include <dev/usb/usb_busdma.h>
71 #include <dev/usb/usb_process.h>
72 #include <dev/usb/usb_transfer.h>
73 #include <dev/usb/usb_device.h>
74 #include <dev/usb/usb_hub.h>
75 #include <dev/usb/usb_util.h>
76
77 #include <dev/usb/usb_controller.h>
78 #include <dev/usb/usb_bus.h>
79 #endif                  /* USB_GLOBAL_INCLUDE_FILE */
80
81 #include <dev/usb/controller/uhci.h>
82 #include <dev/usb/controller/uhcireg.h>
83
84 #define alt_next next
85 #define UHCI_BUS2SC(bus) \
86    ((uhci_softc_t *)(((uint8_t *)(bus)) - \
87     ((uint8_t *)&(((uhci_softc_t *)0)->sc_bus))))
88
89 #ifdef USB_DEBUG
90 static int uhcidebug = 0;
91 static int uhcinoloop = 0;
92
93 static SYSCTL_NODE(_hw_usb, OID_AUTO, uhci, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
94     "USB uhci");
95 SYSCTL_INT(_hw_usb_uhci, OID_AUTO, debug, CTLFLAG_RWTUN,
96     &uhcidebug, 0, "uhci debug level");
97 SYSCTL_INT(_hw_usb_uhci, OID_AUTO, loop, CTLFLAG_RWTUN,
98     &uhcinoloop, 0, "uhci noloop");
99
100 static void uhci_dumpregs(uhci_softc_t *sc);
101 static void uhci_dump_tds(uhci_td_t *td);
102
103 #endif
104
105 #define UBARR(sc) bus_space_barrier((sc)->sc_io_tag, (sc)->sc_io_hdl, 0, (sc)->sc_io_size, \
106                         BUS_SPACE_BARRIER_READ|BUS_SPACE_BARRIER_WRITE)
107 #define UWRITE1(sc, r, x) \
108  do { UBARR(sc); bus_space_write_1((sc)->sc_io_tag, (sc)->sc_io_hdl, (r), (x)); \
109  } while (/*CONSTCOND*/0)
110 #define UWRITE2(sc, r, x) \
111  do { UBARR(sc); bus_space_write_2((sc)->sc_io_tag, (sc)->sc_io_hdl, (r), (x)); \
112  } while (/*CONSTCOND*/0)
113 #define UWRITE4(sc, r, x) \
114  do { UBARR(sc); bus_space_write_4((sc)->sc_io_tag, (sc)->sc_io_hdl, (r), (x)); \
115  } while (/*CONSTCOND*/0)
116 #define UREAD1(sc, r) (UBARR(sc), bus_space_read_1((sc)->sc_io_tag, (sc)->sc_io_hdl, (r)))
117 #define UREAD2(sc, r) (UBARR(sc), bus_space_read_2((sc)->sc_io_tag, (sc)->sc_io_hdl, (r)))
118 #define UREAD4(sc, r) (UBARR(sc), bus_space_read_4((sc)->sc_io_tag, (sc)->sc_io_hdl, (r)))
119
120 #define UHCICMD(sc, cmd) UWRITE2(sc, UHCI_CMD, cmd)
121 #define UHCISTS(sc) UREAD2(sc, UHCI_STS)
122
123 #define UHCI_RESET_TIMEOUT 100          /* ms, reset timeout */
124
125 #define UHCI_INTR_ENDPT 1
126
127 struct uhci_mem_layout {
128         struct usb_page_search buf_res;
129         struct usb_page_search fix_res;
130
131         struct usb_page_cache *buf_pc;
132         struct usb_page_cache *fix_pc;
133
134         uint32_t buf_offset;
135
136         uint16_t max_frame_size;
137 };
138
139 struct uhci_std_temp {
140         struct uhci_mem_layout ml;
141         uhci_td_t *td;
142         uhci_td_t *td_next;
143         uint32_t average;
144         uint32_t td_status;
145         uint32_t td_token;
146         uint32_t len;
147         uint16_t max_frame_size;
148         uint8_t shortpkt;
149         uint8_t setup_alt_next;
150         uint8_t last_frame;
151 };
152
153 static const struct usb_bus_methods uhci_bus_methods;
154 static const struct usb_pipe_methods uhci_device_bulk_methods;
155 static const struct usb_pipe_methods uhci_device_ctrl_methods;
156 static const struct usb_pipe_methods uhci_device_intr_methods;
157 static const struct usb_pipe_methods uhci_device_isoc_methods;
158
159 static uint8_t  uhci_restart(uhci_softc_t *sc);
160 static void     uhci_do_poll(struct usb_bus *);
161 static void     uhci_device_done(struct usb_xfer *, usb_error_t);
162 static void     uhci_transfer_intr_enqueue(struct usb_xfer *);
163 static void     uhci_timeout(void *);
164 static uint8_t  uhci_check_transfer(struct usb_xfer *);
165 static void     uhci_root_intr(uhci_softc_t *sc);
166
167 void
168 uhci_iterate_hw_softc(struct usb_bus *bus, usb_bus_mem_sub_cb_t *cb)
169 {
170         struct uhci_softc *sc = UHCI_BUS2SC(bus);
171         uint32_t i;
172
173         cb(bus, &sc->sc_hw.pframes_pc, &sc->sc_hw.pframes_pg,
174             sizeof(uint32_t) * UHCI_FRAMELIST_COUNT, UHCI_FRAMELIST_ALIGN);
175
176         cb(bus, &sc->sc_hw.ls_ctl_start_pc, &sc->sc_hw.ls_ctl_start_pg,
177             sizeof(uhci_qh_t), UHCI_QH_ALIGN);
178
179         cb(bus, &sc->sc_hw.fs_ctl_start_pc, &sc->sc_hw.fs_ctl_start_pg,
180             sizeof(uhci_qh_t), UHCI_QH_ALIGN);
181
182         cb(bus, &sc->sc_hw.bulk_start_pc, &sc->sc_hw.bulk_start_pg,
183             sizeof(uhci_qh_t), UHCI_QH_ALIGN);
184
185         cb(bus, &sc->sc_hw.last_qh_pc, &sc->sc_hw.last_qh_pg,
186             sizeof(uhci_qh_t), UHCI_QH_ALIGN);
187
188         cb(bus, &sc->sc_hw.last_td_pc, &sc->sc_hw.last_td_pg,
189             sizeof(uhci_td_t), UHCI_TD_ALIGN);
190
191         for (i = 0; i != UHCI_VFRAMELIST_COUNT; i++) {
192                 cb(bus, sc->sc_hw.isoc_start_pc + i,
193                     sc->sc_hw.isoc_start_pg + i,
194                     sizeof(uhci_td_t), UHCI_TD_ALIGN);
195         }
196
197         for (i = 0; i != UHCI_IFRAMELIST_COUNT; i++) {
198                 cb(bus, sc->sc_hw.intr_start_pc + i,
199                     sc->sc_hw.intr_start_pg + i,
200                     sizeof(uhci_qh_t), UHCI_QH_ALIGN);
201         }
202 }
203
204 static void
205 uhci_mem_layout_init(struct uhci_mem_layout *ml, struct usb_xfer *xfer)
206 {
207         ml->buf_pc = xfer->frbuffers + 0;
208         ml->fix_pc = xfer->buf_fixup;
209
210         ml->buf_offset = 0;
211
212         ml->max_frame_size = xfer->max_frame_size;
213 }
214
215 static void
216 uhci_mem_layout_fixup(struct uhci_mem_layout *ml, struct uhci_td *td)
217 {
218         usbd_get_page(ml->buf_pc, ml->buf_offset, &ml->buf_res);
219
220         if (ml->buf_res.length < td->len) {
221                 /* need to do a fixup */
222
223                 usbd_get_page(ml->fix_pc, 0, &ml->fix_res);
224
225                 td->td_buffer = htole32(ml->fix_res.physaddr);
226
227                 /*
228                  * The UHCI driver cannot handle
229                  * page crossings, so a fixup is
230                  * needed:
231                  *
232                  *  +----+----+ - - -
233                  *  | YYY|Y   |
234                  *  +----+----+ - - -
235                  *     \    \
236                  *      \    \
237                  *       +----+
238                  *       |YYYY|  (fixup)
239                  *       +----+
240                  */
241
242                 if ((td->td_token & htole32(UHCI_TD_PID)) ==
243                     htole32(UHCI_TD_PID_IN)) {
244                         td->fix_pc = ml->fix_pc;
245                         usb_pc_cpu_invalidate(ml->fix_pc);
246
247                 } else {
248                         td->fix_pc = NULL;
249
250                         /* copy data to fixup location */
251
252                         usbd_copy_out(ml->buf_pc, ml->buf_offset,
253                             ml->fix_res.buffer, td->len);
254
255                         usb_pc_cpu_flush(ml->fix_pc);
256                 }
257
258                 /* prepare next fixup */
259
260                 ml->fix_pc++;
261
262         } else {
263                 td->td_buffer = htole32(ml->buf_res.physaddr);
264                 td->fix_pc = NULL;
265         }
266
267         /* prepare next data location */
268
269         ml->buf_offset += td->len;
270 }
271
272 /*
273  * Return values:
274  * 0: Success
275  * Else: Failure
276  */
277 static uint8_t
278 uhci_restart(uhci_softc_t *sc)
279 {
280         struct usb_page_search buf_res;
281
282         USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
283
284         if (UREAD2(sc, UHCI_CMD) & UHCI_CMD_RS) {
285                 DPRINTFN(2, "Already started\n");
286                 return (0);
287         }
288
289         DPRINTFN(2, "Restarting\n");
290
291         usbd_get_page(&sc->sc_hw.pframes_pc, 0, &buf_res);
292
293         /* Reload fresh base address */
294         UWRITE4(sc, UHCI_FLBASEADDR, buf_res.physaddr);
295
296         /*
297          * Assume 64 byte packets at frame end and start HC controller:
298          */
299         UHCICMD(sc, (UHCI_CMD_MAXP | UHCI_CMD_RS));
300
301         /* wait 10 milliseconds */
302
303         usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 100);
304
305         /* check that controller has started */
306
307         if (UREAD2(sc, UHCI_STS) & UHCI_STS_HCH) {
308                 DPRINTFN(2, "Failed\n");
309                 return (1);
310         }
311         return (0);
312 }
313
314 void
315 uhci_reset(uhci_softc_t *sc)
316 {
317         uint16_t n;
318
319         USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
320
321         DPRINTF("resetting the HC\n");
322
323         /* disable interrupts */
324
325         UWRITE2(sc, UHCI_INTR, 0);
326
327         /* global reset */
328
329         UHCICMD(sc, UHCI_CMD_GRESET);
330
331         /* wait */
332
333         usb_pause_mtx(&sc->sc_bus.bus_mtx,
334             USB_MS_TO_TICKS(USB_BUS_RESET_DELAY));
335
336         /* terminate all transfers */
337
338         UHCICMD(sc, UHCI_CMD_HCRESET);
339
340         /* the reset bit goes low when the controller is done */
341
342         n = UHCI_RESET_TIMEOUT;
343         while (n--) {
344                 /* wait one millisecond */
345
346                 usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 1000);
347
348                 if (!(UREAD2(sc, UHCI_CMD) & UHCI_CMD_HCRESET)) {
349                         goto done_1;
350                 }
351         }
352
353         device_printf(sc->sc_bus.bdev,
354             "controller did not reset\n");
355
356 done_1:
357
358         n = 10;
359         while (n--) {
360                 /* wait one millisecond */
361
362                 usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 1000);
363
364                 /* check if HC is stopped */
365                 if (UREAD2(sc, UHCI_STS) & UHCI_STS_HCH) {
366                         goto done_2;
367                 }
368         }
369
370         device_printf(sc->sc_bus.bdev,
371             "controller did not stop\n");
372
373 done_2:
374
375         /* reset frame number */
376         UWRITE2(sc, UHCI_FRNUM, 0);
377         /* set default SOF value */
378         UWRITE1(sc, UHCI_SOF, 0x40);
379
380         USB_BUS_UNLOCK(&sc->sc_bus);
381
382         /* stop root interrupt */
383         usb_callout_drain(&sc->sc_root_intr);
384
385         USB_BUS_LOCK(&sc->sc_bus);
386 }
387
388 static void
389 uhci_start(uhci_softc_t *sc)
390 {
391         USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
392
393         DPRINTFN(2, "enabling\n");
394
395         /* enable interrupts */
396
397         UWRITE2(sc, UHCI_INTR,
398             (UHCI_INTR_TOCRCIE |
399             UHCI_INTR_RIE |
400             UHCI_INTR_IOCE |
401             UHCI_INTR_SPIE));
402
403         if (uhci_restart(sc)) {
404                 device_printf(sc->sc_bus.bdev,
405                     "cannot start HC controller\n");
406         }
407
408         /* start root interrupt */
409         uhci_root_intr(sc);
410 }
411
412 static struct uhci_qh *
413 uhci_init_qh(struct usb_page_cache *pc)
414 {
415         struct usb_page_search buf_res;
416         struct uhci_qh *qh;
417
418         usbd_get_page(pc, 0, &buf_res);
419
420         qh = buf_res.buffer;
421
422         qh->qh_self =
423             htole32(buf_res.physaddr) |
424             htole32(UHCI_PTR_QH);
425
426         qh->page_cache = pc;
427
428         return (qh);
429 }
430
431 static struct uhci_td *
432 uhci_init_td(struct usb_page_cache *pc)
433 {
434         struct usb_page_search buf_res;
435         struct uhci_td *td;
436
437         usbd_get_page(pc, 0, &buf_res);
438
439         td = buf_res.buffer;
440
441         td->td_self =
442             htole32(buf_res.physaddr) |
443             htole32(UHCI_PTR_TD);
444
445         td->page_cache = pc;
446
447         return (td);
448 }
449
450 usb_error_t
451 uhci_init(uhci_softc_t *sc)
452 {
453         uint16_t bit;
454         uint16_t x;
455         uint16_t y;
456
457         DPRINTF("start\n");
458
459         usb_callout_init_mtx(&sc->sc_root_intr, &sc->sc_bus.bus_mtx, 0);
460
461 #ifdef USB_DEBUG
462         if (uhcidebug > 2) {
463                 uhci_dumpregs(sc);
464         }
465 #endif
466         /*
467          * Setup QH's
468          */
469         sc->sc_ls_ctl_p_last =
470             uhci_init_qh(&sc->sc_hw.ls_ctl_start_pc);
471
472         sc->sc_fs_ctl_p_last =
473             uhci_init_qh(&sc->sc_hw.fs_ctl_start_pc);
474
475         sc->sc_bulk_p_last =
476             uhci_init_qh(&sc->sc_hw.bulk_start_pc);
477 #if 0
478         sc->sc_reclaim_qh_p =
479             sc->sc_fs_ctl_p_last;
480 #else
481         /* setup reclaim looping point */
482         sc->sc_reclaim_qh_p =
483             sc->sc_bulk_p_last;
484 #endif
485
486         sc->sc_last_qh_p =
487             uhci_init_qh(&sc->sc_hw.last_qh_pc);
488
489         sc->sc_last_td_p =
490             uhci_init_td(&sc->sc_hw.last_td_pc);
491
492         for (x = 0; x != UHCI_VFRAMELIST_COUNT; x++) {
493                 sc->sc_isoc_p_last[x] =
494                     uhci_init_td(sc->sc_hw.isoc_start_pc + x);
495         }
496
497         for (x = 0; x != UHCI_IFRAMELIST_COUNT; x++) {
498                 sc->sc_intr_p_last[x] =
499                     uhci_init_qh(sc->sc_hw.intr_start_pc + x);
500         }
501
502         /*
503          * the QHs are arranged to give poll intervals that are
504          * powers of 2 times 1ms
505          */
506         bit = UHCI_IFRAMELIST_COUNT / 2;
507         while (bit) {
508                 x = bit;
509                 while (x & bit) {
510                         uhci_qh_t *qh_x;
511                         uhci_qh_t *qh_y;
512
513                         y = (x ^ bit) | (bit / 2);
514
515                         /*
516                          * the next QH has half the poll interval
517                          */
518                         qh_x = sc->sc_intr_p_last[x];
519                         qh_y = sc->sc_intr_p_last[y];
520
521                         qh_x->h_next = NULL;
522                         qh_x->qh_h_next = qh_y->qh_self;
523                         qh_x->e_next = NULL;
524                         qh_x->qh_e_next = htole32(UHCI_PTR_T);
525                         x++;
526                 }
527                 bit >>= 1;
528         }
529
530         if (1) {
531                 uhci_qh_t *qh_ls;
532                 uhci_qh_t *qh_intr;
533
534                 qh_ls = sc->sc_ls_ctl_p_last;
535                 qh_intr = sc->sc_intr_p_last[0];
536
537                 /* start QH for interrupt traffic */
538                 qh_intr->h_next = qh_ls;
539                 qh_intr->qh_h_next = qh_ls->qh_self;
540                 qh_intr->e_next = 0;
541                 qh_intr->qh_e_next = htole32(UHCI_PTR_T);
542         }
543         for (x = 0; x != UHCI_VFRAMELIST_COUNT; x++) {
544                 uhci_td_t *td_x;
545                 uhci_qh_t *qh_intr;
546
547                 td_x = sc->sc_isoc_p_last[x];
548                 qh_intr = sc->sc_intr_p_last[x | (UHCI_IFRAMELIST_COUNT / 2)];
549
550                 /* start TD for isochronous traffic */
551                 td_x->next = NULL;
552                 td_x->td_next = qh_intr->qh_self;
553                 td_x->td_status = htole32(UHCI_TD_IOS);
554                 td_x->td_token = htole32(0);
555                 td_x->td_buffer = htole32(0);
556         }
557
558         if (1) {
559                 uhci_qh_t *qh_ls;
560                 uhci_qh_t *qh_fs;
561
562                 qh_ls = sc->sc_ls_ctl_p_last;
563                 qh_fs = sc->sc_fs_ctl_p_last;
564
565                 /* start QH where low speed control traffic will be queued */
566                 qh_ls->h_next = qh_fs;
567                 qh_ls->qh_h_next = qh_fs->qh_self;
568                 qh_ls->e_next = 0;
569                 qh_ls->qh_e_next = htole32(UHCI_PTR_T);
570         }
571         if (1) {
572                 uhci_qh_t *qh_ctl;
573                 uhci_qh_t *qh_blk;
574                 uhci_qh_t *qh_lst;
575                 uhci_td_t *td_lst;
576
577                 qh_ctl = sc->sc_fs_ctl_p_last;
578                 qh_blk = sc->sc_bulk_p_last;
579
580                 /* start QH where full speed control traffic will be queued */
581                 qh_ctl->h_next = qh_blk;
582                 qh_ctl->qh_h_next = qh_blk->qh_self;
583                 qh_ctl->e_next = 0;
584                 qh_ctl->qh_e_next = htole32(UHCI_PTR_T);
585
586                 qh_lst = sc->sc_last_qh_p;
587
588                 /* start QH where bulk traffic will be queued */
589                 qh_blk->h_next = qh_lst;
590                 qh_blk->qh_h_next = qh_lst->qh_self;
591                 qh_blk->e_next = 0;
592                 qh_blk->qh_e_next = htole32(UHCI_PTR_T);
593
594                 td_lst = sc->sc_last_td_p;
595
596                 /* end QH which is used for looping the QHs */
597                 qh_lst->h_next = 0;
598                 qh_lst->qh_h_next = htole32(UHCI_PTR_T);        /* end of QH chain */
599                 qh_lst->e_next = td_lst;
600                 qh_lst->qh_e_next = td_lst->td_self;
601
602                 /*
603                  * end TD which hangs from the last QH, to avoid a bug in the PIIX
604                  * that makes it run berserk otherwise
605                  */
606                 td_lst->next = 0;
607                 td_lst->td_next = htole32(UHCI_PTR_T);
608                 td_lst->td_status = htole32(0); /* inactive */
609                 td_lst->td_token = htole32(0);
610                 td_lst->td_buffer = htole32(0);
611         }
612         if (1) {
613                 struct usb_page_search buf_res;
614                 uint32_t *pframes;
615
616                 usbd_get_page(&sc->sc_hw.pframes_pc, 0, &buf_res);
617
618                 pframes = buf_res.buffer;
619
620                 /*
621                  * Setup UHCI framelist
622                  *
623                  * Execution order:
624                  *
625                  * pframes -> full speed isochronous -> interrupt QH's -> low
626                  * speed control -> full speed control -> bulk transfers
627                  *
628                  */
629
630                 for (x = 0; x != UHCI_FRAMELIST_COUNT; x++) {
631                         pframes[x] =
632                             sc->sc_isoc_p_last[x % UHCI_VFRAMELIST_COUNT]->td_self;
633                 }
634         }
635         /* flush all cache into memory */
636
637         usb_bus_mem_flush_all(&sc->sc_bus, &uhci_iterate_hw_softc);
638
639         /* set up the bus struct */
640         sc->sc_bus.methods = &uhci_bus_methods;
641
642         USB_BUS_LOCK(&sc->sc_bus);
643         /* reset the controller */
644         uhci_reset(sc);
645
646         /* start the controller */
647         uhci_start(sc);
648         USB_BUS_UNLOCK(&sc->sc_bus);
649
650         /* catch lost interrupts */
651         uhci_do_poll(&sc->sc_bus);
652
653         return (0);
654 }
655
656 static void
657 uhci_suspend(uhci_softc_t *sc)
658 {
659 #ifdef USB_DEBUG
660         if (uhcidebug > 2) {
661                 uhci_dumpregs(sc);
662         }
663 #endif
664
665         USB_BUS_LOCK(&sc->sc_bus);
666
667         /* stop the controller */
668
669         uhci_reset(sc);
670
671         /* enter global suspend */
672
673         UHCICMD(sc, UHCI_CMD_EGSM);
674
675         USB_BUS_UNLOCK(&sc->sc_bus);
676 }
677
678 static void
679 uhci_resume(uhci_softc_t *sc)
680 {
681         USB_BUS_LOCK(&sc->sc_bus);
682
683         /* reset the controller */
684
685         uhci_reset(sc);
686
687         /* force global resume */
688
689         UHCICMD(sc, UHCI_CMD_FGR);
690
691         /* and start traffic again */
692
693         uhci_start(sc);
694
695         USB_BUS_UNLOCK(&sc->sc_bus);
696
697 #ifdef USB_DEBUG
698         if (uhcidebug > 2)
699                 uhci_dumpregs(sc);
700 #endif
701
702         /* catch lost interrupts */
703         uhci_do_poll(&sc->sc_bus);
704 }
705
706 #ifdef USB_DEBUG
707 static void
708 uhci_dumpregs(uhci_softc_t *sc)
709 {
710         DPRINTFN(0, "%s regs: cmd=%04x, sts=%04x, intr=%04x, frnum=%04x, "
711             "flbase=%08x, sof=%04x, portsc1=%04x, portsc2=%04x\n",
712             device_get_nameunit(sc->sc_bus.bdev),
713             UREAD2(sc, UHCI_CMD),
714             UREAD2(sc, UHCI_STS),
715             UREAD2(sc, UHCI_INTR),
716             UREAD2(sc, UHCI_FRNUM),
717             UREAD4(sc, UHCI_FLBASEADDR),
718             UREAD1(sc, UHCI_SOF),
719             UREAD2(sc, UHCI_PORTSC1),
720             UREAD2(sc, UHCI_PORTSC2));
721 }
722
723 static uint8_t
724 uhci_dump_td(uhci_td_t *p)
725 {
726         uint32_t td_next;
727         uint32_t td_status;
728         uint32_t td_token;
729         uint8_t temp;
730
731         usb_pc_cpu_invalidate(p->page_cache);
732
733         td_next = le32toh(p->td_next);
734         td_status = le32toh(p->td_status);
735         td_token = le32toh(p->td_token);
736
737         /*
738          * Check whether the link pointer in this TD marks the link pointer
739          * as end of queue:
740          */
741         temp = ((td_next & UHCI_PTR_T) || (td_next == 0));
742
743         printf("TD(%p) at 0x%08x = link=0x%08x status=0x%08x "
744             "token=0x%08x buffer=0x%08x\n",
745             p,
746             le32toh(p->td_self),
747             td_next,
748             td_status,
749             td_token,
750             le32toh(p->td_buffer));
751
752         printf("TD(%p) td_next=%s%s%s td_status=%s%s%s%s%s%s%s%s%s%s%s, errcnt=%d, actlen=%d pid=%02x,"
753             "addr=%d,endpt=%d,D=%d,maxlen=%d\n",
754             p,
755             (td_next & 1) ? "-T" : "",
756             (td_next & 2) ? "-Q" : "",
757             (td_next & 4) ? "-VF" : "",
758             (td_status & UHCI_TD_BITSTUFF) ? "-BITSTUFF" : "",
759             (td_status & UHCI_TD_CRCTO) ? "-CRCTO" : "",
760             (td_status & UHCI_TD_NAK) ? "-NAK" : "",
761             (td_status & UHCI_TD_BABBLE) ? "-BABBLE" : "",
762             (td_status & UHCI_TD_DBUFFER) ? "-DBUFFER" : "",
763             (td_status & UHCI_TD_STALLED) ? "-STALLED" : "",
764             (td_status & UHCI_TD_ACTIVE) ? "-ACTIVE" : "",
765             (td_status & UHCI_TD_IOC) ? "-IOC" : "",
766             (td_status & UHCI_TD_IOS) ? "-IOS" : "",
767             (td_status & UHCI_TD_LS) ? "-LS" : "",
768             (td_status & UHCI_TD_SPD) ? "-SPD" : "",
769             UHCI_TD_GET_ERRCNT(td_status),
770             UHCI_TD_GET_ACTLEN(td_status),
771             UHCI_TD_GET_PID(td_token),
772             UHCI_TD_GET_DEVADDR(td_token),
773             UHCI_TD_GET_ENDPT(td_token),
774             UHCI_TD_GET_DT(td_token),
775             UHCI_TD_GET_MAXLEN(td_token));
776
777         return (temp);
778 }
779
780 static uint8_t
781 uhci_dump_qh(uhci_qh_t *sqh)
782 {
783         uint8_t temp;
784         uint32_t qh_h_next;
785         uint32_t qh_e_next;
786
787         usb_pc_cpu_invalidate(sqh->page_cache);
788
789         qh_h_next = le32toh(sqh->qh_h_next);
790         qh_e_next = le32toh(sqh->qh_e_next);
791
792         DPRINTFN(0, "QH(%p) at 0x%08x: h_next=0x%08x e_next=0x%08x\n", sqh,
793             le32toh(sqh->qh_self), qh_h_next, qh_e_next);
794
795         temp = ((((sqh->h_next != NULL) && !(qh_h_next & UHCI_PTR_T)) ? 1 : 0) |
796             (((sqh->e_next != NULL) && !(qh_e_next & UHCI_PTR_T)) ? 2 : 0));
797
798         return (temp);
799 }
800
801 static void
802 uhci_dump_all(uhci_softc_t *sc)
803 {
804         uhci_dumpregs(sc);
805         uhci_dump_qh(sc->sc_ls_ctl_p_last);
806         uhci_dump_qh(sc->sc_fs_ctl_p_last);
807         uhci_dump_qh(sc->sc_bulk_p_last);
808         uhci_dump_qh(sc->sc_last_qh_p);
809 }
810
811 static void
812 uhci_dump_tds(uhci_td_t *td)
813 {
814         for (;
815             td != NULL;
816             td = td->obj_next) {
817                 if (uhci_dump_td(td)) {
818                         break;
819                 }
820         }
821 }
822
823 #endif
824
825 /*
826  * Let the last QH loop back to the full speed control transfer QH.
827  * This is what intel calls "bandwidth reclamation" and improves
828  * USB performance a lot for some devices.
829  * If we are already looping, just count it.
830  */
831 static void
832 uhci_add_loop(uhci_softc_t *sc)
833 {
834         struct uhci_qh *qh_lst;
835         struct uhci_qh *qh_rec;
836
837 #ifdef USB_DEBUG
838         if (uhcinoloop) {
839                 return;
840         }
841 #endif
842         if (++(sc->sc_loops) == 1) {
843                 DPRINTFN(6, "add\n");
844
845                 qh_lst = sc->sc_last_qh_p;
846                 qh_rec = sc->sc_reclaim_qh_p;
847
848                 /* NOTE: we don't loop back the soft pointer */
849
850                 qh_lst->qh_h_next = qh_rec->qh_self;
851                 usb_pc_cpu_flush(qh_lst->page_cache);
852         }
853 }
854
855 static void
856 uhci_rem_loop(uhci_softc_t *sc)
857 {
858         struct uhci_qh *qh_lst;
859
860 #ifdef USB_DEBUG
861         if (uhcinoloop) {
862                 return;
863         }
864 #endif
865         if (--(sc->sc_loops) == 0) {
866                 DPRINTFN(6, "remove\n");
867
868                 qh_lst = sc->sc_last_qh_p;
869                 qh_lst->qh_h_next = htole32(UHCI_PTR_T);
870                 usb_pc_cpu_flush(qh_lst->page_cache);
871         }
872 }
873
874 static void
875 uhci_transfer_intr_enqueue(struct usb_xfer *xfer)
876 {
877         /* check for early completion */
878         if (uhci_check_transfer(xfer)) {
879                 return;
880         }
881         /* put transfer on interrupt queue */
882         usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer);
883
884         /* start timeout, if any */
885         if (xfer->timeout != 0) {
886                 usbd_transfer_timeout_ms(xfer, &uhci_timeout, xfer->timeout);
887         }
888 }
889
890 #define UHCI_APPEND_TD(std,last) (last) = _uhci_append_td(std,last)
891 static uhci_td_t *
892 _uhci_append_td(uhci_td_t *std, uhci_td_t *last)
893 {
894         DPRINTFN(11, "%p to %p\n", std, last);
895
896         /* (sc->sc_bus.mtx) must be locked */
897
898         std->next = last->next;
899         std->td_next = last->td_next;
900
901         std->prev = last;
902
903         usb_pc_cpu_flush(std->page_cache);
904
905         /*
906          * the last->next->prev is never followed: std->next->prev = std;
907          */
908         last->next = std;
909         last->td_next = std->td_self;
910
911         usb_pc_cpu_flush(last->page_cache);
912
913         return (std);
914 }
915
916 #define UHCI_APPEND_QH(sqh,last) (last) = _uhci_append_qh(sqh,last)
917 static uhci_qh_t *
918 _uhci_append_qh(uhci_qh_t *sqh, uhci_qh_t *last)
919 {
920         DPRINTFN(11, "%p to %p\n", sqh, last);
921
922         if (sqh->h_prev != NULL) {
923                 /* should not happen */
924                 DPRINTFN(0, "QH already linked!\n");
925                 return (last);
926         }
927         /* (sc->sc_bus.mtx) must be locked */
928
929         sqh->h_next = last->h_next;
930         sqh->qh_h_next = last->qh_h_next;
931
932         sqh->h_prev = last;
933
934         usb_pc_cpu_flush(sqh->page_cache);
935
936         /*
937          * The "last->h_next->h_prev" is never followed:
938          *
939          * "sqh->h_next->h_prev" = sqh;
940          */
941
942         last->h_next = sqh;
943         last->qh_h_next = sqh->qh_self;
944
945         usb_pc_cpu_flush(last->page_cache);
946
947         return (sqh);
948 }
949
950 /**/
951
952 #define UHCI_REMOVE_TD(std,last) (last) = _uhci_remove_td(std,last)
953 static uhci_td_t *
954 _uhci_remove_td(uhci_td_t *std, uhci_td_t *last)
955 {
956         DPRINTFN(11, "%p from %p\n", std, last);
957
958         /* (sc->sc_bus.mtx) must be locked */
959
960         std->prev->next = std->next;
961         std->prev->td_next = std->td_next;
962
963         usb_pc_cpu_flush(std->prev->page_cache);
964
965         if (std->next) {
966                 std->next->prev = std->prev;
967                 usb_pc_cpu_flush(std->next->page_cache);
968         }
969         return ((last == std) ? std->prev : last);
970 }
971
972 #define UHCI_REMOVE_QH(sqh,last) (last) = _uhci_remove_qh(sqh,last)
973 static uhci_qh_t *
974 _uhci_remove_qh(uhci_qh_t *sqh, uhci_qh_t *last)
975 {
976         DPRINTFN(11, "%p from %p\n", sqh, last);
977
978         /* (sc->sc_bus.mtx) must be locked */
979
980         /* only remove if not removed from a queue */
981         if (sqh->h_prev) {
982                 sqh->h_prev->h_next = sqh->h_next;
983                 sqh->h_prev->qh_h_next = sqh->qh_h_next;
984
985                 usb_pc_cpu_flush(sqh->h_prev->page_cache);
986
987                 if (sqh->h_next) {
988                         sqh->h_next->h_prev = sqh->h_prev;
989                         usb_pc_cpu_flush(sqh->h_next->page_cache);
990                 }
991                 last = ((last == sqh) ? sqh->h_prev : last);
992
993                 sqh->h_prev = 0;
994
995                 usb_pc_cpu_flush(sqh->page_cache);
996         }
997         return (last);
998 }
999
1000 static void
1001 uhci_isoc_done(uhci_softc_t *sc, struct usb_xfer *xfer)
1002 {
1003         struct usb_page_search res;
1004         uint32_t nframes = xfer->nframes;
1005         uint32_t status;
1006         uint32_t offset = 0;
1007         uint32_t *plen = xfer->frlengths;
1008         uint16_t len = 0;
1009         uhci_td_t *td = xfer->td_transfer_first;
1010         uhci_td_t **pp_last = &sc->sc_isoc_p_last[xfer->qh_pos];
1011
1012         DPRINTFN(13, "xfer=%p endpoint=%p transfer done\n",
1013             xfer, xfer->endpoint);
1014
1015         /* sync any DMA memory before doing fixups */
1016
1017         usb_bdma_post_sync(xfer);
1018
1019         while (nframes--) {
1020                 if (td == NULL) {
1021                         panic("%s:%d: out of TD's\n",
1022                             __FUNCTION__, __LINE__);
1023                 }
1024                 if (pp_last >= &sc->sc_isoc_p_last[UHCI_VFRAMELIST_COUNT]) {
1025                         pp_last = &sc->sc_isoc_p_last[0];
1026                 }
1027 #ifdef USB_DEBUG
1028                 if (uhcidebug > 5) {
1029                         DPRINTF("isoc TD\n");
1030                         uhci_dump_td(td);
1031                 }
1032 #endif
1033                 usb_pc_cpu_invalidate(td->page_cache);
1034                 status = le32toh(td->td_status);
1035
1036                 len = UHCI_TD_GET_ACTLEN(status);
1037
1038                 if (len > *plen) {
1039                         len = *plen;
1040                 }
1041                 if (td->fix_pc) {
1042                         usbd_get_page(td->fix_pc, 0, &res);
1043
1044                         /* copy data from fixup location to real location */
1045
1046                         usb_pc_cpu_invalidate(td->fix_pc);
1047
1048                         usbd_copy_in(xfer->frbuffers, offset,
1049                             res.buffer, len);
1050                 }
1051                 offset += *plen;
1052
1053                 *plen = len;
1054
1055                 /* remove TD from schedule */
1056                 UHCI_REMOVE_TD(td, *pp_last);
1057
1058                 pp_last++;
1059                 plen++;
1060                 td = td->obj_next;
1061         }
1062
1063         xfer->aframes = xfer->nframes;
1064 }
1065
1066 static usb_error_t
1067 uhci_non_isoc_done_sub(struct usb_xfer *xfer)
1068 {
1069         struct usb_page_search res;
1070         uhci_td_t *td;
1071         uhci_td_t *td_alt_next;
1072         uint32_t status;
1073         uint32_t token;
1074         uint16_t len;
1075
1076         td = xfer->td_transfer_cache;
1077         td_alt_next = td->alt_next;
1078
1079         if (xfer->aframes != xfer->nframes) {
1080                 usbd_xfer_set_frame_len(xfer, xfer->aframes, 0);
1081         }
1082         while (1) {
1083                 usb_pc_cpu_invalidate(td->page_cache);
1084                 status = le32toh(td->td_status);
1085                 token = le32toh(td->td_token);
1086
1087                 /*
1088                  * Verify the status and add
1089                  * up the actual length:
1090                  */
1091
1092                 len = UHCI_TD_GET_ACTLEN(status);
1093                 if (len > td->len) {
1094                         /* should not happen */
1095                         DPRINTF("Invalid status length, "
1096                             "0x%04x/0x%04x bytes\n", len, td->len);
1097                         status |= UHCI_TD_STALLED;
1098
1099                 } else if ((xfer->aframes != xfer->nframes) && (len > 0)) {
1100                         if (td->fix_pc) {
1101                                 usbd_get_page(td->fix_pc, 0, &res);
1102
1103                                 /*
1104                                  * copy data from fixup location to real
1105                                  * location
1106                                  */
1107
1108                                 usb_pc_cpu_invalidate(td->fix_pc);
1109
1110                                 usbd_copy_in(xfer->frbuffers + xfer->aframes,
1111                                     xfer->frlengths[xfer->aframes], res.buffer, len);
1112                         }
1113                         /* update actual length */
1114
1115                         xfer->frlengths[xfer->aframes] += len;
1116                 }
1117                 /* Check for last transfer */
1118                 if (((void *)td) == xfer->td_transfer_last) {
1119                         td = NULL;
1120                         break;
1121                 }
1122                 if (status & UHCI_TD_STALLED) {
1123                         /* the transfer is finished */
1124                         td = NULL;
1125                         break;
1126                 }
1127                 /* Check for short transfer */
1128                 if (len != td->len) {
1129                         if (xfer->flags_int.short_frames_ok) {
1130                                 /* follow alt next */
1131                                 td = td->alt_next;
1132                         } else {
1133                                 /* the transfer is finished */
1134                                 td = NULL;
1135                         }
1136                         break;
1137                 }
1138                 td = td->obj_next;
1139
1140                 if (td->alt_next != td_alt_next) {
1141                         /* this USB frame is complete */
1142                         break;
1143                 }
1144         }
1145
1146         /* update transfer cache */
1147
1148         xfer->td_transfer_cache = td;
1149
1150         /* update data toggle */
1151
1152         xfer->endpoint->toggle_next = (token & UHCI_TD_SET_DT(1)) ? 0 : 1;
1153
1154 #ifdef USB_DEBUG
1155         if (status & UHCI_TD_ERROR) {
1156                 DPRINTFN(11, "error, addr=%d, endpt=0x%02x, frame=0x%02x "
1157                     "status=%s%s%s%s%s%s%s%s%s%s%s\n",
1158                     xfer->address, xfer->endpointno, xfer->aframes,
1159                     (status & UHCI_TD_BITSTUFF) ? "[BITSTUFF]" : "",
1160                     (status & UHCI_TD_CRCTO) ? "[CRCTO]" : "",
1161                     (status & UHCI_TD_NAK) ? "[NAK]" : "",
1162                     (status & UHCI_TD_BABBLE) ? "[BABBLE]" : "",
1163                     (status & UHCI_TD_DBUFFER) ? "[DBUFFER]" : "",
1164                     (status & UHCI_TD_STALLED) ? "[STALLED]" : "",
1165                     (status & UHCI_TD_ACTIVE) ? "[ACTIVE]" : "[NOT_ACTIVE]",
1166                     (status & UHCI_TD_IOC) ? "[IOC]" : "",
1167                     (status & UHCI_TD_IOS) ? "[IOS]" : "",
1168                     (status & UHCI_TD_LS) ? "[LS]" : "",
1169                     (status & UHCI_TD_SPD) ? "[SPD]" : "");
1170         }
1171 #endif
1172         if (status & UHCI_TD_STALLED) {
1173                 /* try to separate I/O errors from STALL */
1174                 if (UHCI_TD_GET_ERRCNT(status) == 0)
1175                         return (USB_ERR_IOERROR);
1176                 return (USB_ERR_STALLED);
1177         }
1178         return (USB_ERR_NORMAL_COMPLETION);
1179 }
1180
1181 static void
1182 uhci_non_isoc_done(struct usb_xfer *xfer)
1183 {
1184         usb_error_t err = 0;
1185
1186         DPRINTFN(13, "xfer=%p endpoint=%p transfer done\n",
1187             xfer, xfer->endpoint);
1188
1189 #ifdef USB_DEBUG
1190         if (uhcidebug > 10) {
1191                 uhci_dump_tds(xfer->td_transfer_first);
1192         }
1193 #endif
1194
1195         /* sync any DMA memory before doing fixups */
1196
1197         usb_bdma_post_sync(xfer);
1198
1199         /* reset scanner */
1200
1201         xfer->td_transfer_cache = xfer->td_transfer_first;
1202
1203         if (xfer->flags_int.control_xfr) {
1204                 if (xfer->flags_int.control_hdr) {
1205                         err = uhci_non_isoc_done_sub(xfer);
1206                 }
1207                 xfer->aframes = 1;
1208
1209                 if (xfer->td_transfer_cache == NULL) {
1210                         goto done;
1211                 }
1212         }
1213         while (xfer->aframes != xfer->nframes) {
1214                 err = uhci_non_isoc_done_sub(xfer);
1215                 xfer->aframes++;
1216
1217                 if (xfer->td_transfer_cache == NULL) {
1218                         goto done;
1219                 }
1220         }
1221
1222         if (xfer->flags_int.control_xfr &&
1223             !xfer->flags_int.control_act) {
1224                 err = uhci_non_isoc_done_sub(xfer);
1225         }
1226 done:
1227         uhci_device_done(xfer, err);
1228 }
1229
1230 /*------------------------------------------------------------------------*
1231  *      uhci_check_transfer_sub
1232  *
1233  * The main purpose of this function is to update the data-toggle
1234  * in case it is wrong.
1235  *------------------------------------------------------------------------*/
1236 static void
1237 uhci_check_transfer_sub(struct usb_xfer *xfer)
1238 {
1239         uhci_qh_t *qh;
1240         uhci_td_t *td;
1241         uhci_td_t *td_alt_next;
1242
1243         uint32_t td_token;
1244         uint32_t td_self;
1245
1246         td = xfer->td_transfer_cache;
1247         qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
1248
1249         td_token = td->obj_next->td_token;
1250         td = td->alt_next;
1251         xfer->td_transfer_cache = td;
1252         td_self = td->td_self;
1253         td_alt_next = td->alt_next;
1254
1255         if (xfer->flags_int.control_xfr)
1256                 goto skip;      /* don't touch the DT value! */
1257
1258         if (!((td->td_token ^ td_token) & htole32(UHCI_TD_SET_DT(1))))
1259                 goto skip;      /* data toggle has correct value */
1260
1261         /*
1262          * The data toggle is wrong and we need to toggle it !
1263          */
1264         while (1) {
1265                 td->td_token ^= htole32(UHCI_TD_SET_DT(1));
1266                 usb_pc_cpu_flush(td->page_cache);
1267
1268                 if (td == xfer->td_transfer_last) {
1269                         /* last transfer */
1270                         break;
1271                 }
1272                 td = td->obj_next;
1273
1274                 if (td->alt_next != td_alt_next) {
1275                         /* next frame */
1276                         break;
1277                 }
1278         }
1279 skip:
1280
1281         /* update the QH */
1282         qh->qh_e_next = td_self;
1283         usb_pc_cpu_flush(qh->page_cache);
1284
1285         DPRINTFN(13, "xfer=%p following alt next\n", xfer);
1286 }
1287
1288 /*------------------------------------------------------------------------*
1289  *      uhci_check_transfer
1290  *
1291  * Return values:
1292  *    0: USB transfer is not finished
1293  * Else: USB transfer is finished
1294  *------------------------------------------------------------------------*/
1295 static uint8_t
1296 uhci_check_transfer(struct usb_xfer *xfer)
1297 {
1298         uint32_t status;
1299         uint32_t token;
1300         uhci_td_t *td;
1301
1302         DPRINTFN(16, "xfer=%p checking transfer\n", xfer);
1303
1304         if (xfer->endpoint->methods == &uhci_device_isoc_methods) {
1305                 /* isochronous transfer */
1306
1307                 td = xfer->td_transfer_last;
1308
1309                 usb_pc_cpu_invalidate(td->page_cache);
1310                 status = le32toh(td->td_status);
1311
1312                 /* check also if the first is complete */
1313
1314                 td = xfer->td_transfer_first;
1315
1316                 usb_pc_cpu_invalidate(td->page_cache);
1317                 status |= le32toh(td->td_status);
1318
1319                 if (!(status & UHCI_TD_ACTIVE)) {
1320                         uhci_device_done(xfer, USB_ERR_NORMAL_COMPLETION);
1321                         goto transferred;
1322                 }
1323         } else {
1324                 /* non-isochronous transfer */
1325
1326                 /*
1327                  * check whether there is an error somewhere
1328                  * in the middle, or whether there was a short
1329                  * packet (SPD and not ACTIVE)
1330                  */
1331                 td = xfer->td_transfer_cache;
1332
1333                 while (1) {
1334                         usb_pc_cpu_invalidate(td->page_cache);
1335                         status = le32toh(td->td_status);
1336                         token = le32toh(td->td_token);
1337
1338                         /*
1339                          * if there is an active TD the transfer isn't done
1340                          */
1341                         if (status & UHCI_TD_ACTIVE) {
1342                                 /* update cache */
1343                                 xfer->td_transfer_cache = td;
1344                                 goto done;
1345                         }
1346                         /*
1347                          * last transfer descriptor makes the transfer done
1348                          */
1349                         if (((void *)td) == xfer->td_transfer_last) {
1350                                 break;
1351                         }
1352                         /*
1353                          * any kind of error makes the transfer done
1354                          */
1355                         if (status & UHCI_TD_STALLED) {
1356                                 break;
1357                         }
1358                         /*
1359                          * check if we reached the last packet
1360                          * or if there is a short packet:
1361                          */
1362                         if ((td->td_next == htole32(UHCI_PTR_T)) ||
1363                             (UHCI_TD_GET_ACTLEN(status) < td->len)) {
1364                                 if (xfer->flags_int.short_frames_ok) {
1365                                         /* follow alt next */
1366                                         if (td->alt_next) {
1367                                                 /* update cache */
1368                                                 xfer->td_transfer_cache = td;
1369                                                 uhci_check_transfer_sub(xfer);
1370                                                 goto done;
1371                                         }
1372                                 }
1373                                 /* transfer is done */
1374                                 break;
1375                         }
1376                         td = td->obj_next;
1377                 }
1378                 uhci_non_isoc_done(xfer);
1379                 goto transferred;
1380         }
1381
1382 done:
1383         DPRINTFN(13, "xfer=%p is still active\n", xfer);
1384         return (0);
1385
1386 transferred:
1387         return (1);
1388 }
1389
1390 static void
1391 uhci_interrupt_poll(uhci_softc_t *sc)
1392 {
1393         struct usb_xfer *xfer;
1394
1395 repeat:
1396         TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
1397                 /*
1398                  * check if transfer is transferred
1399                  */
1400                 if (uhci_check_transfer(xfer)) {
1401                         /* queue has been modified */
1402                         goto repeat;
1403                 }
1404         }
1405 }
1406
1407 /*------------------------------------------------------------------------*
1408  *      uhci_interrupt - UHCI interrupt handler
1409  *
1410  * NOTE: Do not access "sc->sc_bus.bdev" inside the interrupt handler,
1411  * hence the interrupt handler will be setup before "sc->sc_bus.bdev"
1412  * is present !
1413  *------------------------------------------------------------------------*/
1414 void
1415 uhci_interrupt(uhci_softc_t *sc)
1416 {
1417         uint32_t status;
1418
1419         USB_BUS_LOCK(&sc->sc_bus);
1420
1421         DPRINTFN(16, "real interrupt\n");
1422
1423 #ifdef USB_DEBUG
1424         if (uhcidebug > 15) {
1425                 uhci_dumpregs(sc);
1426         }
1427 #endif
1428         status = UREAD2(sc, UHCI_STS) & UHCI_STS_ALLINTRS;
1429         if (status == 0) {
1430                 /* the interrupt was not for us */
1431                 goto done;
1432         }
1433         if (status & (UHCI_STS_RD | UHCI_STS_HSE |
1434             UHCI_STS_HCPE | UHCI_STS_HCH)) {
1435                 if (status & UHCI_STS_RD) {
1436 #ifdef USB_DEBUG
1437                         printf("%s: resume detect\n",
1438                             __FUNCTION__);
1439 #endif
1440                 }
1441                 if (status & UHCI_STS_HSE) {
1442                         printf("%s: host system error\n",
1443                             __FUNCTION__);
1444                 }
1445                 if (status & UHCI_STS_HCPE) {
1446                         printf("%s: host controller process error\n",
1447                             __FUNCTION__);
1448                 }
1449                 if (status & UHCI_STS_HCH) {
1450                         /* no acknowledge needed */
1451                         DPRINTF("%s: host controller halted\n",
1452                             __FUNCTION__);
1453 #ifdef USB_DEBUG
1454                         if (uhcidebug > 0) {
1455                                 uhci_dump_all(sc);
1456                         }
1457 #endif
1458                 }
1459         }
1460         /* get acknowledge bits */
1461         status &= (UHCI_STS_USBINT |
1462             UHCI_STS_USBEI |
1463             UHCI_STS_RD |
1464             UHCI_STS_HSE |
1465             UHCI_STS_HCPE |
1466             UHCI_STS_HCH);
1467
1468         if (status == 0) {
1469                 /* nothing to acknowledge */
1470                 goto done;
1471         }
1472         /* acknowledge interrupts */
1473         UWRITE2(sc, UHCI_STS, status);
1474
1475         /* poll all the USB transfers */
1476         uhci_interrupt_poll(sc);
1477
1478 done:
1479         USB_BUS_UNLOCK(&sc->sc_bus);
1480 }
1481
1482 /*
1483  * called when a request does not complete
1484  */
1485 static void
1486 uhci_timeout(void *arg)
1487 {
1488         struct usb_xfer *xfer = arg;
1489
1490         DPRINTF("xfer=%p\n", xfer);
1491
1492         USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
1493
1494         /* transfer is transferred */
1495         uhci_device_done(xfer, USB_ERR_TIMEOUT);
1496 }
1497
1498 static void
1499 uhci_do_poll(struct usb_bus *bus)
1500 {
1501         struct uhci_softc *sc = UHCI_BUS2SC(bus);
1502
1503         USB_BUS_LOCK(&sc->sc_bus);
1504         uhci_interrupt_poll(sc);
1505         USB_BUS_UNLOCK(&sc->sc_bus);
1506 }
1507
1508 static void
1509 uhci_setup_standard_chain_sub(struct uhci_std_temp *temp)
1510 {
1511         uhci_td_t *td;
1512         uhci_td_t *td_next;
1513         uhci_td_t *td_alt_next;
1514         uint32_t average;
1515         uint32_t len_old;
1516         uint8_t shortpkt_old;
1517         uint8_t precompute;
1518
1519         td_alt_next = NULL;
1520         shortpkt_old = temp->shortpkt;
1521         len_old = temp->len;
1522         precompute = 1;
1523
1524         /* software is used to detect short incoming transfers */
1525
1526         if ((temp->td_token & htole32(UHCI_TD_PID)) == htole32(UHCI_TD_PID_IN)) {
1527                 temp->td_status |= htole32(UHCI_TD_SPD);
1528         } else {
1529                 temp->td_status &= ~htole32(UHCI_TD_SPD);
1530         }
1531
1532         temp->ml.buf_offset = 0;
1533
1534 restart:
1535
1536         temp->td_token &= ~htole32(UHCI_TD_SET_MAXLEN(0));
1537         temp->td_token |= htole32(UHCI_TD_SET_MAXLEN(temp->average));
1538
1539         td = temp->td;
1540         td_next = temp->td_next;
1541
1542         while (1) {
1543                 if (temp->len == 0) {
1544                         if (temp->shortpkt) {
1545                                 break;
1546                         }
1547                         /* send a Zero Length Packet, ZLP, last */
1548
1549                         temp->shortpkt = 1;
1550                         temp->td_token |= htole32(UHCI_TD_SET_MAXLEN(0));
1551                         average = 0;
1552
1553                 } else {
1554                         average = temp->average;
1555
1556                         if (temp->len < average) {
1557                                 temp->shortpkt = 1;
1558                                 temp->td_token &= ~htole32(UHCI_TD_SET_MAXLEN(0));
1559                                 temp->td_token |= htole32(UHCI_TD_SET_MAXLEN(temp->len));
1560                                 average = temp->len;
1561                         }
1562                 }
1563
1564                 if (td_next == NULL) {
1565                         panic("%s: out of UHCI transfer descriptors!", __FUNCTION__);
1566                 }
1567                 /* get next TD */
1568
1569                 td = td_next;
1570                 td_next = td->obj_next;
1571
1572                 /* check if we are pre-computing */
1573
1574                 if (precompute) {
1575                         /* update remaining length */
1576
1577                         temp->len -= average;
1578
1579                         continue;
1580                 }
1581                 /* fill out current TD */
1582
1583                 td->td_status = temp->td_status;
1584                 td->td_token = temp->td_token;
1585
1586                 /* update data toggle */
1587
1588                 temp->td_token ^= htole32(UHCI_TD_SET_DT(1));
1589
1590                 if (average == 0) {
1591                         td->len = 0;
1592                         td->td_buffer = 0;
1593                         td->fix_pc = NULL;
1594
1595                 } else {
1596                         /* update remaining length */
1597
1598                         temp->len -= average;
1599
1600                         td->len = average;
1601
1602                         /* fill out buffer pointer and do fixup, if any */
1603
1604                         uhci_mem_layout_fixup(&temp->ml, td);
1605                 }
1606
1607                 td->alt_next = td_alt_next;
1608
1609                 if ((td_next == td_alt_next) && temp->setup_alt_next) {
1610                         /* we need to receive these frames one by one ! */
1611                         td->td_status |= htole32(UHCI_TD_IOC);
1612                         td->td_next = htole32(UHCI_PTR_T);
1613                 } else {
1614                         if (td_next) {
1615                                 /* link the current TD with the next one */
1616                                 td->td_next = td_next->td_self;
1617                         }
1618                 }
1619
1620                 usb_pc_cpu_flush(td->page_cache);
1621         }
1622
1623         if (precompute) {
1624                 precompute = 0;
1625
1626                 /* setup alt next pointer, if any */
1627                 if (temp->last_frame) {
1628                         td_alt_next = NULL;
1629                 } else {
1630                         /* we use this field internally */
1631                         td_alt_next = td_next;
1632                 }
1633
1634                 /* restore */
1635                 temp->shortpkt = shortpkt_old;
1636                 temp->len = len_old;
1637                 goto restart;
1638         }
1639         temp->td = td;
1640         temp->td_next = td_next;
1641 }
1642
1643 static uhci_td_t *
1644 uhci_setup_standard_chain(struct usb_xfer *xfer)
1645 {
1646         struct uhci_std_temp temp;
1647         uhci_td_t *td;
1648         uint32_t x;
1649
1650         DPRINTFN(9, "addr=%d endpt=%d sumlen=%d speed=%d\n",
1651             xfer->address, UE_GET_ADDR(xfer->endpointno),
1652             xfer->sumlen, usbd_get_speed(xfer->xroot->udev));
1653
1654         temp.average = xfer->max_frame_size;
1655         temp.max_frame_size = xfer->max_frame_size;
1656
1657         /* toggle the DMA set we are using */
1658         xfer->flags_int.curr_dma_set ^= 1;
1659
1660         /* get next DMA set */
1661         td = xfer->td_start[xfer->flags_int.curr_dma_set];
1662         xfer->td_transfer_first = td;
1663         xfer->td_transfer_cache = td;
1664
1665         temp.td = NULL;
1666         temp.td_next = td;
1667         temp.last_frame = 0;
1668         temp.setup_alt_next = xfer->flags_int.short_frames_ok;
1669
1670         uhci_mem_layout_init(&temp.ml, xfer);
1671
1672         temp.td_status =
1673             htole32(UHCI_TD_ZERO_ACTLEN(UHCI_TD_SET_ERRCNT(3) |
1674             UHCI_TD_ACTIVE));
1675
1676         if (xfer->xroot->udev->speed == USB_SPEED_LOW) {
1677                 temp.td_status |= htole32(UHCI_TD_LS);
1678         }
1679         temp.td_token =
1680             htole32(UHCI_TD_SET_ENDPT(xfer->endpointno) |
1681             UHCI_TD_SET_DEVADDR(xfer->address));
1682
1683         if (xfer->endpoint->toggle_next) {
1684                 /* DATA1 is next */
1685                 temp.td_token |= htole32(UHCI_TD_SET_DT(1));
1686         }
1687         /* check if we should prepend a setup message */
1688
1689         if (xfer->flags_int.control_xfr) {
1690                 if (xfer->flags_int.control_hdr) {
1691                         temp.td_token &= htole32(UHCI_TD_SET_DEVADDR(0x7F) |
1692                             UHCI_TD_SET_ENDPT(0xF));
1693                         temp.td_token |= htole32(UHCI_TD_PID_SETUP |
1694                             UHCI_TD_SET_DT(0));
1695
1696                         temp.len = xfer->frlengths[0];
1697                         temp.ml.buf_pc = xfer->frbuffers + 0;
1698                         temp.shortpkt = temp.len ? 1 : 0;
1699                         /* check for last frame */
1700                         if (xfer->nframes == 1) {
1701                                 /* no STATUS stage yet, SETUP is last */
1702                                 if (xfer->flags_int.control_act) {
1703                                         temp.last_frame = 1;
1704                                         temp.setup_alt_next = 0;
1705                                 }
1706                         }
1707                         uhci_setup_standard_chain_sub(&temp);
1708                 }
1709                 x = 1;
1710         } else {
1711                 x = 0;
1712         }
1713
1714         while (x != xfer->nframes) {
1715                 /* DATA0 / DATA1 message */
1716
1717                 temp.len = xfer->frlengths[x];
1718                 temp.ml.buf_pc = xfer->frbuffers + x;
1719
1720                 x++;
1721
1722                 if (x == xfer->nframes) {
1723                         if (xfer->flags_int.control_xfr) {
1724                                 /* no STATUS stage yet, DATA is last */
1725                                 if (xfer->flags_int.control_act) {
1726                                         temp.last_frame = 1;
1727                                         temp.setup_alt_next = 0;
1728                                 }
1729                         } else {
1730                                 temp.last_frame = 1;
1731                                 temp.setup_alt_next = 0;
1732                         }
1733                 }
1734                 /*
1735                  * Keep previous data toggle,
1736                  * device address and endpoint number:
1737                  */
1738
1739                 temp.td_token &= htole32(UHCI_TD_SET_DEVADDR(0x7F) |
1740                     UHCI_TD_SET_ENDPT(0xF) |
1741                     UHCI_TD_SET_DT(1));
1742
1743                 if (temp.len == 0) {
1744                         /* make sure that we send an USB packet */
1745
1746                         temp.shortpkt = 0;
1747
1748                 } else {
1749                         /* regular data transfer */
1750
1751                         temp.shortpkt = (xfer->flags.force_short_xfer) ? 0 : 1;
1752                 }
1753
1754                 /* set endpoint direction */
1755
1756                 temp.td_token |=
1757                     (UE_GET_DIR(xfer->endpointno) == UE_DIR_IN) ?
1758                     htole32(UHCI_TD_PID_IN) :
1759                     htole32(UHCI_TD_PID_OUT);
1760
1761                 uhci_setup_standard_chain_sub(&temp);
1762         }
1763
1764         /* check if we should append a status stage */
1765
1766         if (xfer->flags_int.control_xfr &&
1767             !xfer->flags_int.control_act) {
1768                 /*
1769                  * send a DATA1 message and reverse the current endpoint
1770                  * direction
1771                  */
1772
1773                 temp.td_token &= htole32(UHCI_TD_SET_DEVADDR(0x7F) |
1774                     UHCI_TD_SET_ENDPT(0xF) |
1775                     UHCI_TD_SET_DT(1));
1776                 temp.td_token |=
1777                     (UE_GET_DIR(xfer->endpointno) == UE_DIR_OUT) ?
1778                     htole32(UHCI_TD_PID_IN | UHCI_TD_SET_DT(1)) :
1779                     htole32(UHCI_TD_PID_OUT | UHCI_TD_SET_DT(1));
1780
1781                 temp.len = 0;
1782                 temp.ml.buf_pc = NULL;
1783                 temp.shortpkt = 0;
1784                 temp.last_frame = 1;
1785                 temp.setup_alt_next = 0;
1786
1787                 uhci_setup_standard_chain_sub(&temp);
1788         }
1789         td = temp.td;
1790
1791         /* Ensure that last TD is terminating: */
1792         td->td_next = htole32(UHCI_PTR_T);
1793
1794         /* set interrupt bit */
1795
1796         td->td_status |= htole32(UHCI_TD_IOC);
1797
1798         usb_pc_cpu_flush(td->page_cache);
1799
1800         /* must have at least one frame! */
1801
1802         xfer->td_transfer_last = td;
1803
1804 #ifdef USB_DEBUG
1805         if (uhcidebug > 8) {
1806                 DPRINTF("nexttog=%d; data before transfer:\n",
1807                     xfer->endpoint->toggle_next);
1808                 uhci_dump_tds(xfer->td_transfer_first);
1809         }
1810 #endif
1811         return (xfer->td_transfer_first);
1812 }
1813
1814 /* NOTE: "done" can be run two times in a row,
1815  * from close and from interrupt
1816  */
1817
1818 static void
1819 uhci_device_done(struct usb_xfer *xfer, usb_error_t error)
1820 {
1821         const struct usb_pipe_methods *methods = xfer->endpoint->methods;
1822         uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
1823         uhci_qh_t *qh;
1824
1825         USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
1826
1827         DPRINTFN(2, "xfer=%p, endpoint=%p, error=%d\n",
1828             xfer, xfer->endpoint, error);
1829
1830         qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
1831         if (qh) {
1832                 usb_pc_cpu_invalidate(qh->page_cache);
1833         }
1834         if (xfer->flags_int.bandwidth_reclaimed) {
1835                 xfer->flags_int.bandwidth_reclaimed = 0;
1836                 uhci_rem_loop(sc);
1837         }
1838         if (methods == &uhci_device_bulk_methods) {
1839                 UHCI_REMOVE_QH(qh, sc->sc_bulk_p_last);
1840         }
1841         if (methods == &uhci_device_ctrl_methods) {
1842                 if (xfer->xroot->udev->speed == USB_SPEED_LOW) {
1843                         UHCI_REMOVE_QH(qh, sc->sc_ls_ctl_p_last);
1844                 } else {
1845                         UHCI_REMOVE_QH(qh, sc->sc_fs_ctl_p_last);
1846                 }
1847         }
1848         if (methods == &uhci_device_intr_methods) {
1849                 UHCI_REMOVE_QH(qh, sc->sc_intr_p_last[xfer->qh_pos]);
1850         }
1851         /*
1852          * Only finish isochronous transfers once
1853          * which will update "xfer->frlengths".
1854          */
1855         if (xfer->td_transfer_first &&
1856             xfer->td_transfer_last) {
1857                 if (methods == &uhci_device_isoc_methods) {
1858                         uhci_isoc_done(sc, xfer);
1859                 }
1860                 xfer->td_transfer_first = NULL;
1861                 xfer->td_transfer_last = NULL;
1862         }
1863         /* dequeue transfer and start next transfer */
1864         usbd_transfer_done(xfer, error);
1865 }
1866
1867 /*------------------------------------------------------------------------*
1868  * uhci bulk support
1869  *------------------------------------------------------------------------*/
1870 static void
1871 uhci_device_bulk_open(struct usb_xfer *xfer)
1872 {
1873         return;
1874 }
1875
1876 static void
1877 uhci_device_bulk_close(struct usb_xfer *xfer)
1878 {
1879         uhci_device_done(xfer, USB_ERR_CANCELLED);
1880 }
1881
1882 static void
1883 uhci_device_bulk_enter(struct usb_xfer *xfer)
1884 {
1885         return;
1886 }
1887
1888 static void
1889 uhci_device_bulk_start(struct usb_xfer *xfer)
1890 {
1891         uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
1892         uhci_td_t *td;
1893         uhci_qh_t *qh;
1894
1895         /* setup TD's */
1896         td = uhci_setup_standard_chain(xfer);
1897
1898         /* setup QH */
1899         qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
1900
1901         qh->e_next = td;
1902         qh->qh_e_next = td->td_self;
1903
1904         if (xfer->xroot->udev->flags.self_suspended == 0) {
1905                 UHCI_APPEND_QH(qh, sc->sc_bulk_p_last);
1906                 uhci_add_loop(sc);
1907                 xfer->flags_int.bandwidth_reclaimed = 1;
1908         } else {
1909                 usb_pc_cpu_flush(qh->page_cache);
1910         }
1911
1912         /* put transfer on interrupt queue */
1913         uhci_transfer_intr_enqueue(xfer);
1914 }
1915
1916 static const struct usb_pipe_methods uhci_device_bulk_methods =
1917 {
1918         .open = uhci_device_bulk_open,
1919         .close = uhci_device_bulk_close,
1920         .enter = uhci_device_bulk_enter,
1921         .start = uhci_device_bulk_start,
1922 };
1923
1924 /*------------------------------------------------------------------------*
1925  * uhci control support
1926  *------------------------------------------------------------------------*/
1927 static void
1928 uhci_device_ctrl_open(struct usb_xfer *xfer)
1929 {
1930         return;
1931 }
1932
1933 static void
1934 uhci_device_ctrl_close(struct usb_xfer *xfer)
1935 {
1936         uhci_device_done(xfer, USB_ERR_CANCELLED);
1937 }
1938
1939 static void
1940 uhci_device_ctrl_enter(struct usb_xfer *xfer)
1941 {
1942         return;
1943 }
1944
1945 static void
1946 uhci_device_ctrl_start(struct usb_xfer *xfer)
1947 {
1948         uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
1949         uhci_qh_t *qh;
1950         uhci_td_t *td;
1951
1952         /* setup TD's */
1953         td = uhci_setup_standard_chain(xfer);
1954
1955         /* setup QH */
1956         qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
1957
1958         qh->e_next = td;
1959         qh->qh_e_next = td->td_self;
1960
1961         /*
1962          * NOTE: some devices choke on bandwidth- reclamation for control
1963          * transfers
1964          */
1965         if (xfer->xroot->udev->flags.self_suspended == 0) {
1966                 if (xfer->xroot->udev->speed == USB_SPEED_LOW) {
1967                         UHCI_APPEND_QH(qh, sc->sc_ls_ctl_p_last);
1968                 } else {
1969                         UHCI_APPEND_QH(qh, sc->sc_fs_ctl_p_last);
1970                 }
1971         } else {
1972                 usb_pc_cpu_flush(qh->page_cache);
1973         }
1974         /* put transfer on interrupt queue */
1975         uhci_transfer_intr_enqueue(xfer);
1976 }
1977
1978 static const struct usb_pipe_methods uhci_device_ctrl_methods =
1979 {
1980         .open = uhci_device_ctrl_open,
1981         .close = uhci_device_ctrl_close,
1982         .enter = uhci_device_ctrl_enter,
1983         .start = uhci_device_ctrl_start,
1984 };
1985
1986 /*------------------------------------------------------------------------*
1987  * uhci interrupt support
1988  *------------------------------------------------------------------------*/
1989 static void
1990 uhci_device_intr_open(struct usb_xfer *xfer)
1991 {
1992         uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
1993         uint16_t best;
1994         uint16_t bit;
1995         uint16_t x;
1996
1997         best = 0;
1998         bit = UHCI_IFRAMELIST_COUNT / 2;
1999         while (bit) {
2000                 if (xfer->interval >= bit) {
2001                         x = bit;
2002                         best = bit;
2003                         while (x & bit) {
2004                                 if (sc->sc_intr_stat[x] <
2005                                     sc->sc_intr_stat[best]) {
2006                                         best = x;
2007                                 }
2008                                 x++;
2009                         }
2010                         break;
2011                 }
2012                 bit >>= 1;
2013         }
2014
2015         sc->sc_intr_stat[best]++;
2016         xfer->qh_pos = best;
2017
2018         DPRINTFN(3, "best=%d interval=%d\n",
2019             best, xfer->interval);
2020 }
2021
2022 static void
2023 uhci_device_intr_close(struct usb_xfer *xfer)
2024 {
2025         uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
2026
2027         sc->sc_intr_stat[xfer->qh_pos]--;
2028
2029         uhci_device_done(xfer, USB_ERR_CANCELLED);
2030 }
2031
2032 static void
2033 uhci_device_intr_enter(struct usb_xfer *xfer)
2034 {
2035         return;
2036 }
2037
2038 static void
2039 uhci_device_intr_start(struct usb_xfer *xfer)
2040 {
2041         uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
2042         uhci_qh_t *qh;
2043         uhci_td_t *td;
2044
2045         /* setup TD's */
2046         td = uhci_setup_standard_chain(xfer);
2047
2048         /* setup QH */
2049         qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
2050
2051         qh->e_next = td;
2052         qh->qh_e_next = td->td_self;
2053
2054         if (xfer->xroot->udev->flags.self_suspended == 0) {
2055                 /* enter QHs into the controller data structures */
2056                 UHCI_APPEND_QH(qh, sc->sc_intr_p_last[xfer->qh_pos]);
2057         } else {
2058                 usb_pc_cpu_flush(qh->page_cache);
2059         }
2060
2061         /* put transfer on interrupt queue */
2062         uhci_transfer_intr_enqueue(xfer);
2063 }
2064
2065 static const struct usb_pipe_methods uhci_device_intr_methods =
2066 {
2067         .open = uhci_device_intr_open,
2068         .close = uhci_device_intr_close,
2069         .enter = uhci_device_intr_enter,
2070         .start = uhci_device_intr_start,
2071 };
2072
2073 /*------------------------------------------------------------------------*
2074  * uhci isochronous support
2075  *------------------------------------------------------------------------*/
2076 static void
2077 uhci_device_isoc_open(struct usb_xfer *xfer)
2078 {
2079         uhci_td_t *td;
2080         uint32_t td_token;
2081         uint8_t ds;
2082
2083         td_token =
2084             (UE_GET_DIR(xfer->endpointno) == UE_DIR_IN) ?
2085             UHCI_TD_IN(0, xfer->endpointno, xfer->address, 0) :
2086             UHCI_TD_OUT(0, xfer->endpointno, xfer->address, 0);
2087
2088         td_token = htole32(td_token);
2089
2090         /* initialize all TD's */
2091
2092         for (ds = 0; ds != 2; ds++) {
2093                 for (td = xfer->td_start[ds]; td; td = td->obj_next) {
2094                         /* mark TD as inactive */
2095                         td->td_status = htole32(UHCI_TD_IOS);
2096                         td->td_token = td_token;
2097
2098                         usb_pc_cpu_flush(td->page_cache);
2099                 }
2100         }
2101 }
2102
2103 static void
2104 uhci_device_isoc_close(struct usb_xfer *xfer)
2105 {
2106         uhci_device_done(xfer, USB_ERR_CANCELLED);
2107 }
2108
2109 static void
2110 uhci_device_isoc_enter(struct usb_xfer *xfer)
2111 {
2112         struct uhci_mem_layout ml;
2113         uhci_softc_t *sc = UHCI_BUS2SC(xfer->xroot->bus);
2114         uint32_t nframes;
2115         uint32_t temp;
2116         uint32_t *plen;
2117
2118 #ifdef USB_DEBUG
2119         uint8_t once = 1;
2120
2121 #endif
2122         uhci_td_t *td;
2123         uhci_td_t *td_last = NULL;
2124         uhci_td_t **pp_last;
2125
2126         DPRINTFN(6, "xfer=%p next=%d nframes=%d\n",
2127             xfer, xfer->endpoint->isoc_next, xfer->nframes);
2128
2129         nframes = UREAD2(sc, UHCI_FRNUM);
2130
2131         temp = (nframes - xfer->endpoint->isoc_next) &
2132             (UHCI_VFRAMELIST_COUNT - 1);
2133
2134         if ((xfer->endpoint->is_synced == 0) ||
2135             (temp < xfer->nframes)) {
2136                 /*
2137                  * If there is data underflow or the pipe queue is empty we
2138                  * schedule the transfer a few frames ahead of the current
2139                  * frame position. Else two isochronous transfers might
2140                  * overlap.
2141                  */
2142                 xfer->endpoint->isoc_next = (nframes + 3) & (UHCI_VFRAMELIST_COUNT - 1);
2143                 xfer->endpoint->is_synced = 1;
2144                 DPRINTFN(3, "start next=%d\n", xfer->endpoint->isoc_next);
2145         }
2146         /*
2147          * compute how many milliseconds the insertion is ahead of the
2148          * current frame position:
2149          */
2150         temp = (xfer->endpoint->isoc_next - nframes) &
2151             (UHCI_VFRAMELIST_COUNT - 1);
2152
2153         /*
2154          * pre-compute when the isochronous transfer will be finished:
2155          */
2156         xfer->isoc_time_complete =
2157             usb_isoc_time_expand(&sc->sc_bus, nframes) + temp +
2158             xfer->nframes;
2159
2160         /* get the real number of frames */
2161
2162         nframes = xfer->nframes;
2163
2164         uhci_mem_layout_init(&ml, xfer);
2165
2166         plen = xfer->frlengths;
2167
2168         /* toggle the DMA set we are using */
2169         xfer->flags_int.curr_dma_set ^= 1;
2170
2171         /* get next DMA set */
2172         td = xfer->td_start[xfer->flags_int.curr_dma_set];
2173         xfer->td_transfer_first = td;
2174
2175         pp_last = &sc->sc_isoc_p_last[xfer->endpoint->isoc_next];
2176
2177         /* store starting position */
2178
2179         xfer->qh_pos = xfer->endpoint->isoc_next;
2180
2181         while (nframes--) {
2182                 if (td == NULL) {
2183                         panic("%s:%d: out of TD's\n",
2184                             __FUNCTION__, __LINE__);
2185                 }
2186                 if (pp_last >= &sc->sc_isoc_p_last[UHCI_VFRAMELIST_COUNT]) {
2187                         pp_last = &sc->sc_isoc_p_last[0];
2188                 }
2189                 if (*plen > xfer->max_frame_size) {
2190 #ifdef USB_DEBUG
2191                         if (once) {
2192                                 once = 0;
2193                                 printf("%s: frame length(%d) exceeds %d "
2194                                     "bytes (frame truncated)\n",
2195                                     __FUNCTION__, *plen,
2196                                     xfer->max_frame_size);
2197                         }
2198 #endif
2199                         *plen = xfer->max_frame_size;
2200                 }
2201                 /* reuse td_token from last transfer */
2202
2203                 td->td_token &= htole32(~UHCI_TD_MAXLEN_MASK);
2204                 td->td_token |= htole32(UHCI_TD_SET_MAXLEN(*plen));
2205
2206                 td->len = *plen;
2207
2208                 if (td->len == 0) {
2209                         /*
2210                          * Do not call "uhci_mem_layout_fixup()" when the
2211                          * length is zero!
2212                          */
2213                         td->td_buffer = 0;
2214                         td->fix_pc = NULL;
2215
2216                 } else {
2217                         /* fill out buffer pointer and do fixup, if any */
2218
2219                         uhci_mem_layout_fixup(&ml, td);
2220                 }
2221
2222                 /* update status */
2223                 if (nframes == 0) {
2224                         td->td_status = htole32
2225                             (UHCI_TD_ZERO_ACTLEN
2226                             (UHCI_TD_SET_ERRCNT(0) |
2227                             UHCI_TD_ACTIVE |
2228                             UHCI_TD_IOS |
2229                             UHCI_TD_IOC));
2230                 } else {
2231                         td->td_status = htole32
2232                             (UHCI_TD_ZERO_ACTLEN
2233                             (UHCI_TD_SET_ERRCNT(0) |
2234                             UHCI_TD_ACTIVE |
2235                             UHCI_TD_IOS));
2236                 }
2237
2238                 usb_pc_cpu_flush(td->page_cache);
2239
2240 #ifdef USB_DEBUG
2241                 if (uhcidebug > 5) {
2242                         DPRINTF("TD %d\n", nframes);
2243                         uhci_dump_td(td);
2244                 }
2245 #endif
2246                 /* insert TD into schedule */
2247                 UHCI_APPEND_TD(td, *pp_last);
2248                 pp_last++;
2249
2250                 plen++;
2251                 td_last = td;
2252                 td = td->obj_next;
2253         }
2254
2255         xfer->td_transfer_last = td_last;
2256
2257         /* update isoc_next */
2258         xfer->endpoint->isoc_next = (pp_last - &sc->sc_isoc_p_last[0]) &
2259             (UHCI_VFRAMELIST_COUNT - 1);
2260 }
2261
2262 static void
2263 uhci_device_isoc_start(struct usb_xfer *xfer)
2264 {
2265         /* put transfer on interrupt queue */
2266         uhci_transfer_intr_enqueue(xfer);
2267 }
2268
2269 static const struct usb_pipe_methods uhci_device_isoc_methods =
2270 {
2271         .open = uhci_device_isoc_open,
2272         .close = uhci_device_isoc_close,
2273         .enter = uhci_device_isoc_enter,
2274         .start = uhci_device_isoc_start,
2275 };
2276
2277 /*------------------------------------------------------------------------*
2278  * uhci root control support
2279  *------------------------------------------------------------------------*
2280  * Simulate a hardware hub by handling all the necessary requests.
2281  *------------------------------------------------------------------------*/
2282
2283 static const
2284 struct usb_device_descriptor uhci_devd =
2285 {
2286         sizeof(struct usb_device_descriptor),
2287         UDESC_DEVICE,                   /* type */
2288         {0x00, 0x01},                   /* USB version */
2289         UDCLASS_HUB,                    /* class */
2290         UDSUBCLASS_HUB,                 /* subclass */
2291         UDPROTO_FSHUB,                  /* protocol */
2292         64,                             /* max packet */
2293         {0}, {0}, {0x00, 0x01},         /* device id */
2294         1, 2, 0,                        /* string indexes */
2295         1                               /* # of configurations */
2296 };
2297
2298 static const struct uhci_config_desc uhci_confd = {
2299         .confd = {
2300                 .bLength = sizeof(struct usb_config_descriptor),
2301                 .bDescriptorType = UDESC_CONFIG,
2302                 .wTotalLength[0] = sizeof(uhci_confd),
2303                 .bNumInterface = 1,
2304                 .bConfigurationValue = 1,
2305                 .iConfiguration = 0,
2306                 .bmAttributes = UC_SELF_POWERED,
2307                 .bMaxPower = 0          /* max power */
2308         },
2309         .ifcd = {
2310                 .bLength = sizeof(struct usb_interface_descriptor),
2311                 .bDescriptorType = UDESC_INTERFACE,
2312                 .bNumEndpoints = 1,
2313                 .bInterfaceClass = UICLASS_HUB,
2314                 .bInterfaceSubClass = UISUBCLASS_HUB,
2315                 .bInterfaceProtocol = UIPROTO_FSHUB,
2316         },
2317         .endpd = {
2318                 .bLength = sizeof(struct usb_endpoint_descriptor),
2319                 .bDescriptorType = UDESC_ENDPOINT,
2320                 .bEndpointAddress = UE_DIR_IN | UHCI_INTR_ENDPT,
2321                 .bmAttributes = UE_INTERRUPT,
2322                 .wMaxPacketSize[0] = 8, /* max packet (63 ports) */
2323                 .bInterval = 255,
2324         },
2325 };
2326
2327 static const
2328 struct usb_hub_descriptor_min uhci_hubd_piix =
2329 {
2330         .bDescLength = sizeof(uhci_hubd_piix),
2331         .bDescriptorType = UDESC_HUB,
2332         .bNbrPorts = 2,
2333         .wHubCharacteristics = {UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL, 0},
2334         .bPwrOn2PwrGood = 50,
2335 };
2336
2337 /*
2338  * The USB hub protocol requires that SET_FEATURE(PORT_RESET) also
2339  * enables the port, and also states that SET_FEATURE(PORT_ENABLE)
2340  * should not be used by the USB subsystem.  As we cannot issue a
2341  * SET_FEATURE(PORT_ENABLE) externally, we must ensure that the port
2342  * will be enabled as part of the reset.
2343  *
2344  * On the VT83C572, the port cannot be successfully enabled until the
2345  * outstanding "port enable change" and "connection status change"
2346  * events have been reset.
2347  */
2348 static usb_error_t
2349 uhci_portreset(uhci_softc_t *sc, uint16_t index)
2350 {
2351         uint16_t port;
2352         uint16_t x;
2353         uint8_t lim;
2354
2355         if (index == 1)
2356                 port = UHCI_PORTSC1;
2357         else if (index == 2)
2358                 port = UHCI_PORTSC2;
2359         else
2360                 return (USB_ERR_IOERROR);
2361
2362         /*
2363          * Before we do anything, turn on SOF messages on the USB
2364          * BUS. Some USB devices do not cope without them!
2365          */
2366         uhci_restart(sc);
2367
2368         x = URWMASK(UREAD2(sc, port));
2369         UWRITE2(sc, port, x | UHCI_PORTSC_PR);
2370
2371         usb_pause_mtx(&sc->sc_bus.bus_mtx,
2372             USB_MS_TO_TICKS(usb_port_root_reset_delay));
2373
2374         DPRINTFN(4, "uhci port %d reset, status0 = 0x%04x\n",
2375             index, UREAD2(sc, port));
2376
2377         x = URWMASK(UREAD2(sc, port));
2378         UWRITE2(sc, port, x & ~UHCI_PORTSC_PR);
2379
2380         mtx_unlock(&sc->sc_bus.bus_mtx);
2381
2382         /* 
2383          * This delay needs to be exactly 100us, else some USB devices
2384          * fail to attach!
2385          */
2386         DELAY(100);
2387
2388         mtx_lock(&sc->sc_bus.bus_mtx);
2389
2390         DPRINTFN(4, "uhci port %d reset, status1 = 0x%04x\n",
2391             index, UREAD2(sc, port));
2392
2393         x = URWMASK(UREAD2(sc, port));
2394         UWRITE2(sc, port, x | UHCI_PORTSC_PE);
2395
2396         for (lim = 0; lim < 12; lim++) {
2397                 usb_pause_mtx(&sc->sc_bus.bus_mtx,
2398                     USB_MS_TO_TICKS(usb_port_reset_delay));
2399
2400                 x = UREAD2(sc, port);
2401
2402                 DPRINTFN(4, "uhci port %d iteration %u, status = 0x%04x\n",
2403                     index, lim, x);
2404
2405                 if (!(x & UHCI_PORTSC_CCS)) {
2406                         /*
2407                          * No device is connected (or was disconnected
2408                          * during reset).  Consider the port reset.
2409                          * The delay must be long enough to ensure on
2410                          * the initial iteration that the device
2411                          * connection will have been registered.  50ms
2412                          * appears to be sufficient, but 20ms is not.
2413                          */
2414                         DPRINTFN(4, "uhci port %d loop %u, device detached\n",
2415                             index, lim);
2416                         goto done;
2417                 }
2418                 if (x & (UHCI_PORTSC_POEDC | UHCI_PORTSC_CSC)) {
2419                         /*
2420                          * Port enabled changed and/or connection
2421                          * status changed were set.  Reset either or
2422                          * both raised flags (by writing a 1 to that
2423                          * bit), and wait again for state to settle.
2424                          */
2425                         UWRITE2(sc, port, URWMASK(x) |
2426                             (x & (UHCI_PORTSC_POEDC | UHCI_PORTSC_CSC)));
2427                         continue;
2428                 }
2429                 if (x & UHCI_PORTSC_PE) {
2430                         /* port is enabled */
2431                         goto done;
2432                 }
2433                 UWRITE2(sc, port, URWMASK(x) | UHCI_PORTSC_PE);
2434         }
2435
2436         DPRINTFN(2, "uhci port %d reset timed out\n", index);
2437         return (USB_ERR_TIMEOUT);
2438
2439 done:
2440         DPRINTFN(4, "uhci port %d reset, status2 = 0x%04x\n",
2441             index, UREAD2(sc, port));
2442
2443         sc->sc_isreset = 1;
2444         return (USB_ERR_NORMAL_COMPLETION);
2445 }
2446
2447 static usb_error_t
2448 uhci_roothub_exec(struct usb_device *udev,
2449     struct usb_device_request *req, const void **pptr, uint16_t *plength)
2450 {
2451         uhci_softc_t *sc = UHCI_BUS2SC(udev->bus);
2452         const void *ptr;
2453         const char *str_ptr;
2454         uint16_t x;
2455         uint16_t port;
2456         uint16_t value;
2457         uint16_t index;
2458         uint16_t status;
2459         uint16_t change;
2460         uint16_t len;
2461         usb_error_t err;
2462
2463         USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
2464
2465         /* buffer reset */
2466         ptr = (const void *)&sc->sc_hub_desc.temp;
2467         len = 0;
2468         err = 0;
2469
2470         value = UGETW(req->wValue);
2471         index = UGETW(req->wIndex);
2472
2473         DPRINTFN(3, "type=0x%02x request=0x%02x wLen=0x%04x "
2474             "wValue=0x%04x wIndex=0x%04x\n",
2475             req->bmRequestType, req->bRequest,
2476             UGETW(req->wLength), value, index);
2477
2478 #define C(x,y) ((x) | ((y) << 8))
2479         switch (C(req->bRequest, req->bmRequestType)) {
2480         case C(UR_CLEAR_FEATURE, UT_WRITE_DEVICE):
2481         case C(UR_CLEAR_FEATURE, UT_WRITE_INTERFACE):
2482         case C(UR_CLEAR_FEATURE, UT_WRITE_ENDPOINT):
2483                 /*
2484                  * DEVICE_REMOTE_WAKEUP and ENDPOINT_HALT are no-ops
2485                  * for the integrated root hub.
2486                  */
2487                 break;
2488         case C(UR_GET_CONFIG, UT_READ_DEVICE):
2489                 len = 1;
2490                 sc->sc_hub_desc.temp[0] = sc->sc_conf;
2491                 break;
2492         case C(UR_GET_DESCRIPTOR, UT_READ_DEVICE):
2493                 switch (value >> 8) {
2494                 case UDESC_DEVICE:
2495                         if ((value & 0xff) != 0) {
2496                                 err = USB_ERR_IOERROR;
2497                                 goto done;
2498                         }
2499                         len = sizeof(uhci_devd);
2500                         ptr = (const void *)&uhci_devd;
2501                         break;
2502
2503                 case UDESC_CONFIG:
2504                         if ((value & 0xff) != 0) {
2505                                 err = USB_ERR_IOERROR;
2506                                 goto done;
2507                         }
2508                         len = sizeof(uhci_confd);
2509                         ptr = (const void *)&uhci_confd;
2510                         break;
2511
2512                 case UDESC_STRING:
2513                         switch (value & 0xff) {
2514                         case 0: /* Language table */
2515                                 str_ptr = "\001";
2516                                 break;
2517
2518                         case 1: /* Vendor */
2519                                 str_ptr = sc->sc_vendor;
2520                                 break;
2521
2522                         case 2: /* Product */
2523                                 str_ptr = "UHCI root HUB";
2524                                 break;
2525
2526                         default:
2527                                 str_ptr = "";
2528                                 break;
2529                         }
2530
2531                         len = usb_make_str_desc
2532                             (sc->sc_hub_desc.temp,
2533                             sizeof(sc->sc_hub_desc.temp),
2534                             str_ptr);
2535                         break;
2536
2537                 default:
2538                         err = USB_ERR_IOERROR;
2539                         goto done;
2540                 }
2541                 break;
2542         case C(UR_GET_INTERFACE, UT_READ_INTERFACE):
2543                 len = 1;
2544                 sc->sc_hub_desc.temp[0] = 0;
2545                 break;
2546         case C(UR_GET_STATUS, UT_READ_DEVICE):
2547                 len = 2;
2548                 USETW(sc->sc_hub_desc.stat.wStatus, UDS_SELF_POWERED);
2549                 break;
2550         case C(UR_GET_STATUS, UT_READ_INTERFACE):
2551         case C(UR_GET_STATUS, UT_READ_ENDPOINT):
2552                 len = 2;
2553                 USETW(sc->sc_hub_desc.stat.wStatus, 0);
2554                 break;
2555         case C(UR_SET_ADDRESS, UT_WRITE_DEVICE):
2556                 if (value >= UHCI_MAX_DEVICES) {
2557                         err = USB_ERR_IOERROR;
2558                         goto done;
2559                 }
2560                 sc->sc_addr = value;
2561                 break;
2562         case C(UR_SET_CONFIG, UT_WRITE_DEVICE):
2563                 if ((value != 0) && (value != 1)) {
2564                         err = USB_ERR_IOERROR;
2565                         goto done;
2566                 }
2567                 sc->sc_conf = value;
2568                 break;
2569         case C(UR_SET_DESCRIPTOR, UT_WRITE_DEVICE):
2570                 break;
2571         case C(UR_SET_FEATURE, UT_WRITE_DEVICE):
2572         case C(UR_SET_FEATURE, UT_WRITE_INTERFACE):
2573         case C(UR_SET_FEATURE, UT_WRITE_ENDPOINT):
2574                 err = USB_ERR_IOERROR;
2575                 goto done;
2576         case C(UR_SET_INTERFACE, UT_WRITE_INTERFACE):
2577                 break;
2578         case C(UR_SYNCH_FRAME, UT_WRITE_ENDPOINT):
2579                 break;
2580                 /* Hub requests */
2581         case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_DEVICE):
2582                 break;
2583         case C(UR_CLEAR_FEATURE, UT_WRITE_CLASS_OTHER):
2584                 DPRINTFN(4, "UR_CLEAR_PORT_FEATURE "
2585                     "port=%d feature=%d\n",
2586                     index, value);
2587                 if (index == 1)
2588                         port = UHCI_PORTSC1;
2589                 else if (index == 2)
2590                         port = UHCI_PORTSC2;
2591                 else {
2592                         err = USB_ERR_IOERROR;
2593                         goto done;
2594                 }
2595                 switch (value) {
2596                 case UHF_PORT_ENABLE:
2597                         x = URWMASK(UREAD2(sc, port));
2598                         UWRITE2(sc, port, x & ~UHCI_PORTSC_PE);
2599                         break;
2600                 case UHF_PORT_SUSPEND:
2601                         x = URWMASK(UREAD2(sc, port));
2602                         UWRITE2(sc, port, x & ~(UHCI_PORTSC_SUSP));
2603                         break;
2604                 case UHF_PORT_RESET:
2605                         x = URWMASK(UREAD2(sc, port));
2606                         UWRITE2(sc, port, x & ~UHCI_PORTSC_PR);
2607                         break;
2608                 case UHF_C_PORT_CONNECTION:
2609                         x = URWMASK(UREAD2(sc, port));
2610                         UWRITE2(sc, port, x | UHCI_PORTSC_CSC);
2611                         break;
2612                 case UHF_C_PORT_ENABLE:
2613                         x = URWMASK(UREAD2(sc, port));
2614                         UWRITE2(sc, port, x | UHCI_PORTSC_POEDC);
2615                         break;
2616                 case UHF_C_PORT_OVER_CURRENT:
2617                         x = URWMASK(UREAD2(sc, port));
2618                         UWRITE2(sc, port, x | UHCI_PORTSC_OCIC);
2619                         break;
2620                 case UHF_C_PORT_RESET:
2621                         sc->sc_isreset = 0;
2622                         err = USB_ERR_NORMAL_COMPLETION;
2623                         goto done;
2624                 case UHF_C_PORT_SUSPEND:
2625                         sc->sc_isresumed &= ~(1 << index);
2626                         break;
2627                 case UHF_PORT_CONNECTION:
2628                 case UHF_PORT_OVER_CURRENT:
2629                 case UHF_PORT_POWER:
2630                 case UHF_PORT_LOW_SPEED:
2631                 default:
2632                         err = USB_ERR_IOERROR;
2633                         goto done;
2634                 }
2635                 break;
2636         case C(UR_GET_BUS_STATE, UT_READ_CLASS_OTHER):
2637                 if (index == 1)
2638                         port = UHCI_PORTSC1;
2639                 else if (index == 2)
2640                         port = UHCI_PORTSC2;
2641                 else {
2642                         err = USB_ERR_IOERROR;
2643                         goto done;
2644                 }
2645                 len = 1;
2646                 sc->sc_hub_desc.temp[0] =
2647                     ((UREAD2(sc, port) & UHCI_PORTSC_LS) >>
2648                     UHCI_PORTSC_LS_SHIFT);
2649                 break;
2650         case C(UR_GET_DESCRIPTOR, UT_READ_CLASS_DEVICE):
2651                 if ((value & 0xff) != 0) {
2652                         err = USB_ERR_IOERROR;
2653                         goto done;
2654                 }
2655                 len = sizeof(uhci_hubd_piix);
2656                 ptr = (const void *)&uhci_hubd_piix;
2657                 break;
2658         case C(UR_GET_STATUS, UT_READ_CLASS_DEVICE):
2659                 len = 16;
2660                 memset(sc->sc_hub_desc.temp, 0, 16);
2661                 break;
2662         case C(UR_GET_STATUS, UT_READ_CLASS_OTHER):
2663                 if (index == 1)
2664                         port = UHCI_PORTSC1;
2665                 else if (index == 2)
2666                         port = UHCI_PORTSC2;
2667                 else {
2668                         err = USB_ERR_IOERROR;
2669                         goto done;
2670                 }
2671                 x = UREAD2(sc, port);
2672                 status = change = 0;
2673                 if (x & UHCI_PORTSC_CCS)
2674                         status |= UPS_CURRENT_CONNECT_STATUS;
2675                 if (x & UHCI_PORTSC_CSC)
2676                         change |= UPS_C_CONNECT_STATUS;
2677                 if (x & UHCI_PORTSC_PE)
2678                         status |= UPS_PORT_ENABLED;
2679                 if (x & UHCI_PORTSC_POEDC)
2680                         change |= UPS_C_PORT_ENABLED;
2681                 if (x & UHCI_PORTSC_OCI)
2682                         status |= UPS_OVERCURRENT_INDICATOR;
2683                 if (x & UHCI_PORTSC_OCIC)
2684                         change |= UPS_C_OVERCURRENT_INDICATOR;
2685                 if (x & UHCI_PORTSC_LSDA)
2686                         status |= UPS_LOW_SPEED;
2687                 if ((x & UHCI_PORTSC_PE) && (x & UHCI_PORTSC_RD)) {
2688                         /* need to do a write back */
2689                         UWRITE2(sc, port, URWMASK(x));
2690
2691                         /* wait 20ms for resume sequence to complete */
2692                         usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 50);
2693
2694                         /* clear suspend and resume detect */
2695                         UWRITE2(sc, port, URWMASK(x) & ~(UHCI_PORTSC_RD |
2696                             UHCI_PORTSC_SUSP));
2697
2698                         /* wait a little bit */
2699                         usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 500);
2700
2701                         sc->sc_isresumed |= (1 << index);
2702
2703                 } else if (x & UHCI_PORTSC_SUSP) {
2704                         status |= UPS_SUSPEND;
2705                 }
2706                 status |= UPS_PORT_POWER;
2707                 if (sc->sc_isresumed & (1 << index))
2708                         change |= UPS_C_SUSPEND;
2709                 if (sc->sc_isreset)
2710                         change |= UPS_C_PORT_RESET;
2711                 USETW(sc->sc_hub_desc.ps.wPortStatus, status);
2712                 USETW(sc->sc_hub_desc.ps.wPortChange, change);
2713                 len = sizeof(sc->sc_hub_desc.ps);
2714                 break;
2715         case C(UR_SET_DESCRIPTOR, UT_WRITE_CLASS_DEVICE):
2716                 err = USB_ERR_IOERROR;
2717                 goto done;
2718         case C(UR_SET_FEATURE, UT_WRITE_CLASS_DEVICE):
2719                 break;
2720         case C(UR_SET_FEATURE, UT_WRITE_CLASS_OTHER):
2721                 if (index == 1)
2722                         port = UHCI_PORTSC1;
2723                 else if (index == 2)
2724                         port = UHCI_PORTSC2;
2725                 else {
2726                         err = USB_ERR_IOERROR;
2727                         goto done;
2728                 }
2729                 switch (value) {
2730                 case UHF_PORT_ENABLE:
2731                         x = URWMASK(UREAD2(sc, port));
2732                         UWRITE2(sc, port, x | UHCI_PORTSC_PE);
2733                         break;
2734                 case UHF_PORT_SUSPEND:
2735                         x = URWMASK(UREAD2(sc, port));
2736                         UWRITE2(sc, port, x | UHCI_PORTSC_SUSP);
2737                         break;
2738                 case UHF_PORT_RESET:
2739                         err = uhci_portreset(sc, index);
2740                         goto done;
2741                 case UHF_PORT_POWER:
2742                         /* pretend we turned on power */
2743                         err = USB_ERR_NORMAL_COMPLETION;
2744                         goto done;
2745                 case UHF_C_PORT_CONNECTION:
2746                 case UHF_C_PORT_ENABLE:
2747                 case UHF_C_PORT_OVER_CURRENT:
2748                 case UHF_PORT_CONNECTION:
2749                 case UHF_PORT_OVER_CURRENT:
2750                 case UHF_PORT_LOW_SPEED:
2751                 case UHF_C_PORT_SUSPEND:
2752                 case UHF_C_PORT_RESET:
2753                 default:
2754                         err = USB_ERR_IOERROR;
2755                         goto done;
2756                 }
2757                 break;
2758         default:
2759                 err = USB_ERR_IOERROR;
2760                 goto done;
2761         }
2762 done:
2763         *plength = len;
2764         *pptr = ptr;
2765         return (err);
2766 }
2767
2768 /*
2769  * This routine is executed periodically and simulates interrupts from
2770  * the root controller interrupt pipe for port status change:
2771  */
2772 static void
2773 uhci_root_intr(uhci_softc_t *sc)
2774 {
2775         DPRINTFN(21, "\n");
2776
2777         USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED);
2778
2779         sc->sc_hub_idata[0] = 0;
2780
2781         if (UREAD2(sc, UHCI_PORTSC1) & (UHCI_PORTSC_CSC |
2782             UHCI_PORTSC_OCIC | UHCI_PORTSC_RD)) {
2783                 sc->sc_hub_idata[0] |= 1 << 1;
2784         }
2785         if (UREAD2(sc, UHCI_PORTSC2) & (UHCI_PORTSC_CSC |
2786             UHCI_PORTSC_OCIC | UHCI_PORTSC_RD)) {
2787                 sc->sc_hub_idata[0] |= 1 << 2;
2788         }
2789
2790         /* restart timer */
2791         usb_callout_reset(&sc->sc_root_intr, hz,
2792             (void *)&uhci_root_intr, sc);
2793
2794         if (sc->sc_hub_idata[0] != 0) {
2795                 uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata,
2796                     sizeof(sc->sc_hub_idata));
2797         }
2798 }
2799
2800 static void
2801 uhci_xfer_setup(struct usb_setup_params *parm)
2802 {
2803         struct usb_page_search page_info;
2804         struct usb_page_cache *pc;
2805         uhci_softc_t *sc;
2806         struct usb_xfer *xfer;
2807         void *last_obj;
2808         uint32_t ntd;
2809         uint32_t nqh;
2810         uint32_t nfixup;
2811         uint32_t n;
2812         uint16_t align;
2813
2814         sc = UHCI_BUS2SC(parm->udev->bus);
2815         xfer = parm->curr_xfer;
2816
2817         parm->hc_max_packet_size = 0x500;
2818         parm->hc_max_packet_count = 1;
2819         parm->hc_max_frame_size = 0x500;
2820
2821         /*
2822          * compute ntd and nqh
2823          */
2824         if (parm->methods == &uhci_device_ctrl_methods) {
2825                 xfer->flags_int.bdma_enable = 1;
2826                 xfer->flags_int.bdma_no_post_sync = 1;
2827
2828                 usbd_transfer_setup_sub(parm);
2829
2830                 /* see EHCI HC driver for proof of "ntd" formula */
2831
2832                 nqh = 1;
2833                 ntd = ((2 * xfer->nframes) + 1  /* STATUS */
2834                     + (xfer->max_data_length / xfer->max_frame_size));
2835
2836         } else if (parm->methods == &uhci_device_bulk_methods) {
2837                 xfer->flags_int.bdma_enable = 1;
2838                 xfer->flags_int.bdma_no_post_sync = 1;
2839
2840                 usbd_transfer_setup_sub(parm);
2841
2842                 nqh = 1;
2843                 ntd = ((2 * xfer->nframes)
2844                     + (xfer->max_data_length / xfer->max_frame_size));
2845
2846         } else if (parm->methods == &uhci_device_intr_methods) {
2847                 xfer->flags_int.bdma_enable = 1;
2848                 xfer->flags_int.bdma_no_post_sync = 1;
2849
2850                 usbd_transfer_setup_sub(parm);
2851
2852                 nqh = 1;
2853                 ntd = ((2 * xfer->nframes)
2854                     + (xfer->max_data_length / xfer->max_frame_size));
2855
2856         } else if (parm->methods == &uhci_device_isoc_methods) {
2857                 xfer->flags_int.bdma_enable = 1;
2858                 xfer->flags_int.bdma_no_post_sync = 1;
2859
2860                 usbd_transfer_setup_sub(parm);
2861
2862                 nqh = 0;
2863                 ntd = xfer->nframes;
2864
2865         } else {
2866                 usbd_transfer_setup_sub(parm);
2867
2868                 nqh = 0;
2869                 ntd = 0;
2870         }
2871
2872         if (parm->err) {
2873                 return;
2874         }
2875         /*
2876          * NOTE: the UHCI controller requires that
2877          * every packet must be contiguous on
2878          * the same USB memory page !
2879          */
2880         nfixup = (parm->bufsize / USB_PAGE_SIZE) + 1;
2881
2882         /*
2883          * Compute a suitable power of two alignment
2884          * for our "max_frame_size" fixup buffer(s):
2885          */
2886         align = xfer->max_frame_size;
2887         n = 0;
2888         while (align) {
2889                 align >>= 1;
2890                 n++;
2891         }
2892
2893         /* check for power of two */
2894         if (!(xfer->max_frame_size &
2895             (xfer->max_frame_size - 1))) {
2896                 n--;
2897         }
2898         /*
2899          * We don't allow alignments of
2900          * less than 8 bytes:
2901          *
2902          * NOTE: Allocating using an aligment
2903          * of 1 byte has special meaning!
2904          */
2905         if (n < 3) {
2906                 n = 3;
2907         }
2908         align = (1 << n);
2909
2910         if (usbd_transfer_setup_sub_malloc(
2911             parm, &pc, xfer->max_frame_size,
2912             align, nfixup)) {
2913                 parm->err = USB_ERR_NOMEM;
2914                 return;
2915         }
2916         xfer->buf_fixup = pc;
2917
2918 alloc_dma_set:
2919
2920         if (parm->err) {
2921                 return;
2922         }
2923         last_obj = NULL;
2924
2925         if (usbd_transfer_setup_sub_malloc(
2926             parm, &pc, sizeof(uhci_td_t),
2927             UHCI_TD_ALIGN, ntd)) {
2928                 parm->err = USB_ERR_NOMEM;
2929                 return;
2930         }
2931         if (parm->buf) {
2932                 for (n = 0; n != ntd; n++) {
2933                         uhci_td_t *td;
2934
2935                         usbd_get_page(pc + n, 0, &page_info);
2936
2937                         td = page_info.buffer;
2938
2939                         /* init TD */
2940                         if ((parm->methods == &uhci_device_bulk_methods) ||
2941                             (parm->methods == &uhci_device_ctrl_methods) ||
2942                             (parm->methods == &uhci_device_intr_methods)) {
2943                                 /* set depth first bit */
2944                                 td->td_self = htole32(page_info.physaddr |
2945                                     UHCI_PTR_TD | UHCI_PTR_VF);
2946                         } else {
2947                                 td->td_self = htole32(page_info.physaddr |
2948                                     UHCI_PTR_TD);
2949                         }
2950
2951                         td->obj_next = last_obj;
2952                         td->page_cache = pc + n;
2953
2954                         last_obj = td;
2955
2956                         usb_pc_cpu_flush(pc + n);
2957                 }
2958         }
2959         xfer->td_start[xfer->flags_int.curr_dma_set] = last_obj;
2960
2961         last_obj = NULL;
2962
2963         if (usbd_transfer_setup_sub_malloc(
2964             parm, &pc, sizeof(uhci_qh_t),
2965             UHCI_QH_ALIGN, nqh)) {
2966                 parm->err = USB_ERR_NOMEM;
2967                 return;
2968         }
2969         if (parm->buf) {
2970                 for (n = 0; n != nqh; n++) {
2971                         uhci_qh_t *qh;
2972
2973                         usbd_get_page(pc + n, 0, &page_info);
2974
2975                         qh = page_info.buffer;
2976
2977                         /* init QH */
2978                         qh->qh_self = htole32(page_info.physaddr | UHCI_PTR_QH);
2979                         qh->obj_next = last_obj;
2980                         qh->page_cache = pc + n;
2981
2982                         last_obj = qh;
2983
2984                         usb_pc_cpu_flush(pc + n);
2985                 }
2986         }
2987         xfer->qh_start[xfer->flags_int.curr_dma_set] = last_obj;
2988
2989         if (!xfer->flags_int.curr_dma_set) {
2990                 xfer->flags_int.curr_dma_set = 1;
2991                 goto alloc_dma_set;
2992         }
2993 }
2994
2995 static void
2996 uhci_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc,
2997     struct usb_endpoint *ep)
2998 {
2999         uhci_softc_t *sc = UHCI_BUS2SC(udev->bus);
3000
3001         DPRINTFN(2, "endpoint=%p, addr=%d, endpt=%d, mode=%d (%d)\n",
3002             ep, udev->address,
3003             edesc->bEndpointAddress, udev->flags.usb_mode,
3004             sc->sc_addr);
3005
3006         if (udev->device_index != sc->sc_addr) {
3007                 switch (edesc->bmAttributes & UE_XFERTYPE) {
3008                 case UE_CONTROL:
3009                         ep->methods = &uhci_device_ctrl_methods;
3010                         break;
3011                 case UE_INTERRUPT:
3012                         ep->methods = &uhci_device_intr_methods;
3013                         break;
3014                 case UE_ISOCHRONOUS:
3015                         if (udev->speed == USB_SPEED_FULL) {
3016                                 ep->methods = &uhci_device_isoc_methods;
3017                         }
3018                         break;
3019                 case UE_BULK:
3020                         ep->methods = &uhci_device_bulk_methods;
3021                         break;
3022                 default:
3023                         /* do nothing */
3024                         break;
3025                 }
3026         }
3027 }
3028
3029 static void
3030 uhci_xfer_unsetup(struct usb_xfer *xfer)
3031 {
3032         return;
3033 }
3034
3035 static void
3036 uhci_get_dma_delay(struct usb_device *udev, uint32_t *pus)
3037 {
3038         /*
3039          * Wait until hardware has finished any possible use of the
3040          * transfer descriptor(s) and QH
3041          */
3042         *pus = (1125);                  /* microseconds */
3043 }
3044
3045 static void
3046 uhci_device_resume(struct usb_device *udev)
3047 {
3048         struct uhci_softc *sc = UHCI_BUS2SC(udev->bus);
3049         struct usb_xfer *xfer;
3050         const struct usb_pipe_methods *methods;
3051         uhci_qh_t *qh;
3052
3053         DPRINTF("\n");
3054
3055         USB_BUS_LOCK(udev->bus);
3056
3057         TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
3058                 if (xfer->xroot->udev == udev) {
3059                         methods = xfer->endpoint->methods;
3060                         qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
3061
3062                         if (methods == &uhci_device_bulk_methods) {
3063                                 UHCI_APPEND_QH(qh, sc->sc_bulk_p_last);
3064                                 uhci_add_loop(sc);
3065                                 xfer->flags_int.bandwidth_reclaimed = 1;
3066                         }
3067                         if (methods == &uhci_device_ctrl_methods) {
3068                                 if (xfer->xroot->udev->speed == USB_SPEED_LOW) {
3069                                         UHCI_APPEND_QH(qh, sc->sc_ls_ctl_p_last);
3070                                 } else {
3071                                         UHCI_APPEND_QH(qh, sc->sc_fs_ctl_p_last);
3072                                 }
3073                         }
3074                         if (methods == &uhci_device_intr_methods) {
3075                                 UHCI_APPEND_QH(qh, sc->sc_intr_p_last[xfer->qh_pos]);
3076                         }
3077                 }
3078         }
3079
3080         USB_BUS_UNLOCK(udev->bus);
3081
3082         return;
3083 }
3084
3085 static void
3086 uhci_device_suspend(struct usb_device *udev)
3087 {
3088         struct uhci_softc *sc = UHCI_BUS2SC(udev->bus);
3089         struct usb_xfer *xfer;
3090         const struct usb_pipe_methods *methods;
3091         uhci_qh_t *qh;
3092
3093         DPRINTF("\n");
3094
3095         USB_BUS_LOCK(udev->bus);
3096
3097         TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) {
3098                 if (xfer->xroot->udev == udev) {
3099                         methods = xfer->endpoint->methods;
3100                         qh = xfer->qh_start[xfer->flags_int.curr_dma_set];
3101
3102                         if (xfer->flags_int.bandwidth_reclaimed) {
3103                                 xfer->flags_int.bandwidth_reclaimed = 0;
3104                                 uhci_rem_loop(sc);
3105                         }
3106                         if (methods == &uhci_device_bulk_methods) {
3107                                 UHCI_REMOVE_QH(qh, sc->sc_bulk_p_last);
3108                         }
3109                         if (methods == &uhci_device_ctrl_methods) {
3110                                 if (xfer->xroot->udev->speed == USB_SPEED_LOW) {
3111                                         UHCI_REMOVE_QH(qh, sc->sc_ls_ctl_p_last);
3112                                 } else {
3113                                         UHCI_REMOVE_QH(qh, sc->sc_fs_ctl_p_last);
3114                                 }
3115                         }
3116                         if (methods == &uhci_device_intr_methods) {
3117                                 UHCI_REMOVE_QH(qh, sc->sc_intr_p_last[xfer->qh_pos]);
3118                         }
3119                 }
3120         }
3121
3122         USB_BUS_UNLOCK(udev->bus);
3123
3124         return;
3125 }
3126
3127 static void
3128 uhci_set_hw_power_sleep(struct usb_bus *bus, uint32_t state)
3129 {
3130         struct uhci_softc *sc = UHCI_BUS2SC(bus);
3131
3132         switch (state) {
3133         case USB_HW_POWER_SUSPEND:
3134         case USB_HW_POWER_SHUTDOWN:
3135                 uhci_suspend(sc);
3136                 break;
3137         case USB_HW_POWER_RESUME:
3138                 uhci_resume(sc);
3139                 break;
3140         default:
3141                 break;
3142         }
3143 }
3144
3145 static void
3146 uhci_set_hw_power(struct usb_bus *bus)
3147 {
3148         struct uhci_softc *sc = UHCI_BUS2SC(bus);
3149         uint32_t flags;
3150
3151         DPRINTF("\n");
3152
3153         USB_BUS_LOCK(bus);
3154
3155         flags = bus->hw_power_state;
3156
3157         /*
3158          * WARNING: Some FULL speed USB devices require periodic SOF
3159          * messages! If any USB devices are connected through the
3160          * UHCI, power save will be disabled!
3161          */
3162         if (flags & (USB_HW_POWER_CONTROL |
3163             USB_HW_POWER_NON_ROOT_HUB |
3164             USB_HW_POWER_BULK |
3165             USB_HW_POWER_INTERRUPT |
3166             USB_HW_POWER_ISOC)) {
3167                 DPRINTF("Some USB transfer is "
3168                     "active on unit %u.\n",
3169                     device_get_unit(sc->sc_bus.bdev));
3170                 uhci_restart(sc);
3171         } else {
3172                 DPRINTF("Power save on unit %u.\n",
3173                     device_get_unit(sc->sc_bus.bdev));
3174                 UHCICMD(sc, UHCI_CMD_MAXP);
3175         }
3176
3177         USB_BUS_UNLOCK(bus);
3178
3179         return;
3180 }
3181
3182 static const struct usb_bus_methods uhci_bus_methods =
3183 {
3184         .endpoint_init = uhci_ep_init,
3185         .xfer_setup = uhci_xfer_setup,
3186         .xfer_unsetup = uhci_xfer_unsetup,
3187         .get_dma_delay = uhci_get_dma_delay,
3188         .device_resume = uhci_device_resume,
3189         .device_suspend = uhci_device_suspend,
3190         .set_hw_power = uhci_set_hw_power,
3191         .set_hw_power_sleep = uhci_set_hw_power_sleep,
3192         .roothub_exec = uhci_roothub_exec,
3193         .xfer_poll = uhci_do_poll,
3194 };