Fix the keyboard lockup problem. There were two big clues: The first was a
[dragonfly.git] / sys / dev / misc / kbd / kbd.c
1 /*-
2  * Copyright (c) 1999 Kazutaka YOKOTA <yokota@zodiac.mech.utsunomiya-u.ac.jp>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer as
10  *    the first lines of this file unmodified.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/dev/kbd/kbd.c,v 1.17.2.2 2001/07/30 16:46:43 yokota Exp $
27  * $DragonFly: src/sys/dev/misc/kbd/kbd.c,v 1.14 2004/12/16 08:30:15 dillon Exp $
28  */
29 /*
30  * Generic keyboard driver.
31  *
32  * Interrupt note: keyboards use clist functions and since usb keyboard
33  * interrupts are not protected by spltty(), we must use a critical section
34  * to protect against corruption.
35  */
36
37 #include "opt_kbd.h"
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/malloc.h>
43 #include <sys/conf.h>
44 #include <sys/proc.h>
45 #include <sys/tty.h>
46 #include <sys/poll.h>
47 #include <sys/vnode.h>
48 #include <sys/uio.h>
49 #include <sys/thread.h>
50 #include <sys/thread2.h>
51
52 #include <machine/console.h>
53
54 #include "kbdreg.h"
55
56 #define KBD_INDEX(dev)  minor(dev)
57
58 typedef struct genkbd_softc {
59         int             gkb_flags;      /* flag/status bits */
60 #define KB_ASLEEP       (1 << 0)
61         struct clist    gkb_q;          /* input queue */
62         struct selinfo  gkb_rsel;
63 } genkbd_softc_t;
64
65 static  SLIST_HEAD(, keyboard_driver) keyboard_drivers =
66         SLIST_HEAD_INITIALIZER(keyboard_drivers);
67
68 SET_DECLARE(kbddriver_set, const keyboard_driver_t);
69
70 /* local arrays */
71
72 /*
73  * We need at least one entry each in order to initialize a keyboard
74  * for the kernel console.  The arrays will be increased dynamically
75  * when necessary.
76  */
77
78 static int              keyboards = 1;
79 static keyboard_t       *kbd_ini;
80 static keyboard_t       **keyboard = &kbd_ini;
81 static keyboard_switch_t *kbdsw_ini;
82        keyboard_switch_t **kbdsw = &kbdsw_ini;
83
84 #define ARRAY_DELTA     4
85
86 static int
87 kbd_realloc_array(void)
88 {
89         keyboard_t **new_kbd;
90         keyboard_switch_t **new_kbdsw;
91         int newsize;
92
93         newsize = ((keyboards + ARRAY_DELTA)/ARRAY_DELTA)*ARRAY_DELTA;
94         new_kbd = malloc(sizeof(*new_kbd) * newsize, M_DEVBUF,
95                                 M_WAITOK | M_ZERO);
96         new_kbdsw = malloc(sizeof(*new_kbdsw) * newsize, M_DEVBUF,
97                                 M_WAITOK | M_ZERO);
98         bcopy(keyboard, new_kbd, sizeof(*keyboard)*keyboards);
99         bcopy(kbdsw, new_kbdsw, sizeof(*kbdsw)*keyboards);
100         crit_enter();
101         if (keyboards > 1) {
102                 free(keyboard, M_DEVBUF);
103                 free(kbdsw, M_DEVBUF);
104         }
105         keyboard = new_kbd;
106         kbdsw = new_kbdsw;
107         keyboards = newsize;
108         crit_exit();
109
110         if (bootverbose)
111                 printf("kbd: new array size %d\n", keyboards);
112
113         return 0;
114 }
115
116 /*
117  * Low-level keyboard driver functions.
118  *
119  * Keyboard subdrivers, such as the AT keyboard driver and the USB keyboard
120  * driver, call these functions to initialize the keyboard_t structure
121  * and register it to the virtual keyboard driver `kbd'.
122  *
123  * The reinit call is made when a driver has partially detached a keyboard
124  * but does not unregistered it, then wishes to reinitialize it later on.
125  * This is how the USB keyboard driver handles the 'default' keyboard,
126  * because unregistering the keyboard associated with the console will
127  * destroy its console association forever.
128  */
129 void
130 kbd_reinit_struct(keyboard_t *kbd, int config, int pref)
131 {
132         kbd->kb_flags |= KB_NO_DEVICE;  /* device has not been found */
133         kbd->kb_config = config & ~KB_CONF_PROBE_ONLY;
134         kbd->kb_led = 0;                /* unknown */
135         kbd->kb_data = NULL;
136         kbd->kb_keymap = NULL;
137         kbd->kb_accentmap = NULL;
138         kbd->kb_fkeytab = NULL;
139         kbd->kb_fkeytab_size = 0;
140         kbd->kb_delay1 = KB_DELAY1;     /* these values are advisory only */
141         kbd->kb_delay2 = KB_DELAY2;
142         kbd->kb_count = 0;
143         kbd->kb_pref = pref;
144         bzero(kbd->kb_lastact, sizeof(kbd->kb_lastact));
145 }
146
147 /* initialize the keyboard_t structure */
148 void
149 kbd_init_struct(keyboard_t *kbd, char *name, int type, int unit, int config,
150                 int pref, int port, int port_size)
151 {
152         kbd->kb_flags = 0;
153         kbd->kb_name = name;
154         kbd->kb_type = type;
155         kbd->kb_unit = unit;
156         kbd->kb_io_base = port;
157         kbd->kb_io_size = port_size;
158         kbd_reinit_struct(kbd, config, pref);
159 }
160
161 void
162 kbd_set_maps(keyboard_t *kbd, keymap_t *keymap, accentmap_t *accmap,
163              fkeytab_t *fkeymap, int fkeymap_size)
164 {
165         kbd->kb_keymap = keymap;
166         kbd->kb_accentmap = accmap;
167         kbd->kb_fkeytab = fkeymap;
168         kbd->kb_fkeytab_size = fkeymap_size;
169 }
170
171 /* declare a new keyboard driver */
172 int
173 kbd_add_driver(keyboard_driver_t *driver)
174 {
175         if (SLIST_NEXT(driver, link))
176                 return EINVAL;
177         SLIST_INSERT_HEAD(&keyboard_drivers, driver, link);
178         return 0;
179 }
180
181 int
182 kbd_delete_driver(keyboard_driver_t *driver)
183 {
184         SLIST_REMOVE(&keyboard_drivers, driver, keyboard_driver, link);
185         SLIST_NEXT(driver, link) = NULL;
186         return 0;
187 }
188
189 /* register a keyboard and associate it with a function table */
190 int
191 kbd_register(keyboard_t *kbd)
192 {
193         const keyboard_driver_t **list;
194         const keyboard_driver_t *p;
195         int index;
196
197         for (index = 0; index < keyboards; ++index) {
198                 if (keyboard[index] == NULL)
199                         break;
200         }
201         if (index >= keyboards) {
202                 if (kbd_realloc_array())
203                         return -1;
204         }
205
206         kbd->kb_index = index;
207         KBD_UNBUSY(kbd);
208         KBD_VALID(kbd);
209         kbd->kb_active = 0;     /* disabled until someone calls kbd_enable() */
210         kbd->kb_token = NULL;
211         kbd->kb_callback.kc_func = NULL;
212         kbd->kb_callback.kc_arg = NULL;
213         callout_init(&kbd->kb_atkbd_timeout_ch);
214
215         SLIST_FOREACH(p, &keyboard_drivers, link) {
216                 if (strcmp(p->name, kbd->kb_name) == 0) {
217                         keyboard[index] = kbd;
218                         kbdsw[index] = p->kbdsw;
219                         return index;
220                 }
221         }
222         SET_FOREACH(list, kbddriver_set) {
223                 p = *list;
224                 if (strcmp(p->name, kbd->kb_name) == 0) {
225                         keyboard[index] = kbd;
226                         kbdsw[index] = p->kbdsw;
227                         return index;
228                 }
229         }
230
231         return -1;
232 }
233
234 int
235 kbd_unregister(keyboard_t *kbd)
236 {
237         int error;
238
239         if ((kbd->kb_index < 0) || (kbd->kb_index >= keyboards))
240                 return ENOENT;
241         if (keyboard[kbd->kb_index] != kbd)
242                 return ENOENT;
243
244         crit_enter();
245         callout_stop(&kbd->kb_atkbd_timeout_ch);
246         if (KBD_IS_BUSY(kbd)) {
247                 error = (*kbd->kb_callback.kc_func)(kbd, KBDIO_UNLOADING,
248                                                     kbd->kb_callback.kc_arg);
249                 if (error) {
250                         crit_exit();
251                         return error;
252                 }
253                 if (KBD_IS_BUSY(kbd)) {
254                         crit_exit();
255                         return EBUSY;
256                 }
257         }
258         KBD_INVALID(kbd);
259         keyboard[kbd->kb_index] = NULL;
260         kbdsw[kbd->kb_index] = NULL;
261
262         crit_exit();
263         return 0;
264 }
265
266 /* find a funciton table by the driver name */
267 keyboard_switch_t
268 *kbd_get_switch(char *driver)
269 {
270         const keyboard_driver_t **list;
271         const keyboard_driver_t *p;
272
273         SLIST_FOREACH(p, &keyboard_drivers, link) {
274                 if (strcmp(p->name, driver) == 0)
275                         return p->kbdsw;
276         }
277         SET_FOREACH(list, kbddriver_set) {
278                 p = *list;
279                 if (strcmp(p->name, driver) == 0)
280                         return p->kbdsw;
281         }
282
283         return NULL;
284 }
285
286 /*
287  * Keyboard client functions
288  * Keyboard clients, such as the console driver `syscons' and the keyboard
289  * cdev driver, use these functions to claim and release a keyboard for
290  * exclusive use.
291  */
292
293 /* find the keyboard specified by a driver name and a unit number */
294 int
295 kbd_find_keyboard(char *driver, int unit)
296 {
297         int i;
298         int pref;
299         int pref_index;
300
301         pref = 0;
302         pref_index = -1;
303
304         for (i = 0; i < keyboards; ++i) {
305                 if (keyboard[i] == NULL)
306                         continue;
307                 if (!KBD_IS_VALID(keyboard[i]))
308                         continue;
309                 if (strcmp("*", driver) && strcmp(keyboard[i]->kb_name, driver))
310                         continue;
311                 if ((unit != -1) && (keyboard[i]->kb_unit != unit))
312                         continue;
313                 if (pref <= keyboard[i]->kb_pref) {
314                         pref = keyboard[i]->kb_pref;
315                         pref_index = i;
316                 }
317         }
318         return (pref_index);
319 }
320
321 /* allocate a keyboard */
322 int
323 kbd_allocate(char *driver, int unit, void *id, kbd_callback_func_t *func,
324              void *arg)
325 {
326         int index;
327
328         if (func == NULL)
329                 return -1;
330
331         crit_enter();
332         index = kbd_find_keyboard(driver, unit);
333         if (index >= 0) {
334                 if (KBD_IS_BUSY(keyboard[index])) {
335                         crit_exit();
336                         return -1;
337                 }
338                 keyboard[index]->kb_token = id;
339                 KBD_BUSY(keyboard[index]);
340                 keyboard[index]->kb_callback.kc_func = func;
341                 keyboard[index]->kb_callback.kc_arg = arg;
342                 (*kbdsw[index]->clear_state)(keyboard[index]);
343         }
344         crit_exit();
345         return index;
346 }
347
348 int
349 kbd_release(keyboard_t *kbd, void *id)
350 {
351         int error;
352
353         crit_enter();
354         if (!KBD_IS_VALID(kbd) || !KBD_IS_BUSY(kbd)) {
355                 error = EINVAL;
356         } else if (kbd->kb_token != id) {
357                 error = EPERM;
358         } else {
359                 kbd->kb_token = NULL;
360                 KBD_UNBUSY(kbd);
361                 kbd->kb_callback.kc_func = NULL;
362                 kbd->kb_callback.kc_arg = NULL;
363                 (*kbdsw[kbd->kb_index]->clear_state)(kbd);
364                 error = 0;
365         }
366         crit_exit();
367         return error;
368 }
369
370 int
371 kbd_change_callback(keyboard_t *kbd, void *id, kbd_callback_func_t *func,
372                     void *arg)
373 {
374         int error;
375
376         crit_enter();
377         if (!KBD_IS_VALID(kbd) || !KBD_IS_BUSY(kbd)) {
378                 error = EINVAL;
379         } else if (kbd->kb_token != id) {
380                 error = EPERM;
381         } else if (func == NULL) {
382                 error = EINVAL;
383         } else {
384                 kbd->kb_callback.kc_func = func;
385                 kbd->kb_callback.kc_arg = arg;
386                 error = 0;
387         }
388         crit_exit();
389         return error;
390 }
391
392 /* get a keyboard structure */
393 keyboard_t
394 *kbd_get_keyboard(int index)
395 {
396         if ((index < 0) || (index >= keyboards))
397                 return NULL;
398         if (keyboard[index] == NULL)
399                 return NULL;
400         if (!KBD_IS_VALID(keyboard[index]))
401                 return NULL;
402         return keyboard[index];
403 }
404
405 /*
406  * The back door for the console driver; configure keyboards
407  * This function is for the kernel console to initialize keyboards
408  * at very early stage.
409  */
410
411 int
412 kbd_configure(int flags)
413 {
414         const keyboard_driver_t **list;
415         const keyboard_driver_t *p;
416
417         SLIST_FOREACH(p, &keyboard_drivers, link) {
418                 if (p->configure != NULL)
419                         (*p->configure)(flags);
420         }
421         SET_FOREACH(list, kbddriver_set) {
422                 p = *list;
423                 if (p->configure != NULL)
424                         (*p->configure)(flags);
425         }
426
427         return 0;
428 }
429
430 #ifdef KBD_INSTALL_CDEV
431
432 /*
433  * Virtual keyboard cdev driver functions
434  * The virtual keyboard driver dispatches driver functions to
435  * appropriate subdrivers.
436  */
437
438 #define KBD_UNIT(dev)   minor(dev)
439
440 static d_open_t         genkbdopen;
441 static d_close_t        genkbdclose;
442 static d_read_t         genkbdread;
443 static d_write_t        genkbdwrite;
444 static d_ioctl_t        genkbdioctl;
445 static d_poll_t         genkbdpoll;
446
447 #define CDEV_MAJOR      112
448
449 static struct cdevsw kbd_cdevsw = {
450         /* name */      "kbd",
451         /* maj */       CDEV_MAJOR,
452         /* flags */     0,
453         /* port */      NULL,
454         /* clone */     NULL,
455
456         /* open */      genkbdopen,
457         /* close */     genkbdclose,
458         /* read */      genkbdread,
459         /* write */     genkbdwrite,
460         /* ioctl */     genkbdioctl,
461         /* poll */      genkbdpoll,
462         /* mmap */      nommap,
463         /* strategy */  nostrategy,
464         /* dump */      nodump,
465         /* psize */     nopsize
466 };
467
468 int
469 kbd_attach(keyboard_t *kbd)
470 {
471         dev_t dev;
472
473         if (kbd->kb_index >= keyboards)
474                 return EINVAL;
475         if (keyboard[kbd->kb_index] != kbd)
476                 return EINVAL;
477
478         cdevsw_add(&kbd_cdevsw, -1, kbd->kb_index);
479         dev = make_dev(&kbd_cdevsw, kbd->kb_index, UID_ROOT, GID_WHEEL, 0600,
480                        "kbd%r", kbd->kb_index);
481         if (dev->si_drv1 == NULL)
482                 dev->si_drv1 = malloc(sizeof(genkbd_softc_t), M_DEVBUF,
483                                       M_WAITOK);
484         bzero(dev->si_drv1, sizeof(genkbd_softc_t));
485
486         printf("kbd%d at %s%d\n", kbd->kb_index, kbd->kb_name, kbd->kb_unit);
487         return 0;
488 }
489
490 int
491 kbd_detach(keyboard_t *kbd)
492 {
493         dev_t dev;
494
495         if (kbd->kb_index >= keyboards)
496                 return EINVAL;
497         if (keyboard[kbd->kb_index] != kbd)
498                 return EINVAL;
499
500         /*
501          * Deal with refs properly.  The KBD driver really ought to have
502          * recorded the dev_t separately.
503          */
504         if ((dev = make_adhoc_dev(&kbd_cdevsw, kbd->kb_index)) != NODEV) {
505                 if (dev->si_drv1) {
506                         free(dev->si_drv1, M_DEVBUF);
507                         dev->si_drv1 = NULL;
508                 }
509         }
510         cdevsw_remove(&kbd_cdevsw, -1, kbd->kb_index);
511         return 0;
512 }
513
514 /*
515  * Generic keyboard cdev driver functions
516  * Keyboard subdrivers may call these functions to implement common
517  * driver functions.
518  */
519
520 #define KB_QSIZE        512
521 #define KB_BUFSIZE      64
522
523 static kbd_callback_func_t genkbd_event;
524
525 static int
526 genkbdopen(dev_t dev, int mode, int flag, d_thread_t *td)
527 {
528         keyboard_t *kbd;
529         genkbd_softc_t *sc;
530         int i;
531
532         crit_enter();
533         sc = dev->si_drv1;
534         kbd = kbd_get_keyboard(KBD_INDEX(dev));
535         if ((sc == NULL) || (kbd == NULL) || !KBD_IS_VALID(kbd)) {
536                 crit_exit();
537                 return ENXIO;
538         }
539         i = kbd_allocate(kbd->kb_name, kbd->kb_unit, sc,
540                          genkbd_event, (void *)sc);
541         if (i < 0) {
542                 crit_exit();
543                 return EBUSY;
544         }
545         /* assert(i == kbd->kb_index) */
546         /* assert(kbd == kbd_get_keyboard(i)) */
547
548         /*
549          * NOTE: even when we have successfully claimed a keyboard,
550          * the device may still be missing (!KBD_HAS_DEVICE(kbd)).
551          */
552
553 #if 0
554         bzero(&sc->gkb_q, sizeof(sc->gkb_q));
555 #endif
556         clist_alloc_cblocks(&sc->gkb_q, KB_QSIZE, KB_QSIZE/2); /* XXX */
557         sc->gkb_rsel.si_flags = 0;
558         sc->gkb_rsel.si_pid = 0;
559         crit_exit();
560
561         return 0;
562 }
563
564 static int
565 genkbdclose(dev_t dev, int mode, int flag, d_thread_t *td)
566 {
567         keyboard_t *kbd;
568         genkbd_softc_t *sc;
569
570         /*
571          * NOTE: the device may have already become invalid.
572          * kbd == NULL || !KBD_IS_VALID(kbd)
573          */
574         crit_enter();
575         sc = dev->si_drv1;
576         kbd = kbd_get_keyboard(KBD_INDEX(dev));
577         if ((sc == NULL) || (kbd == NULL) || !KBD_IS_VALID(kbd)) {
578                 /* XXX: we shall be forgiving and don't report error... */
579         } else {
580                 kbd_release(kbd, (void *)sc);
581 #if 0
582                 clist_free_cblocks(&sc->gkb_q);
583 #endif
584         }
585         crit_exit();
586         return 0;
587 }
588
589 static int
590 genkbdread(dev_t dev, struct uio *uio, int flag)
591 {
592         keyboard_t *kbd;
593         genkbd_softc_t *sc;
594         u_char buffer[KB_BUFSIZE];
595         int len;
596         int error;
597
598         /* wait for input */
599         crit_enter();
600         sc = dev->si_drv1;
601         kbd = kbd_get_keyboard(KBD_INDEX(dev));
602         if ((sc == NULL) || (kbd == NULL) || !KBD_IS_VALID(kbd)) {
603                 crit_exit();
604                 return ENXIO;
605         }
606         while (sc->gkb_q.c_cc == 0) {
607                 if (flag & IO_NDELAY) {
608                         crit_exit();
609                         return EWOULDBLOCK;
610                 }
611                 sc->gkb_flags |= KB_ASLEEP;
612                 error = tsleep((caddr_t)sc, PCATCH, "kbdrea", 0);
613                 kbd = kbd_get_keyboard(KBD_INDEX(dev));
614                 if ((kbd == NULL) || !KBD_IS_VALID(kbd)) {
615                         crit_exit();
616                         return ENXIO;   /* our keyboard has gone... */
617                 }
618                 if (error) {
619                         sc->gkb_flags &= ~KB_ASLEEP;
620                         crit_exit();
621                         return error;
622                 }
623         }
624         crit_exit();
625
626         /* copy as much input as possible */
627         error = 0;
628         while (uio->uio_resid > 0) {
629                 len = imin(uio->uio_resid, sizeof(buffer));
630                 len = q_to_b(&sc->gkb_q, buffer, len);
631                 if (len <= 0)
632                         break;
633                 error = uiomove(buffer, len, uio);
634                 if (error)
635                         break;
636         }
637
638         return error;
639 }
640
641 static int
642 genkbdwrite(dev_t dev, struct uio *uio, int flag)
643 {
644         keyboard_t *kbd;
645
646         kbd = kbd_get_keyboard(KBD_INDEX(dev));
647         if ((kbd == NULL) || !KBD_IS_VALID(kbd))
648                 return ENXIO;
649         return ENODEV;
650 }
651
652 static int
653 genkbdioctl(dev_t dev, u_long cmd, caddr_t arg, int flag, d_thread_t *td)
654 {
655         keyboard_t *kbd;
656         int error;
657
658         kbd = kbd_get_keyboard(KBD_INDEX(dev));
659         if ((kbd == NULL) || !KBD_IS_VALID(kbd))
660                 return ENXIO;
661         error = (*kbdsw[kbd->kb_index]->ioctl)(kbd, cmd, arg);
662         if (error == ENOIOCTL)
663                 error = ENODEV;
664         return error;
665 }
666
667 static int
668 genkbdpoll(dev_t dev, int events, d_thread_t *td)
669 {
670         keyboard_t *kbd;
671         genkbd_softc_t *sc;
672         int revents;
673
674         revents = 0;
675         crit_enter();
676         sc = dev->si_drv1;
677         kbd = kbd_get_keyboard(KBD_INDEX(dev));
678         if ((sc == NULL) || (kbd == NULL) || !KBD_IS_VALID(kbd)) {
679                 revents =  POLLHUP;     /* the keyboard has gone */
680         } else if (events & (POLLIN | POLLRDNORM)) {
681                 if (sc->gkb_q.c_cc > 0)
682                         revents = events & (POLLIN | POLLRDNORM);
683                 else
684                         selrecord(td, &sc->gkb_rsel);
685         }
686         crit_exit();
687         return revents;
688 }
689
690 static int
691 genkbd_event(keyboard_t *kbd, int event, void *arg)
692 {
693         genkbd_softc_t *sc;
694         size_t len;
695         u_char *cp;
696         int mode;
697         int c;
698
699         /* assert(KBD_IS_VALID(kbd)) */
700         sc = (genkbd_softc_t *)arg;
701
702         switch (event) {
703         case KBDIO_KEYINPUT:
704                 break;
705         case KBDIO_UNLOADING:
706                 /* the keyboard is going... */
707                 kbd_release(kbd, (void *)sc);
708                 if (sc->gkb_flags & KB_ASLEEP) {
709                         sc->gkb_flags &= ~KB_ASLEEP;
710                         wakeup((caddr_t)sc);
711                 }
712                 selwakeup(&sc->gkb_rsel);
713                 return 0;
714         default:
715                 return EINVAL;
716         }
717
718         /* obtain the current key input mode */
719         if ((*kbdsw[kbd->kb_index]->ioctl)(kbd, KDGKBMODE, (caddr_t)&mode))
720                 mode = K_XLATE;
721
722         /* read all pending input */
723         while ((*kbdsw[kbd->kb_index]->check_char)(kbd)) {
724                 c = (*kbdsw[kbd->kb_index]->read_char)(kbd, FALSE);
725                 if (c == NOKEY)
726                         continue;
727                 if (c == ERRKEY)        /* XXX: ring bell? */
728                         continue;
729                 if (!KBD_IS_BUSY(kbd))
730                         /* the device is not open, discard the input */
731                         continue;
732
733                 /* store the byte as is for K_RAW and K_CODE modes */
734                 if (mode != K_XLATE) {
735                         putc(KEYCHAR(c), &sc->gkb_q);
736                         continue;
737                 }
738
739                 /* K_XLATE */
740                 if (c & RELKEY) /* key release is ignored */
741                         continue;
742
743                 /* process special keys; most of them are just ignored... */
744                 if (c & SPCLKEY) {
745                         switch (KEYCHAR(c)) {
746                         default:
747                                 /* ignore them... */
748                                 continue;
749                         case BTAB:      /* a backtab: ESC [ Z */
750                                 putc(0x1b, &sc->gkb_q);
751                                 putc('[', &sc->gkb_q);
752                                 putc('Z', &sc->gkb_q);
753                                 continue;
754                         }
755                 }
756
757                 /* normal chars, normal chars with the META, function keys */
758                 switch (KEYFLAGS(c)) {
759                 case 0:                 /* a normal char */
760                         putc(KEYCHAR(c), &sc->gkb_q);
761                         break;
762                 case MKEY:              /* the META flag: prepend ESC */
763                         putc(0x1b, &sc->gkb_q);
764                         putc(KEYCHAR(c), &sc->gkb_q);
765                         break;
766                 case FKEY | SPCLKEY:    /* a function key, return string */
767                         cp = (*kbdsw[kbd->kb_index]->get_fkeystr)(kbd,
768                                                         KEYCHAR(c), &len);
769                         if (cp != NULL) {
770                                 while (len-- >  0)
771                                         putc(*cp++, &sc->gkb_q);
772                         }
773                         break;
774                 }
775         }
776
777         /* wake up sleeping/polling processes */
778         if (sc->gkb_q.c_cc > 0) {
779                 if (sc->gkb_flags & KB_ASLEEP) {
780                         sc->gkb_flags &= ~KB_ASLEEP;
781                         wakeup((caddr_t)sc);
782                 }
783                 selwakeup(&sc->gkb_rsel);
784         }
785
786         return 0;
787 }
788
789 #endif /* KBD_INSTALL_CDEV */
790
791 /*
792  * Generic low-level keyboard functions
793  * The low-level functions in the keyboard subdriver may use these
794  * functions.
795  */
796
797 int
798 genkbd_commonioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
799 {
800         keyarg_t *keyp;
801         fkeyarg_t *fkeyp;
802         int i;
803
804         crit_enter();
805         switch (cmd) {
806
807         case KDGKBINFO:         /* get keyboard information */
808                 ((keyboard_info_t *)arg)->kb_index = kbd->kb_index;
809                 i = imin(strlen(kbd->kb_name) + 1,
810                          sizeof(((keyboard_info_t *)arg)->kb_name));
811                 bcopy(kbd->kb_name, ((keyboard_info_t *)arg)->kb_name, i);
812                 ((keyboard_info_t *)arg)->kb_unit = kbd->kb_unit;
813                 ((keyboard_info_t *)arg)->kb_type = kbd->kb_type;
814                 ((keyboard_info_t *)arg)->kb_config = kbd->kb_config;
815                 ((keyboard_info_t *)arg)->kb_flags = kbd->kb_flags;
816                 break;
817
818         case KDGKBTYPE:         /* get keyboard type */
819                 *(int *)arg = kbd->kb_type;
820                 break;
821
822         case KDGETREPEAT:       /* get keyboard repeat rate */
823                 ((int *)arg)[0] = kbd->kb_delay1;
824                 ((int *)arg)[1] = kbd->kb_delay2; 
825                 break;
826
827         case GIO_KEYMAP:        /* get keyboard translation table */
828                 bcopy(kbd->kb_keymap, arg, sizeof(*kbd->kb_keymap));
829                 break;
830         case PIO_KEYMAP:        /* set keyboard translation table */
831 #ifndef KBD_DISABLE_KEYMAP_LOAD
832                 bzero(kbd->kb_accentmap, sizeof(*kbd->kb_accentmap));
833                 bcopy(arg, kbd->kb_keymap, sizeof(*kbd->kb_keymap));
834                 break;
835 #else
836                 crit_exit();
837                 return ENODEV;
838 #endif
839
840         case GIO_KEYMAPENT:     /* get keyboard translation table entry */
841                 keyp = (keyarg_t *)arg;
842                 if (keyp->keynum >= sizeof(kbd->kb_keymap->key)
843                                         /sizeof(kbd->kb_keymap->key[0])) {
844                         crit_exit();
845                         return EINVAL;
846                 }
847                 bcopy(&kbd->kb_keymap->key[keyp->keynum], &keyp->key,
848                       sizeof(keyp->key));
849                 break;
850         case PIO_KEYMAPENT:     /* set keyboard translation table entry */
851 #ifndef KBD_DISABLE_KEYMAP_LOAD
852                 keyp = (keyarg_t *)arg;
853                 if (keyp->keynum >= sizeof(kbd->kb_keymap->key)
854                                         /sizeof(kbd->kb_keymap->key[0])) {
855                         crit_exit();
856                         return EINVAL;
857                 }
858                 bcopy(&keyp->key, &kbd->kb_keymap->key[keyp->keynum],
859                       sizeof(keyp->key));
860                 break;
861 #else
862                 crit_exit();
863                 return ENODEV;
864 #endif
865
866         case GIO_DEADKEYMAP:    /* get accent key translation table */
867                 bcopy(kbd->kb_accentmap, arg, sizeof(*kbd->kb_accentmap));
868                 break;
869         case PIO_DEADKEYMAP:    /* set accent key translation table */
870 #ifndef KBD_DISABLE_KEYMAP_LOAD
871                 bcopy(arg, kbd->kb_accentmap, sizeof(*kbd->kb_accentmap));
872                 break;
873 #else
874                 crit_exit();
875                 return ENODEV;
876 #endif
877
878         case GETFKEY:           /* get functionkey string */
879                 fkeyp = (fkeyarg_t *)arg;
880                 if (fkeyp->keynum >= kbd->kb_fkeytab_size) {
881                         crit_exit();
882                         return EINVAL;
883                 }
884                 bcopy(kbd->kb_fkeytab[fkeyp->keynum].str, fkeyp->keydef,
885                       kbd->kb_fkeytab[fkeyp->keynum].len);
886                 fkeyp->flen = kbd->kb_fkeytab[fkeyp->keynum].len;
887                 break;
888         case SETFKEY:           /* set functionkey string */
889 #ifndef KBD_DISABLE_KEYMAP_LOAD
890                 fkeyp = (fkeyarg_t *)arg;
891                 if (fkeyp->keynum >= kbd->kb_fkeytab_size) {
892                         crit_exit();
893                         return EINVAL;
894                 }
895                 kbd->kb_fkeytab[fkeyp->keynum].len = imin(fkeyp->flen, MAXFK);
896                 bcopy(fkeyp->keydef, kbd->kb_fkeytab[fkeyp->keynum].str,
897                       kbd->kb_fkeytab[fkeyp->keynum].len);
898                 break;
899 #else
900                 crit_exit();
901                 return ENODEV;
902 #endif
903
904         default:
905                 crit_exit();
906                 return ENOIOCTL;
907         }
908
909         crit_exit();
910         return 0;
911 }
912
913 /* get a pointer to the string associated with the given function key */
914 u_char
915 *genkbd_get_fkeystr(keyboard_t *kbd, int fkey, size_t *len)
916 {
917         if (kbd == NULL)
918                 return NULL;
919         fkey -= F_FN;
920         if (fkey > kbd->kb_fkeytab_size)
921                 return NULL;
922         *len = kbd->kb_fkeytab[fkey].len;
923         return kbd->kb_fkeytab[fkey].str;
924 }
925
926 /* diagnostic dump */
927 static char
928 *get_kbd_type_name(int type)
929 {
930         static struct {
931                 int type;
932                 char *name;
933         } name_table[] = {
934                 { KB_84,        "AT 84" },
935                 { KB_101,       "AT 101/102" },
936                 { KB_OTHER,     "generic" },
937         };
938         int i;
939
940         for (i = 0; i < sizeof(name_table)/sizeof(name_table[0]); ++i) {
941                 if (type == name_table[i].type)
942                         return name_table[i].name;
943         }
944         return "unknown";
945 }
946
947 void
948 genkbd_diag(keyboard_t *kbd, int level)
949 {
950         if (level > 0) {
951                 printf("kbd%d: %s%d, %s (%d), config:0x%x, flags:0x%x", 
952                        kbd->kb_index, kbd->kb_name, kbd->kb_unit,
953                        get_kbd_type_name(kbd->kb_type), kbd->kb_type,
954                        kbd->kb_config, kbd->kb_flags);
955                 if (kbd->kb_io_base > 0)
956                         printf(", port:0x%x-0x%x", kbd->kb_io_base, 
957                                kbd->kb_io_base + kbd->kb_io_size - 1);
958                 printf("\n");
959         }
960 }
961
962 #define set_lockkey_state(k, s, l)                              \
963         if (!((s) & l ## DOWN)) {                               \
964                 int i;                                          \
965                 (s) |= l ## DOWN;                               \
966                 (s) ^= l ## ED;                                 \
967                 i = (s) & LOCK_MASK;                            \
968                 (*kbdsw[(k)->kb_index]->ioctl)((k), KDSETLED, (caddr_t)&i); \
969         }
970
971 static u_int
972 save_accent_key(keyboard_t *kbd, u_int key, int *accents)
973 {
974         int i;
975
976         /* make an index into the accent map */
977         i = key - F_ACC + 1;
978         if ((i > kbd->kb_accentmap->n_accs)
979             || (kbd->kb_accentmap->acc[i - 1].accchar == 0)) {
980                 /* the index is out of range or pointing to an empty entry */
981                 *accents = 0;
982                 return ERRKEY;
983         }
984
985         /* 
986          * If the same accent key has been hit twice, produce the accent char
987          * itself.
988          */
989         if (i == *accents) {
990                 key = kbd->kb_accentmap->acc[i - 1].accchar;
991                 *accents = 0;
992                 return key;
993         }
994
995         /* remember the index and wait for the next key  */
996         *accents = i; 
997         return NOKEY;
998 }
999
1000 static u_int
1001 make_accent_char(keyboard_t *kbd, u_int ch, int *accents)
1002 {
1003         struct acc_t *acc;
1004         int i;
1005
1006         acc = &kbd->kb_accentmap->acc[*accents - 1];
1007         *accents = 0;
1008
1009         /* 
1010          * If the accent key is followed by the space key,
1011          * produce the accent char itself.
1012          */
1013         if (ch == ' ')
1014                 return acc->accchar;
1015
1016         /* scan the accent map */
1017         for (i = 0; i < NUM_ACCENTCHARS; ++i) {
1018                 if (acc->map[i][0] == 0)        /* end of table */
1019                         break;
1020                 if (acc->map[i][0] == ch)
1021                         return acc->map[i][1];
1022         }
1023         /* this char cannot be accented... */
1024         return ERRKEY;
1025 }
1026
1027 int
1028 genkbd_keyaction(keyboard_t *kbd, int keycode, int up, int *shiftstate,
1029                  int *accents)
1030 {
1031         struct keyent_t *key;
1032         int state = *shiftstate;
1033         int action;
1034         int f;
1035         int i;
1036
1037         i = keycode;
1038         f = state & (AGRS | ALKED);
1039         if ((f == AGRS1) || (f == AGRS2) || (f == ALKED))
1040                 i += ALTGR_OFFSET;
1041         key = &kbd->kb_keymap->key[i];
1042         i = ((state & SHIFTS) ? 1 : 0)
1043             | ((state & CTLS) ? 2 : 0)
1044             | ((state & ALTS) ? 4 : 0);
1045         if (((key->flgs & FLAG_LOCK_C) && (state & CLKED))
1046                 || ((key->flgs & FLAG_LOCK_N) && (state & NLKED)) )
1047                 i ^= 1;
1048
1049         if (up) {       /* break: key released */
1050                 action = kbd->kb_lastact[keycode];
1051                 kbd->kb_lastact[keycode] = NOP;
1052                 switch (action) {
1053                 case LSHA:
1054                         if (state & SHIFTAON) {
1055                                 set_lockkey_state(kbd, state, ALK);
1056                                 state &= ~ALKDOWN;
1057                         }
1058                         action = LSH;
1059                         /* FALL THROUGH */
1060                 case LSH:
1061                         state &= ~SHIFTS1;
1062                         break;
1063                 case RSHA:
1064                         if (state & SHIFTAON) {
1065                                 set_lockkey_state(kbd, state, ALK);
1066                                 state &= ~ALKDOWN;
1067                         }
1068                         action = RSH;
1069                         /* FALL THROUGH */
1070                 case RSH:
1071                         state &= ~SHIFTS2;
1072                         break;
1073                 case LCTRA:
1074                         if (state & SHIFTAON) {
1075                                 set_lockkey_state(kbd, state, ALK);
1076                                 state &= ~ALKDOWN;
1077                         }
1078                         action = LCTR;
1079                         /* FALL THROUGH */
1080                 case LCTR:
1081                         state &= ~CTLS1;
1082                         break;
1083                 case RCTRA:
1084                         if (state & SHIFTAON) {
1085                                 set_lockkey_state(kbd, state, ALK);
1086                                 state &= ~ALKDOWN;
1087                         }
1088                         action = RCTR;
1089                         /* FALL THROUGH */
1090                 case RCTR:
1091                         state &= ~CTLS2;
1092                         break;
1093                 case LALTA:
1094                         if (state & SHIFTAON) {
1095                                 set_lockkey_state(kbd, state, ALK);
1096                                 state &= ~ALKDOWN;
1097                         }
1098                         action = LALT;
1099                         /* FALL THROUGH */
1100                 case LALT:
1101                         state &= ~ALTS1;
1102                         break;
1103                 case RALTA:
1104                         if (state & SHIFTAON) {
1105                                 set_lockkey_state(kbd, state, ALK);
1106                                 state &= ~ALKDOWN;
1107                         }
1108                         action = RALT;
1109                         /* FALL THROUGH */
1110                 case RALT:
1111                         state &= ~ALTS2;
1112                         break;
1113                 case ASH:
1114                         state &= ~AGRS1;
1115                         break;
1116                 case META:
1117                         state &= ~METAS1;
1118                         break;
1119                 case NLK:
1120                         state &= ~NLKDOWN;
1121                         break;
1122                 case CLK:
1123 #ifndef PC98
1124                         state &= ~CLKDOWN;
1125 #else
1126                         state &= ~CLKED;
1127                         i = state & LOCK_MASK;
1128                         (*kbdsw[kbd->kb_index]->ioctl)(kbd, KDSETLED,
1129                                                        (caddr_t)&i);
1130 #endif
1131                         break;
1132                 case SLK:
1133                         state &= ~SLKDOWN;
1134                         break;
1135                 case ALK:
1136                         state &= ~ALKDOWN;
1137                         break;
1138                 case NOP:
1139                         /* release events of regular keys are not reported */
1140                         *shiftstate &= ~SHIFTAON;
1141                         return NOKEY;
1142                 }
1143                 *shiftstate = state & ~SHIFTAON;
1144                 return (SPCLKEY | RELKEY | action);
1145         } else {        /* make: key pressed */
1146                 action = key->map[i];
1147                 state &= ~SHIFTAON;
1148                 if (key->spcl & (0x80 >> i)) {
1149                         /* special keys */
1150                         if (kbd->kb_lastact[keycode] == NOP)
1151                                 kbd->kb_lastact[keycode] = action;
1152                         if (kbd->kb_lastact[keycode] != action)
1153                                 action = NOP;
1154                         switch (action) {
1155                         /* LOCKING KEYS */
1156                         case NLK:
1157                                 set_lockkey_state(kbd, state, NLK);
1158                                 break;
1159                         case CLK:
1160 #ifndef PC98
1161                                 set_lockkey_state(kbd, state, CLK);
1162 #else
1163                                 state |= CLKED;
1164                                 i = state & LOCK_MASK;
1165                                 (*kbdsw[kbd->kb_index]->ioctl)(kbd, KDSETLED,
1166                                                                (caddr_t)&i);
1167 #endif
1168                                 break;
1169                         case SLK:
1170                                 set_lockkey_state(kbd, state, SLK);
1171                                 break;
1172                         case ALK:
1173                                 set_lockkey_state(kbd, state, ALK);
1174                                 break;
1175                         /* NON-LOCKING KEYS */
1176                         case SPSC: case RBT:  case SUSP: case STBY:
1177                         case DBG:  case NEXT: case PREV: case PNC:
1178                         case HALT: case PDWN:
1179                                 *accents = 0;
1180                                 break;
1181                         case BTAB:
1182                                 *accents = 0;
1183                                 action |= BKEY;
1184                                 break;
1185                         case LSHA:
1186                                 state |= SHIFTAON;
1187                                 action = LSH;
1188                                 /* FALL THROUGH */
1189                         case LSH:
1190                                 state |= SHIFTS1;
1191                                 break;
1192                         case RSHA:
1193                                 state |= SHIFTAON;
1194                                 action = RSH;
1195                                 /* FALL THROUGH */
1196                         case RSH:
1197                                 state |= SHIFTS2;
1198                                 break;
1199                         case LCTRA:
1200                                 state |= SHIFTAON;
1201                                 action = LCTR;
1202                                 /* FALL THROUGH */
1203                         case LCTR:
1204                                 state |= CTLS1;
1205                                 break;
1206                         case RCTRA:
1207                                 state |= SHIFTAON;
1208                                 action = RCTR;
1209                                 /* FALL THROUGH */
1210                         case RCTR:
1211                                 state |= CTLS2;
1212                                 break;
1213                         case LALTA:
1214                                 state |= SHIFTAON;
1215                                 action = LALT;
1216                                 /* FALL THROUGH */
1217                         case LALT:
1218                                 state |= ALTS1;
1219                                 break;
1220                         case RALTA:
1221                                 state |= SHIFTAON;
1222                                 action = RALT;
1223                                 /* FALL THROUGH */
1224                         case RALT:
1225                                 state |= ALTS2;
1226                                 break;
1227                         case ASH:
1228                                 state |= AGRS1;
1229                                 break;
1230                         case META:
1231                                 state |= METAS1;
1232                                 break;
1233                         case NOP:
1234                                 *shiftstate = state;
1235                                 return NOKEY;
1236                         default:
1237                                 /* is this an accent (dead) key? */
1238                                 *shiftstate = state;
1239                                 if (action >= F_ACC && action <= L_ACC) {
1240                                         action = save_accent_key(kbd, action,
1241                                                                  accents);
1242                                         switch (action) {
1243                                         case NOKEY:
1244                                         case ERRKEY:
1245                                                 return action;
1246                                         default:
1247                                                 if (state & METAS)
1248                                                         return (action | MKEY);
1249                                                 else
1250                                                         return action;
1251                                         }
1252                                         /* NOT REACHED */
1253                                 }
1254                                 /* other special keys */
1255                                 if (*accents > 0) {
1256                                         *accents = 0;
1257                                         return ERRKEY;
1258                                 }
1259                                 if (action >= F_FN && action <= L_FN)
1260                                         action |= FKEY;
1261                                 /* XXX: return fkey string for the FKEY? */
1262                                 return (SPCLKEY | action);
1263                         }
1264                         *shiftstate = state;
1265                         return (SPCLKEY | action);
1266                 } else {
1267                         /* regular keys */
1268                         kbd->kb_lastact[keycode] = NOP;
1269                         *shiftstate = state;
1270                         if (*accents > 0) {
1271                                 /* make an accented char */
1272                                 action = make_accent_char(kbd, action, accents);
1273                                 if (action == ERRKEY)
1274                                         return action;
1275                         }
1276                         if (state & METAS)
1277                                 action |= MKEY;
1278                         return action;
1279                 }
1280         }
1281         /* NOT REACHED */
1282 }