DEVFS - remove dev_ops_add(), dev_ops_get(), and get_dev()
[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.23 2007/05/08 02:31:39 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 = kmalloc(sizeof(*new_kbd) * newsize, M_DEVBUF,
95                                 M_WAITOK | M_ZERO);
96         new_kbdsw = kmalloc(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                 kfree(keyboard, M_DEVBUF);
103                 kfree(kbdsw, M_DEVBUF);
104         }
105         keyboard = new_kbd;
106         kbdsw = new_kbdsw;
107         keyboards = newsize;
108         crit_exit();
109
110         if (bootverbose)
111                 kprintf("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 dev_ops kbd_ops = {
450         { "kbd", CDEV_MAJOR, 0 },
451         .d_open =       genkbdopen,
452         .d_close =      genkbdclose,
453         .d_read =       genkbdread,
454         .d_write =      genkbdwrite,
455         .d_ioctl =      genkbdioctl,
456         .d_poll =       genkbdpoll,
457 };
458
459 int
460 kbd_attach(keyboard_t *kbd)
461 {
462         cdev_t dev;
463
464         if (kbd->kb_index >= keyboards)
465                 return EINVAL;
466         if (keyboard[kbd->kb_index] != kbd)
467                 return EINVAL;
468
469         dev = make_dev(&kbd_ops, kbd->kb_index, UID_ROOT, GID_WHEEL, 0600,
470                        "kbd%r", kbd->kb_index);
471         if (dev->si_drv1 == NULL)
472                 dev->si_drv1 = kmalloc(sizeof(genkbd_softc_t), M_DEVBUF,
473                                       M_WAITOK);
474         bzero(dev->si_drv1, sizeof(genkbd_softc_t));
475
476         kprintf("kbd%d at %s%d\n", kbd->kb_index, kbd->kb_name, kbd->kb_unit);
477         return 0;
478 }
479
480 int
481 kbd_detach(keyboard_t *kbd)
482 {
483         cdev_t dev;
484
485         if (kbd->kb_index >= keyboards)
486                 return EINVAL;
487         if (keyboard[kbd->kb_index] != kbd)
488                 return EINVAL;
489
490         /*
491          * Deal with refs properly.  The KBD driver really ought to have
492          * recorded the cdev_t separately.
493          */
494         if ((dev = make_adhoc_dev(&kbd_ops, kbd->kb_index)) != NULL) {
495                 if (dev->si_drv1) {
496                         kfree(dev->si_drv1, M_DEVBUF);
497                         dev->si_drv1 = NULL;
498                 }
499         }
500         dev_ops_remove_minor(&kbd_ops, kbd->kb_index);
501         return 0;
502 }
503
504 /*
505  * Generic keyboard cdev driver functions
506  * Keyboard subdrivers may call these functions to implement common
507  * driver functions.
508  */
509
510 #define KB_QSIZE        512
511 #define KB_BUFSIZE      64
512
513 static kbd_callback_func_t genkbd_event;
514
515 static int
516 genkbdopen(struct dev_open_args *ap)
517 {
518         cdev_t dev = ap->a_head.a_dev;
519         keyboard_t *kbd;
520         genkbd_softc_t *sc;
521         int i;
522
523         crit_enter();
524         sc = dev->si_drv1;
525         kbd = kbd_get_keyboard(KBD_INDEX(dev));
526         if ((sc == NULL) || (kbd == NULL) || !KBD_IS_VALID(kbd)) {
527                 crit_exit();
528                 return ENXIO;
529         }
530         i = kbd_allocate(kbd->kb_name, kbd->kb_unit, sc,
531                          genkbd_event, (void *)sc);
532         if (i < 0) {
533                 crit_exit();
534                 return EBUSY;
535         }
536         /* assert(i == kbd->kb_index) */
537         /* assert(kbd == kbd_get_keyboard(i)) */
538
539         /*
540          * NOTE: even when we have successfully claimed a keyboard,
541          * the device may still be missing (!KBD_HAS_DEVICE(kbd)).
542          */
543
544 #if 0
545         bzero(&sc->gkb_q, sizeof(sc->gkb_q));
546 #endif
547         clist_alloc_cblocks(&sc->gkb_q, KB_QSIZE, KB_QSIZE/2); /* XXX */
548         sc->gkb_rsel.si_flags = 0;
549         sc->gkb_rsel.si_pid = 0;
550         crit_exit();
551
552         return 0;
553 }
554
555 static int
556 genkbdclose(struct dev_close_args *ap)
557 {
558         cdev_t dev = ap->a_head.a_dev;
559         keyboard_t *kbd;
560         genkbd_softc_t *sc;
561
562         /*
563          * NOTE: the device may have already become invalid.
564          * kbd == NULL || !KBD_IS_VALID(kbd)
565          */
566         crit_enter();
567         sc = dev->si_drv1;
568         kbd = kbd_get_keyboard(KBD_INDEX(dev));
569         if ((sc == NULL) || (kbd == NULL) || !KBD_IS_VALID(kbd)) {
570                 /* XXX: we shall be forgiving and don't report error... */
571         } else {
572                 kbd_release(kbd, (void *)sc);
573 #if 0
574                 clist_free_cblocks(&sc->gkb_q);
575 #endif
576         }
577         crit_exit();
578         return 0;
579 }
580
581 static int
582 genkbdread(struct dev_read_args *ap)
583 {
584         cdev_t dev = ap->a_head.a_dev;
585         struct uio *uio = ap->a_uio;
586         keyboard_t *kbd;
587         genkbd_softc_t *sc;
588         u_char buffer[KB_BUFSIZE];
589         int len;
590         int error;
591
592         /* wait for input */
593         crit_enter();
594         sc = dev->si_drv1;
595         kbd = kbd_get_keyboard(KBD_INDEX(dev));
596         if ((sc == NULL) || (kbd == NULL) || !KBD_IS_VALID(kbd)) {
597                 crit_exit();
598                 return ENXIO;
599         }
600         while (sc->gkb_q.c_cc == 0) {
601                 if (ap->a_ioflag & IO_NDELAY) {
602                         crit_exit();
603                         return EWOULDBLOCK;
604                 }
605                 sc->gkb_flags |= KB_ASLEEP;
606                 error = tsleep((caddr_t)sc, PCATCH, "kbdrea", 0);
607                 kbd = kbd_get_keyboard(KBD_INDEX(dev));
608                 if ((kbd == NULL) || !KBD_IS_VALID(kbd)) {
609                         crit_exit();
610                         return ENXIO;   /* our keyboard has gone... */
611                 }
612                 if (error) {
613                         sc->gkb_flags &= ~KB_ASLEEP;
614                         crit_exit();
615                         return error;
616                 }
617         }
618         crit_exit();
619
620         /* copy as much input as possible */
621         error = 0;
622         while (uio->uio_resid > 0) {
623                 len = imin(uio->uio_resid, sizeof(buffer));
624                 len = q_to_b(&sc->gkb_q, buffer, len);
625                 if (len <= 0)
626                         break;
627                 error = uiomove(buffer, len, uio);
628                 if (error)
629                         break;
630         }
631
632         return error;
633 }
634
635 static int
636 genkbdwrite(struct dev_write_args *ap)
637 {
638         cdev_t dev = ap->a_head.a_dev;
639         keyboard_t *kbd;
640
641         kbd = kbd_get_keyboard(KBD_INDEX(dev));
642         if ((kbd == NULL) || !KBD_IS_VALID(kbd))
643                 return ENXIO;
644         return ENODEV;
645 }
646
647 static int
648 genkbdioctl(struct dev_ioctl_args *ap)
649 {
650         cdev_t dev = ap->a_head.a_dev;
651         keyboard_t *kbd;
652         int error;
653
654         kbd = kbd_get_keyboard(KBD_INDEX(dev));
655         if ((kbd == NULL) || !KBD_IS_VALID(kbd))
656                 return ENXIO;
657         error = (*kbdsw[kbd->kb_index]->ioctl)(kbd, ap->a_cmd, ap->a_data);
658         if (error == ENOIOCTL)
659                 error = ENODEV;
660         return error;
661 }
662
663 static int
664 genkbdpoll(struct dev_poll_args *ap)
665 {
666         cdev_t dev = ap->a_head.a_dev;
667         keyboard_t *kbd;
668         genkbd_softc_t *sc;
669         int revents;
670
671         revents = 0;
672         crit_enter();
673         sc = dev->si_drv1;
674         kbd = kbd_get_keyboard(KBD_INDEX(dev));
675         if ((sc == NULL) || (kbd == NULL) || !KBD_IS_VALID(kbd)) {
676                 revents =  POLLHUP;     /* the keyboard has gone */
677         } else if (ap->a_events & (POLLIN | POLLRDNORM)) {
678                 if (sc->gkb_q.c_cc > 0)
679                         revents = ap->a_events & (POLLIN | POLLRDNORM);
680                 else
681                         selrecord(curthread, &sc->gkb_rsel);
682         }
683         crit_exit();
684         ap->a_events = revents;
685         return (0);
686 }
687
688 static int
689 genkbd_event(keyboard_t *kbd, int event, void *arg)
690 {
691         genkbd_softc_t *sc;
692         size_t len;
693         u_char *cp;
694         int mode;
695         int c;
696
697         /* assert(KBD_IS_VALID(kbd)) */
698         sc = (genkbd_softc_t *)arg;
699
700         switch (event) {
701         case KBDIO_KEYINPUT:
702                 break;
703         case KBDIO_UNLOADING:
704                 /* the keyboard is going... */
705                 kbd_release(kbd, (void *)sc);
706                 if (sc->gkb_flags & KB_ASLEEP) {
707                         sc->gkb_flags &= ~KB_ASLEEP;
708                         wakeup((caddr_t)sc);
709                 }
710                 selwakeup(&sc->gkb_rsel);
711                 return 0;
712         default:
713                 return EINVAL;
714         }
715
716         /* obtain the current key input mode */
717         if ((*kbdsw[kbd->kb_index]->ioctl)(kbd, KDGKBMODE, (caddr_t)&mode))
718                 mode = K_XLATE;
719
720         /* read all pending input */
721         while ((*kbdsw[kbd->kb_index]->check_char)(kbd)) {
722                 c = (*kbdsw[kbd->kb_index]->read_char)(kbd, FALSE);
723                 if (c == NOKEY)
724                         continue;
725                 if (c == ERRKEY)        /* XXX: ring bell? */
726                         continue;
727                 if (!KBD_IS_BUSY(kbd))
728                         /* the device is not open, discard the input */
729                         continue;
730
731                 /* store the byte as is for K_RAW and K_CODE modes */
732                 if (mode != K_XLATE) {
733                         clist_putc(KEYCHAR(c), &sc->gkb_q);
734                         continue;
735                 }
736
737                 /* K_XLATE */
738                 if (c & RELKEY) /* key release is ignored */
739                         continue;
740
741                 /* process special keys; most of them are just ignored... */
742                 if (c & SPCLKEY) {
743                         switch (KEYCHAR(c)) {
744                         default:
745                                 /* ignore them... */
746                                 continue;
747                         case BTAB:      /* a backtab: ESC [ Z */
748                                 clist_putc(0x1b, &sc->gkb_q);
749                                 clist_putc('[', &sc->gkb_q);
750                                 clist_putc('Z', &sc->gkb_q);
751                                 continue;
752                         }
753                 }
754
755                 /* normal chars, normal chars with the META, function keys */
756                 switch (KEYFLAGS(c)) {
757                 case 0:                 /* a normal char */
758                         clist_putc(KEYCHAR(c), &sc->gkb_q);
759                         break;
760                 case MKEY:              /* the META flag: prepend ESC */
761                         clist_putc(0x1b, &sc->gkb_q);
762                         clist_putc(KEYCHAR(c), &sc->gkb_q);
763                         break;
764                 case FKEY | SPCLKEY:    /* a function key, return string */
765                         cp = (*kbdsw[kbd->kb_index]->get_fkeystr)(kbd,
766                                                         KEYCHAR(c), &len);
767                         if (cp != NULL) {
768                                 while (len-- >  0)
769                                         clist_putc(*cp++, &sc->gkb_q);
770                         }
771                         break;
772                 }
773         }
774
775         /* wake up sleeping/polling processes */
776         if (sc->gkb_q.c_cc > 0) {
777                 if (sc->gkb_flags & KB_ASLEEP) {
778                         sc->gkb_flags &= ~KB_ASLEEP;
779                         wakeup((caddr_t)sc);
780                 }
781                 selwakeup(&sc->gkb_rsel);
782         }
783
784         return 0;
785 }
786
787 #endif /* KBD_INSTALL_CDEV */
788
789 /*
790  * Generic low-level keyboard functions
791  * The low-level functions in the keyboard subdriver may use these
792  * functions.
793  */
794
795 int
796 genkbd_commonioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
797 {
798         keyarg_t *keyp;
799         fkeyarg_t *fkeyp;
800         int i;
801
802         crit_enter();
803         switch (cmd) {
804
805         case KDGKBINFO:         /* get keyboard information */
806                 ((keyboard_info_t *)arg)->kb_index = kbd->kb_index;
807                 i = imin(strlen(kbd->kb_name) + 1,
808                          sizeof(((keyboard_info_t *)arg)->kb_name));
809                 bcopy(kbd->kb_name, ((keyboard_info_t *)arg)->kb_name, i);
810                 ((keyboard_info_t *)arg)->kb_unit = kbd->kb_unit;
811                 ((keyboard_info_t *)arg)->kb_type = kbd->kb_type;
812                 ((keyboard_info_t *)arg)->kb_config = kbd->kb_config;
813                 ((keyboard_info_t *)arg)->kb_flags = kbd->kb_flags;
814                 break;
815
816         case KDGKBTYPE:         /* get keyboard type */
817                 *(int *)arg = kbd->kb_type;
818                 break;
819
820         case KDGETREPEAT:       /* get keyboard repeat rate */
821                 ((int *)arg)[0] = kbd->kb_delay1;
822                 ((int *)arg)[1] = kbd->kb_delay2; 
823                 break;
824
825         case GIO_KEYMAP:        /* get keyboard translation table */
826                 bcopy(kbd->kb_keymap, arg, sizeof(*kbd->kb_keymap));
827                 break;
828         case PIO_KEYMAP:        /* set keyboard translation table */
829 #ifndef KBD_DISABLE_KEYMAP_LOAD
830                 bzero(kbd->kb_accentmap, sizeof(*kbd->kb_accentmap));
831                 bcopy(arg, kbd->kb_keymap, sizeof(*kbd->kb_keymap));
832                 break;
833 #else
834                 crit_exit();
835                 return ENODEV;
836 #endif
837
838         case GIO_KEYMAPENT:     /* get keyboard translation table entry */
839                 keyp = (keyarg_t *)arg;
840                 if (keyp->keynum >= sizeof(kbd->kb_keymap->key)
841                                         /sizeof(kbd->kb_keymap->key[0])) {
842                         crit_exit();
843                         return EINVAL;
844                 }
845                 bcopy(&kbd->kb_keymap->key[keyp->keynum], &keyp->key,
846                       sizeof(keyp->key));
847                 break;
848         case PIO_KEYMAPENT:     /* set keyboard translation table entry */
849 #ifndef KBD_DISABLE_KEYMAP_LOAD
850                 keyp = (keyarg_t *)arg;
851                 if (keyp->keynum >= sizeof(kbd->kb_keymap->key)
852                                         /sizeof(kbd->kb_keymap->key[0])) {
853                         crit_exit();
854                         return EINVAL;
855                 }
856                 bcopy(&keyp->key, &kbd->kb_keymap->key[keyp->keynum],
857                       sizeof(keyp->key));
858                 break;
859 #else
860                 crit_exit();
861                 return ENODEV;
862 #endif
863
864         case GIO_DEADKEYMAP:    /* get accent key translation table */
865                 bcopy(kbd->kb_accentmap, arg, sizeof(*kbd->kb_accentmap));
866                 break;
867         case PIO_DEADKEYMAP:    /* set accent key translation table */
868 #ifndef KBD_DISABLE_KEYMAP_LOAD
869                 bcopy(arg, kbd->kb_accentmap, sizeof(*kbd->kb_accentmap));
870                 break;
871 #else
872                 crit_exit();
873                 return ENODEV;
874 #endif
875
876         case GETFKEY:           /* get functionkey string */
877                 fkeyp = (fkeyarg_t *)arg;
878                 if (fkeyp->keynum >= kbd->kb_fkeytab_size) {
879                         crit_exit();
880                         return EINVAL;
881                 }
882                 bcopy(kbd->kb_fkeytab[fkeyp->keynum].str, fkeyp->keydef,
883                       kbd->kb_fkeytab[fkeyp->keynum].len);
884                 fkeyp->flen = kbd->kb_fkeytab[fkeyp->keynum].len;
885                 break;
886         case SETFKEY:           /* set functionkey string */
887 #ifndef KBD_DISABLE_KEYMAP_LOAD
888                 fkeyp = (fkeyarg_t *)arg;
889                 if (fkeyp->keynum >= kbd->kb_fkeytab_size) {
890                         crit_exit();
891                         return EINVAL;
892                 }
893                 kbd->kb_fkeytab[fkeyp->keynum].len = imin(fkeyp->flen, MAXFK);
894                 bcopy(fkeyp->keydef, kbd->kb_fkeytab[fkeyp->keynum].str,
895                       kbd->kb_fkeytab[fkeyp->keynum].len);
896                 break;
897 #else
898                 crit_exit();
899                 return ENODEV;
900 #endif
901
902         default:
903                 crit_exit();
904                 return ENOIOCTL;
905         }
906
907         crit_exit();
908         return 0;
909 }
910
911 /* get a pointer to the string associated with the given function key */
912 u_char *
913 genkbd_get_fkeystr(keyboard_t *kbd, int fkey, size_t *len)
914 {
915         if (kbd == NULL)
916                 return NULL;
917         fkey -= F_FN;
918         if (fkey > kbd->kb_fkeytab_size)
919                 return NULL;
920         *len = kbd->kb_fkeytab[fkey].len;
921         return kbd->kb_fkeytab[fkey].str;
922 }
923
924 /* diagnostic dump */
925 static char *
926 get_kbd_type_name(int type)
927 {
928         static struct {
929                 int type;
930                 char *name;
931         } name_table[] = {
932                 { KB_84,        "AT 84" },
933                 { KB_101,       "AT 101/102" },
934                 { KB_OTHER,     "generic" },
935         };
936         int i;
937
938         for (i = 0; i < sizeof(name_table)/sizeof(name_table[0]); ++i) {
939                 if (type == name_table[i].type)
940                         return name_table[i].name;
941         }
942         return "unknown";
943 }
944
945 void
946 genkbd_diag(keyboard_t *kbd, int level)
947 {
948         if (level > 0) {
949                 kprintf("kbd%d: %s%d, %s (%d), config:0x%x, flags:0x%x", 
950                        kbd->kb_index, kbd->kb_name, kbd->kb_unit,
951                        get_kbd_type_name(kbd->kb_type), kbd->kb_type,
952                        kbd->kb_config, kbd->kb_flags);
953                 if (kbd->kb_io_base > 0)
954                         kprintf(", port:0x%x-0x%x", kbd->kb_io_base, 
955                                kbd->kb_io_base + kbd->kb_io_size - 1);
956                 kprintf("\n");
957         }
958 }
959
960 #define set_lockkey_state(k, s, l)                              \
961         if (!((s) & l ## DOWN)) {                               \
962                 int i;                                          \
963                 (s) |= l ## DOWN;                               \
964                 (s) ^= l ## ED;                                 \
965                 i = (s) & LOCK_MASK;                            \
966                 (*kbdsw[(k)->kb_index]->ioctl)((k), KDSETLED, (caddr_t)&i); \
967         }
968
969 static u_int
970 save_accent_key(keyboard_t *kbd, u_int key, int *accents)
971 {
972         int i;
973
974         /* make an index into the accent map */
975         i = key - F_ACC + 1;
976         if ((i > kbd->kb_accentmap->n_accs)
977             || (kbd->kb_accentmap->acc[i - 1].accchar == 0)) {
978                 /* the index is out of range or pointing to an empty entry */
979                 *accents = 0;
980                 return ERRKEY;
981         }
982
983         /* 
984          * If the same accent key has been hit twice, produce the accent char
985          * itself.
986          */
987         if (i == *accents) {
988                 key = kbd->kb_accentmap->acc[i - 1].accchar;
989                 *accents = 0;
990                 return key;
991         }
992
993         /* remember the index and wait for the next key  */
994         *accents = i; 
995         return NOKEY;
996 }
997
998 static u_int
999 make_accent_char(keyboard_t *kbd, u_int ch, int *accents)
1000 {
1001         struct acc_t *acc;
1002         int i;
1003
1004         acc = &kbd->kb_accentmap->acc[*accents - 1];
1005         *accents = 0;
1006
1007         /* 
1008          * If the accent key is followed by the space key,
1009          * produce the accent char itself.
1010          */
1011         if (ch == ' ')
1012                 return acc->accchar;
1013
1014         /* scan the accent map */
1015         for (i = 0; i < NUM_ACCENTCHARS; ++i) {
1016                 if (acc->map[i][0] == 0)        /* end of table */
1017                         break;
1018                 if (acc->map[i][0] == ch)
1019                         return acc->map[i][1];
1020         }
1021         /* this char cannot be accented... */
1022         return ERRKEY;
1023 }
1024
1025 int
1026 genkbd_keyaction(keyboard_t *kbd, int keycode, int up, int *shiftstate,
1027                  int *accents)
1028 {
1029         struct keyent_t *key;
1030         int state = *shiftstate;
1031         int action;
1032         int f;
1033         int i;
1034
1035         i = keycode;
1036         f = state & (AGRS | ALKED);
1037         if ((f == AGRS1) || (f == AGRS2) || (f == ALKED))
1038                 i += ALTGR_OFFSET;
1039         key = &kbd->kb_keymap->key[i];
1040         i = ((state & SHIFTS) ? 1 : 0)
1041             | ((state & CTLS) ? 2 : 0)
1042             | ((state & ALTS) ? 4 : 0);
1043         if (((key->flgs & FLAG_LOCK_C) && (state & CLKED))
1044                 || ((key->flgs & FLAG_LOCK_N) && (state & NLKED)) )
1045                 i ^= 1;
1046
1047         if (up) {       /* break: key released */
1048                 action = kbd->kb_lastact[keycode];
1049                 kbd->kb_lastact[keycode] = NOP;
1050                 switch (action) {
1051                 case LSHA:
1052                         if (state & SHIFTAON) {
1053                                 set_lockkey_state(kbd, state, ALK);
1054                                 state &= ~ALKDOWN;
1055                         }
1056                         action = LSH;
1057                         /* FALL THROUGH */
1058                 case LSH:
1059                         state &= ~SHIFTS1;
1060                         break;
1061                 case RSHA:
1062                         if (state & SHIFTAON) {
1063                                 set_lockkey_state(kbd, state, ALK);
1064                                 state &= ~ALKDOWN;
1065                         }
1066                         action = RSH;
1067                         /* FALL THROUGH */
1068                 case RSH:
1069                         state &= ~SHIFTS2;
1070                         break;
1071                 case LCTRA:
1072                         if (state & SHIFTAON) {
1073                                 set_lockkey_state(kbd, state, ALK);
1074                                 state &= ~ALKDOWN;
1075                         }
1076                         action = LCTR;
1077                         /* FALL THROUGH */
1078                 case LCTR:
1079                         state &= ~CTLS1;
1080                         break;
1081                 case RCTRA:
1082                         if (state & SHIFTAON) {
1083                                 set_lockkey_state(kbd, state, ALK);
1084                                 state &= ~ALKDOWN;
1085                         }
1086                         action = RCTR;
1087                         /* FALL THROUGH */
1088                 case RCTR:
1089                         state &= ~CTLS2;
1090                         break;
1091                 case LALTA:
1092                         if (state & SHIFTAON) {
1093                                 set_lockkey_state(kbd, state, ALK);
1094                                 state &= ~ALKDOWN;
1095                         }
1096                         action = LALT;
1097                         /* FALL THROUGH */
1098                 case LALT:
1099                         state &= ~ALTS1;
1100                         break;
1101                 case RALTA:
1102                         if (state & SHIFTAON) {
1103                                 set_lockkey_state(kbd, state, ALK);
1104                                 state &= ~ALKDOWN;
1105                         }
1106                         action = RALT;
1107                         /* FALL THROUGH */
1108                 case RALT:
1109                         state &= ~ALTS2;
1110                         break;
1111                 case ASH:
1112                         state &= ~AGRS1;
1113                         break;
1114                 case META:
1115                         state &= ~METAS1;
1116                         break;
1117                 case NLK:
1118                         state &= ~NLKDOWN;
1119                         break;
1120                 case CLK:
1121                         state &= ~CLKDOWN;
1122                         break;
1123                 case SLK:
1124                         state &= ~SLKDOWN;
1125                         break;
1126                 case ALK:
1127                         state &= ~ALKDOWN;
1128                         break;
1129                 case NOP:
1130                         /* release events of regular keys are not reported */
1131                         *shiftstate &= ~SHIFTAON;
1132                         return NOKEY;
1133                 }
1134                 *shiftstate = state & ~SHIFTAON;
1135                 return (SPCLKEY | RELKEY | action);
1136         } else {        /* make: key pressed */
1137                 action = key->map[i];
1138                 state &= ~SHIFTAON;
1139                 if (key->spcl & (0x80 >> i)) {
1140                         /* special keys */
1141                         if (kbd->kb_lastact[keycode] == NOP)
1142                                 kbd->kb_lastact[keycode] = action;
1143                         if (kbd->kb_lastact[keycode] != action)
1144                                 action = NOP;
1145                         switch (action) {
1146                         /* LOCKING KEYS */
1147                         case NLK:
1148                                 set_lockkey_state(kbd, state, NLK);
1149                                 break;
1150                         case CLK:
1151                                 set_lockkey_state(kbd, state, CLK);
1152                                 break;
1153                         case SLK:
1154                                 set_lockkey_state(kbd, state, SLK);
1155                                 break;
1156                         case ALK:
1157                                 set_lockkey_state(kbd, state, ALK);
1158                                 break;
1159                         /* NON-LOCKING KEYS */
1160                         case SPSC: case RBT:  case SUSP: case STBY:
1161                         case DBG:  case NEXT: case PREV: case PNC:
1162                         case HALT: case PDWN:
1163                                 *accents = 0;
1164                                 break;
1165                         case BTAB:
1166                                 *accents = 0;
1167                                 action |= BKEY;
1168                                 break;
1169                         case LSHA:
1170                                 state |= SHIFTAON;
1171                                 action = LSH;
1172                                 /* FALL THROUGH */
1173                         case LSH:
1174                                 state |= SHIFTS1;
1175                                 break;
1176                         case RSHA:
1177                                 state |= SHIFTAON;
1178                                 action = RSH;
1179                                 /* FALL THROUGH */
1180                         case RSH:
1181                                 state |= SHIFTS2;
1182                                 break;
1183                         case LCTRA:
1184                                 state |= SHIFTAON;
1185                                 action = LCTR;
1186                                 /* FALL THROUGH */
1187                         case LCTR:
1188                                 state |= CTLS1;
1189                                 break;
1190                         case RCTRA:
1191                                 state |= SHIFTAON;
1192                                 action = RCTR;
1193                                 /* FALL THROUGH */
1194                         case RCTR:
1195                                 state |= CTLS2;
1196                                 break;
1197                         case LALTA:
1198                                 state |= SHIFTAON;
1199                                 action = LALT;
1200                                 /* FALL THROUGH */
1201                         case LALT:
1202                                 state |= ALTS1;
1203                                 break;
1204                         case RALTA:
1205                                 state |= SHIFTAON;
1206                                 action = RALT;
1207                                 /* FALL THROUGH */
1208                         case RALT:
1209                                 state |= ALTS2;
1210                                 break;
1211                         case ASH:
1212                                 state |= AGRS1;
1213                                 break;
1214                         case META:
1215                                 state |= METAS1;
1216                                 break;
1217                         case NOP:
1218                                 *shiftstate = state;
1219                                 return NOKEY;
1220                         default:
1221                                 /* is this an accent (dead) key? */
1222                                 *shiftstate = state;
1223                                 if (action >= F_ACC && action <= L_ACC) {
1224                                         action = save_accent_key(kbd, action,
1225                                                                  accents);
1226                                         switch (action) {
1227                                         case NOKEY:
1228                                         case ERRKEY:
1229                                                 return action;
1230                                         default:
1231                                                 if (state & METAS)
1232                                                         return (action | MKEY);
1233                                                 else
1234                                                         return action;
1235                                         }
1236                                         /* NOT REACHED */
1237                                 }
1238                                 /* other special keys */
1239                                 if (*accents > 0) {
1240                                         *accents = 0;
1241                                         return ERRKEY;
1242                                 }
1243                                 if (action >= F_FN && action <= L_FN)
1244                                         action |= FKEY;
1245                                 /* XXX: return fkey string for the FKEY? */
1246                                 return (SPCLKEY | action);
1247                         }
1248                         *shiftstate = state;
1249                         return (SPCLKEY | action);
1250                 } else {
1251                         /* regular keys */
1252                         kbd->kb_lastact[keycode] = NOP;
1253                         *shiftstate = state;
1254                         if (*accents > 0) {
1255                                 /* make an accented char */
1256                                 action = make_accent_char(kbd, action, accents);
1257                                 if (action == ERRKEY)
1258                                         return action;
1259                         }
1260                         if (state & METAS)
1261                                 action |= MKEY;
1262                         return action;
1263                 }
1264         }
1265         /* NOT REACHED */
1266 }