xref: /dragonfly/sys/dev/misc/kbd/atkbd.c (revision a162a738eca94f99d45d88429e86cfd0fbfbe95d)
1 /*-
2  * (MPSAFE)
3  *
4  * Copyright (c) 1999 Kazutaka YOKOTA <yokota@zodiac.mech.utsunomiya-u.ac.jp>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer as
12  *    the first lines of this file unmodified.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * $FreeBSD: src/sys/dev/kbd/atkbd.c,v 1.25.2.4 2002/04/08 19:21:38 asmodai Exp $
29  */
30 /*
31  * NOTE: All locks are handled by the kbd wrappers.
32  */
33 
34 #include "opt_kbd.h"
35 #include "opt_atkbd.h"
36 #include "opt_evdev.h"
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/bus.h>
42 #include <sys/proc.h>
43 #include <sys/malloc.h>
44 #include <sys/sysctl.h>
45 #include <sys/thread2.h>
46 
47 #include <sys/kbio.h>
48 #include "kbdreg.h"
49 #include "atkbdreg.h"
50 #include "atkbdcreg.h"
51 
52 #include <bus/isa/isareg.h>
53 
54 #ifdef EVDEV_SUPPORT
55 #include <dev/misc/evdev/evdev.h>
56 #include <dev/misc/evdev/input.h>
57 #endif
58 
59 typedef struct atkbd_state {
60           KBDC                kbdc;               /* keyboard controller */
61           int                 ks_mode;  /* input mode (K_XLATE,K_RAW,K_CODE) */
62           int                 ks_flags; /* flags */
63 #define COMPOSE               (1 << 0)
64           int                 ks_polling;
65           int                 ks_state; /* shift/lock key state */
66           int                 ks_accents;         /* accent key index (> 0) */
67           u_int               ks_composed_char; /* composed char code (> 0) */
68           u_char              ks_prefix;          /* AT scan code prefix */
69 #ifdef EVDEV_SUPPORT
70           struct evdev_dev *ks_evdev;
71           int                 ks_evdev_state;
72 #endif
73 } atkbd_state_t;
74 
75 static SYSCTL_NODE(_hw, OID_AUTO, atkbd, CTLFLAG_RD, 0, "AT keyboard");
76 
77 static int atkbdhz = 0;
78 
79 TUNABLE_INT("hw.atkbd.hz", &atkbdhz);
80 SYSCTL_INT(_hw_atkbd, OID_AUTO, hz, CTLFLAG_RW, &atkbdhz, 0,
81     "Polling frequency (in hz)");
82 
83 
84 static void                   atkbd_timeout(void *arg);
85 static int                    atkbd_reset(KBDC kbdc, int flags, int c);
86 
87 #define HAS_QUIRK(p, q)                 (((atkbdc_softc_t *)(p))->quirks & q)
88 #define ALLOW_DISABLE_KBD(kbdc)         !HAS_QUIRK(kbdc, KBDC_QUIRK_KEEP_ACTIVATED)
89 
90 #define DEFAULT_DELAY                   0x1  /* 500ms */
91 #define DEFAULT_RATE                    0x10 /* 14Hz */
92 
93 #ifdef EVDEV_SUPPORT
94 #define PS2_KEYBOARD_VENDOR   1
95 #define PS2_KEYBOARD_PRODUCT  1
96 #endif
97 
98 int
atkbd_probe_unit(int unit,int ctlr,int irq,int flags)99 atkbd_probe_unit(int unit, int ctlr, int irq, int flags)
100 {
101           keyboard_switch_t *sw;
102           int args[2];
103           int error;
104 
105           sw = kbd_get_switch(ATKBD_DRIVER_NAME);
106           if (sw == NULL) {
107                     return ENXIO;
108           }
109 
110           args[0] = ctlr;
111           args[1] = irq;
112           error = (*sw->probe)(unit, args, flags);
113 
114           if (error)
115                     return error;
116           return 0;
117 }
118 
119 int
atkbd_attach_unit(int unit,keyboard_t ** kbd,int ctlr,int irq,int flags)120 atkbd_attach_unit(int unit, keyboard_t **kbd, int ctlr, int irq, int flags)
121 {
122           keyboard_switch_t *sw;
123           int args[2];
124           int error;
125 
126           sw = kbd_get_switch(ATKBD_DRIVER_NAME);
127           if (sw == NULL) {
128                     return ENXIO;
129           }
130 
131           /* reset, initialize and enable the device */
132           args[0] = ctlr;
133           args[1] = irq;
134           *kbd = NULL;
135           error = (*sw->probe)(unit, args, flags);
136           if (error) {
137                     return error;
138           }
139           error = (*sw->init)(unit, kbd, args, flags);
140           if (error) {
141                     return error;
142           }
143           (*sw->enable)(*kbd);
144 
145 #ifdef KBD_INSTALL_CDEV
146           /* attach a virtual keyboard cdev */
147           error = kbd_attach(*kbd);
148           if (error) {
149                     return error;
150           }
151 #endif
152 
153           /*
154            * This is a kludge to compensate for lost keyboard interrupts.
155            * A similar code used to be in syscons. See below. XXX
156            */
157           atkbd_timeout(*kbd);
158 
159           if (bootverbose)
160                     (*sw->diag)(*kbd, bootverbose);
161 
162           return 0;
163 }
164 
165 static void
atkbd_timeout(void * arg)166 atkbd_timeout(void *arg)
167 {
168           keyboard_t *kbd;
169 
170           /*
171            * The original text of the following comments are extracted
172            * from syscons.c (1.287)
173            *
174            * With release 2.1 of the Xaccel server, the keyboard is left
175            * hanging pretty often. Apparently an interrupt from the
176            * keyboard is lost, and I don't know why (yet).
177            * This ugly hack calls the low-level interrupt routine if input
178            * is ready for the keyboard and conveniently hides the problem. XXX
179            *
180            * Try removing anything stuck in the keyboard controller; whether
181            * it's a keyboard scan code or mouse data. The low-level
182            * interrupt routine doesn't read the mouse data directly,
183            * but the keyboard controller driver will, as a side effect.
184            */
185           /*
186            * And here is bde's original comment about this:
187            *
188            * This is necessary to handle edge triggered interrupts - if we
189            * returned when our IRQ is high due to unserviced input, then there
190            * would be no more keyboard IRQs until the keyboard is reset by
191            * external powers.
192            *
193            * The keyboard apparently unwedges the irq in most cases.
194            */
195           crit_enter();
196           kbd = (keyboard_t *)arg;
197           if (kbd_lock(kbd, TRUE)) {
198                     /*
199                      * We have seen the lock flag is not set. Let's reset
200                      * the flag early, otherwise the LED update routine fails
201                      * which may want the lock during the interrupt routine.
202                      */
203                     kbd_lock(kbd, FALSE);
204                     if (kbd_check_char(kbd))
205                               kbd_intr(kbd, NULL);
206           }
207           if (atkbdhz > 0) {
208                     callout_reset(&kbd->kb_atkbd_timeout_ch, hz / atkbdhz,
209                                         atkbd_timeout, arg);
210           }
211           crit_exit();
212 }
213 
214 /* LOW-LEVEL */
215 
216 #include <machine/limits.h>
217 #include <machine/clock.h>
218 
219 #define ATKBD_DEFAULT         0
220 
221 
222 /* keyboard driver declaration */
223 static int                    atkbd_configure(int flags);
224 static kbd_probe_t  atkbd_probe;
225 static kbd_init_t   atkbd_init;
226 static kbd_term_t   atkbd_term;
227 static kbd_intr_t   atkbd_intr;
228 static kbd_test_if_t          atkbd_test_if;
229 static kbd_enable_t atkbd_enable;
230 static kbd_disable_t          atkbd_disable;
231 static kbd_read_t   atkbd_read;
232 static kbd_check_t  atkbd_check;
233 static kbd_read_char_t        atkbd_read_char;
234 static kbd_check_char_t       atkbd_check_char;
235 static kbd_ioctl_t  atkbd_ioctl;
236 static kbd_lock_t   atkbd_lock;
237 static kbd_clear_state_t atkbd_clear_state;
238 static kbd_get_state_t        atkbd_get_state;
239 static kbd_set_state_t        atkbd_set_state;
240 static kbd_poll_mode_t        atkbd_poll;
241 
242 static keyboard_switch_t atkbdsw = {
243           .probe =  atkbd_probe,
244           .init =             atkbd_init,
245           .term =             atkbd_term,
246           .intr =             atkbd_intr,
247           .test_if =          atkbd_test_if,
248           .enable = atkbd_enable,
249           .disable =          atkbd_disable,
250           .read =             atkbd_read,
251           .check =  atkbd_check,
252           .read_char =        atkbd_read_char,
253           .check_char =       atkbd_check_char,
254           .ioctl =  atkbd_ioctl,
255           .lock =             atkbd_lock,
256           .clear_state =      atkbd_clear_state,
257           .get_state =        atkbd_get_state,
258           .set_state =        atkbd_set_state,
259           .get_fkeystr =      genkbd_get_fkeystr,
260           .poll =             atkbd_poll,
261           .diag =             genkbd_diag,
262 };
263 
264 KEYBOARD_DRIVER(atkbd, atkbdsw, atkbd_configure);
265 
266 /* local functions */
267 static int                    set_typematic(keyboard_t *kbd);
268 static int                    setup_kbd_port(KBDC kbdc, int port, int intr);
269 static int                    get_kbd_echo(KBDC kbdc);
270 static int                    probe_keyboard(KBDC kbdc, int flags);
271 static int                    init_keyboard(KBDC kbdc, int *type, int flags);
272 static int                    write_kbd(KBDC kbdc, int command, int data);
273 static int                    get_kbd_id(KBDC kbdc);
274 static int                    typematic(int delay, int rate);
275 static int                    typematic_delay(int delay);
276 static int                    typematic_rate(int rate);
277 
278 #ifdef EVDEV_SUPPORT
279 static evdev_event_t atkbd_ev_event;
280 
281 static const struct evdev_methods atkbd_evdev_methods = {
282           .ev_event = atkbd_ev_event,
283 };
284 #endif
285 
286 /* local variables */
287 
288 /* the initial key map, accent map and fkey strings */
289 #ifdef ATKBD_DFLT_KEYMAP
290 #define KBD_DFLT_KEYMAP
291 #include "atkbdmap.h"
292 #endif
293 #include "kbdtables.h"
294 
295 /* structures for the default keyboard */
296 static keyboard_t   default_kbd;
297 static atkbd_state_t          default_kbd_state;
298 static keymap_t               default_keymap;
299 static accentmap_t  default_accentmap;
300 static fkeytab_t    default_fkeytab[NUM_FKEYS];
301 
302 /*
303  * The back door to the keyboard driver!
304  * This function is called by the console driver, via the kbdio module,
305  * to tickle keyboard drivers when the low-level console is being initialized.
306  * Almost nothing in the kernel has been initialied yet.  Try to probe
307  * keyboards if possible.
308  * NOTE: because of the way the low-level console is initialized, this routine
309  * may be called more than once!!
310  */
311 static int
atkbd_configure(int flags)312 atkbd_configure(int flags)
313 {
314           keyboard_t *kbd;
315           int arg[2];
316           int i;
317 
318           /*
319            * Probe the keyboard controller, if not present or if the driver
320            * is disabled, unregister the keyboard if any.
321            */
322           if (atkbdc_configure() != 0 ||
323               resource_disabled("atkbd", ATKBD_DEFAULT)) {
324                     i = kbd_find_keyboard(ATKBD_DRIVER_NAME, ATKBD_DEFAULT);
325                     if (i >= 0) {
326                               kbd = kbd_get_keyboard(i);
327                               /* XXX */
328                               KBD_ALWAYS_LOCK(kbd);
329                               kbd_unregister(kbd);
330                               kbd->kb_flags &= ~KB_REGISTERED;
331                     }
332                     return 0;
333           }
334 
335           /* XXX: a kludge to obtain the device configuration flags */
336           if (resource_int_value("atkbd", ATKBD_DEFAULT, "flags", &i) == 0)
337                     flags |= i;
338 
339           /* probe the default keyboard */
340           arg[0] = -1;
341           arg[1] = -1;
342           kbd = NULL;
343           if (atkbd_probe(ATKBD_DEFAULT, arg, flags)) {
344                     return 0;
345           }
346           if (atkbd_init(ATKBD_DEFAULT, &kbd, arg, flags)) {
347                     return 0;
348           }
349 
350           /* return the number of found keyboards */
351           return 1;
352 }
353 
354 /* low-level functions */
355 
356 /* detect a keyboard */
357 static int
atkbd_probe(int unit,void * arg,int flags)358 atkbd_probe(int unit, void *arg, int flags)
359 {
360           KBDC kbdc;
361           int *data = (int *)arg;       /* data[0]: controller, data[1]: irq */
362 
363 
364           if (unit == ATKBD_DEFAULT) {
365                     if (KBD_IS_PROBED(&default_kbd)) {
366                               return 0;
367                     }
368           }
369 
370           kbdc = atkbdc_open(data[0]);
371           if (kbdc == NULL) {
372                     return ENXIO;
373           }
374           if (probe_keyboard(kbdc, flags)) {
375                     if (flags & KB_CONF_FAIL_IF_NO_KBD) {
376                               return ENXIO;
377                     }
378           }
379 
380           return 0;
381 }
382 
383 #ifdef EVDEV_SUPPORT
384   #if defined(__FreeBSD__)
385     #define KBD_EVDEV_REGISTER(evdev) evdev_register_mtx(evdev, &Giant)
386   #elif defined(__DragonFly__)
387     #define KBD_EVDEV_REGISTER(evdev) evdev_register(evdev)
388   #else
389     #error "FreeBSD or DragonFly expected"
390   #endif
391 #endif /* EVDEV_SUPPORT */
392 
393 /* reset and initialize the device */
394 static int
atkbd_init(int unit,keyboard_t ** kbdp,void * arg,int flags)395 atkbd_init(int unit, keyboard_t **kbdp, void *arg, int flags)
396 {
397           keyboard_t *kbd;
398           atkbd_state_t *state;
399           keymap_t *keymap;
400           accentmap_t *accmap;
401           fkeytab_t *fkeymap;
402           int fkeymap_size;
403           int delay[2];
404           int *data = (int *)arg;       /* data[0]: controller, data[1]: irq */
405           int error, needfree;
406 #ifdef EVDEV_SUPPORT
407           struct evdev_dev *evdev;
408           char phys_loc[8];
409 #endif
410 
411           /* XXX */
412           if (unit == ATKBD_DEFAULT) {
413                     *kbdp = kbd = &default_kbd;
414                     if (KBD_IS_INITIALIZED(kbd) && KBD_IS_CONFIGURED(kbd)) {
415                               return 0;
416                     }
417                     state = &default_kbd_state;
418                     keymap = &default_keymap;
419                     accmap = &default_accentmap;
420                     fkeymap = default_fkeytab;
421                     fkeymap_size = nitems(default_fkeytab);
422                     needfree = 0;
423           } else if (*kbdp == NULL) {
424                     *kbdp = kbd = kmalloc(sizeof(*kbd), M_DEVBUF, M_WAITOK|M_ZERO);
425                     state = kmalloc(sizeof(*state), M_DEVBUF, M_WAITOK|M_ZERO);
426                     keymap = kmalloc(sizeof(key_map), M_DEVBUF, M_WAITOK);
427                     accmap = kmalloc(sizeof(accent_map), M_DEVBUF, M_WAITOK);
428                     fkeymap = kmalloc(sizeof(fkey_tab), M_DEVBUF, M_WAITOK);
429                     fkeymap_size = nitems(fkey_tab);
430                     needfree = 1;
431                     if ((kbd == NULL) || (state == NULL) || (keymap == NULL)
432                          || (accmap == NULL) || (fkeymap == NULL)) {
433                               error = ENOMEM;
434                               goto bad;
435                     }
436           } else if (KBD_IS_INITIALIZED(*kbdp) && KBD_IS_CONFIGURED(*kbdp)) {
437                     return 0;
438           } else {
439                     kbd = *kbdp;
440                     state = (atkbd_state_t *)kbd->kb_data;
441                     bzero(state, sizeof(*state));
442                     keymap = kbd->kb_keymap;
443                     accmap = kbd->kb_accentmap;
444                     fkeymap = kbd->kb_fkeytab;
445                     fkeymap_size = kbd->kb_fkeytab_size;
446                     needfree = 0;
447           }
448 
449           if (!KBD_IS_PROBED(kbd)) {
450                     state->kbdc = atkbdc_open(data[0]);
451                     if (state->kbdc == NULL) {
452                               error = ENXIO;
453                               goto bad;
454                     }
455                     kbd_init_struct(kbd, ATKBD_DRIVER_NAME, KB_OTHER, unit, flags,
456                                         KB_PRI_ATKBD, 0, 0);
457                     bcopy(&key_map, keymap, sizeof(key_map));
458                     bcopy(&accent_map, accmap, sizeof(accent_map));
459                     bcopy(fkey_tab, fkeymap,
460                           imin(fkeymap_size*sizeof(fkeymap[0]), sizeof(fkey_tab)));
461                     kbd_set_maps(kbd, keymap, accmap, fkeymap, fkeymap_size);
462                     kbd->kb_data = (void *)state;
463 
464                     if (probe_keyboard(state->kbdc, flags)) { /* shouldn't happen */
465                               if (flags & KB_CONF_FAIL_IF_NO_KBD) {
466                                         error = ENXIO;
467                                         goto bad;
468                               }
469                     } else {
470                               KBD_FOUND_DEVICE(kbd);
471                     }
472                     atkbd_clear_state(kbd);
473                     state->ks_mode = K_XLATE;
474                     /*
475                      * FIXME: set the initial value for lock keys in ks_state
476                      * according to the BIOS data?
477                      */
478                     KBD_PROBE_DONE(kbd);
479           }
480           if (!KBD_IS_INITIALIZED(kbd) && !(flags & KB_CONF_PROBE_ONLY)) {
481                     kbd->kb_config = flags & ~KB_CONF_PROBE_ONLY;
482                     if (KBD_HAS_DEVICE(kbd)
483                         && init_keyboard(state->kbdc, &kbd->kb_type, kbd->kb_config)
484                         && (kbd->kb_config & KB_CONF_FAIL_IF_NO_KBD)) {
485                               kbd_unregister(kbd);
486                               error = ENXIO;
487                               goto bad;
488                     }
489                     atkbd_ioctl(kbd, KDSETLED, (caddr_t)&state->ks_state);
490                     set_typematic(kbd);
491                     delay[0] = kbd->kb_delay1;
492                     delay[1] = kbd->kb_delay2;
493                     atkbd_ioctl(kbd, KDSETREPEAT, (caddr_t)delay);
494 
495 #ifdef EVDEV_SUPPORT
496                     /* register as evdev provider on first init */
497                     if (state->ks_evdev == NULL) {
498                               ksnprintf(phys_loc, sizeof(phys_loc), "atkbd%d", unit);
499                               evdev = evdev_alloc();
500                               evdev_set_name(evdev, "AT keyboard");
501                               evdev_set_phys(evdev, phys_loc);
502                               evdev_set_id(evdev, BUS_I8042, PS2_KEYBOARD_VENDOR,
503                                   PS2_KEYBOARD_PRODUCT, 0);
504                               evdev_set_methods(evdev, kbd, &atkbd_evdev_methods);
505                               evdev_support_event(evdev, EV_SYN);
506                               evdev_support_event(evdev, EV_KEY);
507                               evdev_support_event(evdev, EV_LED);
508                               evdev_support_event(evdev, EV_REP);
509                               evdev_support_all_known_keys(evdev);
510                               evdev_support_led(evdev, LED_NUML);
511                               evdev_support_led(evdev, LED_CAPSL);
512                               evdev_support_led(evdev, LED_SCROLLL);
513 
514                               /*
515                                * NOTE: in freebsd, this depends on their Giant
516                                * mutex lock, discuss with the others which
517                                * locking would be best here
518                                */
519                               if (KBD_EVDEV_REGISTER(evdev))
520                                         evdev_free(evdev);
521                               else
522                                         state->ks_evdev = evdev;
523                               state->ks_evdev_state = 0;
524                     }
525 #endif
526 
527                     KBD_INIT_DONE(kbd);
528           }
529           if (!KBD_IS_CONFIGURED(kbd)) {
530                     if (kbd_register(kbd) < 0) {
531                               error = ENXIO;
532                               goto bad;
533                     }
534                     KBD_CONFIG_DONE(kbd);
535           }
536 
537           return 0;
538 bad:
539           if (needfree) {
540                     if (state != NULL)
541                               kfree(state, M_DEVBUF);
542                     if (keymap != NULL)
543                               kfree(keymap, M_DEVBUF);
544                     if (accmap != NULL)
545                               kfree(accmap, M_DEVBUF);
546                     if (fkeymap != NULL)
547                               kfree(fkeymap, M_DEVBUF);
548                     if (kbd != NULL) {
549                               kfree(kbd, M_DEVBUF);
550                               *kbdp = NULL;       /* insure ref doesn't leak to caller */
551                     }
552           }
553 
554           return error;
555 }
556 
557 /* finish using this keyboard */
558 static int
atkbd_term(keyboard_t * kbd)559 atkbd_term(keyboard_t *kbd)
560 {
561 #ifdef EVDEV_SUPPORT
562           atkbd_state_t *state = (atkbd_state_t *)kbd->kb_data;
563 
564           if(state->ks_evdev) {
565                     evdev_free(state->ks_evdev);
566                     state->ks_evdev = NULL;
567                     state->ks_evdev_state = 0;
568           }
569 #endif
570 
571           kbd_unregister(kbd);
572           return 0;
573 }
574 
575 /* keyboard interrupt routine */
576 static int
atkbd_intr(keyboard_t * kbd,void * arg)577 atkbd_intr(keyboard_t *kbd, void *arg)
578 {
579           atkbd_state_t *state = (atkbd_state_t *)kbd->kb_data;
580           int delay[2];
581           int c;
582 
583           if (!KBD_HAS_DEVICE(kbd)) {
584                     /*
585                      * The keyboard was not detected before;
586                      * it must have been reconnected!
587                      */
588                     init_keyboard(state->kbdc, &kbd->kb_type, kbd->kb_config);
589                     KBD_FOUND_DEVICE(kbd);
590                     atkbd_ioctl(kbd, KDSETLED, (caddr_t)&state->ks_state);
591                     set_typematic(kbd);
592                     delay[0] = kbd->kb_delay1;
593                     delay[1] = kbd->kb_delay2;
594                     atkbd_ioctl(kbd, KDSETREPEAT, (caddr_t)delay);
595           }
596 
597           if (state->ks_polling)
598                     return 0;
599 
600           if (KBD_IS_ACTIVE(kbd) && KBD_IS_BUSY(kbd)) {
601                     /* let the callback function to process the input */
602                     (*kbd->kb_callback.kc_func)(kbd, KBDIO_KEYINPUT,
603                                                       kbd->kb_callback.kc_arg);
604           } else {
605                     /* read and discard the input; no one is waiting for input */
606                     do {
607                               c = atkbd_read_char(kbd, FALSE);
608                     } while (c != NOKEY);
609           }
610 
611           return 0;
612 }
613 
614 /* test the interface to the device */
615 static int
atkbd_test_if(keyboard_t * kbd)616 atkbd_test_if(keyboard_t *kbd)
617 {
618           int error;
619 
620           error = 0;
621           empty_both_buffers(((atkbd_state_t *)kbd->kb_data)->kbdc, 10);
622           crit_enter();
623           if (!test_controller(((atkbd_state_t *)kbd->kb_data)->kbdc))
624                     error = EIO;
625           else if (test_kbd_port(((atkbd_state_t *)kbd->kb_data)->kbdc) != 0)
626                     error = EIO;
627           crit_exit();
628 
629           return error;
630 }
631 
632 /*
633  * Enable the access to the device; until this function is called,
634  * the client cannot read from the keyboard.
635  */
636 static int
atkbd_enable(keyboard_t * kbd)637 atkbd_enable(keyboard_t *kbd)
638 {
639           crit_enter();
640           KBD_ACTIVATE(kbd);
641           crit_exit();
642           return 0;
643 }
644 
645 /* disallow the access to the device */
646 static int
atkbd_disable(keyboard_t * kbd)647 atkbd_disable(keyboard_t *kbd)
648 {
649           crit_enter();
650           KBD_DEACTIVATE(kbd);
651           crit_exit();
652           return 0;
653 }
654 
655 /* read one byte from the keyboard if it's allowed */
656 static int
atkbd_read(keyboard_t * kbd,int wait)657 atkbd_read(keyboard_t *kbd, int wait)
658 {
659           int c, ret;
660 
661           if (wait)
662                     c = read_kbd_data(((atkbd_state_t *)kbd->kb_data)->kbdc);
663           else
664                     c = read_kbd_data_no_wait(((atkbd_state_t *)kbd->kb_data)->kbdc);
665           if (c != -1)
666                     ++kbd->kb_count;
667 
668           ret = (KBD_IS_ACTIVE(kbd) ? c : -1);
669 
670           return ret;
671 }
672 
673 /* check if data is waiting */
674 static int
atkbd_check(keyboard_t * kbd)675 atkbd_check(keyboard_t *kbd)
676 {
677           int ret;
678 
679           if (!KBD_IS_ACTIVE(kbd)) {
680                     return FALSE;
681           }
682           ret = kbdc_data_ready(((atkbd_state_t *)kbd->kb_data)->kbdc);
683 
684           return ret;
685 }
686 
687 /* read char from the keyboard */
688 static u_int
atkbd_read_char(keyboard_t * kbd,int wait)689 atkbd_read_char(keyboard_t *kbd, int wait)
690 {
691           atkbd_state_t *state;
692           u_int action;
693           int scancode;
694           int keycode;
695 
696           state = (atkbd_state_t *)kbd->kb_data;
697 next_code:
698           /* do we have a composed char to return? */
699           if (!(state->ks_flags & COMPOSE) && (state->ks_composed_char > 0)) {
700                     action = state->ks_composed_char;
701                     state->ks_composed_char = 0;
702                     if (action > UCHAR_MAX) {
703                               return ERRKEY;
704                     }
705                     return action;
706           }
707 
708           /* see if there is something in the keyboard port */
709           if (wait) {
710                     do {
711                               scancode = read_kbd_data(state->kbdc);
712                     } while (scancode == -1);
713           } else {
714                     scancode = read_kbd_data_no_wait(state->kbdc);
715                     if (scancode == -1) {
716                               return NOKEY;
717                     }
718           }
719           ++kbd->kb_count;
720 
721 #if KBDIO_DEBUG >= 10
722           kprintf("atkbd_read_char(): scancode:0x%x\n", scancode);
723 #endif
724 #ifdef EVDEV_SUPPORT
725           /* push evdev event */
726           if (evdev_rcpt_mask & EVDEV_RCPT_HW_KBD && state->ks_evdev != NULL) {
727                     /* "hancha" and "han/yong" korean keys handling */
728                     if (state->ks_evdev_state == 0 &&
729                         (scancode == 0xF1 || scancode == 0xF2)) {
730                               keycode = evdev_scancode2key(&state->ks_evdev_state,
731                                         scancode & 0x7F);
732                               evdev_push_event(state->ks_evdev, EV_KEY,
733                                   (uint16_t)keycode, 1);
734                               evdev_sync(state->ks_evdev);
735                     }
736 
737                     keycode = evdev_scancode2key(&state->ks_evdev_state,
738                         scancode);
739 
740                     if (keycode != KEY_RESERVED) {
741                               evdev_push_event(state->ks_evdev, EV_KEY,
742                                   (uint16_t)keycode, scancode & 0x80 ? 0 : 1);
743                               evdev_sync(state->ks_evdev);
744                     }
745           }
746 
747           if (state->ks_evdev != NULL && evdev_is_grabbed(state->ks_evdev))
748                     return (NOKEY);
749 #endif
750 
751 
752           /* return the byte as is for the K_RAW mode */
753           if (state->ks_mode == K_RAW) {
754                     return scancode;
755           }
756 
757           /* translate the scan code into a keycode */
758           keycode = scancode & 0x7F;
759           switch (state->ks_prefix) {
760           case 0x00:          /* normal scancode */
761                     switch(scancode) {
762                     case 0xB8:          /* left alt (compose key) released */
763                               if (state->ks_flags & COMPOSE) {
764                                         state->ks_flags &= ~COMPOSE;
765                                         if (state->ks_composed_char > UCHAR_MAX)
766                                                   state->ks_composed_char = 0;
767                               }
768                               break;
769                     case 0x38:          /* left alt (compose key) pressed */
770                               if (!(state->ks_flags & COMPOSE)) {
771                                         state->ks_flags |= COMPOSE;
772                                         state->ks_composed_char = 0;
773                               }
774                               break;
775                     case 0xE0:
776                     case 0xE1:
777                               state->ks_prefix = scancode;
778                               goto next_code;
779                     }
780                     break;
781           case 0xE0:      /* 0xE0 prefix */
782                     state->ks_prefix = 0;
783                     switch (keycode) {
784                     case 0x1C:          /* right enter key */
785                               keycode = 0x59;
786                               break;
787                     case 0x1D:          /* right ctrl key */
788                               keycode = 0x5A;
789                               break;
790                     case 0x35:          /* keypad divide key */
791                               keycode = 0x5B;
792                               break;
793                     case 0x37:          /* print scrn key */
794                               keycode = 0x5C;
795                               break;
796                     case 0x38:          /* right alt key (alt gr) */
797                               keycode = 0x5D;
798                               break;
799                     case 0x46:          /* ctrl-pause/break on AT 101 (see below) */
800                               keycode = 0x68;
801                               break;
802                     case 0x47:          /* grey home key */
803                               keycode = 0x5E;
804                               break;
805                     case 0x48:          /* grey up arrow key */
806                               keycode = 0x5F;
807                               break;
808                     case 0x49:          /* grey page up key */
809                               keycode = 0x60;
810                               break;
811                     case 0x4B:          /* grey left arrow key */
812                               keycode = 0x61;
813                               break;
814                     case 0x4D:          /* grey right arrow key */
815                               keycode = 0x62;
816                               break;
817                     case 0x4F:          /* grey end key */
818                               keycode = 0x63;
819                               break;
820                     case 0x50:          /* grey down arrow key */
821                               keycode = 0x64;
822                               break;
823                     case 0x51:          /* grey page down key */
824                               keycode = 0x65;
825                               break;
826                     case 0x52:          /* grey insert key */
827                               keycode = 0x66;
828                               break;
829                     case 0x53:          /* grey delete key */
830                               keycode = 0x67;
831                               break;
832                     /* the following 3 are only used on the MS "Natural" keyboard */
833                     case 0x5b:          /* left Window key */
834                               keycode = 0x69;
835                               break;
836                     case 0x5c:          /* right Window key */
837                               keycode = 0x6a;
838                               break;
839                     case 0x5d:          /* menu key */
840                               keycode = 0x6b;
841                               break;
842                     case 0x5e:          /* power key */
843                               keycode = 0x6d;
844                               break;
845                     case 0x5f:          /* sleep key */
846                               keycode = 0x6e;
847                               break;
848                     case 0x63:          /* wake key */
849                               keycode = 0x6f;
850                               break;
851                     default:  /* ignore everything else */
852                               goto next_code;
853                     }
854                     break;
855           case 0xE1:          /* 0xE1 prefix */
856                     /*
857                      * The pause/break key on the 101 keyboard produces:
858                      * E1-1D-45 E1-9D-C5
859                      * Ctrl-pause/break produces:
860                      * E0-46 E0-C6 (See above.)
861                      */
862                     state->ks_prefix = 0;
863                     if (keycode == 0x1D)
864                               state->ks_prefix = 0x1D;
865                     goto next_code;
866                     /* NOT REACHED */
867           case 0x1D:          /* pause / break */
868                     state->ks_prefix = 0;
869                     if (keycode != 0x45)
870                               goto next_code;
871                     keycode = 0x68;
872                     break;
873           }
874 
875           if (kbd->kb_type == KB_84) {
876                     switch (keycode) {
877                     case 0x37:          /* *(numpad)/print screen */
878                               if (state->ks_flags & SHIFTS)
879                                         keycode = 0x5c;     /* print screen */
880                               break;
881                     case 0x45:          /* num lock/pause */
882                               if (state->ks_flags & CTLS)
883                                         keycode = 0x68;     /* pause */
884                               break;
885                     case 0x46:          /* scroll lock/break */
886                               if (state->ks_flags & CTLS)
887                                         keycode = 0x6c;     /* break */
888                               break;
889                     }
890           } else if (kbd->kb_type == KB_101) {
891                     switch (keycode) {
892                     case 0x5c:          /* print screen */
893                               if (state->ks_flags & ALTS)
894                                         keycode = 0x54;     /* sysrq */
895                               break;
896                     case 0x68:          /* pause/break */
897                               if (state->ks_flags & CTLS)
898                                         keycode = 0x6c;     /* break */
899                               break;
900                     }
901           }
902 
903           /* return the key code in the K_CODE mode */
904           if (state->ks_mode == K_CODE) {
905                     return (keycode | (scancode & 0x80));
906           }
907 
908           /* compose a character code */
909           if (state->ks_flags & COMPOSE) {
910                     switch (keycode | (scancode & 0x80)) {
911                     /* key pressed, process it */
912                     case 0x47: case 0x48: case 0x49:        /* keypad 7,8,9 */
913                               state->ks_composed_char *= 10;
914                               state->ks_composed_char += keycode - 0x40;
915                               if (state->ks_composed_char > UCHAR_MAX)
916                                         return ERRKEY;
917                               goto next_code;
918                     case 0x4B: case 0x4C: case 0x4D:        /* keypad 4,5,6 */
919                               state->ks_composed_char *= 10;
920                               state->ks_composed_char += keycode - 0x47;
921                               if (state->ks_composed_char > UCHAR_MAX)
922                                         return ERRKEY;
923                               goto next_code;
924                     case 0x4F: case 0x50: case 0x51:        /* keypad 1,2,3 */
925                               state->ks_composed_char *= 10;
926                               state->ks_composed_char += keycode - 0x4E;
927                               if (state->ks_composed_char > UCHAR_MAX)
928                                         return ERRKEY;
929                               goto next_code;
930                     case 0x52:                                        /* keypad 0 */
931                               state->ks_composed_char *= 10;
932                               if (state->ks_composed_char > UCHAR_MAX)
933                                         return ERRKEY;
934                               goto next_code;
935 
936                     /* key released, no interest here */
937                     case 0xC7: case 0xC8: case 0xC9:        /* keypad 7,8,9 */
938                     case 0xCB: case 0xCC: case 0xCD:        /* keypad 4,5,6 */
939                     case 0xCF: case 0xD0: case 0xD1:        /* keypad 1,2,3 */
940                     case 0xD2:                                        /* keypad 0 */
941                               goto next_code;
942 
943                     case 0x38:                                        /* left alt key */
944                               break;
945 
946                     default:
947                               if (state->ks_composed_char > 0) {
948                                         state->ks_flags &= ~COMPOSE;
949                                         state->ks_composed_char = 0;
950                                         return ERRKEY;
951                               }
952                               break;
953                     }
954           }
955 
956           /* keycode to key action */
957           action = genkbd_keyaction(kbd, keycode, scancode & 0x80,
958                                           &state->ks_state, &state->ks_accents);
959           if (action == NOKEY) {
960                     goto next_code;
961           } else {
962                     return action;
963           }
964 }
965 
966 /* check if char is waiting */
967 static int
atkbd_check_char(keyboard_t * kbd)968 atkbd_check_char(keyboard_t *kbd)
969 {
970           atkbd_state_t *state;
971 
972           if (!KBD_IS_ACTIVE(kbd)) {
973                     return FALSE;
974           }
975           state = (atkbd_state_t *)kbd->kb_data;
976           if (!(state->ks_flags & COMPOSE) && (state->ks_composed_char > 0)) {
977                     return TRUE;
978           }
979           return kbdc_data_ready(state->kbdc);
980 }
981 
982 /* some useful control functions */
983 static int
atkbd_ioctl(keyboard_t * kbd,u_long cmd,caddr_t arg)984 atkbd_ioctl(keyboard_t *kbd, u_long cmd, caddr_t arg)
985 {
986           /* translate LED_XXX bits into the device specific bits */
987           static u_char ledmap[8] = {
988                     0, 4, 2, 6, 1, 5, 3, 7,
989           };
990           atkbd_state_t *state = kbd->kb_data;
991           int error;
992           int i;
993 
994           crit_enter();
995 
996           switch (cmd) {
997 
998           case KDGKBMODE:               /* get keyboard mode */
999                     *(int *)arg = state->ks_mode;
1000                     break;
1001           case KDSKBMODE:               /* set keyboard mode */
1002                     switch (*(int *)arg) {
1003                     case K_XLATE:
1004                               if (state->ks_mode != K_XLATE) {
1005                                         /* make lock key state and LED state match */
1006                                         state->ks_state &= ~LOCK_MASK;
1007                                         state->ks_state |= KBD_LED_VAL(kbd);
1008                               }
1009                               /* FALL THROUGH */
1010                     case K_RAW:
1011                     case K_CODE:
1012                               if (state->ks_mode != *(int *)arg) {
1013                                         atkbd_clear_state(kbd);
1014                                         state->ks_mode = *(int *)arg;
1015                               }
1016                               break;
1017                     default:
1018                               crit_exit();
1019                               return EINVAL;
1020                     }
1021                     break;
1022 
1023           case KDGETLED:                /* get keyboard LED */
1024                     *(int *)arg = KBD_LED_VAL(kbd);
1025                     break;
1026           case KDSETLED:                /* set keyboard LED */
1027                     /* NOTE: lock key state in ks_state won't be changed */
1028                     if (*(int *)arg & ~LOCK_MASK) {
1029                               crit_exit();
1030                               return EINVAL;
1031                     }
1032                     i = *(int *)arg;
1033                     /* replace CAPS LED with ALTGR LED for ALTGR keyboards */
1034                     if (state->ks_mode == K_XLATE &&
1035                         kbd->kb_keymap->n_keys > ALTGR_OFFSET) {
1036                               if (i & ALKED)
1037                                         i |= CLKED;
1038                               else
1039                                         i &= ~CLKED;
1040                     }
1041                     if (KBD_HAS_DEVICE(kbd)) {
1042                               error = write_kbd(state->kbdc, KBDC_SET_LEDS,
1043                                                     ledmap[i & LED_MASK]);
1044                               if (error) {
1045                                         crit_exit();
1046                                         return error;
1047                               }
1048                     }
1049 #ifdef EVDEV_SUPPORT
1050                     /* push LED states to evdev */
1051                     if (state->ks_evdev != NULL &&
1052                         evdev_rcpt_mask & EVDEV_RCPT_HW_KBD)
1053                               evdev_push_leds(state->ks_evdev, *(int *)arg);
1054 #endif
1055                     KBD_LED_VAL(kbd) = *(int *)arg;
1056                     break;
1057 
1058           case KDGKBSTATE:    /* get lock key state */
1059                     *(int *)arg = state->ks_state & LOCK_MASK;
1060                     break;
1061           case KDSKBSTATE:    /* set lock key state */
1062                     if (*(int *)arg & ~LOCK_MASK) {
1063                               crit_exit();
1064                               return EINVAL;
1065                     }
1066                     state->ks_state &= ~LOCK_MASK;
1067                     state->ks_state |= *(int *)arg;
1068                     crit_exit();
1069                     /* set LEDs and quit */
1070                     return atkbd_ioctl(kbd, KDSETLED, arg);
1071 
1072           case KDSETREPEAT:   /* set keyboard repeat rate (new interface) */
1073                     crit_exit();
1074                     if (!KBD_HAS_DEVICE(kbd)) {
1075                               return 0;
1076                     }
1077                     i = typematic(((int *)arg)[0], ((int *)arg)[1]);
1078                     error = write_kbd(state->kbdc, KBDC_SET_TYPEMATIC, i);
1079                     if (error == 0) {
1080                               kbd->kb_delay1 = typematic_delay(i);
1081                               kbd->kb_delay2 = typematic_rate(i);
1082 #ifdef EVDEV_SUPPORT
1083                               if (state->ks_evdev != NULL &&
1084                                   evdev_rcpt_mask & EVDEV_RCPT_HW_KBD)
1085                                         evdev_push_repeats(state->ks_evdev, kbd);
1086 #endif
1087                     }
1088                     return error;
1089 
1090 #if 0 /* obsolete */
1091           case KDSETRAD:                /* set keyboard repeat rate (old interface) */
1092                     crit_exit();
1093                     if (!KBD_HAS_DEVICE(kbd))
1094                               return 0;
1095                     error = write_kbd(state->kbdc, KBDC_SET_TYPEMATIC, *(int *)arg);
1096                     if (error == 0) {
1097                               kbd->kb_delay1 = typematic_delay(*(int *)arg);
1098                               kbd->kb_delay2 = typematic_rate(*(int *)arg);
1099 #ifdef EVDEV_SUPPORT
1100                               if (state->ks_evdev != NULL &&
1101                                   evdev_rcpt_mask & EVDEV_RCPT_HW_KBD)
1102                                         evdev_push_repeats(state->ks_evdev, kbd);
1103 #endif
1104                     }
1105                     return error;
1106 #endif
1107 
1108           case PIO_KEYMAP:    /* set keyboard translation table */
1109           case PIO_KEYMAPENT: /* set keyboard translation table entry */
1110           case PIO_DEADKEYMAP:          /* set accent key translation table */
1111                     state->ks_accents = 0;
1112                     /* FALL THROUGH */
1113           default:
1114                     crit_exit();
1115                     return genkbd_commonioctl(kbd, cmd, arg);
1116           }
1117 
1118           crit_exit();
1119           return 0;
1120 }
1121 
1122 /* lock the access to the keyboard */
1123 static int
atkbd_lock(keyboard_t * kbd,int lock)1124 atkbd_lock(keyboard_t *kbd, int lock)
1125 {
1126           return kbdc_lock(((atkbd_state_t *)kbd->kb_data)->kbdc, lock);
1127 }
1128 
1129 /* clear the internal state of the keyboard */
1130 static void
atkbd_clear_state(keyboard_t * kbd)1131 atkbd_clear_state(keyboard_t *kbd)
1132 {
1133           atkbd_state_t *state;
1134 
1135           state = (atkbd_state_t *)kbd->kb_data;
1136           state->ks_flags = 0;
1137           state->ks_polling = 0;
1138           state->ks_state &= LOCK_MASK; /* preserve locking key state */
1139           state->ks_accents = 0;
1140           state->ks_composed_char = 0;
1141 #if 0
1142           state->ks_prefix = 0; /* XXX */
1143 #endif
1144 }
1145 
1146 /* save the internal state */
1147 static int
atkbd_get_state(keyboard_t * kbd,void * buf,size_t len)1148 atkbd_get_state(keyboard_t *kbd, void *buf, size_t len)
1149 {
1150           if (len == 0)
1151                     return sizeof(atkbd_state_t);
1152           if (len < sizeof(atkbd_state_t))
1153                     return -1;
1154 
1155           bcopy(kbd->kb_data, buf, sizeof(atkbd_state_t));
1156           return 0;
1157 }
1158 
1159 /* set the internal state */
1160 static int
atkbd_set_state(keyboard_t * kbd,void * buf,size_t len)1161 atkbd_set_state(keyboard_t *kbd, void *buf, size_t len)
1162 {
1163           if (len < sizeof(atkbd_state_t))
1164                     return ENOMEM;
1165           if (((atkbd_state_t *)kbd->kb_data)->kbdc
1166                     != ((atkbd_state_t *)buf)->kbdc)
1167                     return ENOMEM;
1168           bcopy(buf, kbd->kb_data, sizeof(atkbd_state_t));
1169           return 0;
1170 }
1171 
1172 static int
atkbd_poll(keyboard_t * kbd,int on)1173 atkbd_poll(keyboard_t *kbd, int on)
1174 {
1175           atkbd_state_t *state;
1176 
1177           state = (atkbd_state_t *)kbd->kb_data;
1178           crit_enter();
1179           if (on)
1180                     state->ks_polling = 1;
1181           else
1182                     state->ks_polling = 0;
1183           crit_exit();
1184           return 0;
1185 }
1186 
1187 static int
atkbd_reset(KBDC kbdc,int flags,int c)1188 atkbd_reset(KBDC kbdc, int flags, int c)
1189 {
1190           /* reset keyboard hardware */
1191           if (!(flags & KB_CONF_NO_RESET) && !reset_kbd(kbdc)) {
1192                     /*
1193                      * KEYBOARD ERROR
1194                      * Keyboard reset may fail either because the keyboard
1195                      * doen't exist, or because the keyboard doesn't pass
1196                      * the self-test, or the keyboard controller on the
1197                      * motherboard and the keyboard somehow fail to shake hands.
1198                      * It is just possible, particularly in the last case,
1199                      * that the keyboard controller may be left in a hung state.
1200                      * test_controller() and test_kbd_port() appear to bring
1201                      * the keyboard controller back (I don't know why and how,
1202                      * though.)
1203                      */
1204                     empty_both_buffers(kbdc, 10);
1205                     test_controller(kbdc);
1206                     test_kbd_port(kbdc);
1207                     /*
1208                      * We could disable the keyboard port and interrupt... but,
1209                      * the keyboard may still exist (see above).
1210                      */
1211                     set_controller_command_byte(kbdc,
1212                         ALLOW_DISABLE_KBD(kbdc) ? 0xff : KBD_KBD_CONTROL_BITS, c);
1213                     if (bootverbose)
1214                               kprintf("atkbd: failed to reset the keyboard.\n");
1215                     return (EIO);
1216           }
1217           return (0);
1218 }
1219 
1220 #ifdef EVDEV_SUPPORT
1221 static void
atkbd_ev_event(struct evdev_dev * evdev,uint16_t type,uint16_t code,int32_t value)1222 atkbd_ev_event(struct evdev_dev *evdev, uint16_t type, uint16_t code,
1223     int32_t value)
1224 {
1225           keyboard_t *kbd = evdev_get_softc(evdev);
1226 
1227           if (evdev_rcpt_mask & EVDEV_RCPT_HW_KBD &&
1228               (type == EV_LED || type == EV_REP)) {
1229                     /*
1230                      * NOTE: the current data writing part of kbd_ev_event() and its calls
1231                      * kbd_ioctl() performs a lockmgr lock per the KBD_LOCK macro,
1232                      * so unlike FreeBSD we don't lock here.
1233                      *
1234                      * Should the data writes in kbd_ev_event(), which is a completely FreeBSD ported
1235                      * function, ever change to encompass things outside of kbd_ioctl,
1236                      * then this needs to be redesigned or rethought, possibly by:
1237                      *
1238                      * setting a lockmgr(&kbd->kb_lock, LK_EXCLUSIVE)
1239                      * saving the KB_POLLING flag of kbd->kb_flags
1240                      * setting it
1241                      * doing our stuff in kbd_ev_event()
1242                      * and restoring the original KB_POLLING FLAG afterwards
1243                      * releasing the lockmgr() held lock
1244                      *
1245                      * KBD_LOCK defined at sys/dev/misc/kbd/kbdreg.h:137
1246                      * and works by checking if KB_POLLING is not set.
1247                      * This would obviously be quite a hack, if it were needed.
1248                      * Note by htse (harald.brinkhof@gmail.com).
1249                      */
1250 #if defined(__FreeBSD__)
1251                     mtx_lock(&Giant);
1252 #endif
1253 #if defined(__DragonFly__) && 0
1254                     if(!lockmgr(&kbd->kb_lock, LK_EXCLUSIVE)) {
1255                               /* save original flag */
1256                               int orig_is_polled = KBD_IS_POLLED(kbd);
1257                               /* set state to polling */
1258                               KBD_POLL(kbd);
1259 #endif
1260                     kbd_ev_event(kbd, type, code, value);
1261 #if defined(__FreeBSD__)
1262                     mtx_unlock(&Giant);
1263 #endif
1264 #if defined(__DragonFly__) && 0
1265                               /* restore original state if not polling */
1266                               if(orig_is_polled == 0)
1267                                         KBD_UNPOLL(kbd);
1268 
1269                               lockmgr(&kbd->kb_lock, LK_RELEASE);
1270                     }
1271 #endif
1272           }
1273 }
1274 #endif
1275 
1276 /* local functions */
1277 
1278 static int
set_typematic(keyboard_t * kbd)1279 set_typematic(keyboard_t *kbd)
1280 {
1281           int val, error;
1282           atkbd_state_t *state = kbd->kb_data;
1283 
1284           val = typematic(DEFAULT_DELAY, DEFAULT_RATE);
1285           error = write_kbd(state->kbdc, KBDC_SET_TYPEMATIC, val);
1286           if (error == 0) {
1287                     kbd->kb_delay1 = typematic_delay(val);
1288                     kbd->kb_delay2 = typematic_rate(val);
1289           }
1290 
1291           return (error);
1292 }
1293 
1294 static int
setup_kbd_port(KBDC kbdc,int port,int intr)1295 setup_kbd_port(KBDC kbdc, int port, int intr)
1296 {
1297           if (!set_controller_command_byte(kbdc,
1298                     KBD_KBD_CONTROL_BITS,
1299                     ((port) ? KBD_ENABLE_KBD_PORT : KBD_DISABLE_KBD_PORT)
1300                         | ((intr) ? KBD_ENABLE_KBD_INT : KBD_DISABLE_KBD_INT)))
1301                     return 1;
1302           return 0;
1303 }
1304 
1305 static int
get_kbd_echo(KBDC kbdc)1306 get_kbd_echo(KBDC kbdc)
1307 {
1308           /* enable the keyboard port, but disable the keyboard intr. */
1309           if (setup_kbd_port(kbdc, TRUE, FALSE))
1310                     /* CONTROLLER ERROR: there is very little we can do... */
1311                     return ENXIO;
1312 
1313           /* see if something is present */
1314           write_kbd_command(kbdc, KBDC_ECHO);
1315           if (read_kbd_data(kbdc) != KBD_ECHO) {
1316                     empty_both_buffers(kbdc, 10);
1317                     test_controller(kbdc);
1318                     test_kbd_port(kbdc);
1319                     return ENXIO;
1320           }
1321 
1322           /* enable the keyboard port and intr. */
1323           if (setup_kbd_port(kbdc, TRUE, TRUE)) {
1324                     /*
1325                      * CONTROLLER ERROR
1326                      * This is serious; the keyboard intr is left disabled!
1327                      */
1328                     return ENXIO;
1329           }
1330 
1331           return 0;
1332 }
1333 
1334 static int
probe_keyboard(KBDC kbdc,int flags)1335 probe_keyboard(KBDC kbdc, int flags)
1336 {
1337           /*
1338            * Don't try to print anything in this function.  The low-level
1339            * console may not have been initialized yet...
1340            */
1341           int err;
1342           int c;
1343           int m;
1344 
1345           if (!kbdc_lock(kbdc, TRUE)) {
1346                     /* driver error? */
1347                     return ENXIO;
1348           }
1349 
1350           /*
1351            * XXX block data transmission from the keyboard.  This can cause
1352            * the keyboard to stop sending keystrokes even when re-enabled
1353            * under certain circumstances if not followed by a full reset.
1354            */
1355           write_controller_command(kbdc, KBDC_DISABLE_KBD_PORT);
1356 
1357           /* flush any noise in the buffer */
1358           empty_both_buffers(kbdc, 100);
1359 
1360           /* save the current keyboard controller command byte */
1361           m = kbdc_get_device_mask(kbdc) & ~KBD_KBD_CONTROL_BITS;
1362           c = get_controller_command_byte(kbdc);
1363           if (c == -1) {
1364                     /* CONTROLLER ERROR */
1365                     kbdc_set_device_mask(kbdc, m);
1366                     kbdc_lock(kbdc, FALSE);
1367                     return ENXIO;
1368           }
1369 
1370           /*
1371            * The keyboard may have been screwed up by the boot block.
1372            * We may just be able to recover from error by testing the controller
1373            * and the keyboard port. The controller command byte needs to be
1374            * saved before this recovery operation, as some controllers seem
1375            * to set the command byte to particular values.
1376            */
1377           test_controller(kbdc);
1378           if (!(flags & KB_CONF_NO_PROBE_TEST))
1379                     test_kbd_port(kbdc);
1380 
1381           err = get_kbd_echo(kbdc);
1382 
1383           /*
1384            * Even if the keyboard doesn't seem to be present (err != 0),
1385            * we shall enable the keyboard port and interrupt so that
1386            * the driver will be operable when the keyboard is attached
1387            * to the system later.  It is NOT recommended to hot-plug
1388            * the AT keyboard, but many people do so...
1389            */
1390           kbdc_set_device_mask(kbdc, m | KBD_KBD_CONTROL_BITS);
1391           setup_kbd_port(kbdc, TRUE, TRUE);
1392 #if 0
1393           if (err == 0) {
1394                     kbdc_set_device_mask(kbdc, m | KBD_KBD_CONTROL_BITS);
1395           } else {
1396                     /* try to restore the command byte as before */
1397                     set_controller_command_byte(kbdc,
1398                         ALLOW_DISABLE_KBD(kbdc) ? 0xff : KBD_KBD_CONTROL_BITS, c);
1399                     kbdc_set_device_mask(kbdc, m);
1400           }
1401 #endif
1402 
1403           kbdc_lock(kbdc, FALSE);
1404           return (HAS_QUIRK(kbdc, KBDC_QUIRK_IGNORE_PROBE_RESULT) ? 0 : err);
1405 }
1406 
1407 static int
init_keyboard(KBDC kbdc,int * type,int flags)1408 init_keyboard(KBDC kbdc, int *type, int flags)
1409 {
1410           int codeset;
1411           int id;
1412           int c;
1413 
1414           if (!kbdc_lock(kbdc, TRUE)) {
1415                     /* driver error? */
1416                     return EIO;
1417           }
1418 
1419           /*
1420            * XXX block data transmission from the keyboard.  This can cause
1421            * the keyboard to stop sending keystrokes even when re-enabled
1422            * under certain circumstances if not followed by a full reset.
1423            */
1424           write_controller_command(kbdc, KBDC_DISABLE_KBD_PORT);
1425 
1426 
1427           /* save the current controller command byte */
1428           empty_both_buffers(kbdc, 200);
1429           c = get_controller_command_byte(kbdc);
1430           if (c == -1) {
1431                     /* CONTROLLER ERROR */
1432                     kbdc_lock(kbdc, FALSE);
1433                     kprintf("atkbd: unable to get the current command byte value.\n");
1434                     return EIO;
1435           }
1436           if (bootverbose)
1437                     kprintf("atkbd: the current kbd controller command byte %04x\n",
1438                            c);
1439 #if 0
1440           /* override the keyboard lock switch */
1441           c |= KBD_OVERRIDE_KBD_LOCK;
1442 #endif
1443 
1444           /* enable the keyboard port, but disable the keyboard intr. */
1445           if (setup_kbd_port(kbdc, TRUE, FALSE)) {
1446                     /* CONTROLLER ERROR: there is very little we can do... */
1447                     kprintf("atkbd: unable to set the command byte.\n");
1448                     kbdc_lock(kbdc, FALSE);
1449                     return EIO;
1450           }
1451 
1452           if (HAS_QUIRK(kbdc, KBDC_QUIRK_RESET_AFTER_PROBE) &&
1453                     atkbd_reset(kbdc, flags, c)) {
1454                     kbdc_lock(kbdc, FALSE);
1455                     return (EIO);
1456           }
1457 
1458           /*
1459            * Check if we have an XT keyboard before we attempt to reset it.
1460            * The procedure assumes that the keyboard and the controller have
1461            * been set up properly by BIOS and have not been messed up
1462            * during the boot process.
1463            */
1464           codeset = -1;
1465           if (flags & KB_CONF_ALT_SCANCODESET)
1466                     /* the user says there is a XT keyboard */
1467                     codeset = 1;
1468 #ifdef KBD_DETECT_XT_KEYBOARD
1469           else if ((c & KBD_TRANSLATION) == 0) {
1470                     /* SET_SCANCODE_SET is not always supported; ignore error */
1471                     if (send_kbd_command_and_data(kbdc, KBDC_SET_SCANCODE_SET, 0)
1472                               == KBD_ACK)
1473                               codeset = read_kbd_data(kbdc);
1474           }
1475 #endif /* KBD_DETECT_XT_KEYBOARD */
1476           if (bootverbose)
1477                     kprintf("atkbd: scancode set %d\n", codeset);
1478 
1479           /*
1480            * Get the keyboard id.
1481            */
1482           *type = KB_OTHER;
1483           id = get_kbd_id(kbdc);
1484           switch(id) {
1485           case 0x41ab:        /* 101/102/... Enhanced */
1486           case 0x83ab:        /* ditto */
1487           case 0x54ab:        /* SpaceSaver */
1488           case 0x84ab:        /* ditto */
1489 #if 0
1490           case 0x90ab:        /* 'G' */
1491           case 0x91ab:        /* 'P' */
1492           case 0x92ab:        /* 'A' */
1493 #endif
1494                     *type = KB_101;
1495                     break;
1496           case -1:  /* AT 84 keyboard doesn't return ID */
1497                     *type = KB_84;
1498                     break;
1499           default:
1500                     break;
1501           }
1502           if (bootverbose)
1503                     kprintf("atkbd: keyboard ID 0x%x (%d)\n", id, *type);
1504 
1505           if (!HAS_QUIRK(kbdc, KBDC_QUIRK_RESET_AFTER_PROBE) &&
1506               atkbd_reset(kbdc, flags, c)) {
1507                     kbdc_lock(kbdc, FALSE);
1508                     return (EIO);
1509           }
1510 
1511           /*
1512            * Allow us to set the XT_KEYBD flag so that keyboards
1513            * such as those on the IBM ThinkPad laptop computers can be used
1514            * with the standard console driver.
1515            */
1516           if (codeset == 1) {
1517                     if (send_kbd_command_and_data(kbdc,
1518                               KBDC_SET_SCANCODE_SET, codeset) == KBD_ACK) {
1519                               /* XT kbd doesn't need scan code translation */
1520                               c &= ~KBD_TRANSLATION;
1521                     } else {
1522                               /*
1523                                * KEYBOARD ERROR
1524                                * The XT kbd isn't usable unless the proper scan
1525                                * code set is selected.
1526                                */
1527                               set_controller_command_byte(kbdc, ALLOW_DISABLE_KBD(kbdc)
1528                                   ? 0xff : KBD_KBD_CONTROL_BITS, c);
1529                               kbdc_lock(kbdc, FALSE);
1530                               kprintf("atkbd: unable to set the XT keyboard mode.\n");
1531                               return EIO;
1532                     }
1533           }
1534 
1535           /*
1536            * Some keyboards require a SETLEDS command to be sent after
1537            * the reset command before they will send keystrokes to us
1538            * (Acer C720).
1539            */
1540           if (HAS_QUIRK(kbdc, KBDC_QUIRK_SETLEDS_ON_INIT) &&
1541               send_kbd_command_and_data(kbdc, KBDC_SET_LEDS, 0) != KBD_ACK) {
1542                     kprintf("atkbd: setleds failed\n");
1543           }
1544 
1545 #if 0
1546           /* DEBUGGING */
1547           {
1548                     int retry;
1549                     int c;
1550                     kprintf("atkbd: waiting for keypress");
1551                     for (retry = 0; retry < 10; ++retry) {
1552                               c = read_kbd_data_no_wait(kbdc);
1553                               kprintf(" %d", c);
1554                               tsleep(&c, 0, "wait", hz);
1555                     }
1556                     kprintf("\n");
1557           }
1558 #endif
1559           if (!ALLOW_DISABLE_KBD(kbdc))
1560               send_kbd_command(kbdc, KBDC_ENABLE_KBD);
1561 
1562           /* enable the keyboard port and intr. */
1563           if (!set_controller_command_byte(kbdc,
1564                     KBD_KBD_CONTROL_BITS | KBD_TRANSLATION | KBD_OVERRIDE_KBD_LOCK,
1565                     (c & (KBD_TRANSLATION | KBD_OVERRIDE_KBD_LOCK))
1566                         | KBD_ENABLE_KBD_PORT | KBD_ENABLE_KBD_INT)) {
1567                     /*
1568                      * CONTROLLER ERROR
1569                      * This is serious; we are left with the disabled
1570                      * keyboard intr.
1571                      */
1572                     set_controller_command_byte(kbdc, ALLOW_DISABLE_KBD(kbdc)
1573                         ? 0xff : (KBD_KBD_CONTROL_BITS | KBD_TRANSLATION |
1574                               KBD_OVERRIDE_KBD_LOCK), c);
1575                     kbdc_lock(kbdc, FALSE);
1576                     kprintf("atkbd: unable to enable the keyboard port and intr.\n");
1577                     return EIO;
1578           }
1579 
1580           kbdc_lock(kbdc, FALSE);
1581           return 0;
1582 }
1583 
1584 static int
write_kbd(KBDC kbdc,int command,int data)1585 write_kbd(KBDC kbdc, int command, int data)
1586 {
1587           /* prevent the timeout routine from polling the keyboard */
1588           if (!kbdc_lock(kbdc, TRUE))
1589                     return EBUSY;
1590 
1591           /* disable the keyboard and mouse interrupt */
1592           crit_enter();
1593 
1594 #if 0
1595           /*
1596            * XXX NOTE: We can't just disable the KBD port any more, even
1597            *                 temporarily, without blowing up some BIOS emulations
1598            *                   if not followed by a full reset.
1599            */
1600           c = get_controller_command_byte(kbdc);
1601           if ((c == -1)
1602               || !set_controller_command_byte(kbdc,
1603                     kbdc_get_device_mask(kbdc),
1604                     KBD_DISABLE_KBD_PORT | KBD_DISABLE_KBD_INT
1605                     | KBD_DISABLE_AUX_PORT | KBD_DISABLE_AUX_INT)) {
1606                     /* CONTROLLER ERROR */
1607                     kbdc_lock(kbdc, FALSE);
1608                     crit_exit();
1609                     return EIO;
1610           }
1611           /*
1612            * Now that the keyboard controller is told not to generate
1613            * the keyboard and mouse interrupts, call `splx()' to allow
1614            * the other tty interrupts. The clock interrupt may also occur,
1615            * but the timeout routine (`scrn_timer()') will be blocked
1616            * by the lock flag set via `kbdc_lock()'
1617            */
1618           crit_exit();
1619 #endif
1620 
1621           if (send_kbd_command_and_data(kbdc, command, data) != KBD_ACK)
1622                     send_kbd_command(kbdc, KBDC_ENABLE_KBD);
1623 
1624 #if 0
1625           /* restore the interrupts */
1626           if (!set_controller_command_byte(kbdc, kbdc_get_device_mask(kbdc),
1627               c & (KBD_KBD_CONTROL_BITS | KBD_AUX_CONTROL_BITS))) {
1628                     /* CONTROLLER ERROR */
1629           }
1630 #else
1631           crit_exit();
1632 #endif
1633           kbdc_lock(kbdc, FALSE);
1634 
1635           return 0;
1636 }
1637 
1638 static int
get_kbd_id(KBDC kbdc)1639 get_kbd_id(KBDC kbdc)
1640 {
1641           int id1, id2;
1642 
1643           empty_both_buffers(kbdc, 10);
1644           id1 = id2 = -1;
1645           if (send_kbd_command(kbdc, KBDC_SEND_DEV_ID) != KBD_ACK)
1646                     return -1;
1647 
1648           DELAY(10000);       /* 10 msec delay */
1649           id1 = read_kbd_data(kbdc);
1650           if (id1 != -1)
1651                     id2 = read_kbd_data(kbdc);
1652 
1653           if ((id1 == -1) || (id2 == -1)) {
1654                     empty_both_buffers(kbdc, 10);
1655                     test_controller(kbdc);
1656                     test_kbd_port(kbdc);
1657                     return -1;
1658           }
1659           return ((id2 << 8) | id1);
1660 }
1661 
1662 static int kbdelays[] = { 250, 500, 750, 1000 };
1663 static int kbrates[] = {  34,  38,  42,  46,  50,  55,  59,  63,
1664                               68,  76,  84,  92, 100, 110, 118, 126,
1665                            136, 152, 168, 184, 200, 220, 236, 252,
1666                            272, 304, 336, 368, 400, 440, 472, 504 };
1667 
1668 static int
typematic_delay(int i)1669 typematic_delay(int i)
1670 {
1671           return (kbdelays[(i >> 5) & 3]);
1672 }
1673 
1674 static int
typematic_rate(int i)1675 typematic_rate(int i)
1676 {
1677           return (kbrates[i & 0x1f]);
1678 }
1679 
1680 static int
typematic(int delay,int rate)1681 typematic(int delay, int rate)
1682 {
1683           int value;
1684           int i;
1685 
1686           for (i = nitems(kbdelays) - 1; i > 0; --i) {
1687                     if (delay >= kbdelays[i])
1688                               break;
1689           }
1690           value = i << 5;
1691           for (i = nitems(kbrates) - 1; i > 0; --i) {
1692                     if (rate >= kbrates[i])
1693                               break;
1694           }
1695           value |= i;
1696           return value;
1697 }
1698