xref: /illumos-gate/usr/src/uts/common/io/kb8042/kb8042.c (revision b6a0e2cd4ce8d91fe9dc750c44e662d7c7e5fb8e)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*	Copyright (c) 1990, 1991 UNIX System Laboratories, Inc.	*/
22 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989, 1990 AT&T	*/
23 /*	  All Rights Reserved	*/
24 
25 /*
26  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
27  * Use is subject to license terms.
28  */
29 
30 #define	KEYMAP_SIZE_VARIABLE
31 
32 #include <sys/types.h>
33 #include <sys/errno.h>
34 #include <sys/inline.h>
35 #include <sys/termio.h>
36 #include <sys/stropts.h>
37 #include <sys/termios.h>
38 #include <sys/stream.h>
39 #include <sys/strtty.h>
40 #include <sys/strsubr.h>
41 #include <sys/strsun.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/note.h>
45 #include "sys/consdev.h"
46 #include <sys/kbd.h>
47 #include <sys/kbtrans.h>
48 #include "kb8042.h"
49 
50 #include <sys/i8042.h>
51 
52 #include "sys/kbio.h"		/* for KIOCSLAYOUT */
53 #include "sys/stat.h"
54 #include "sys/reboot.h"
55 #include <sys/promif.h>
56 #include <sys/beep.h>
57 #include <sys/inttypes.h>
58 #include <sys/policy.h>
59 
60 /*
61  * For any keyboard, there is a unique code describing the position
62  * of the key on a keyboard. We refer to the code as "station number".
63  * The following table is used to map the station numbers from ps2
64  * AT/XT keyboards to that of a USB one.
65  *
66  * A mapping was added for entry K8042_STOP, to map to USB key code 120 (which
67  * maps to the STOP key) when in KB_USB mode, and maps to a HOLE entry
68  * when in KB_PC mode.  Note that this does not need to be made conditional
69  * on the architecture for which this module is complied because there are no
70  * keys that map to K8042_STOP on non-SPARC platforms.
71  */
72 static kbtrans_key_t keytab_pc2usb[KBTRANS_KEYNUMS_MAX] = {
73 /*  0 */	0,	53,	30,	31,	32,	33,	34,	35,
74 /*  8 */	36,	37,	38,	39,	45,	46,	137,	42,
75 /* 16 */	43,	20,	26,	8,	21,	23,	28,	24,
76 /* 24 */	12,	18,	19,	47,	48,	49,	57,	4,
77 /* 32 */	22,	7,	9,	10,	11,	13,	14,	15,
78 /* 40 */	51,	52,	50,	40,	225,	100,	29,	27,
79 /* 48 */	6,	25,	5,	17,	16,	54,	55,	56,
80 /* 56 */	135,	229,	224,	227,	226,	44,	230,	231,
81 /* 64 */	228,	101,	0,	0,	0,	0,	0,	0,
82 /* 72 */	0,	0,	0,	73,	76,	0,	0,	80,
83 /* 80 */	74,	77,	0,	82,	81,	75,	78,	0,
84 /* 88 */	0,	79,	83,	95,	92,	89,	0,	84,
85 /* 96 */	96,	93,	90,	98,	85,	97,	94,	91,
86 /* 104 */	99,	86,	87,	133,	88,	0,	41,	0,
87 /* 112 */	58,	59,	60,	61,	62,	63,	64,	65,
88 /* 120 */	66,	67,	68,	69,	70,	71,	72,	0,
89 /* 128 */	0,	0,	0,	139,	138,	136,	0,	0,
90 /* 136 */	0,	0,	0,	0,	0,	0,	0,	0,
91 /* 144 */	0,	0,	0,	0,	0,	0,	0,	0,
92 /* 152 */	0,	0,	0,	0,	0,	0,	0,	0,
93 /* 160 */	120,	0,	0,	0,	0,	0,	0,	0,
94 /* 168 */	0,	0,	0,	0,	0,	0,	0,	0,
95 /* 176 */	0,	0,	0,	0,	0,	0,	0,	0,
96 /* 184 */	0,	0,	0,	0,	0,	0,	0,	0,
97 /* 192 */	0,	0,	0,	0,	0,	0,	0,	0,
98 /* 200 */	0,	0,	0,	0,	0,	0,	0,	0,
99 /* 208 */	0,	0,	0,	0,	0,	0,	0,	0,
100 /* 216 */	0,	0,	0,	0,	0,	0,	0,	0,
101 /* 224 */	0,	0,	0,	0,	0,	0,	0,	0,
102 /* 232 */	0,	128,	129,	127,	0,	0,	0,	0,
103 /* 240 */	0,	0,	0,	0,	0,	0,	0,	0,
104 /* 248 */	0,	0,	0,	0
105 };
106 
107 #ifdef __sparc
108 #define	USECS_PER_WAIT 100
109 #define	MAX_WAIT_USECS 100000 /* in usecs = 100 ms */
110 #define	MIN_DELAY_USECS USECS_PER_WAIT
111 
112 boolean_t kb8042_warn_unknown_scanset = B_TRUE;
113 int kb8042_default_scanset = 2;
114 
115 #endif
116 
117 #define	MAX_KB8042_WAIT_MAX_MS	500		/* 500ms total */
118 #define	MAX_KB8042_RETRIES	5
119 
120 enum state_return { STATE_NORMAL, STATE_INTERNAL };
121 
122 static void kb8042_init(struct kb8042 *kb8042, boolean_t from_resume);
123 static uint_t kb8042_intr(caddr_t arg);
124 static void kb8042_wait_poweron(struct kb8042 *kb8042);
125 static void kb8042_send_to_keyboard(struct kb8042 *, int, boolean_t);
126 static int kb8042_xlate_leds(int);
127 static void kb8042_setled(struct kb8042 *, int led_state, boolean_t polled);
128 static void kb8042_streams_setled(struct kbtrans_hardware *hw, int led_state);
129 static void kb8042_polled_setled(struct kbtrans_hardware *hw, int led_state);
130 static boolean_t kb8042_polled_keycheck(
131 			struct kbtrans_hardware *hw, int *key,
132 			enum keystate *state);
133 static void kb8042_get_initial_leds(struct kb8042 *, int *, int *);
134 static boolean_t kb8042_autorepeat_detect(struct kb8042 *kb8042, int key_pos,
135 			enum keystate state);
136 static void kb8042_type4_cmd(struct kb8042 *kb8042, int cmd);
137 static void kb8042_ioctlmsg(struct kb8042 *kb8042, queue_t *, mblk_t *);
138 static void kb8042_iocdatamsg(queue_t *, mblk_t *);
139 static void kb8042_process_key(struct kb8042 *, kbtrans_key_t, enum keystate);
140 static int kb8042_polled_ischar(cons_polledio_arg_t arg);
141 static int kb8042_polled_getchar(cons_polledio_arg_t arg);
142 static void kb8042_cleanup(struct kb8042 *kb8042);
143 static void kb8042_received_byte(struct kb8042 *, int);
144 
145 static struct kbtrans_callbacks kb8042_callbacks = {
146 	kb8042_streams_setled,
147 	kb8042_polled_setled,
148 	kb8042_polled_keycheck,
149 };
150 
151 extern struct keyboard keyindex_pc;
152 
153 #define	DRIVER_NAME(dip) ddi_driver_name(dip)
154 
155 static	char	module_name[] = "kb8042";
156 
157 static int kb8042_open(queue_t *qp, dev_t *devp, int flag, int sflag,
158 			cred_t *credp);
159 static int kb8042_close(queue_t *qp, int flag, cred_t *credp);
160 static int kb8042_rsrv(queue_t *);
161 static int kb8042_wsrv(queue_t *);
162 
163 struct module_info kb8042_sinfo = {
164 	.mi_idnum = 42,			/* Module ID */
165 	.mi_idname = module_name,	/* Module name */
166 	.mi_minpsz = 0,			/* Minimum packet size */
167 	.mi_maxpsz = 32,		/* Maximum packet size */
168 	.mi_hiwat = 256,		/* High water mark */
169 	.mi_lowat = 128			/* Low water mark */
170 };
171 
172 static struct qinit kb8042_rinit = {
173 	.qi_putp = NULL,
174 	.qi_srvp = kb8042_rsrv,
175 	.qi_qopen = kb8042_open,
176 	.qi_qclose = kb8042_close,
177 	.qi_qadmin = NULL,
178 	.qi_minfo = &kb8042_sinfo,
179 	.qi_mstat = NULL,
180 	.qi_rwp = NULL,
181 	.qi_infop = NULL,
182 	.qi_struiot = 0
183 };
184 
185 static struct qinit kb8042_winit = {
186 	.qi_putp = putq,
187 	.qi_srvp = kb8042_wsrv,
188 	.qi_qopen = kb8042_open,
189 	.qi_qclose = kb8042_close,
190 	.qi_qadmin = NULL,
191 	.qi_minfo = &kb8042_sinfo,
192 	.qi_mstat = NULL,
193 	.qi_rwp = NULL,
194 	.qi_infop = NULL,
195 	.qi_struiot = 0
196 };
197 
198 struct streamtab kb8042_str_info = {
199 	.st_rdinit = &kb8042_rinit,
200 	.st_wrinit = &kb8042_winit,
201 	.st_muxrinit = NULL,
202 	.st_muxwinit = NULL
203 };
204 
205 struct kb8042	Kdws = {0};
206 static dev_info_t *kb8042_dip = NULL;
207 
208 static int kb8042_getinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
209 		void **result);
210 static int kb8042_attach(dev_info_t *, ddi_attach_cmd_t);
211 static int kb8042_detach(dev_info_t *, ddi_detach_cmd_t);
212 
213 static struct cb_ops cb_kb8042_ops = {
214 	.cb_open = nulldev,
215 	.cb_close = nulldev,
216 	.cb_strategy = nodev,
217 	.cb_print = nodev,
218 	.cb_dump = nodev,
219 	.cb_read = nodev,
220 	.cb_write = nodev,
221 	.cb_ioctl = nodev,
222 	.cb_devmap = nodev,
223 	.cb_mmap = nodev,
224 	.cb_segmap = nodev,
225 	.cb_chpoll = nochpoll,
226 	.cb_prop_op = ddi_prop_op,
227 	.cb_str = &kb8042_str_info,
228 	.cb_flag = D_MP,
229 	.cb_rev = CB_REV,
230 	.cb_aread = nodev,
231 	.cb_awrite = nodev
232 };
233 
234 struct dev_ops kb8042_ops = {
235 	.devo_rev = DEVO_REV,
236 	.devo_refcnt = 0,
237 	.devo_getinfo = kb8042_getinfo,
238 	.devo_identify = nulldev,
239 	.devo_probe = nulldev,
240 	.devo_attach = kb8042_attach,
241 	.devo_detach = kb8042_detach,
242 	.devo_reset = nodev,
243 	.devo_cb_ops = &cb_kb8042_ops,
244 	.devo_bus_ops = NULL,
245 	.devo_power = NULL,
246 	.devo_quiesce = ddi_quiesce_not_needed
247 };
248 
249 
250 /*
251  * This is the loadable module wrapper.
252  */
253 #include <sys/modctl.h>
254 
255 /*
256  * Module linkage information for the kernel.
257  */
258 static struct modldrv modldrv = {
259 	.drv_modops = &mod_driverops,	/* Type of module. */
260 	.drv_linkinfo = "PS/2 keyboard driver",
261 	.drv_dev_ops = &kb8042_ops,	/* driver ops */
262 };
263 
264 static struct modlinkage modlinkage = {
265 	.ml_rev = MODREV_1,
266 	.ml_linkage = { &modldrv, NULL }
267 };
268 
269 int
270 _init(void)
271 {
272 	int	rv;
273 
274 	rv = mod_install(&modlinkage);
275 	return (rv);
276 }
277 
278 
279 int
280 _fini(void)
281 {
282 	return (mod_remove(&modlinkage));
283 }
284 
285 int
286 _info(struct modinfo *modinfop)
287 {
288 	return (mod_info(&modlinkage, modinfop));
289 }
290 
291 #ifdef __sparc
292 static boolean_t
293 kb8042_is_input_avail(struct kb8042 *kb8042, int timeout_usec, boolean_t polled)
294 {
295 	int i;
296 	int port = (polled == B_TRUE) ? I8042_POLL_INPUT_AVAIL :
297 	    I8042_INT_INPUT_AVAIL;
298 	int reps = timeout_usec / USECS_PER_WAIT;
299 
300 	for (i = 0; i < reps; i++) {
301 		if (ddi_get8(kb8042->handle, kb8042->addr + port) != 0)
302 			return (B_TRUE);
303 
304 		if (i < (reps - 1))
305 			drv_usecwait(USECS_PER_WAIT);
306 	}
307 	return (B_FALSE);
308 }
309 
310 static void
311 kb8042_clear_input_buffer(struct kb8042 *kb8042, boolean_t polled)
312 {
313 	int port = (polled == B_TRUE) ? I8042_POLL_INPUT_DATA :
314 	    I8042_INT_INPUT_DATA;
315 
316 	while (kb8042_is_input_avail(kb8042, MIN_DELAY_USECS, polled)) {
317 		(void) ddi_get8(kb8042->handle, kb8042->addr + port);
318 	}
319 }
320 
321 /*
322  * kb8042_send_and_expect does all its I/O via polling interfaces
323  */
324 static boolean_t
325 kb8042_send_and_expect(struct kb8042 *kb8042, uint8_t send, uint8_t expect,
326     int timeout, int *error, uint8_t *got)
327 {
328 	uint8_t datab;
329 	int err;
330 	boolean_t rval;
331 
332 	ddi_put8(kb8042->handle,
333 	    kb8042->addr + I8042_POLL_OUTPUT_DATA, send);
334 
335 	if (kb8042_is_input_avail(kb8042, timeout, B_TRUE)) {
336 		err = 0;
337 		datab = ddi_get8(kb8042->handle,
338 		    kb8042->addr + I8042_POLL_INPUT_DATA);
339 		rval = ((datab == expect) ? B_TRUE : B_FALSE);
340 	} else {
341 		err = EAGAIN;
342 		rval = B_FALSE;
343 	}
344 
345 	if (error != NULL)
346 		*error = err;
347 	if (got != NULL)
348 		*got = datab;
349 	return (rval);
350 }
351 
352 static const char *
353 kb8042_error_string(int errcode)
354 {
355 	switch (errcode) {
356 	case EAGAIN:
357 		return ("Timed out");
358 	default:
359 		return ("Unknown error");
360 	}
361 }
362 
363 /*
364  * kb8042_read_scanset works properly because it is called before ddi_add_intr
365  * (if it is called after ddi_add_intr, i8042_intr would call kb8042_intr
366  * instead of just storing the data that comes in from the keyboard, which
367  * would prevent the code here from getting it.)
368  */
369 static int
370 kb8042_read_scanset(struct kb8042 *kb8042)
371 {
372 	int scanset = -1;
373 	int err;
374 	uint8_t got;
375 
376 	kb8042_clear_input_buffer(kb8042, B_TRUE);
377 
378 	/*
379 	 * Send a "change scan code set" command to the keyboard.
380 	 * It should respond with an ACK.
381 	 */
382 	if (kb8042_send_and_expect(kb8042, KB_SET_SCAN, KB_ACK, MAX_WAIT_USECS,
383 	    &err, &got) != B_TRUE) {
384 		goto fail_read_scanset;
385 	}
386 
387 	/*
388 	 * Send a 0.  The keyboard should ACK the 0, then it should send the
389 	 * scan code set in use.
390 	 */
391 	if (kb8042_send_and_expect(kb8042, 0, KB_ACK, MAX_WAIT_USECS, &err,
392 	    &got) != B_TRUE) {
393 		goto fail_read_scanset;
394 	}
395 
396 	/*
397 	 * The next input byte from the keyboard should be the scan code
398 	 * set in use, though some keyboards like to send a few more acks
399 	 * just for fun, so blow past those to get the keyboard scan code.
400 	 */
401 	while (kb8042_is_input_avail(kb8042, MAX_WAIT_USECS, B_TRUE) &&
402 	    (scanset = ddi_get8(kb8042->handle,
403 	    kb8042->addr + I8042_POLL_INPUT_DATA)) == KB_ACK)
404 		;
405 
406 #ifdef DEBUG
407 	cmn_err(CE_NOTE, "!Scan code set from keyboard is `%d'.",
408 	    scanset);
409 #endif
410 
411 	return (scanset);
412 
413 fail_read_scanset:
414 #ifdef DEBUG
415 	if (err == 0)
416 		cmn_err(CE_NOTE, "Could not read current scan set from "
417 		    "keyboard: %s. (Expected 0x%x, but got 0x%x).",
418 		    kb8042_error_string(err), KB_ACK, got);
419 	else
420 		cmn_err(CE_NOTE, "Could not read current scan set from "
421 		    "keyboard: %s.", kb8042_error_string(err));
422 #endif
423 	return (-1);
424 }
425 #endif
426 
427 static int
428 kb8042_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
429 {
430 	int	rc;
431 	int	scanset;
432 	int	leds;
433 
434 	struct kb8042	*kb8042 = &Kdws;
435 	static ddi_device_acc_attr_t attr = {
436 		DDI_DEVICE_ATTR_V0,
437 		DDI_NEVERSWAP_ACC,
438 		DDI_STRICTORDER_ACC,
439 	};
440 
441 	switch (cmd) {
442 	case DDI_RESUME:
443 		leds = kb8042->leds.commanded;
444 		kb8042->w_init = 0;
445 		kb8042_init(kb8042, B_TRUE);
446 		kb8042_setled(kb8042, leds, B_FALSE);
447 		mutex_enter(&kb8042->w_hw_mutex);
448 		kb8042->suspended = B_FALSE;
449 		if (kb8042->w_qp != NULL) {
450 			enableok(WR(kb8042->w_qp));
451 			qenable(WR(kb8042->w_qp));
452 		}
453 		cv_broadcast(&kb8042->suspend_cv);
454 		mutex_exit(&kb8042->w_hw_mutex);
455 		return (DDI_SUCCESS);
456 
457 	case DDI_ATTACH:
458 		if (kb8042_dip != NULL)
459 			return (DDI_FAILURE);
460 		/* The rest of the function is for attach */
461 		break;
462 
463 	default:
464 		return (DDI_FAILURE);
465 	}
466 
467 	kb8042->debugger.mod1 = 58;	/* Left Ctrl */
468 	kb8042->debugger.mod2 = 60;	/* Left Alt */
469 	kb8042->debugger.trigger = 33;	/* D */
470 	kb8042->debugger.mod1_down = B_FALSE;
471 	kb8042->debugger.mod2_down = B_FALSE;
472 	kb8042->debugger.enabled = B_FALSE;
473 
474 	kb8042_dip = devi;
475 	kb8042->init_state = KB8042_UNINITIALIZED;
476 
477 	kb8042->polled_synthetic_release_pending = B_FALSE;
478 
479 	if (ddi_create_minor_node(devi, module_name, S_IFCHR, 0,
480 	    DDI_NT_KEYBOARD, 0) == DDI_FAILURE) {
481 		goto failure;
482 	}
483 
484 	kb8042->init_state |= KB8042_MINOR_NODE_CREATED;
485 
486 	rc = ddi_regs_map_setup(devi, 0, (caddr_t *)&kb8042->addr,
487 	    (offset_t)0, (offset_t)0, &attr, &kb8042->handle);
488 	if (rc != DDI_SUCCESS) {
489 #ifdef DEBUG
490 		cmn_err(CE_WARN, "kb8042_attach:  can't map registers");
491 #endif
492 		goto failure;
493 	}
494 
495 	kb8042->init_state |= KB8042_REGS_MAPPED;
496 
497 	if (ddi_get_iblock_cookie(devi, 0, &kb8042->w_iblock) !=
498 	    DDI_SUCCESS) {
499 		cmn_err(CE_WARN, "kb8042_attach:  Can't get iblock cookie");
500 		goto failure;
501 	}
502 
503 	mutex_init(&kb8042->w_hw_mutex, NULL, MUTEX_DRIVER, kb8042->w_iblock);
504 	cv_init(&kb8042->ops_cv, NULL, CV_DRIVER, NULL);
505 	cv_init(&kb8042->suspend_cv, NULL, CV_DRIVER, NULL);
506 	cv_init(&kb8042->cmd_cv, NULL, CV_DRIVER, NULL);
507 	kb8042->init_state |= KB8042_HW_MUTEX_INITTED;
508 
509 	kb8042_init(kb8042, B_FALSE);
510 
511 #ifdef __sparc
512 	/* Detect the scan code set currently in use */
513 	scanset = kb8042_read_scanset(kb8042);
514 
515 	if (scanset < 0 && kb8042_warn_unknown_scanset) {
516 
517 		cmn_err(CE_WARN, "Cannot determine keyboard scan code set ");
518 		cmn_err(CE_CONT, "(is the keyboard plugged in?). ");
519 		cmn_err(CE_CONT, "Defaulting to scan code set %d.  If the "
520 		    "keyboard does not ", kb8042_default_scanset);
521 		cmn_err(CE_CONT, "work properly, add "
522 		    "`set kb8042:kb8042_default_scanset=%d' to /etc/system ",
523 		    (kb8042_default_scanset == 1) ? 2 : 1);
524 		cmn_err(CE_CONT, "(via network or with a USB keyboard) and "
525 		    "restart the system.  If you ");
526 		cmn_err(CE_CONT, "do not want to see this message in the "
527 		    "future, add ");
528 		cmn_err(CE_CONT, "`set kb8042:kb8042_warn_unknown_scanset=0' "
529 		    "to /etc/system.\n");
530 
531 		/* Use the default scan code set. */
532 		scanset = kb8042_default_scanset;
533 	}
534 #else
535 	/* x86 systems use scan code set 1 -- no detection required */
536 	scanset = 1;
537 #endif
538 	if (KeyboardConvertScan_init(kb8042, scanset) != DDI_SUCCESS) {
539 		cmn_err(CE_WARN, "Cannot initialize keyboard scan converter: "
540 		    "Unknown scan code set `%d'.", scanset);
541 		/* Scan code set is not supported */
542 		goto failure;
543 	}
544 
545 	/*
546 	 * Turn on interrupts...
547 	 */
548 	if (ddi_add_intr(devi, 0,
549 	    &kb8042->w_iblock, (ddi_idevice_cookie_t *)NULL,
550 	    kb8042_intr, (caddr_t)kb8042) != DDI_SUCCESS) {
551 		cmn_err(CE_WARN, "kb8042_attach: cannot add interrupt");
552 		goto failure;
553 	}
554 
555 	kb8042->init_state |= KB8042_INTR_ADDED;
556 
557 	ddi_report_dev(devi);
558 
559 #ifdef DEBUG
560 	cmn_err(CE_CONT, "?%s instance #%d READY\n",
561 	    DRIVER_NAME(devi), ddi_get_instance(devi));
562 #endif
563 
564 	return (DDI_SUCCESS);
565 
566 failure:
567 	kb8042_cleanup(kb8042);
568 	return (DDI_FAILURE);
569 }
570 
571 static int
572 kb8042_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
573 {
574 	struct kb8042 *kb8042 = &Kdws;
575 
576 	switch (cmd) {
577 	case DDI_SUSPEND:
578 		mutex_enter(&kb8042->w_hw_mutex);
579 		ASSERT(kb8042->ops >= 0);
580 		while (kb8042->ops > 0)
581 			cv_wait(&kb8042->ops_cv, &kb8042->w_hw_mutex);
582 		kb8042->suspended = B_TRUE;
583 		mutex_exit(&kb8042->w_hw_mutex);
584 		return (DDI_SUCCESS);
585 
586 	case DDI_DETACH:
587 		/* If someone has a stream open, fail to detach */
588 		if (kb8042->w_qp != NULL)
589 			return (DDI_FAILURE);
590 
591 		ASSERT(kb8042_dip == dip);
592 
593 		kb8042_cleanup(kb8042);
594 
595 		return (DDI_SUCCESS);
596 
597 	default:
598 		return (DDI_FAILURE);
599 	}
600 }
601 
602 /*ARGSUSED*/
603 static int
604 kb8042_getinfo(
605     dev_info_t *dip,
606     ddi_info_cmd_t infocmd,
607     void *arg,
608     void **result)
609 {
610 	register int error;
611 
612 	switch (infocmd) {
613 	case DDI_INFO_DEVT2DEVINFO:
614 		if (kb8042_dip == NULL) {
615 			error = DDI_FAILURE;
616 		} else {
617 			*result = (void *) kb8042_dip;
618 			error = DDI_SUCCESS;
619 		}
620 		break;
621 	case DDI_INFO_DEVT2INSTANCE:
622 		*result = (void *)0;
623 		error = DDI_SUCCESS;
624 		break;
625 	default:
626 		error = DDI_FAILURE;
627 		break;
628 	}
629 	return (error);
630 }
631 
632 static void
633 kb8042_cleanup(struct kb8042 *kb8042)
634 {
635 	ASSERT(kb8042_dip != NULL);
636 
637 	if (kb8042->init_state & KB8042_INTR_ADDED)
638 		ddi_remove_intr(kb8042_dip, 0, kb8042->w_iblock);
639 
640 	if (kb8042->init_state & KB8042_HW_MUTEX_INITTED) {
641 		cv_destroy(&kb8042->cmd_cv);
642 		cv_destroy(&kb8042->suspend_cv);
643 		cv_destroy(&kb8042->ops_cv);
644 		mutex_destroy(&kb8042->w_hw_mutex);
645 	}
646 
647 	if (kb8042->init_state & KB8042_REGS_MAPPED)
648 		ddi_regs_map_free(&kb8042->handle);
649 
650 	if (kb8042->init_state & KB8042_MINOR_NODE_CREATED)
651 		ddi_remove_minor_node(kb8042_dip, NULL);
652 
653 	kb8042->init_state = KB8042_UNINITIALIZED;
654 	kb8042_dip = NULL;
655 }
656 
657 static void
658 kb8042_init(struct kb8042 *kb8042, boolean_t from_resume)
659 {
660 	if (kb8042->w_init)
661 		return;
662 
663 	if (!from_resume) {
664 		kb8042->w_kblayout = 0;	/* Default to US */
665 		kb8042->w_qp = (queue_t *)NULL;
666 		kb8042->simulated_kbd_type = KB_PC;
667 		kb8042->leds.commanded = -1;	/* Unknown initial state */
668 		kb8042->leds.desired = -1;	/* Unknown initial state */
669 	}
670 
671 	kb8042_wait_poweron(kb8042);
672 
673 	kb8042->kb_old_key_pos = 0;
674 
675 	/*
676 	 * Explicitly grab and release the 8042 lock outside of
677 	 * kb8042_send_to_keyboard, because this is the only situation
678 	 * where a polling interface is used with locking required.
679 	 */
680 	(void) ddi_get8(kb8042->handle, kb8042->addr + I8042_LOCK);
681 	/* Set up the command state machine and start it running. */
682 	kb8042_send_to_keyboard(kb8042, KB_ENABLE, B_TRUE);
683 	(void) ddi_get8(kb8042->handle, kb8042->addr + I8042_UNLOCK);
684 
685 	kb8042->w_init++;
686 
687 	(void) drv_setparm(SYSRINT, 1);	/* reset keyboard interrupts */
688 }
689 
690 /*ARGSUSED2*/
691 static int
692 kb8042_open(queue_t *qp, dev_t *devp, int flag, int sflag, cred_t *credp)
693 {
694 	struct kb8042	*kb8042;
695 	int err = 0;
696 	int initial_leds;
697 	int initial_led_mask;
698 
699 	kb8042 = &Kdws;
700 
701 	mutex_enter(&kb8042->w_hw_mutex);
702 	if (qp->q_ptr) {
703 		kb8042->w_dev = *devp;
704 		mutex_exit(&kb8042->w_hw_mutex);
705 		return (0);
706 	}
707 
708 	if (secpolicy_console(credp) != 0) {
709 		mutex_exit(&kb8042->w_hw_mutex);
710 		return (EPERM);
711 	}
712 
713 	while (kb8042->suspended) {
714 		if (cv_wait_sig(&kb8042->suspend_cv, &kb8042->w_hw_mutex) ==
715 		    0) {
716 			mutex_exit(&kb8042->w_hw_mutex);
717 			return (EINTR);
718 		}
719 	}
720 
721 	kb8042->w_dev = *devp;
722 	qp->q_ptr = (caddr_t)kb8042;
723 	WR(qp)->q_ptr = qp->q_ptr;
724 	if (!kb8042->w_qp)
725 		kb8042->w_qp = qp;
726 
727 	ASSERT(kb8042->ops >= 0);
728 	kb8042->ops++;
729 	mutex_exit(&kb8042->w_hw_mutex);
730 
731 	kb8042_get_initial_leds(kb8042, &initial_leds, &initial_led_mask);
732 	err = kbtrans_streams_init(qp, sflag,
733 	    (struct kbtrans_hardware *)kb8042, &kb8042_callbacks,
734 	    &kb8042->hw_kbtrans,
735 	    initial_leds, initial_led_mask);
736 	if (err != 0)
737 		goto out;
738 
739 	kbtrans_streams_set_keyboard(kb8042->hw_kbtrans, KB_PC, &keyindex_pc);
740 
741 	kb8042->polledio.cons_polledio_version = CONSPOLLEDIO_V1;
742 	kb8042->polledio.cons_polledio_argument =
743 	    (cons_polledio_arg_t)kb8042;
744 	kb8042->polledio.cons_polledio_putchar = NULL;
745 	kb8042->polledio.cons_polledio_getchar =
746 	    (int (*)(cons_polledio_arg_t))kb8042_polled_getchar;
747 	kb8042->polledio.cons_polledio_ischar =
748 	    (boolean_t (*)(cons_polledio_arg_t))kb8042_polled_ischar;
749 	kb8042->polledio.cons_polledio_enter = NULL;
750 	kb8042->polledio.cons_polledio_exit = NULL;
751 	kb8042->polledio.cons_polledio_setled =
752 	    (void (*)(cons_polledio_arg_t, int))kb8042_polled_setled;
753 	kb8042->polledio.cons_polledio_keycheck =
754 	    (boolean_t (*)(cons_polledio_arg_t, int *,
755 	    enum keystate *))kb8042_polled_keycheck;
756 
757 	qprocson(qp);
758 
759 	kbtrans_streams_enable(kb8042->hw_kbtrans);
760 
761 out:
762 	mutex_enter(&kb8042->w_hw_mutex);
763 	ASSERT(kb8042->ops > 0);
764 	kb8042->ops--;
765 	if (kb8042->ops == 0)
766 		cv_broadcast(&kb8042->ops_cv);
767 	mutex_exit(&kb8042->w_hw_mutex);
768 
769 	return (err);
770 }
771 
772 /*ARGSUSED1*/
773 static int
774 kb8042_close(queue_t *qp, int flag, cred_t *credp)
775 {
776 	struct kb8042	*kb8042;
777 
778 	/* If a beep is in progress, stop that */
779 	(void) beeper_off();
780 
781 	kb8042 = (struct kb8042 *)qp->q_ptr;
782 
783 	mutex_enter(&kb8042->w_hw_mutex);
784 	while (kb8042->suspended) {
785 		if (cv_wait_sig(&kb8042->suspend_cv, &kb8042->w_hw_mutex) ==
786 		    0) {
787 			mutex_exit(&kb8042->w_hw_mutex);
788 			return (EINTR);
789 		}
790 	}
791 
792 	ASSERT(kb8042->ops >= 0);
793 	kb8042->ops++;
794 	mutex_exit(&kb8042->w_hw_mutex);
795 
796 	(void) kbtrans_streams_fini(kb8042->hw_kbtrans);
797 
798 	kb8042->w_qp = (queue_t *)NULL;
799 	qprocsoff(qp);
800 
801 	mutex_enter(&kb8042->w_hw_mutex);
802 	ASSERT(kb8042->ops > 0);
803 	kb8042->ops--;
804 	if (kb8042->ops == 0)
805 		cv_broadcast(&kb8042->ops_cv);
806 	mutex_exit(&kb8042->w_hw_mutex);
807 
808 	return (0);
809 }
810 
811 static int
812 kb8042_rsrv(queue_t *qp)
813 {
814 	mblk_t *mp;
815 	struct kb8042 *kb8042;
816 
817 	while ((mp = getq(qp)) != NULL) {
818 		if (mp->b_datap->db_type == M_DATA) {
819 			kb8042 = (struct kb8042 *)qp->q_ptr;
820 			kb8042_received_byte(kb8042, *mp->b_rptr);
821 		}
822 		freemsg(mp);
823 	}
824 	return (0);
825 }
826 
827 static int
828 kb8042_wsrv(queue_t *qp)
829 {
830 	struct kb8042 *kb8042;
831 
832 	mblk_t	*mp;
833 	boolean_t suspended;
834 
835 	kb8042 = (struct kb8042 *)qp->q_ptr;
836 
837 	mutex_enter(&kb8042->w_hw_mutex);
838 	suspended = kb8042->suspended;
839 	ASSERT(kb8042->ops >= 0);
840 	if (!suspended)
841 		kb8042->ops++;
842 	mutex_exit(&kb8042->w_hw_mutex);
843 
844 #ifdef NO_KB_DEBUG
845 	while (!suspended && (mp = getq(qp)) != NULL) {
846 #else
847 	/*
848 	 * Not taking keyboard input while suspending can make debugging
849 	 * difficult.  However, we still do the ops counting so that we
850 	 * don't suspend at a bad time.
851 	 */
852 	while ((mp = getq(qp))) {
853 #endif
854 		switch (kbtrans_streams_message(kb8042->hw_kbtrans, mp)) {
855 		case KBTRANS_MESSAGE_HANDLED:
856 			continue;
857 		case KBTRANS_MESSAGE_NOT_HANDLED:
858 			break;
859 		}
860 		switch (mp->b_datap->db_type) {
861 		case M_IOCTL:
862 			kb8042_ioctlmsg(kb8042, qp, mp);
863 			continue;
864 		case M_IOCDATA:
865 			kb8042_iocdatamsg(qp, mp);
866 			continue;
867 		case M_DELAY:
868 		case M_STARTI:
869 		case M_STOPI:
870 		case M_READ:	/* ignore, no buffered data */
871 			freemsg(mp);
872 			continue;
873 		case M_FLUSH:
874 			*mp->b_rptr &= ~FLUSHW;
875 			if (*mp->b_rptr & FLUSHR)
876 				qreply(qp, mp);
877 			else
878 				freemsg(mp);
879 			continue;
880 		default:
881 			cmn_err(CE_NOTE, "kb8042_wsrv: bad msg %x",
882 			    mp->b_datap->db_type);
883 			freemsg(mp);
884 			continue;
885 		}
886 	}
887 
888 	mutex_enter(&kb8042->w_hw_mutex);
889 	if (!suspended) {
890 		ASSERT(kb8042->ops > 0);
891 		kb8042->ops--;
892 		if (kb8042->ops == 0)
893 			cv_broadcast(&kb8042->ops_cv);
894 	}
895 	mutex_exit(&kb8042->w_hw_mutex);
896 
897 	return (0);
898 }
899 
900 static void
901 kb8042_ioctlmsg(struct kb8042 *kb8042, queue_t *qp, mblk_t *mp)
902 {
903 	struct iocblk	*iocp;
904 	mblk_t		*datap;
905 	int		error;
906 	int		tmp;
907 	int		cycles;
908 	int		frequency;
909 	int		msecs;
910 
911 	iocp = (struct iocblk *)mp->b_rptr;
912 
913 	switch (iocp->ioc_cmd) {
914 
915 	case CONSOPENPOLLEDIO:
916 		error = miocpullup(mp, sizeof (struct cons_polledio *));
917 		if (error != 0) {
918 			miocnak(qp, mp, 0, error);
919 			return;
920 		}
921 
922 		/*
923 		 * We are given an appropriate-sized data block,
924 		 * and return a pointer to our structure in it.
925 		 */
926 		*(struct cons_polledio **)mp->b_cont->b_rptr =
927 		    &kb8042->polledio;
928 		mp->b_datap->db_type = M_IOCACK;
929 		iocp->ioc_error = 0;
930 		qreply(qp, mp);
931 		break;
932 
933 	case CONSCLOSEPOLLEDIO:
934 		miocack(qp, mp, 0, 0);
935 		break;
936 
937 	case CONSSETABORTENABLE:
938 		if (iocp->ioc_count != TRANSPARENT) {
939 			miocnak(qp, mp, 0, EINVAL);
940 			return;
941 		}
942 
943 		kb8042->debugger.enabled = *(intptr_t *)mp->b_cont->b_rptr;
944 		miocack(qp, mp, 0, 0);
945 		break;
946 
947 	/*
948 	 * Valid only in TR_UNTRANS_MODE mode.
949 	 */
950 	case CONSSETKBDTYPE:
951 		error = miocpullup(mp, sizeof (int));
952 		if (error != 0) {
953 			miocnak(qp, mp, 0, error);
954 			return;
955 		}
956 		tmp =  *(int *)mp->b_cont->b_rptr;
957 		if (tmp != KB_PC && tmp != KB_USB) {
958 			miocnak(qp, mp, 0, EINVAL);
959 			break;
960 		}
961 		kb8042->simulated_kbd_type = tmp;
962 		miocack(qp, mp, 0, 0);
963 		break;
964 
965 	case KIOCLAYOUT:
966 		if (kb8042->w_kblayout == -1) {
967 			miocnak(qp, mp, 0, EINVAL);
968 			return;
969 		}
970 
971 		if ((datap = allocb(sizeof (int), BPRI_HI)) == NULL) {
972 			miocnak(qp, mp, 0, ENOMEM);
973 			return;
974 		}
975 
976 		if (kb8042->simulated_kbd_type == KB_USB)
977 			*(int *)datap->b_wptr = KBTRANS_USBKB_DEFAULT_LAYOUT;
978 		else
979 			*(int *)datap->b_wptr = kb8042->w_kblayout;
980 
981 		datap->b_wptr += sizeof (int);
982 		if (mp->b_cont)
983 			freemsg(mp->b_cont);
984 		mp->b_cont = datap;
985 		iocp->ioc_count = sizeof (int);
986 		mp->b_datap->db_type = M_IOCACK;
987 		iocp->ioc_error = 0;
988 		qreply(qp, mp);
989 		break;
990 
991 	case KIOCSLAYOUT:
992 		if (iocp->ioc_count != TRANSPARENT) {
993 			miocnak(qp, mp, 0, EINVAL);
994 			return;
995 		}
996 
997 		kb8042->w_kblayout = *(intptr_t *)mp->b_cont->b_rptr;
998 		miocack(qp, mp, 0, 0);
999 		break;
1000 
1001 	case KIOCCMD:
1002 		error = miocpullup(mp, sizeof (int));
1003 		if (error != 0) {
1004 			miocnak(qp, mp, 0, error);
1005 			return;
1006 		}
1007 
1008 		kb8042_type4_cmd(kb8042, *(int *)mp->b_cont->b_rptr);
1009 		miocack(qp, mp, 0, 0);
1010 		break;
1011 
1012 	case KIOCMKTONE:
1013 		if (iocp->ioc_count != TRANSPARENT) {
1014 			miocnak(qp, mp, 0, EINVAL);
1015 			return;
1016 		}
1017 
1018 		tmp = (int)(*(intptr_t *)mp->b_cont->b_rptr);
1019 		cycles = tmp & 0xffff;
1020 		msecs = (tmp >> 16) & 0xffff;
1021 
1022 		if (cycles == 0)
1023 			frequency = UINT16_MAX;
1024 		else if (cycles == UINT16_MAX)
1025 			frequency = 0;
1026 		else {
1027 			frequency = (PIT_HZ + cycles / 2) / cycles;
1028 			if (frequency > UINT16_MAX)
1029 				frequency = UINT16_MAX;
1030 		}
1031 
1032 		error = beep_mktone(frequency, msecs);
1033 		if (error != 0)
1034 			miocnak(qp, mp, 0, error);
1035 		else
1036 			miocack(qp, mp, 0, 0);
1037 		break;
1038 
1039 	default:
1040 #ifdef DEBUG1
1041 		cmn_err(CE_NOTE, "!kb8042_ioctlmsg %x", iocp->ioc_cmd);
1042 #endif
1043 		miocnak(qp, mp, 0, EINVAL);
1044 		return;
1045 	}
1046 }
1047 
1048 /*
1049  * Process a byte received from the keyboard
1050  */
1051 static void
1052 kb8042_received_byte(
1053 	struct kb8042	*kb8042,
1054 	int		scancode)	/* raw scan code */
1055 {
1056 	boolean_t	legit;		/* is this a legit key pos'n? */
1057 	int		key_pos = -1;
1058 	enum keystate	state;
1059 	boolean_t	synthetic_release_needed;
1060 
1061 	if (!kb8042->w_init)	/* can't do anything anyway */
1062 		return;
1063 
1064 	legit = KeyboardConvertScan(kb8042, scancode, &key_pos, &state,
1065 	    &synthetic_release_needed);
1066 
1067 	if (legit == 0) {
1068 		/* Eaten by translation */
1069 		return;
1070 	}
1071 
1072 	/*
1073 	 * Don't know if we want this permanently, but it seems interesting
1074 	 * for the moment.
1075 	 */
1076 	if (key_pos == kb8042->debugger.mod1) {
1077 		kb8042->debugger.mod1_down = (state == KEY_PRESSED);
1078 	}
1079 	if (key_pos == kb8042->debugger.mod2) {
1080 		kb8042->debugger.mod2_down = (state == KEY_PRESSED);
1081 	}
1082 	if (kb8042->debugger.enabled &&
1083 	    key_pos == kb8042->debugger.trigger &&
1084 	    kb8042->debugger.mod1_down &&
1085 	    kb8042->debugger.mod2_down) {
1086 		/*
1087 		 * Require new presses of the modifiers.
1088 		 */
1089 		kb8042->debugger.mod1_down = B_FALSE;
1090 		kb8042->debugger.mod2_down = B_FALSE;
1091 		abort_sequence_enter(NULL);
1092 		return;
1093 	}
1094 
1095 	/*
1096 	 * If there's no queue above us - as can happen if we've been
1097 	 * attached but not opened - drop the keystroke.
1098 	 * Note that we do this here instead of above so that
1099 	 * Ctrl-Alt-D still works.
1100 	 */
1101 	if (kb8042->w_qp == NULL) {
1102 		return;
1103 	}
1104 
1105 	/*
1106 	 * This is to filter out auto repeat since it can't be
1107 	 * turned off at the hardware.  (Yeah, yeah, PS/2 keyboards
1108 	 * can.  Don't know whether they've taken over the world.
1109 	 * Don't think so.)
1110 	 */
1111 	if (kb8042_autorepeat_detect(kb8042, key_pos, state)) {
1112 		return;
1113 	}
1114 
1115 
1116 	kb8042_process_key(kb8042, key_pos, state);
1117 
1118 	/*
1119 	 * This is a total hack.  For some stupid reason, the two additional
1120 	 * keys on Korean keyboards (Hangul and Hangul/Hanja) report press
1121 	 * only.  We synthesize a release immediately.
1122 	 */
1123 	if (synthetic_release_needed) {
1124 		(void) kb8042_autorepeat_detect(kb8042, key_pos, KEY_RELEASED);
1125 		kb8042_process_key(kb8042, key_pos, state);
1126 	}
1127 }
1128 
1129 
1130 static void
1131 kb8042_process_key(struct kb8042 *kb8042, kbtrans_key_t key_pos,
1132     enum keystate state)
1133 {
1134 	kbtrans_key_t key;
1135 
1136 	ASSERT(key_pos >= 0 && key_pos <= 255);
1137 	if (kb8042->simulated_kbd_type == KB_PC) {
1138 		kbtrans_streams_key(kb8042->hw_kbtrans, key_pos, state);
1139 	} else if (kb8042->simulated_kbd_type == KB_USB) {
1140 		key = keytab_pc2usb[key_pos];
1141 		if (key != 0) {
1142 			kbtrans_streams_key(kb8042->hw_kbtrans, key, state);
1143 		}
1144 	}
1145 }
1146 
1147 /*
1148  * Called from interrupt handler when keyboard interrupt occurs.
1149  */
1150 static uint_t
1151 kb8042_intr(caddr_t arg)
1152 {
1153 	uchar_t scancode;	/* raw scan code */
1154 	int rc;
1155 	struct kb8042 *kb8042 = (struct kb8042 *)arg;
1156 
1157 	rc = DDI_INTR_UNCLAIMED;
1158 
1159 	if (kb8042->init_state == KB8042_UNINITIALIZED)
1160 		return (DDI_INTR_UNCLAIMED);
1161 
1162 	/* don't care if drv_setparm succeeds */
1163 	(void) drv_setparm(SYSRINT, 1);
1164 
1165 	while (ddi_get8(kb8042->handle, kb8042->addr + I8042_INT_INPUT_AVAIL)
1166 	    != 0) {
1167 		mblk_t *mp;
1168 
1169 		rc = DDI_INTR_CLAIMED;
1170 
1171 		scancode = ddi_get8(kb8042->handle,
1172 		    kb8042->addr + I8042_INT_INPUT_DATA);
1173 
1174 		/*
1175 		 * Intercept ACK and RESEND and signal the condition that
1176 		 * kb8042_send_and_wait is waiting for.
1177 		 */
1178 		switch (scancode) {
1179 		case KB_ACK:
1180 			mutex_enter(&kb8042->w_hw_mutex);
1181 			kb8042->acked = 1;
1182 			cv_signal(&kb8042->cmd_cv);
1183 			mutex_exit(&kb8042->w_hw_mutex);
1184 			return (rc);
1185 		case KB_RESEND:
1186 			mutex_enter(&kb8042->w_hw_mutex);
1187 			kb8042->need_retry = 1;
1188 			cv_signal(&kb8042->cmd_cv);
1189 			mutex_exit(&kb8042->w_hw_mutex);
1190 			return (rc);
1191 		default:
1192 			break;
1193 		}
1194 
1195 		if ((mp = allocb(sizeof (scancode), BPRI_HI)) == NULL)
1196 			return (rc);
1197 		*mp->b_wptr++ = scancode;
1198 		if (putq(RD(kb8042->w_qp), mp) == 0)
1199 			freemsg(mp);
1200 	}
1201 
1202 	return (rc);
1203 }
1204 
1205 static void
1206 kb8042_iocdatamsg(queue_t *qp, mblk_t *mp)
1207 {
1208 	struct copyresp	*csp;
1209 
1210 	csp = (struct copyresp *)mp->b_rptr;
1211 	if (csp->cp_rval) {
1212 		freemsg(mp);
1213 		return;
1214 	}
1215 
1216 	switch (csp->cp_cmd) {
1217 	default:
1218 		miocack(qp, mp, 0, 0);
1219 		break;
1220 	}
1221 }
1222 
1223 static boolean_t
1224 kb8042_polled_keycheck(
1225     struct kbtrans_hardware *hw,
1226     int *key,
1227     enum keystate *state)
1228 {
1229 	struct kb8042 *kb8042 = (struct kb8042 *)hw;
1230 	int	scancode;
1231 	boolean_t	legit;
1232 	boolean_t	synthetic_release_needed;
1233 
1234 	if (kb8042->polled_synthetic_release_pending) {
1235 		*key = kb8042->polled_synthetic_release_key;
1236 		*state = KEY_RELEASED;
1237 		kb8042->polled_synthetic_release_pending = B_FALSE;
1238 		(void) kb8042_autorepeat_detect(kb8042, *key, *state);
1239 		return (B_TRUE);
1240 	}
1241 
1242 	for (;;) {
1243 		if (ddi_get8(kb8042->handle,
1244 		    kb8042->addr + I8042_POLL_INPUT_AVAIL) == 0) {
1245 			return (B_FALSE);
1246 		}
1247 
1248 		scancode = ddi_get8(kb8042->handle,
1249 		    kb8042->addr + I8042_POLL_INPUT_DATA);
1250 
1251 		legit = KeyboardConvertScan(kb8042, scancode, key, state,
1252 		    &synthetic_release_needed);
1253 		if (!legit) {
1254 			continue;
1255 		}
1256 		/*
1257 		 * For the moment at least, we rely on hardware autorepeat
1258 		 * for polled I/O autorepeat.  However, for coordination
1259 		 * with the interrupt-driven code, maintain the last key
1260 		 * pressed.
1261 		 */
1262 		(void) kb8042_autorepeat_detect(kb8042, *key, *state);
1263 
1264 		/*
1265 		 * This is a total hack to support two additional keys
1266 		 * on Korean keyboards.  They report only on press, and
1267 		 * so we synthesize a release.  Most likely this will
1268 		 * never be important to polled  I/O, but if I do it
1269 		 * "right" the first time it _won't_ be an issue.
1270 		 */
1271 		if (synthetic_release_needed) {
1272 			kb8042->polled_synthetic_release_pending = B_TRUE;
1273 			kb8042->polled_synthetic_release_key = *key;
1274 		}
1275 
1276 		if (kb8042->simulated_kbd_type == KB_USB) {
1277 			*key = keytab_pc2usb[*key];
1278 		}
1279 		return (B_TRUE);
1280 	}
1281 }
1282 
1283 static void
1284 kb8042_setled(struct kb8042 *kb8042, int led_state, boolean_t polled)
1285 {
1286 	kb8042->leds.desired = led_state;
1287 
1288 	if (!polled)
1289 		mutex_enter(&kb8042->w_hw_mutex);
1290 
1291 	if (kb8042->leds.desired != kb8042->leds.commanded) {
1292 		kb8042_send_to_keyboard(kb8042, KB_SET_LED, polled);
1293 	}
1294 
1295 	if (!polled)
1296 		mutex_exit(&kb8042->w_hw_mutex);
1297 }
1298 
1299 static void
1300 kb8042_polled_setled(struct kbtrans_hardware *hw, int led_state)
1301 {
1302 	struct kb8042 *kb8042 = (struct kb8042 *)hw;
1303 	kb8042_setled(kb8042, led_state, B_TRUE);
1304 }
1305 
1306 static void
1307 kb8042_streams_setled(struct kbtrans_hardware *hw, int led_state)
1308 {
1309 	struct kb8042 *kb8042 = (struct kb8042 *)hw;
1310 	kb8042_setled(kb8042, led_state, B_FALSE);
1311 }
1312 
1313 
1314 static int
1315 kb8042_send_and_wait(struct kb8042 *kb8042, uint8_t u8, boolean_t polled)
1316 {
1317 	uint8_t *outp = kb8042->addr +
1318 	    (polled ? I8042_POLL_OUTPUT_DATA : I8042_INT_OUTPUT_DATA);
1319 	uint8_t *inavp = kb8042->addr +
1320 	    (polled ? I8042_POLL_INPUT_AVAIL : I8042_INT_INPUT_AVAIL);
1321 	uint8_t *inp = kb8042->addr +
1322 	    (polled ? I8042_POLL_INPUT_DATA : I8042_INT_INPUT_DATA);
1323 	uint8_t b;
1324 	int ms_waited;
1325 	int timedout;
1326 	int expire;
1327 	int retries = 0;
1328 
1329 	do {
1330 		kb8042->acked = 0;
1331 		kb8042->need_retry = 0;
1332 		ms_waited = 0;		/* Zero it whether polled or not */
1333 		timedout = 0;
1334 
1335 		ddi_put8(kb8042->handle, outp, u8);
1336 
1337 		while (!kb8042->acked && !kb8042->need_retry && !timedout) {
1338 
1339 			if (polled) {
1340 				if (ddi_get8(kb8042->handle, inavp)) {
1341 					b = ddi_get8(kb8042->handle, inp);
1342 					switch (b) {
1343 					case KB_ACK:
1344 						kb8042->acked = 1;
1345 						break;
1346 					case KB_RESEND:
1347 						kb8042->need_retry = 1;
1348 						break;
1349 					default:
1350 						/*
1351 						 * drop it: We should never
1352 						 * get scancodes while
1353 						 * we're in the middle of a
1354 						 * command anyway.
1355 						 */
1356 #ifdef DEBUG
1357 						cmn_err(CE_WARN, "!Unexpected "
1358 						    " byte 0x%x", b);
1359 #endif
1360 						break;
1361 					}
1362 				}
1363 
1364 				/*
1365 				 * Wait 1ms if an ACK wasn't received yet
1366 				 */
1367 				if (!kb8042->acked) {
1368 					drv_usecwait(1000);
1369 					ms_waited++;
1370 					if (ms_waited >= MAX_KB8042_WAIT_MAX_MS)
1371 						timedout = B_TRUE;
1372 				}
1373 			} else {
1374 				/* Interrupt-driven */
1375 				expire = ddi_get_lbolt() +
1376 				    drv_usectohz(MAX_KB8042_WAIT_MAX_MS * 1000);
1377 
1378 				/*
1379 				 * If cv_timedwait returned -1 and we neither
1380 				 * received an ACK nor a RETRY response, then
1381 				 * we timed out.
1382 				 */
1383 				if (cv_timedwait(&kb8042->cmd_cv,
1384 				    &kb8042->w_hw_mutex, expire) == -1 &&
1385 				    !kb8042->acked && !kb8042->need_retry) {
1386 					timedout = B_TRUE;
1387 				}
1388 			}
1389 
1390 		}
1391 	} while ((kb8042->need_retry || timedout) &&
1392 	    ++retries < MAX_KB8042_RETRIES);
1393 
1394 	return (kb8042->acked);
1395 }
1396 
1397 /*
1398  * kb8042_send_to_keyboard should be called with w_hw_mutex held if
1399  * polled is FALSE.
1400  */
1401 static void
1402 kb8042_send_to_keyboard(struct kb8042 *kb8042, int byte, boolean_t polled)
1403 {
1404 
1405 	/*
1406 	 * KB_SET_LED and KB_ENABLE are special commands which require blocking
1407 	 * other 8042 consumers while executing.
1408 	 *
1409 	 * Other commands/data are sent using the single put8 I/O access
1410 	 * function.
1411 	 */
1412 	if (byte == KB_SET_LED) {
1413 
1414 		if (!polled) {
1415 			(void) ddi_get8(kb8042->handle, kb8042->addr +
1416 			    I8042_LOCK);
1417 		}
1418 
1419 		if (kb8042_send_and_wait(kb8042, KB_SET_LED, polled)) {
1420 			/*
1421 			 * Ignore return value, as there's nothing we can
1422 			 * do about it if the SET LED command fails.
1423 			 */
1424 			(void) kb8042_send_and_wait(kb8042,
1425 			    kb8042_xlate_leds(kb8042->leds.desired), polled);
1426 		}
1427 
1428 		if (!polled) {
1429 			(void) ddi_get8(kb8042->handle, kb8042->addr +
1430 			    I8042_UNLOCK);
1431 		}
1432 		kb8042->leds.commanded = kb8042->leds.desired;
1433 
1434 	} else if (byte == KB_ENABLE) {
1435 
1436 		if (!polled) {
1437 			(void) ddi_get8(kb8042->handle, kb8042->addr +
1438 			    I8042_LOCK);
1439 		}
1440 
1441 		(void) kb8042_send_and_wait(kb8042, KB_ENABLE, polled);
1442 
1443 		if (!polled) {
1444 			(void) ddi_get8(kb8042->handle, kb8042->addr +
1445 			    I8042_UNLOCK);
1446 		}
1447 
1448 	} else {
1449 		/* All other commands use the "normal" virtual output port */
1450 		if (polled) {
1451 			ddi_put8(kb8042->handle,
1452 			    kb8042->addr + I8042_POLL_OUTPUT_DATA, byte);
1453 		} else {
1454 			ddi_put8(kb8042->handle,
1455 			    kb8042->addr + I8042_INT_OUTPUT_DATA, byte);
1456 		}
1457 	}
1458 }
1459 
1460 /*
1461  * Wait until the keyboard is fully up, maybe.
1462  * We may be the first person to talk to the keyboard, in which case
1463  * it's patiently waiting to say "AA" to us to tell us it's up.
1464  * In theory it sends the AA in 300ms < n < 9s, but it's a pretty
1465  * good bet that we've already spent that long getting to that point,
1466  * so we'll only wait long enough for the communications electronics to
1467  * run.
1468  */
1469 static void
1470 kb8042_wait_poweron(struct kb8042 *kb8042)
1471 {
1472 	int cnt;
1473 	int ready;
1474 
1475 	/* wait for up to 250 ms for a response */
1476 	for (cnt = 0; cnt < 250; cnt++) {
1477 		ready = ddi_get8(kb8042->handle,
1478 		    kb8042->addr + I8042_INT_INPUT_AVAIL);
1479 		if (ready != 0)
1480 			break;
1481 		drv_usecwait(1000);
1482 	}
1483 
1484 	/*
1485 	 * If there's something pending, read and discard it.  If not,
1486 	 * assume things are OK anyway - maybe somebody else ate it
1487 	 * already.  (On a PC, the BIOS almost certainly did.)
1488 	 */
1489 	if (ready != 0) {
1490 		(void) ddi_get8(kb8042->handle,
1491 		    kb8042->addr + I8042_INT_INPUT_DATA);
1492 	}
1493 }
1494 
1495 static int
1496 kb8042_xlate_leds(int led)
1497 {
1498 	int res;
1499 
1500 	res = 0;
1501 
1502 	if (led & LED_NUM_LOCK)
1503 		res |= LED_NUM;
1504 	if (led & LED_SCROLL_LOCK)
1505 		res |= LED_SCR;
1506 	if (led & LED_CAPS_LOCK)
1507 		res |= LED_CAP;
1508 
1509 	return (res);
1510 }
1511 
1512 /*ARGSUSED*/
1513 static void
1514 kb8042_get_initial_leds(
1515     struct kb8042 *kb8042,
1516     int *initial_leds,
1517     int *initial_led_mask)
1518 {
1519 #if defined(__i386) || defined(__amd64)
1520 	extern caddr_t	p0_va;
1521 	uint8_t		bios_kb_flag;
1522 
1523 	bios_kb_flag = p0_va[BIOS_KB_FLAG];
1524 
1525 	*initial_led_mask = LED_CAPS_LOCK | LED_NUM_LOCK | LED_SCROLL_LOCK;
1526 	*initial_leds = 0;
1527 	if (bios_kb_flag & BIOS_CAPS_STATE)
1528 		*initial_leds |= LED_CAPS_LOCK;
1529 	if (bios_kb_flag & BIOS_NUM_STATE)
1530 		*initial_leds |= LED_NUM_LOCK;
1531 	if (bios_kb_flag & BIOS_SCROLL_STATE)
1532 		*initial_leds |= LED_SCROLL_LOCK;
1533 #else
1534 	*initial_leds = 0;
1535 	*initial_led_mask = 0;
1536 #endif
1537 }
1538 
1539 static boolean_t
1540 kb8042_autorepeat_detect(
1541     struct kb8042 *kb8042,
1542     int key_pos,
1543     enum keystate state)
1544 {
1545 	if (state == KEY_RELEASED) {
1546 		if (kb8042->kb_old_key_pos == key_pos)
1547 			kb8042->kb_old_key_pos = 0;
1548 	} else {
1549 		if (kb8042->kb_old_key_pos == key_pos) {
1550 			return (B_TRUE);
1551 		}
1552 		kb8042->kb_old_key_pos = key_pos;
1553 	}
1554 	return (B_FALSE);
1555 }
1556 
1557 /* ARGSUSED */
1558 static void
1559 kb8042_type4_cmd(struct kb8042 *kb8042, int cmd)
1560 {
1561 	switch (cmd) {
1562 	case KBD_CMD_BELL:
1563 		(void) beeper_on(BEEP_TYPE4);
1564 		break;
1565 	case KBD_CMD_NOBELL:
1566 		(void) beeper_off();
1567 		break;
1568 	}
1569 }
1570 
1571 
1572 /*
1573  * This is a pass-thru routine to get a character at poll time.
1574  */
1575 static int
1576 kb8042_polled_getchar(cons_polledio_arg_t arg)
1577 {
1578 	struct kb8042	*kb8042;
1579 
1580 	kb8042 = (struct kb8042 *)arg;
1581 
1582 	return (kbtrans_getchar(kb8042->hw_kbtrans));
1583 }
1584 
1585 /*
1586  * This is a pass-thru routine to get a character at poll time.
1587  */
1588 static int
1589 kb8042_polled_ischar(cons_polledio_arg_t arg)
1590 {
1591 	struct kb8042	*kb8042;
1592 
1593 	kb8042 = (struct kb8042 *)arg;
1594 
1595 	return (kbtrans_ischar(kb8042->hw_kbtrans));
1596 }
1597