1e5a64a152040fe2d546746e4a03b5ace3873996
[pintos-anon] / src / devices / usb_uhci.c
1 /**
2  * Universal Host Controller Interface driver
3  * TODO:
4  *      Stall timeouts
5  *      Better (any) root hub handling
6  */
7
8 #include <round.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include <kernel/bitmap.h>
12 #include "threads/pte.h"
13 #include "threads/malloc.h"
14 #include "threads/palloc.h"
15 #include "threads/synch.h"
16 #include "threads/interrupt.h"
17 #include "threads/thread.h"
18 #include "devices/pci.h"
19 #include "devices/usb.h"
20 #include "devices/timer.h"
21
22 #define UHCI_MAX_PORTS          8
23
24 #define FRAME_LIST_ENTRIES      1024
25 #define TD_ENTRIES              (4096/32)       /* number of entries allocated */
26 #define QH_ENTRIES              (4096/16)
27
28 /* uhci pci registers */
29 #define UHCI_REG_USBCMD         0x00    /* Command */
30 #define UHCI_REG_USBSTS         0x02    /* Status */
31 #define UHCI_REG_USBINTR        0x04    /* interrupt enable */
32 #define UHCI_REG_FRNUM          0x06    /* frame number */
33 #define UHCI_REG_FLBASEADD      0x08    /* frame list base address */
34 #define UHCI_REG_SOFMOD         0x0c    /* start of frame modify */
35 #define UHCI_REG_PORTSC1        0x10    /* port 1 status/control */
36 #define UHCI_REG_PORTSC2        0x12    /* port 2 status/control */
37 #define UHCI_REGSZ              0x20    /* register iospace size */
38
39 /* in PCI config space for some reason */
40 #define UHCI_REG_LEGSUP         0xC0
41
42
43 /* command register */
44 #define USB_CMD_MAX_PACKET      (1 << 7)
45 #define USB_CMD_CONFIGURE       (1 << 6)
46 #define USB_CMD_FGR             (1 << 4)        /* force global resume */
47 #define USB_CMD_EGSM            (1 << 3)        /* global suspend mode */
48 #define USB_CMD_GRESET          (1 << 2)        /* global reset */
49 #define USB_CMD_HCRESET         (1 << 1)        /* host controller reset */
50 #define USB_CMD_RS              (1 << 0)        /* run/stop */
51
52 /* status register */
53 #define USB_STATUS_HALTED       (1 << 5)
54 #define USB_STATUS_PROCESSERR   (1 << 4)
55 #define USB_STATUS_HOSTERR      (1 << 3)
56 #define USB_STATUS_RESUME       (1 << 2)
57 #define USB_STATUS_INTERR       (1 << 1)
58 #define USB_STATUS_USBINT       (1 << 0)
59
60 /* interrupt enable register */
61 #define USB_INTR_SHORT          (1 << 3)        /* enable short packets */
62 #define USB_INTR_IOC            (1 << 2)        /* interrupt on complete */
63 #define USB_INTR_RESUME         (1 << 1)        /* resume interrupt enable */
64 #define USB_INTR_TIMEOUT        (1 << 0)        /* timeout int enable */
65
66 /* port control register */
67 #define USB_PORT_SUSPEND        (1 << 12)
68 #define USB_PORT_RESET          (1 << 9)
69 #define USB_PORT_LOWSPEED       (1 << 8)
70 #define USB_PORT_RESUMED        (1 << 6)        /* resume detected */
71 #define USB_PORT_CHANGE         (1 << 3)        /* enable change */
72 #define USB_PORT_ENABLE         (1 << 2)        /* enable the port */
73 #define USB_PORT_CONNECTCHG     (1 << 1)        /* connect status changed */
74 #define USB_PORT_CONNECTSTATUS  (1 << 0)        /* device is connected */
75
76 #define ptr_to_flp(x)   (((uintptr_t)x) >> 4)
77 #define flp_to_ptr(x)   (uintptr_t)(((uintptr_t)x) << 4)
78
79 /* frame structures */
80 #pragma pack(1)
81 struct frame_list_ptr
82 {
83   uint32_t terminate:1;
84   uint32_t qh_select:1;
85   uint32_t depth_select:1;      /* only for TD */
86   uint32_t resv:1;              /* zero */
87   uint32_t flp:28;              /* frame list pointer */
88 };
89
90 struct td_token
91 {
92   uint32_t pid:8;               /* packet id */
93   uint32_t dev_addr:7;          /* device address */
94   uint32_t end_point:4;
95   uint32_t data_toggle:1;
96   uint32_t resv:1;
97   uint32_t maxlen:11;           /* maximum pkt length */
98 };
99
100 struct td_control
101 {
102   uint32_t actual_len:11;
103   uint32_t resv1:5;
104
105   /* status information */
106   uint32_t resv2:1;
107   uint32_t bitstuff:1;
108   uint32_t timeout:1;
109   uint32_t nak:1;
110   uint32_t babble:1;
111   uint32_t buffer_error:1;
112   uint32_t stalled:1;
113   uint32_t active:1;
114
115   /* config data */
116   uint32_t ioc:1;               /* issue int on complete */
117   uint32_t ios:1;               /* isochronous select */
118   uint32_t ls:1;                /* low speed device */
119   uint32_t error_limit:2;       /* errors before interrupt */
120   uint32_t spd:1;               /* short packet detect */
121   uint32_t resv3:2;
122 };
123
124 #define TD_FL_ASYNC     1
125 #define TD_FL_USED      0x80000000
126
127 struct tx_descriptor
128 {
129   struct frame_list_ptr flp;
130   struct td_control control;
131   struct td_token token;
132   uint32_t buf_ptr;
133
134
135   struct frame_list_ptr *head;  /* for fast removal */
136   uint32_t flags;
137 };
138
139 struct queue_head
140 {
141   struct frame_list_ptr qhlp;   /* queue head link pointer */
142   struct frame_list_ptr qelp;   /* queue elem link pointer */
143 };
144 #pragma pack()
145
146 struct uhci_info
147 {
148   struct pci_dev *dev;
149   struct pci_io *io;            /* pci io space */
150   struct lock lock;
151   struct frame_list_ptr *frame_list;    /* page aligned frame list */
152
153   struct tx_descriptor *td_pool;
154   struct bitmap *td_used;
155   struct queue_head *qh_pool;
156   struct bitmap *qh_used;
157
158   uint8_t num_ports;
159   uint8_t attached_ports;
160
161   int timeouts;                 /* number of timeouts */
162
163   struct semaphore td_sem;
164   struct list devices;          /* devices on host */
165   struct list waiting;          /* threads waiting */
166 };
167
168 struct usb_wait
169 {
170   struct tx_descriptor *td;
171   struct uhci_dev_info *ud;
172   struct semaphore sem;
173   struct list_elem peers;
174 };
175
176 struct uhci_dev_info
177 {
178   struct uhci_info *ui;         /* owner */
179   bool low_speed;               /* whether device is low speed */
180   int dev_addr;                 /* device address */
181   int errors;                   /* aggregate errors */
182   struct list_elem peers;       /* next dev on host */
183   struct lock lock;
184   struct queue_head *qh;
185 };
186
187 struct uhci_eop_info
188 {
189   struct uhci_dev_info *ud;
190   int eop;
191   int maxpkt;                   /* max packet size */
192   int toggle;                   /* data toggle bit for bulk transfers */
193 };
194
195 #define uhci_lock(x)    lock_acquire(&(x)->lock)
196 #define uhci_unlock(x)  lock_release(&(x)->lock)
197 #define dev_lock(x)     lock_acquire(&(x)->lock)
198 #define dev_unlock(x)   lock_release(&(x)->lock)
199
200
201 static int token_to_pid (int token);
202
203 static int uhci_tx_pkt (host_eop_info eop, int token, void *pkt,
204                         int min_sz, int max_sz, int *in_sz, bool wait);
205
206 static int uhci_detect_change (host_info);
207
208
209 static int uhci_tx_pkt_now (struct uhci_eop_info *ue, int token, void *pkt,
210                             int sz);
211 static int uhci_tx_pkt_wait (struct uhci_eop_info *ue, int token, void *pkt,
212                              int max_sz, int *in_sz);
213 static int uhci_tx_pkt_bulk (struct uhci_eop_info *ue, int token, void *buf,
214                              int sz, int *tx);
215
216
217 static int uhci_process_completed (struct uhci_info *ui);
218
219 static struct tx_descriptor *uhci_acquire_td (struct uhci_info *);
220 static void uhci_release_td (struct uhci_info *, struct tx_descriptor *);
221 static void uhci_remove_qh (struct uhci_info *ui, struct queue_head *qh);
222
223
224 static void qh_free (struct uhci_info *ui, struct queue_head *qh);
225 static struct queue_head *qh_alloc (struct uhci_info *ui);
226
227 static struct uhci_info *uhci_create_info (struct pci_io *io);
228 static void uhci_destroy_info (struct uhci_info *ui);
229 static host_eop_info uhci_create_eop (host_dev_info hd, int eop, int maxpkt);
230 static void uhci_remove_eop (host_eop_info hei);
231 static host_dev_info uhci_create_chan (host_info hi, int dev_addr, int ver);
232 static void uhci_destroy_chan (host_dev_info);
233 static void uhci_modify_chan (host_dev_info, int dev_addr, int ver);
234
235 static struct tx_descriptor *td_from_pool (struct uhci_info *ui, int idx);
236
237 static int check_and_flip_change (struct uhci_info *ui, int reg);
238 static void uhci_stop (struct uhci_info *ui);
239 static void uhci_run (struct uhci_info *ui);
240 static void uhci_stop_unlocked (struct uhci_info *ui);
241 static void uhci_run_unlocked (struct uhci_info *ui);
242 #define uhci_is_stopped(x)      (pci_reg_read16((x)->io, UHCI_REG_USBSTS) \
243                                 & USB_STATUS_HALTED)
244 #define uhci_port_enabled(x, y) (pci_reg_read16((x)->io, (y)) & USB_PORT_ENABLE)
245 static void uhci_add_td_to_qh (struct queue_head *qh,
246                                struct tx_descriptor *td);
247 static void uhci_remove_error_td (struct tx_descriptor *td);
248 static void uhci_setup_td (struct tx_descriptor *td, int dev_addr, int token,
249                            int eop, void *pkt, int sz, int toggle, bool ls);
250 static int uhci_enable_port (struct uhci_info *ui, int port);
251 static void uhci_irq (void *uhci_data);
252 static void uhci_detect_ports (struct uhci_info *ui);
253
254 static int uhci_remove_stalled (struct uhci_info *ui);
255 static void uhci_stall_watchdog (struct uhci_info *ui);
256
257 static void dump_all_qh (struct uhci_info *ui);
258 static void dump_qh (struct queue_head *qh);
259
260 static void dump_regs (struct uhci_info *ui);
261
262 void uhci_init (void);
263
264
265 static struct usb_host uhci_host = {
266   .name = "UHCI",
267   .tx_pkt = uhci_tx_pkt,
268   .detect_change = uhci_detect_change,
269   .create_dev_channel = uhci_create_chan,
270   .remove_dev_channel = uhci_destroy_chan,
271   .modify_dev_channel = uhci_modify_chan,
272   .create_eop = uhci_create_eop,
273   .remove_eop = uhci_remove_eop
274 };
275
276 void
277 uhci_init (void)
278 {
279   struct pci_dev *pd;
280   int dev_num;
281
282   dev_num = 0;
283   while ((pd = pci_get_dev_by_class (PCI_MAJOR_SERIALBUS, PCI_MINOR_USB,
284                                      PCI_USB_IFACE_UHCI, dev_num)) != NULL)
285     {
286       struct pci_io *io;
287       struct uhci_info *ui;
288       uint8_t sof;
289       int i;
290
291       dev_num++;
292
293       /* find IO space */
294       io = NULL;
295       while ((io = pci_io_enum (pd, io)) != NULL)
296         {
297           if (pci_io_size (io) == UHCI_REGSZ)
298             break;
299         }
300
301       /* not found, next PCI */
302       if (io == NULL)
303         continue;
304
305       ui = uhci_create_info (io);
306       ui->dev = pd;
307
308       sof = pci_reg_read8 (ui->io, UHCI_REG_SOFMOD);
309       uhci_detect_ports (ui);
310
311       /* reset devices */
312       pci_reg_write16 (ui->io, UHCI_REG_USBCMD, USB_CMD_GRESET);
313       timer_msleep (50);
314       pci_reg_write16 (ui->io, UHCI_REG_USBCMD, 0);
315       timer_msleep (1);
316
317       /* reset controller */
318       pci_reg_write16 (ui->io, UHCI_REG_USBCMD, USB_CMD_HCRESET);
319       timer_msleep (1);
320       if (pci_reg_read16 (ui->io, UHCI_REG_USBCMD) & USB_CMD_HCRESET)
321         {
322           printf ("UHCI: Reset timed out\n");
323           uhci_destroy_info (ui);
324           continue;
325         }
326       pci_reg_write16 (ui->io, UHCI_REG_USBINTR, 0);
327       pci_reg_write16 (ui->io, UHCI_REG_USBCMD, 0);
328
329       for (i = 0; i < ui->num_ports; i++)
330         pci_reg_write16 (ui->io, UHCI_REG_PORTSC1 + i * 2, 0);
331
332       timer_msleep (100);
333       printf ("UHCI: Enabling %d root ports\n", ui->num_ports);
334       ui->attached_ports = 0;
335       for (i = 0; i < ui->num_ports; i++)
336         ui->attached_ports += uhci_enable_port (ui, i);
337
338       pci_reg_write8 (ui->io, UHCI_REG_SOFMOD, sof);
339       pci_reg_write16 (ui->io, UHCI_REG_FRNUM, 0);
340       pci_reg_write32 (ui->io, UHCI_REG_FLBASEADD, vtop (ui->frame_list));
341       pci_reg_write16 (ui->io, UHCI_REG_USBINTR,
342                        USB_INTR_SHORT | USB_INTR_IOC |
343                        USB_INTR_TIMEOUT | USB_INTR_RESUME);
344
345       /* deactivate SMM junk, only enable IRQ */
346       pci_write_config16 (ui->dev, UHCI_REG_LEGSUP, 0x2000);
347
348       uhci_lock (ui);
349       uhci_run (ui);
350       uhci_unlock (ui);
351
352       pci_register_irq (pd, uhci_irq, ui);
353
354       usb_register_host (&uhci_host, ui);
355     }
356 }
357
358 #define UHCI_PORT_TIMEOUT       1000
359 static int
360 uhci_enable_port (struct uhci_info *ui, int port)
361 {
362   uint16_t status;
363   int count;
364
365   /* individual ports must be reset for QEMU to go into USB_STATE_DEFAULT */
366   pci_reg_write16 (ui->io, UHCI_REG_PORTSC1 + port * 2, USB_PORT_RESET);
367   timer_msleep (50);
368
369   /* ACK disconnect from reset so we can see if port is connected */
370   pci_reg_write16 (ui->io, UHCI_REG_PORTSC1 + port * 2,
371                    USB_PORT_ENABLE | USB_PORT_CONNECTCHG);
372   timer_msleep (10);
373   status = pci_reg_read16 (ui->io, UHCI_REG_PORTSC1 + port * 2);
374   if (!(status & USB_PORT_CONNECTSTATUS))
375     {
376       return 0;
377     }
378
379   /* ACK CONNECTCHG status so port can be enabled */
380   pci_reg_write16 (ui->io, UHCI_REG_PORTSC1 + port * 2,
381                    USB_PORT_ENABLE | USB_PORT_CONNECTCHG);
382   for (count = 0; count < UHCI_PORT_TIMEOUT; count++)
383     {
384       if (uhci_port_enabled (ui, UHCI_REG_PORTSC1 + port * 2))
385         {
386           pci_reg_write16 (ui->io, UHCI_REG_PORTSC1 + port * 2,
387                            USB_PORT_ENABLE | USB_PORT_CONNECTCHG);
388           return 1;
389         }
390     }
391
392   printf ("UHCI: Port %d enable timed out\n", port);
393   dump_regs (ui);
394
395   return 0;
396 }
397
398
399 static void
400 dump_regs (struct uhci_info *ui)
401 {
402   int regs[] = { 0, 2, 4, 6, 8, 0xc, 0x10, 0x12 };
403   int sz[] = { 2, 2, 2, 2, 4, 2, 2, 2 };
404   char *name[] =
405     { "cmd", "sts", "intr", "frnum", "base", "sofmod", "portsc1", "portsc2" };
406   int i;
407   printf ("UHCI registers:\n");
408   for (i = 0; i < 8; i++)
409     {
410       printf ("%s: %x\n", name[i], (sz[i] == 2) ?
411               pci_reg_read16 (ui->io, regs[i]) :
412               pci_reg_read32 (ui->io, regs[i]));
413
414     }
415 }
416
417
418 static void
419 uhci_destroy_info (struct uhci_info *ui)
420 {
421   palloc_free_page (ui->frame_list);
422   palloc_free_page (ui->td_pool);
423   palloc_free_page (ui->qh_pool);
424   bitmap_destroy (ui->qh_used);
425   bitmap_destroy (ui->td_used);
426   free (ui);
427 }
428
429 static struct uhci_info *
430 uhci_create_info (struct pci_io *io)
431 {
432   struct uhci_info *ui;
433   int i;
434
435   ui = malloc (sizeof (struct uhci_info));
436
437   ui->io = io;
438   lock_init (&ui->lock);
439
440   /* create an empty schedule */
441   ui->frame_list = palloc_get_page (PAL_ASSERT | PAL_NOCACHE);
442   memset (ui->frame_list, 0, PGSIZE);
443   for (i = 0; i < FRAME_LIST_ENTRIES; i++)
444     ui->frame_list[i].terminate = 1;
445
446   /* permit 3 timeouts */
447   ui->timeouts = 3;
448 //  thread_create ("uhci watchdog", PRI_MIN,
449 //               (thread_func *) uhci_stall_watchdog, ui);
450   ui->td_pool = palloc_get_page (PAL_ASSERT | PAL_NOCACHE);
451   ui->td_used = bitmap_create (TD_ENTRIES);
452   ui->qh_pool = palloc_get_page (PAL_ASSERT | PAL_NOCACHE);
453   ui->qh_used = bitmap_create (QH_ENTRIES);
454   sema_init (&ui->td_sem, TD_ENTRIES);
455
456   list_init (&ui->devices);
457   list_init (&ui->waiting);
458
459   return ui;
460 }
461
462
463 static int
464 uhci_tx_pkt (host_eop_info hei, int token, void *pkt, int min_sz,
465              int max_sz, int *in_sz, bool wait)
466 {
467   struct uhci_eop_info *ue;
468   struct uhci_dev_info *ud;
469
470   ASSERT (min_sz <= max_sz);
471
472   /* can't have page overlap */
473   if (pkt != NULL)
474     {
475       ASSERT (max_sz > 0);
476       ASSERT (pg_no (pkt + max_sz - 1) == pg_no (pkt));
477     }
478
479   ue = hei;
480   ud = ue->ud;
481
482   /* don't bother if ports are down */
483   if (ud->ui->attached_ports == 0)
484     {
485       return USB_HOST_ERR_NODEV;
486     }
487
488   /* setup token acts to synchronize data toggle */
489   if (token == USB_TOKEN_SETUP)
490     ue->toggle = 0;
491
492   if (min_sz != 0)
493     {
494       return uhci_tx_pkt_bulk (ue, token, pkt, max_sz, in_sz);
495     }
496   else
497     {
498       if (wait == false)
499         {
500           if (in_sz != NULL)
501             *in_sz = max_sz;
502           return uhci_tx_pkt_now (ue, token, pkt, max_sz);
503         }
504       else
505         {
506           return uhci_tx_pkt_wait (ue, token, pkt, max_sz, in_sz);
507         }
508     }
509
510   return 0;
511 }
512
513 static int
514 uhci_tx_pkt_bulk (struct uhci_eop_info *ue, int token, void *buf,
515                   int sz, int *tx)
516 {
517   /* XXX this can be made to use async packets */
518   int bytes = 0;
519   int txed = 0;
520
521   /* send data in max_pkt sized chunks */
522   while (bytes < sz)
523     {
524       int to_tx, pkt_txed;
525       int left;
526       int err;
527       bool wait_on_pkt;
528
529       left = sz - bytes;
530       to_tx = (left > ue->maxpkt) ? ue->maxpkt : left;
531       wait_on_pkt = (left <= to_tx) ? true : false;
532
533       pkt_txed = 0;
534       err = uhci_tx_pkt (ue, token, buf + bytes, 0, to_tx, &pkt_txed, 
535                          wait_on_pkt);
536       if (err)
537         {
538           if (tx != NULL)
539             *tx = txed;
540           return err;
541         }
542       txed += pkt_txed;
543       bytes += pkt_txed;
544     }
545
546   if (tx != NULL)
547     *tx = txed;
548
549   return USB_HOST_ERR_NONE;
550 }
551
552 static int
553 token_to_pid (int token)
554 {
555   switch (token)
556     {
557     case USB_TOKEN_SETUP:
558       return USB_PID_SETUP;
559     case USB_TOKEN_IN:
560       return USB_PID_IN;
561     case USB_TOKEN_OUT:
562       return USB_PID_OUT;
563     default:
564       PANIC ("Unknown USB token\n");
565     }
566 }
567
568 static void
569 uhci_setup_td (struct tx_descriptor *td, int dev_addr, int token,
570                int eop, void *pkt, int sz, int toggle, bool ls)
571 {
572   td->buf_ptr = (sz == 0) ? 0 : vtop (pkt);
573
574   td->token.pid = token_to_pid (token);
575   td->token.dev_addr = dev_addr;
576   td->token.end_point = eop;
577   td->token.data_toggle = toggle;
578   td->token.maxlen = sz - 1;
579 //  td->control.ls = ls;
580
581   td->control.actual_len = 0;
582   td->control.active = 1;
583   td->flp.qh_select = 0;
584   td->flp.depth_select = 0;
585
586   /* kill packet if too many errors */
587   td->control.error_limit = 3;
588 }
589
590 static int
591 uhci_tx_pkt_now (struct uhci_eop_info *ue, int token, void *pkt, int sz)
592 {
593   struct tx_descriptor *td;
594   struct uhci_dev_info *ud;
595
596   ud = ue->ud;
597
598   uhci_lock (ud->ui);
599
600   td = uhci_acquire_td (ud->ui);
601   memset (td, 0, sizeof (struct tx_descriptor));
602   uhci_setup_td (td, ud->dev_addr, token, ue->eop, pkt, sz, ue->toggle,
603                  ud->low_speed);
604   td->control.ioc = 1;
605
606   uhci_stop (ud->ui);
607
608   uhci_add_td_to_qh (ud->qh, td);
609   td->flags = TD_FL_ASYNC | TD_FL_USED;
610
611   uhci_run (ud->ui);
612   uhci_unlock (ud->ui);
613
614   ue->toggle ^= 1;
615   return USB_HOST_ERR_NONE;
616 }
617
618 static int
619 uhci_tx_pkt_wait (struct uhci_eop_info *ue, int token, void *pkt,
620                   int max_sz, int *in_sz)
621 {
622   enum intr_level old_lvl;
623   struct tx_descriptor *td;
624   struct usb_wait w;
625   int err;
626   struct uhci_dev_info *ud;
627
628   ud = ue->ud;
629
630   uhci_lock (ud->ui);
631
632   td = uhci_acquire_td (ud->ui);
633   memset (td, 0, sizeof (struct tx_descriptor));
634
635   uhci_setup_td (td, ud->dev_addr, token, ue->eop, pkt, max_sz, ue->toggle,
636                  ud->low_speed);
637   td->control.ioc = 1;
638
639   w.td = td;
640   w.ud = ud;
641   sema_init (&w.sem, 0);
642
643   uhci_stop (ud->ui);
644
645   /* put into device's queue and add to waiting packet list */
646   uhci_add_td_to_qh (ud->qh, td);
647   td->flags = TD_FL_USED;
648
649   list_push_back (&ud->ui->waiting, &w.peers);
650
651   /* reactivate controller and wait */
652   old_lvl = intr_disable ();
653   uhci_run (ud->ui);
654   uhci_unlock (ud->ui);
655   sema_down (&w.sem);
656   intr_set_level (old_lvl);
657
658   if (in_sz != NULL)
659     {
660       if (w.td->control.actual_len == 0x7ff)
661         *in_sz = 0;
662       else
663         *in_sz = w.td->control.actual_len + 1;
664     }
665
666   if (w.td->control.bitstuff)
667     err = USB_HOST_ERR_BITSTUFF;
668   else if (w.td->control.timeout)
669     err = USB_HOST_ERR_TIMEOUT;
670   else if (w.td->control.nak)
671     err = USB_HOST_ERR_NAK;
672   else if (w.td->control.babble)
673     err = USB_HOST_ERR_BABBLE;
674   else if (w.td->control.buffer_error)
675     err = USB_HOST_ERR_BUFFER;
676   else if (w.td->control.stalled)
677     err = USB_HOST_ERR_STALL;
678   else
679     {
680       err = USB_HOST_ERR_NONE;
681       ue->toggle ^= 1;
682     }
683
684   uhci_release_td (ud->ui, td);
685
686   return err;
687 }
688
689 static void
690 uhci_add_td_to_qh (struct queue_head *qh, struct tx_descriptor *td)
691 {
692   struct frame_list_ptr *fp;
693
694   ASSERT (td != NULL);
695
696   td->head = &qh->qelp;
697   if (qh->qelp.terminate == 1)
698     {
699       /* queue is empty */
700       td->flp.terminate = 1;
701       barrier ();
702       td->flp.flp = 0;
703       qh->qelp.flp = ptr_to_flp (vtop (td));
704       qh->qelp.terminate = 0;
705     }
706   else
707     {
708       /* find the last element in the queue */
709       fp = ptov (flp_to_ptr (qh->qelp.flp));
710       ASSERT (qh->qelp.terminate == 0);
711       while (!fp->terminate)
712         {
713           fp = ptov (flp_to_ptr (fp->flp));
714         }
715
716       /* set TD to terminated ptr */
717       td->flp = *fp;
718
719       fp->qh_select = 0;
720       fp->depth_select = 0;
721       fp->flp = ptr_to_flp (vtop (td));
722       barrier ();
723       fp->terminate = 0;
724     }
725 }
726
727 static void
728 uhci_irq (void *uhci_data)
729 {
730   struct uhci_info *ui;
731   uint16_t status;
732
733   ui = uhci_data;
734   status = pci_reg_read16 (ui->io, UHCI_REG_USBSTS);
735   if (status & USB_STATUS_PROCESSERR)
736     {
737       dump_all_qh (ui);
738       dump_regs (ui);
739       PANIC ("UHCI: Malformed schedule");
740     }
741   else if (status & USB_STATUS_HOSTERR)
742     {
743       dump_all_qh (ui);
744       dump_regs (ui);
745       PANIC ("UHCI: Host system error");
746     }
747   else if (status & USB_STATUS_INTERR)
748     {
749       /* errors */
750       pci_reg_write16 (ui->io, UHCI_REG_USBSTS, USB_STATUS_INTERR);
751     }
752
753   if (status & USB_STATUS_USBINT)
754     {
755       /* turn off interrupt */
756       uhci_stop_unlocked (ui);
757       pci_reg_write16 (ui->io, UHCI_REG_USBSTS, USB_STATUS_USBINT);
758       uhci_process_completed (ui);
759       uhci_run_unlocked (ui);
760     }
761 }
762
763 static int
764 uhci_process_completed (struct uhci_info *ui)
765 {
766   struct list_elem *li;
767   int completed = 0;
768   size_t start = 0;
769
770   li = list_begin (&ui->waiting);
771   while (li != list_end (&ui->waiting))
772     {
773       struct usb_wait *uw;
774       struct list_elem *next;
775
776       next = list_next (li);
777       uw = list_entry (li, struct usb_wait, peers);
778
779       if (!uw->td->control.active)
780         {
781           list_remove (li);
782           if (uw->td->control.error_limit == 0 || uw->td->control.stalled)
783             {
784               uhci_remove_error_td (uw->td);
785             }
786           uw->td->flags = 0;
787           sema_up (&uw->sem);
788           completed++;
789         }
790       li = next;
791     }
792
793   /* must be a completed async TD.. */
794   /* is this too time consuming? I hope not */
795   if (completed != 0)
796     return completed;
797
798   while (start < TD_ENTRIES)
799     {
800       struct tx_descriptor *td;
801
802       start = bitmap_scan (ui->td_used, start, 1, true);
803       if (start == BITMAP_ERROR)
804         break;
805
806       td = td_from_pool (ui, start);
807
808       if (!td->control.active && (td->flags & TD_FL_ASYNC) &&
809           (td->flags & TD_FL_USED))
810         {
811           if (td->control.error_limit == 0 || td->control.stalled)
812             {
813               uhci_remove_error_td (td);
814             }
815           uhci_release_td (ui, td);
816           completed++;
817         }
818       start++;
819     }
820
821   return completed;
822 }
823
824 static void
825 uhci_remove_error_td (struct tx_descriptor *td)
826 {
827   struct frame_list_ptr *fp;
828   uint32_t td_flp;
829
830   ASSERT (td->head != NULL);
831
832   fp = td->head;
833   td_flp = ptr_to_flp (vtop (td));
834   while (fp->flp != td_flp)
835     {
836       ASSERT (fp->terminate == 0);
837       fp = ptov (flp_to_ptr (fp->flp));
838     }
839   *fp = td->flp;
840 }
841
842 static int
843 uhci_detect_change (host_info hi)
844 {
845   struct uhci_info *ui;
846   int change;
847   int i;
848
849   ui = hi;
850   change = 0;
851   uhci_lock (ui);
852   for (i = 0; i < ui->num_ports; i++)
853     {
854       change = check_and_flip_change (ui, i);
855       if (change != 0)
856         break;
857     }
858   uhci_unlock (ui);
859
860   return change;
861 }
862
863 static int
864 check_and_flip_change (struct uhci_info *ui, int port)
865 {
866   int val;
867   int reg;
868
869   reg = UHCI_REG_PORTSC1 + port * 2;
870   val = pci_reg_read16 (ui->io, reg);
871   if (val & USB_PORT_CHANGE)
872     {
873       pci_reg_write16 (ui->io, reg, val & ~(USB_PORT_CHANGE));
874       return 1;
875     }
876
877   return 0;
878 }
879
880 static host_dev_info
881 uhci_create_chan (host_info hi, int dev_addr, int ver)
882 {
883   struct uhci_info *ui;
884   struct uhci_dev_info *ud;
885   int i;
886
887   ASSERT (dev_addr <= 127 && dev_addr >= 0);
888
889   ui = hi;
890
891   ud = malloc (sizeof (struct uhci_dev_info));
892   ud->dev_addr = dev_addr;
893   ud->low_speed = (ver == USB_VERSION_1_0) ? true : false;
894
895   ud->errors = 0;
896   ud->ui = ui;
897   lock_init (&ud->lock);
898
899   uhci_lock (ui);
900
901   ud->qh = qh_alloc (ud->ui);
902
903   /* queue data */
904   memset (ud->qh, 0, sizeof (*ud->qh));
905   ud->qh->qelp.terminate = 1;
906   barrier ();
907   ud->qh->qelp.flp = 0;
908   ud->qh->qelp.qh_select = 0;
909   ud->qh->qhlp.qh_select = 1;
910
911   uhci_stop (ui);
912
913   /* add to queues in frame list */
914   ud->qh->qhlp.flp = ui->frame_list[0].flp;
915   ud->qh->qhlp.terminate = ui->frame_list[0].terminate;
916   for (i = 0; i < FRAME_LIST_ENTRIES; i++)
917     {
918       ui->frame_list[i].flp = ptr_to_flp (vtop (ud->qh));
919       ui->frame_list[i].qh_select = 1;
920       ui->frame_list[i].terminate = 0;
921     }
922
923   /* add to device list */
924   list_push_back (&ui->devices, &ud->peers);
925
926   uhci_run (ui);
927   uhci_unlock (ui);
928
929   return ud;
930 }
931
932 static void
933 uhci_destroy_chan (host_dev_info hd)
934 {
935   struct uhci_dev_info *ud;
936   struct list_elem *li;
937
938   ud = hd;
939   uhci_lock (ud->ui);
940
941   uhci_stop (ud->ui);
942
943   uhci_remove_qh (ud->ui, ud->qh);
944
945   /* wake up all waiting */
946   li = list_begin (&ud->ui->waiting);
947   while (li != list_end (&ud->ui->waiting))
948     {
949       struct usb_wait *w;
950       w = list_entry (li, struct usb_wait, peers);
951       if (w->ud == ud)
952         {
953           sema_up (&w->sem);
954           list_remove (li);
955         }
956       li = list_next (li);
957     }
958
959   list_remove (&ud->peers);
960
961   uhci_run (ud->ui);
962
963   qh_free (ud->ui, ud->qh);
964
965   uhci_unlock (ud->ui);
966
967   free (ud);
968 }
969
970 /**
971  * Remove a queue from the UHCI schedule
972  */
973 static void
974 uhci_remove_qh (struct uhci_info *ui, struct queue_head *qh)
975 {
976   uintptr_t qh_flp;
977
978   ASSERT (lock_held_by_current_thread (&ui->lock));
979   ASSERT (uhci_is_stopped (ui));
980   ASSERT (qh != NULL);
981
982   qh_flp = ptr_to_flp (vtop (qh));
983   /* remove from host queue */
984   if (ui->frame_list[0].flp == qh_flp)
985     {
986       int i;
987       /* up top */
988       for (i = 0; i < FRAME_LIST_ENTRIES; i++)
989         {
990           ui->frame_list[i] = qh->qhlp;
991         }
992     }
993   else
994     {
995       /* in the middle */
996       struct frame_list_ptr *fp;
997       struct frame_list_ptr *prev;
998
999       fp = ptov (flp_to_ptr (ui->frame_list[0].flp));
1000       ASSERT (!fp->terminate);
1001       do
1002         {
1003           prev = fp;
1004           fp = ptov (flp_to_ptr (fp->flp));
1005         }
1006       while (!fp->terminate && fp->flp != qh_flp);
1007       *prev = qh->qhlp;
1008     }
1009 }
1010
1011 /**
1012  * Put UHCI into stop state
1013  * Wait until status register reflects setting
1014  */
1015 static void
1016 uhci_stop (struct uhci_info *ui)
1017 {
1018   ASSERT (intr_get_level () != INTR_OFF);
1019   ASSERT (lock_held_by_current_thread (&ui->lock));
1020
1021   uhci_stop_unlocked (ui);
1022 }
1023
1024 static void
1025 uhci_stop_unlocked (struct uhci_info *ui)
1026 {
1027   uint16_t cmd;
1028   int i;
1029
1030   cmd = pci_reg_read16 (ui->io, UHCI_REG_USBCMD);
1031   cmd = cmd & ~USB_CMD_RS;
1032
1033   pci_reg_write16 (ui->io, UHCI_REG_USBCMD, cmd);
1034
1035   /* wait for execution schedule to finish up */
1036   for (i = 0; i < 1000; i++)
1037     {
1038       if (uhci_is_stopped (ui))
1039         return;
1040     }
1041
1042   PANIC ("UHCI: Controller did not halt\n");
1043
1044 }
1045
1046 static void
1047 uhci_run_unlocked (struct uhci_info *ui)
1048 {
1049   uint16_t cmd;
1050   cmd = pci_reg_read16 (ui->io, UHCI_REG_USBCMD);
1051   cmd = cmd | USB_CMD_RS | USB_CMD_MAX_PACKET;
1052   pci_reg_write16 (ui->io, UHCI_REG_USBCMD, cmd);
1053 }
1054
1055 /**
1056  * Put UHCI into 'Run' State 
1057  */
1058 static void
1059 uhci_run (struct uhci_info *ui)
1060 {
1061   ASSERT (lock_held_by_current_thread (&ui->lock));
1062   uhci_run_unlocked (ui);
1063 }
1064
1065 static struct tx_descriptor *
1066 uhci_acquire_td (struct uhci_info *ui)
1067 {
1068   size_t td_idx;
1069   struct tx_descriptor *td;
1070
1071   ASSERT (lock_held_by_current_thread (&ui->lock));
1072   ASSERT (!uhci_is_stopped (ui));
1073
1074   sema_down (&ui->td_sem);
1075   td_idx = bitmap_scan_and_flip (ui->td_used, 0, 1, false);
1076   ASSERT (td_idx != BITMAP_ERROR);
1077   td = td_from_pool (ui, td_idx);
1078
1079   return td;
1080 }
1081
1082 static void
1083 uhci_modify_chan (host_dev_info hd, int dev_addr, int ver)
1084 {
1085   struct uhci_dev_info *ud;
1086
1087   ud = hd;
1088   ud->dev_addr = dev_addr;
1089   ud->low_speed = (ver == USB_VERSION_1_0) ? true : false;
1090 }
1091
1092 static void
1093 dump_all_qh (struct uhci_info *ui)
1094 {
1095   struct list_elem *li;
1096
1097   printf ("schedule: %x...", vtop (ui->frame_list));
1098   printf ("%x", *((uint32_t *) ui->frame_list));
1099   li = list_begin (&ui->devices);
1100   while (li != list_end (&ui->devices))
1101     {
1102       struct uhci_dev_info *ud;
1103       ud = list_entry (li, struct uhci_dev_info, peers);
1104       dump_qh (ud->qh);
1105       li = list_next (li);
1106     }
1107 }
1108
1109 static void
1110 dump_qh (struct queue_head *qh)
1111 {
1112   struct frame_list_ptr *fp;
1113   printf ("qh: %p %x\n", qh, vtop (qh));
1114   fp = &qh->qelp;
1115   while (!fp->terminate)
1116     {
1117       printf ("%x %x\n", *((uint32_t *) fp), *(uint32_t *) (fp + 1));
1118       fp = ptov (flp_to_ptr (fp->flp));
1119     }
1120   printf ("%x %x\n\n", *(uint32_t *) fp, *(uint32_t *) (fp + 1));
1121 }
1122
1123 static struct tx_descriptor *
1124 td_from_pool (struct uhci_info *ui, int idx)
1125 {
1126   ASSERT (idx >= 0 && idx < TD_ENTRIES);
1127   return (((void *) ui->td_pool) + idx * 32);
1128 }
1129
1130 static void
1131 uhci_detect_ports (struct uhci_info *ui)
1132 {
1133   int i;
1134   ui->num_ports = 0;
1135   for (i = 0; i < UHCI_MAX_PORTS; i++)
1136     {
1137       uint16_t status;
1138       status = pci_reg_read16 (ui->io, UHCI_REG_PORTSC1 + i * 2);
1139       if (!(status & 0x0080) || status == 0xffff)
1140         return;
1141       ui->num_ports++;
1142     }
1143 }
1144
1145 static void
1146 uhci_stall_watchdog (struct uhci_info *ui)
1147 {
1148   while (1)
1149     {
1150       int rmved;
1151       timer_msleep (1000);
1152       printf ("watchdog\n");
1153       uhci_lock (ui);
1154       uhci_stop (ui);
1155       rmved = uhci_remove_stalled (ui);
1156       if (rmved > 0)
1157         printf ("removed stalled packet in watchdog\n");
1158       uhci_run (ui);
1159       uhci_unlock (ui);
1160     }
1161 }
1162
1163 static int
1164 uhci_remove_stalled (struct uhci_info *ui)
1165 {
1166   struct list_elem *li;
1167   int rmved;
1168
1169   rmved = 0;
1170   li = list_begin (&ui->waiting);
1171
1172   intr_disable ();
1173
1174   while (li != list_end (&ui->waiting))
1175     {
1176       struct usb_wait *uw;
1177       struct list_elem *next;
1178       uint32_t ctrl;
1179
1180       next = list_next (li);
1181       uw = list_entry (li, struct usb_wait, peers);
1182
1183       if ((!uw->td->control.active && uw->td->control.stalled) ||
1184           (uw->td->control.nak))
1185         {
1186           memcpy (&ctrl, &uw->td->control, 4);
1187           printf ("CTRL: %x\n", ctrl);
1188           list_remove (li);
1189           uhci_remove_error_td (uw->td);
1190           sema_up (&uw->sem);
1191           rmved++;
1192         }
1193       li = next;
1194     }
1195
1196   intr_enable ();
1197
1198   return rmved;
1199 }
1200
1201 static void
1202 uhci_release_td (struct uhci_info *ui, struct tx_descriptor *td)
1203 {
1204   int ofs = (uintptr_t) td - (uintptr_t) ui->td_pool;
1205   int entry = ofs / 32;
1206
1207   ASSERT (entry < TD_ENTRIES);
1208
1209   td->flags = 0;
1210   bitmap_reset (ui->td_used, entry);
1211   sema_up (&ui->td_sem);
1212 }
1213
1214 static host_eop_info
1215 uhci_create_eop (host_dev_info hd, int eop, int maxpkt)
1216 {
1217   struct uhci_dev_info *ud;
1218   struct uhci_eop_info *e;
1219
1220   ud = hd;
1221
1222   e = malloc (sizeof (struct uhci_eop_info));
1223   e->eop = eop;
1224   e->ud = ud;
1225   e->maxpkt = maxpkt;
1226   e->toggle = 0;
1227
1228   return e;
1229 }
1230
1231 static void
1232 uhci_remove_eop (host_eop_info hei)
1233 {
1234   free (hei);
1235 }
1236
1237 static struct queue_head *
1238 qh_alloc (struct uhci_info *ui)
1239 {
1240   size_t qh_idx;
1241   struct queue_head *qh;
1242
1243   ASSERT (lock_held_by_current_thread (&ui->lock));
1244
1245   qh_idx = bitmap_scan_and_flip (ui->qh_used, 0, 1, false);
1246   if (qh_idx == BITMAP_ERROR)
1247     {
1248       PANIC ("UHCI: Too many queue heads in use-- runaway USB stack?\n");
1249     }
1250   qh = (void *) (((intptr_t) ui->qh_pool) + qh_idx * 16);
1251
1252   return qh;
1253 }
1254
1255 static void
1256 qh_free (struct uhci_info *ui, struct queue_head *qh)
1257 {
1258   size_t entry;
1259   ASSERT (lock_held_by_current_thread (&ui->lock));
1260
1261   entry = ((intptr_t) qh - (intptr_t) ui->qh_pool) / 16;
1262   bitmap_reset (ui->qh_used, entry);
1263 }