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