xref: /illumos-gate/usr/src/uts/common/io/kb8042/kb8042.c (revision 1a2d662a91cee3bf82f41cd47c7ae6f3825d9db2)
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 static int
603 kb8042_getinfo(dev_info_t *dip __unused, ddi_info_cmd_t infocmd,
604     void *arg __unused, void **result)
605 {
606 	int error;
607 
608 	switch (infocmd) {
609 	case DDI_INFO_DEVT2DEVINFO:
610 		if (kb8042_dip == NULL) {
611 			error = DDI_FAILURE;
612 		} else {
613 			*result = (void *) kb8042_dip;
614 			error = DDI_SUCCESS;
615 		}
616 		break;
617 	case DDI_INFO_DEVT2INSTANCE:
618 		if (kb8042_dip == NULL) {
619 			error = DDI_FAILURE;
620 		} else {
621 			int instance;
622 
623 			instance = ddi_get_instance(kb8042_dip);
624 			*result = (void *)(uintptr_t)instance;
625 			error = DDI_SUCCESS;
626 		}
627 		break;
628 	default:
629 		error = DDI_FAILURE;
630 		break;
631 	}
632 	return (error);
633 }
634 
635 static void
636 kb8042_cleanup(struct kb8042 *kb8042)
637 {
638 	ASSERT(kb8042_dip != NULL);
639 
640 	if (kb8042->init_state & KB8042_INTR_ADDED)
641 		ddi_remove_intr(kb8042_dip, 0, kb8042->w_iblock);
642 
643 	if (kb8042->init_state & KB8042_HW_MUTEX_INITTED) {
644 		cv_destroy(&kb8042->cmd_cv);
645 		cv_destroy(&kb8042->suspend_cv);
646 		cv_destroy(&kb8042->ops_cv);
647 		mutex_destroy(&kb8042->w_hw_mutex);
648 	}
649 
650 	if (kb8042->init_state & KB8042_REGS_MAPPED)
651 		ddi_regs_map_free(&kb8042->handle);
652 
653 	if (kb8042->init_state & KB8042_MINOR_NODE_CREATED)
654 		ddi_remove_minor_node(kb8042_dip, NULL);
655 
656 	kb8042->init_state = KB8042_UNINITIALIZED;
657 	kb8042_dip = NULL;
658 }
659 
660 static void
661 kb8042_init(struct kb8042 *kb8042, boolean_t from_resume)
662 {
663 	if (kb8042->w_init)
664 		return;
665 
666 	if (!from_resume) {
667 		kb8042->w_kblayout = 0;	/* Default to US */
668 		kb8042->w_qp = (queue_t *)NULL;
669 		kb8042->simulated_kbd_type = KB_PC;
670 		kb8042->leds.commanded = -1;	/* Unknown initial state */
671 		kb8042->leds.desired = -1;	/* Unknown initial state */
672 	}
673 
674 	kb8042_wait_poweron(kb8042);
675 
676 	kb8042->kb_old_key_pos = 0;
677 
678 	/*
679 	 * Explicitly grab and release the 8042 lock outside of
680 	 * kb8042_send_to_keyboard, because this is the only situation
681 	 * where a polling interface is used with locking required.
682 	 */
683 	(void) ddi_get8(kb8042->handle, kb8042->addr + I8042_LOCK);
684 	/* Set up the command state machine and start it running. */
685 	kb8042_send_to_keyboard(kb8042, KB_ENABLE, B_TRUE);
686 	(void) ddi_get8(kb8042->handle, kb8042->addr + I8042_UNLOCK);
687 
688 	kb8042->w_init++;
689 
690 	(void) drv_setparm(SYSRINT, 1);	/* reset keyboard interrupts */
691 }
692 
693 /*ARGSUSED2*/
694 static int
695 kb8042_open(queue_t *qp, dev_t *devp, int flag, int sflag, cred_t *credp)
696 {
697 	struct kb8042	*kb8042;
698 	int err = 0;
699 	int initial_leds;
700 	int initial_led_mask;
701 
702 	kb8042 = &Kdws;
703 
704 	mutex_enter(&kb8042->w_hw_mutex);
705 	if (qp->q_ptr) {
706 		kb8042->w_dev = *devp;
707 		mutex_exit(&kb8042->w_hw_mutex);
708 		return (0);
709 	}
710 
711 	if (secpolicy_console(credp) != 0) {
712 		mutex_exit(&kb8042->w_hw_mutex);
713 		return (EPERM);
714 	}
715 
716 	while (kb8042->suspended) {
717 		if (cv_wait_sig(&kb8042->suspend_cv, &kb8042->w_hw_mutex) ==
718 		    0) {
719 			mutex_exit(&kb8042->w_hw_mutex);
720 			return (EINTR);
721 		}
722 	}
723 
724 	kb8042->w_dev = *devp;
725 	qp->q_ptr = (caddr_t)kb8042;
726 	WR(qp)->q_ptr = qp->q_ptr;
727 	if (!kb8042->w_qp)
728 		kb8042->w_qp = qp;
729 
730 	ASSERT(kb8042->ops >= 0);
731 	kb8042->ops++;
732 	mutex_exit(&kb8042->w_hw_mutex);
733 
734 	kb8042_get_initial_leds(kb8042, &initial_leds, &initial_led_mask);
735 	err = kbtrans_streams_init(qp, sflag,
736 	    (struct kbtrans_hardware *)kb8042, &kb8042_callbacks,
737 	    &kb8042->hw_kbtrans,
738 	    initial_leds, initial_led_mask);
739 	if (err != 0)
740 		goto out;
741 
742 	kbtrans_streams_set_keyboard(kb8042->hw_kbtrans, KB_PC, &keyindex_pc);
743 
744 	kb8042->polledio.cons_polledio_version = CONSPOLLEDIO_V1;
745 	kb8042->polledio.cons_polledio_argument =
746 	    (cons_polledio_arg_t)kb8042;
747 	kb8042->polledio.cons_polledio_putchar = NULL;
748 	kb8042->polledio.cons_polledio_getchar =
749 	    (int (*)(cons_polledio_arg_t))kb8042_polled_getchar;
750 	kb8042->polledio.cons_polledio_ischar =
751 	    (boolean_t (*)(cons_polledio_arg_t))kb8042_polled_ischar;
752 	kb8042->polledio.cons_polledio_enter = NULL;
753 	kb8042->polledio.cons_polledio_exit = NULL;
754 	kb8042->polledio.cons_polledio_setled =
755 	    (void (*)(cons_polledio_arg_t, int))kb8042_polled_setled;
756 	kb8042->polledio.cons_polledio_keycheck =
757 	    (boolean_t (*)(cons_polledio_arg_t, int *,
758 	    enum keystate *))kb8042_polled_keycheck;
759 
760 	qprocson(qp);
761 
762 	kbtrans_streams_enable(kb8042->hw_kbtrans);
763 
764 out:
765 	mutex_enter(&kb8042->w_hw_mutex);
766 	ASSERT(kb8042->ops > 0);
767 	kb8042->ops--;
768 	if (kb8042->ops == 0)
769 		cv_broadcast(&kb8042->ops_cv);
770 	mutex_exit(&kb8042->w_hw_mutex);
771 
772 	return (err);
773 }
774 
775 /*ARGSUSED1*/
776 static int
777 kb8042_close(queue_t *qp, int flag, cred_t *credp)
778 {
779 	struct kb8042	*kb8042;
780 
781 	/* If a beep is in progress, stop that */
782 	(void) beeper_off();
783 
784 	kb8042 = (struct kb8042 *)qp->q_ptr;
785 
786 	mutex_enter(&kb8042->w_hw_mutex);
787 	while (kb8042->suspended) {
788 		if (cv_wait_sig(&kb8042->suspend_cv, &kb8042->w_hw_mutex) ==
789 		    0) {
790 			mutex_exit(&kb8042->w_hw_mutex);
791 			return (EINTR);
792 		}
793 	}
794 
795 	ASSERT(kb8042->ops >= 0);
796 	kb8042->ops++;
797 	mutex_exit(&kb8042->w_hw_mutex);
798 
799 	(void) kbtrans_streams_fini(kb8042->hw_kbtrans);
800 
801 	kb8042->w_qp = (queue_t *)NULL;
802 	qprocsoff(qp);
803 
804 	mutex_enter(&kb8042->w_hw_mutex);
805 	ASSERT(kb8042->ops > 0);
806 	kb8042->ops--;
807 	if (kb8042->ops == 0)
808 		cv_broadcast(&kb8042->ops_cv);
809 	mutex_exit(&kb8042->w_hw_mutex);
810 
811 	return (0);
812 }
813 
814 static int
815 kb8042_rsrv(queue_t *qp)
816 {
817 	mblk_t *mp;
818 	struct kb8042 *kb8042;
819 
820 	while ((mp = getq(qp)) != NULL) {
821 		if (mp->b_datap->db_type == M_DATA) {
822 			kb8042 = (struct kb8042 *)qp->q_ptr;
823 			kb8042_received_byte(kb8042, *mp->b_rptr);
824 		}
825 		freemsg(mp);
826 	}
827 	return (0);
828 }
829 
830 static int
831 kb8042_wsrv(queue_t *qp)
832 {
833 	struct kb8042 *kb8042;
834 
835 	mblk_t	*mp;
836 	boolean_t suspended;
837 
838 	kb8042 = (struct kb8042 *)qp->q_ptr;
839 
840 	mutex_enter(&kb8042->w_hw_mutex);
841 	suspended = kb8042->suspended;
842 	ASSERT(kb8042->ops >= 0);
843 	if (!suspended)
844 		kb8042->ops++;
845 	mutex_exit(&kb8042->w_hw_mutex);
846 
847 #ifdef NO_KB_DEBUG
848 	while (!suspended && (mp = getq(qp)) != NULL) {
849 #else
850 	/*
851 	 * Not taking keyboard input while suspending can make debugging
852 	 * difficult.  However, we still do the ops counting so that we
853 	 * don't suspend at a bad time.
854 	 */
855 	while ((mp = getq(qp))) {
856 #endif
857 		switch (kbtrans_streams_message(kb8042->hw_kbtrans, mp)) {
858 		case KBTRANS_MESSAGE_HANDLED:
859 			continue;
860 		case KBTRANS_MESSAGE_NOT_HANDLED:
861 			break;
862 		}
863 		switch (mp->b_datap->db_type) {
864 		case M_IOCTL:
865 			kb8042_ioctlmsg(kb8042, qp, mp);
866 			continue;
867 		case M_IOCDATA:
868 			kb8042_iocdatamsg(qp, mp);
869 			continue;
870 		case M_DELAY:
871 		case M_STARTI:
872 		case M_STOPI:
873 		case M_READ:	/* ignore, no buffered data */
874 			freemsg(mp);
875 			continue;
876 		case M_FLUSH:
877 			*mp->b_rptr &= ~FLUSHW;
878 			if (*mp->b_rptr & FLUSHR)
879 				qreply(qp, mp);
880 			else
881 				freemsg(mp);
882 			continue;
883 		default:
884 			cmn_err(CE_NOTE, "kb8042_wsrv: bad msg %x",
885 			    mp->b_datap->db_type);
886 			freemsg(mp);
887 			continue;
888 		}
889 	}
890 
891 	mutex_enter(&kb8042->w_hw_mutex);
892 	if (!suspended) {
893 		ASSERT(kb8042->ops > 0);
894 		kb8042->ops--;
895 		if (kb8042->ops == 0)
896 			cv_broadcast(&kb8042->ops_cv);
897 	}
898 	mutex_exit(&kb8042->w_hw_mutex);
899 
900 	return (0);
901 }
902 
903 static void
904 kb8042_ioctlmsg(struct kb8042 *kb8042, queue_t *qp, mblk_t *mp)
905 {
906 	struct iocblk	*iocp;
907 	mblk_t		*datap;
908 	int		error;
909 	int		tmp;
910 	int		cycles;
911 	int		frequency;
912 	int		msecs;
913 
914 	iocp = (struct iocblk *)mp->b_rptr;
915 
916 	switch (iocp->ioc_cmd) {
917 
918 	case CONSOPENPOLLEDIO:
919 		error = miocpullup(mp, sizeof (struct cons_polledio *));
920 		if (error != 0) {
921 			miocnak(qp, mp, 0, error);
922 			return;
923 		}
924 
925 		/*
926 		 * We are given an appropriate-sized data block,
927 		 * and return a pointer to our structure in it.
928 		 */
929 		*(struct cons_polledio **)mp->b_cont->b_rptr =
930 		    &kb8042->polledio;
931 		mp->b_datap->db_type = M_IOCACK;
932 		iocp->ioc_error = 0;
933 		qreply(qp, mp);
934 		break;
935 
936 	case CONSCLOSEPOLLEDIO:
937 		miocack(qp, mp, 0, 0);
938 		break;
939 
940 	case CONSSETABORTENABLE:
941 		if (iocp->ioc_count != TRANSPARENT) {
942 			miocnak(qp, mp, 0, EINVAL);
943 			return;
944 		}
945 
946 		kb8042->debugger.enabled = *(intptr_t *)mp->b_cont->b_rptr;
947 		miocack(qp, mp, 0, 0);
948 		break;
949 
950 	/*
951 	 * Valid only in TR_UNTRANS_MODE mode.
952 	 */
953 	case CONSSETKBDTYPE:
954 		error = miocpullup(mp, sizeof (int));
955 		if (error != 0) {
956 			miocnak(qp, mp, 0, error);
957 			return;
958 		}
959 		tmp =  *(int *)mp->b_cont->b_rptr;
960 		if (tmp != KB_PC && tmp != KB_USB) {
961 			miocnak(qp, mp, 0, EINVAL);
962 			break;
963 		}
964 		kb8042->simulated_kbd_type = tmp;
965 		miocack(qp, mp, 0, 0);
966 		break;
967 
968 	case KIOCLAYOUT:
969 		if (kb8042->w_kblayout == -1) {
970 			miocnak(qp, mp, 0, EINVAL);
971 			return;
972 		}
973 
974 		if ((datap = allocb(sizeof (int), BPRI_HI)) == NULL) {
975 			miocnak(qp, mp, 0, ENOMEM);
976 			return;
977 		}
978 
979 		if (kb8042->simulated_kbd_type == KB_USB)
980 			*(int *)datap->b_wptr = KBTRANS_USBKB_DEFAULT_LAYOUT;
981 		else
982 			*(int *)datap->b_wptr = kb8042->w_kblayout;
983 
984 		datap->b_wptr += sizeof (int);
985 		if (mp->b_cont)
986 			freemsg(mp->b_cont);
987 		mp->b_cont = datap;
988 		iocp->ioc_count = sizeof (int);
989 		mp->b_datap->db_type = M_IOCACK;
990 		iocp->ioc_error = 0;
991 		qreply(qp, mp);
992 		break;
993 
994 	case KIOCSLAYOUT:
995 		if (iocp->ioc_count != TRANSPARENT) {
996 			miocnak(qp, mp, 0, EINVAL);
997 			return;
998 		}
999 
1000 		kb8042->w_kblayout = *(intptr_t *)mp->b_cont->b_rptr;
1001 		miocack(qp, mp, 0, 0);
1002 		break;
1003 
1004 	case KIOCCMD:
1005 		error = miocpullup(mp, sizeof (int));
1006 		if (error != 0) {
1007 			miocnak(qp, mp, 0, error);
1008 			return;
1009 		}
1010 
1011 		kb8042_type4_cmd(kb8042, *(int *)mp->b_cont->b_rptr);
1012 		miocack(qp, mp, 0, 0);
1013 		break;
1014 
1015 	case KIOCMKTONE:
1016 		if (iocp->ioc_count != TRANSPARENT) {
1017 			miocnak(qp, mp, 0, EINVAL);
1018 			return;
1019 		}
1020 
1021 		tmp = (int)(*(intptr_t *)mp->b_cont->b_rptr);
1022 		cycles = tmp & 0xffff;
1023 		msecs = (tmp >> 16) & 0xffff;
1024 
1025 		if (cycles == 0)
1026 			frequency = UINT16_MAX;
1027 		else if (cycles == UINT16_MAX)
1028 			frequency = 0;
1029 		else {
1030 			frequency = (PIT_HZ + cycles / 2) / cycles;
1031 			if (frequency > UINT16_MAX)
1032 				frequency = UINT16_MAX;
1033 		}
1034 
1035 		error = beep_mktone(frequency, msecs);
1036 		if (error != 0)
1037 			miocnak(qp, mp, 0, error);
1038 		else
1039 			miocack(qp, mp, 0, 0);
1040 		break;
1041 
1042 	default:
1043 #ifdef DEBUG1
1044 		cmn_err(CE_NOTE, "!kb8042_ioctlmsg %x", iocp->ioc_cmd);
1045 #endif
1046 		miocnak(qp, mp, 0, EINVAL);
1047 		return;
1048 	}
1049 }
1050 
1051 /*
1052  * Process a byte received from the keyboard
1053  */
1054 static void
1055 kb8042_received_byte(
1056 	struct kb8042	*kb8042,
1057 	int		scancode)	/* raw scan code */
1058 {
1059 	boolean_t	legit;		/* is this a legit key pos'n? */
1060 	int		key_pos = -1;
1061 	enum keystate	state;
1062 	boolean_t	synthetic_release_needed;
1063 
1064 	if (!kb8042->w_init)	/* can't do anything anyway */
1065 		return;
1066 
1067 	legit = KeyboardConvertScan(kb8042, scancode, &key_pos, &state,
1068 	    &synthetic_release_needed);
1069 
1070 	if (legit == 0) {
1071 		/* Eaten by translation */
1072 		return;
1073 	}
1074 
1075 	/*
1076 	 * Don't know if we want this permanently, but it seems interesting
1077 	 * for the moment.
1078 	 */
1079 	if (key_pos == kb8042->debugger.mod1) {
1080 		kb8042->debugger.mod1_down = (state == KEY_PRESSED);
1081 	}
1082 	if (key_pos == kb8042->debugger.mod2) {
1083 		kb8042->debugger.mod2_down = (state == KEY_PRESSED);
1084 	}
1085 	if (kb8042->debugger.enabled &&
1086 	    key_pos == kb8042->debugger.trigger &&
1087 	    kb8042->debugger.mod1_down &&
1088 	    kb8042->debugger.mod2_down) {
1089 		/*
1090 		 * Require new presses of the modifiers.
1091 		 */
1092 		kb8042->debugger.mod1_down = B_FALSE;
1093 		kb8042->debugger.mod2_down = B_FALSE;
1094 		abort_sequence_enter(NULL);
1095 		return;
1096 	}
1097 
1098 	/*
1099 	 * If there's no queue above us - as can happen if we've been
1100 	 * attached but not opened - drop the keystroke.
1101 	 * Note that we do this here instead of above so that
1102 	 * Ctrl-Alt-D still works.
1103 	 */
1104 	if (kb8042->w_qp == NULL) {
1105 		return;
1106 	}
1107 
1108 	/*
1109 	 * This is to filter out auto repeat since it can't be
1110 	 * turned off at the hardware.  (Yeah, yeah, PS/2 keyboards
1111 	 * can.  Don't know whether they've taken over the world.
1112 	 * Don't think so.)
1113 	 */
1114 	if (kb8042_autorepeat_detect(kb8042, key_pos, state)) {
1115 		return;
1116 	}
1117 
1118 
1119 	kb8042_process_key(kb8042, key_pos, state);
1120 
1121 	/*
1122 	 * This is a total hack.  For some stupid reason, the two additional
1123 	 * keys on Korean keyboards (Hangul and Hangul/Hanja) report press
1124 	 * only.  We synthesize a release immediately.
1125 	 */
1126 	if (synthetic_release_needed) {
1127 		(void) kb8042_autorepeat_detect(kb8042, key_pos, KEY_RELEASED);
1128 		kb8042_process_key(kb8042, key_pos, state);
1129 	}
1130 }
1131 
1132 
1133 static void
1134 kb8042_process_key(struct kb8042 *kb8042, kbtrans_key_t key_pos,
1135     enum keystate state)
1136 {
1137 	kbtrans_key_t key;
1138 
1139 	ASSERT(key_pos >= 0 && key_pos <= 255);
1140 	if (kb8042->simulated_kbd_type == KB_PC) {
1141 		kbtrans_streams_key(kb8042->hw_kbtrans, key_pos, state);
1142 	} else if (kb8042->simulated_kbd_type == KB_USB) {
1143 		key = keytab_pc2usb[key_pos];
1144 		if (key != 0) {
1145 			kbtrans_streams_key(kb8042->hw_kbtrans, key, state);
1146 		}
1147 	}
1148 }
1149 
1150 /*
1151  * Called from interrupt handler when keyboard interrupt occurs.
1152  */
1153 static uint_t
1154 kb8042_intr(caddr_t arg)
1155 {
1156 	uchar_t scancode;	/* raw scan code */
1157 	int rc;
1158 	struct kb8042 *kb8042 = (struct kb8042 *)arg;
1159 
1160 	rc = DDI_INTR_UNCLAIMED;
1161 
1162 	if (kb8042->init_state == KB8042_UNINITIALIZED)
1163 		return (DDI_INTR_UNCLAIMED);
1164 
1165 	/* don't care if drv_setparm succeeds */
1166 	(void) drv_setparm(SYSRINT, 1);
1167 
1168 	while (ddi_get8(kb8042->handle, kb8042->addr + I8042_INT_INPUT_AVAIL)
1169 	    != 0) {
1170 		mblk_t *mp;
1171 
1172 		rc = DDI_INTR_CLAIMED;
1173 
1174 		scancode = ddi_get8(kb8042->handle,
1175 		    kb8042->addr + I8042_INT_INPUT_DATA);
1176 
1177 		/*
1178 		 * Intercept ACK and RESEND and signal the condition that
1179 		 * kb8042_send_and_wait is waiting for.
1180 		 */
1181 		switch (scancode) {
1182 		case KB_ACK:
1183 			mutex_enter(&kb8042->w_hw_mutex);
1184 			kb8042->acked = 1;
1185 			cv_signal(&kb8042->cmd_cv);
1186 			mutex_exit(&kb8042->w_hw_mutex);
1187 			return (rc);
1188 		case KB_RESEND:
1189 			mutex_enter(&kb8042->w_hw_mutex);
1190 			kb8042->need_retry = 1;
1191 			cv_signal(&kb8042->cmd_cv);
1192 			mutex_exit(&kb8042->w_hw_mutex);
1193 			return (rc);
1194 		default:
1195 			break;
1196 		}
1197 
1198 		if ((mp = allocb(sizeof (scancode), BPRI_HI)) == NULL)
1199 			return (rc);
1200 		*mp->b_wptr++ = scancode;
1201 		if (putq(RD(kb8042->w_qp), mp) == 0)
1202 			freemsg(mp);
1203 	}
1204 
1205 	return (rc);
1206 }
1207 
1208 static void
1209 kb8042_iocdatamsg(queue_t *qp, mblk_t *mp)
1210 {
1211 	struct copyresp	*csp;
1212 
1213 	csp = (struct copyresp *)mp->b_rptr;
1214 	if (csp->cp_rval) {
1215 		freemsg(mp);
1216 		return;
1217 	}
1218 
1219 	switch (csp->cp_cmd) {
1220 	default:
1221 		miocack(qp, mp, 0, 0);
1222 		break;
1223 	}
1224 }
1225 
1226 static boolean_t
1227 kb8042_polled_keycheck(
1228     struct kbtrans_hardware *hw,
1229     int *key,
1230     enum keystate *state)
1231 {
1232 	struct kb8042 *kb8042 = (struct kb8042 *)hw;
1233 	int	scancode;
1234 	boolean_t	legit;
1235 	boolean_t	synthetic_release_needed;
1236 
1237 	if (kb8042->polled_synthetic_release_pending) {
1238 		*key = kb8042->polled_synthetic_release_key;
1239 		*state = KEY_RELEASED;
1240 		kb8042->polled_synthetic_release_pending = B_FALSE;
1241 		(void) kb8042_autorepeat_detect(kb8042, *key, *state);
1242 		return (B_TRUE);
1243 	}
1244 
1245 	for (;;) {
1246 		if (ddi_get8(kb8042->handle,
1247 		    kb8042->addr + I8042_POLL_INPUT_AVAIL) == 0) {
1248 			return (B_FALSE);
1249 		}
1250 
1251 		scancode = ddi_get8(kb8042->handle,
1252 		    kb8042->addr + I8042_POLL_INPUT_DATA);
1253 
1254 		legit = KeyboardConvertScan(kb8042, scancode, key, state,
1255 		    &synthetic_release_needed);
1256 		if (!legit) {
1257 			continue;
1258 		}
1259 		/*
1260 		 * For the moment at least, we rely on hardware autorepeat
1261 		 * for polled I/O autorepeat.  However, for coordination
1262 		 * with the interrupt-driven code, maintain the last key
1263 		 * pressed.
1264 		 */
1265 		(void) kb8042_autorepeat_detect(kb8042, *key, *state);
1266 
1267 		/*
1268 		 * This is a total hack to support two additional keys
1269 		 * on Korean keyboards.  They report only on press, and
1270 		 * so we synthesize a release.  Most likely this will
1271 		 * never be important to polled  I/O, but if I do it
1272 		 * "right" the first time it _won't_ be an issue.
1273 		 */
1274 		if (synthetic_release_needed) {
1275 			kb8042->polled_synthetic_release_pending = B_TRUE;
1276 			kb8042->polled_synthetic_release_key = *key;
1277 		}
1278 
1279 		if (kb8042->simulated_kbd_type == KB_USB) {
1280 			*key = keytab_pc2usb[*key];
1281 		}
1282 		return (B_TRUE);
1283 	}
1284 }
1285 
1286 static void
1287 kb8042_setled(struct kb8042 *kb8042, int led_state, boolean_t polled)
1288 {
1289 	kb8042->leds.desired = led_state;
1290 
1291 	if (!polled)
1292 		mutex_enter(&kb8042->w_hw_mutex);
1293 
1294 	if (kb8042->leds.desired != kb8042->leds.commanded) {
1295 		kb8042_send_to_keyboard(kb8042, KB_SET_LED, polled);
1296 	}
1297 
1298 	if (!polled)
1299 		mutex_exit(&kb8042->w_hw_mutex);
1300 }
1301 
1302 static void
1303 kb8042_polled_setled(struct kbtrans_hardware *hw, int led_state)
1304 {
1305 	struct kb8042 *kb8042 = (struct kb8042 *)hw;
1306 	kb8042_setled(kb8042, led_state, B_TRUE);
1307 }
1308 
1309 static void
1310 kb8042_streams_setled(struct kbtrans_hardware *hw, int led_state)
1311 {
1312 	struct kb8042 *kb8042 = (struct kb8042 *)hw;
1313 	kb8042_setled(kb8042, led_state, B_FALSE);
1314 }
1315 
1316 
1317 static int
1318 kb8042_send_and_wait(struct kb8042 *kb8042, uint8_t u8, boolean_t polled)
1319 {
1320 	uint8_t *outp = kb8042->addr +
1321 	    (polled ? I8042_POLL_OUTPUT_DATA : I8042_INT_OUTPUT_DATA);
1322 	uint8_t *inavp = kb8042->addr +
1323 	    (polled ? I8042_POLL_INPUT_AVAIL : I8042_INT_INPUT_AVAIL);
1324 	uint8_t *inp = kb8042->addr +
1325 	    (polled ? I8042_POLL_INPUT_DATA : I8042_INT_INPUT_DATA);
1326 	uint8_t b;
1327 	int ms_waited;
1328 	int timedout;
1329 	int expire;
1330 	int retries = 0;
1331 
1332 	do {
1333 		kb8042->acked = 0;
1334 		kb8042->need_retry = 0;
1335 		ms_waited = 0;		/* Zero it whether polled or not */
1336 		timedout = 0;
1337 
1338 		ddi_put8(kb8042->handle, outp, u8);
1339 
1340 		while (!kb8042->acked && !kb8042->need_retry && !timedout) {
1341 
1342 			if (polled) {
1343 				if (ddi_get8(kb8042->handle, inavp)) {
1344 					b = ddi_get8(kb8042->handle, inp);
1345 					switch (b) {
1346 					case KB_ACK:
1347 						kb8042->acked = 1;
1348 						break;
1349 					case KB_RESEND:
1350 						kb8042->need_retry = 1;
1351 						break;
1352 					default:
1353 						/*
1354 						 * drop it: We should never
1355 						 * get scancodes while
1356 						 * we're in the middle of a
1357 						 * command anyway.
1358 						 */
1359 #ifdef DEBUG
1360 						cmn_err(CE_WARN, "!Unexpected "
1361 						    " byte 0x%x", b);
1362 #endif
1363 						break;
1364 					}
1365 				}
1366 
1367 				/*
1368 				 * Wait 1ms if an ACK wasn't received yet
1369 				 */
1370 				if (!kb8042->acked) {
1371 					drv_usecwait(1000);
1372 					ms_waited++;
1373 					if (ms_waited >= MAX_KB8042_WAIT_MAX_MS)
1374 						timedout = B_TRUE;
1375 				}
1376 			} else {
1377 				/* Interrupt-driven */
1378 				expire = ddi_get_lbolt() +
1379 				    drv_usectohz(MAX_KB8042_WAIT_MAX_MS * 1000);
1380 
1381 				/*
1382 				 * If cv_timedwait returned -1 and we neither
1383 				 * received an ACK nor a RETRY response, then
1384 				 * we timed out.
1385 				 */
1386 				if (cv_timedwait(&kb8042->cmd_cv,
1387 				    &kb8042->w_hw_mutex, expire) == -1 &&
1388 				    !kb8042->acked && !kb8042->need_retry) {
1389 					timedout = B_TRUE;
1390 				}
1391 			}
1392 
1393 		}
1394 	} while ((kb8042->need_retry || timedout) &&
1395 	    ++retries < MAX_KB8042_RETRIES);
1396 
1397 	return (kb8042->acked);
1398 }
1399 
1400 /*
1401  * kb8042_send_to_keyboard should be called with w_hw_mutex held if
1402  * polled is FALSE.
1403  */
1404 static void
1405 kb8042_send_to_keyboard(struct kb8042 *kb8042, int byte, boolean_t polled)
1406 {
1407 
1408 	/*
1409 	 * KB_SET_LED and KB_ENABLE are special commands which require blocking
1410 	 * other 8042 consumers while executing.
1411 	 *
1412 	 * Other commands/data are sent using the single put8 I/O access
1413 	 * function.
1414 	 */
1415 	if (byte == KB_SET_LED) {
1416 
1417 		if (!polled) {
1418 			(void) ddi_get8(kb8042->handle, kb8042->addr +
1419 			    I8042_LOCK);
1420 		}
1421 
1422 		if (kb8042_send_and_wait(kb8042, KB_SET_LED, polled)) {
1423 			/*
1424 			 * Ignore return value, as there's nothing we can
1425 			 * do about it if the SET LED command fails.
1426 			 */
1427 			(void) kb8042_send_and_wait(kb8042,
1428 			    kb8042_xlate_leds(kb8042->leds.desired), polled);
1429 		}
1430 
1431 		if (!polled) {
1432 			(void) ddi_get8(kb8042->handle, kb8042->addr +
1433 			    I8042_UNLOCK);
1434 		}
1435 		kb8042->leds.commanded = kb8042->leds.desired;
1436 
1437 	} else if (byte == KB_ENABLE) {
1438 
1439 		if (!polled) {
1440 			(void) ddi_get8(kb8042->handle, kb8042->addr +
1441 			    I8042_LOCK);
1442 		}
1443 
1444 		(void) kb8042_send_and_wait(kb8042, KB_ENABLE, polled);
1445 
1446 		if (!polled) {
1447 			(void) ddi_get8(kb8042->handle, kb8042->addr +
1448 			    I8042_UNLOCK);
1449 		}
1450 
1451 	} else {
1452 		/* All other commands use the "normal" virtual output port */
1453 		if (polled) {
1454 			ddi_put8(kb8042->handle,
1455 			    kb8042->addr + I8042_POLL_OUTPUT_DATA, byte);
1456 		} else {
1457 			ddi_put8(kb8042->handle,
1458 			    kb8042->addr + I8042_INT_OUTPUT_DATA, byte);
1459 		}
1460 	}
1461 }
1462 
1463 /*
1464  * Wait until the keyboard is fully up, maybe.
1465  * We may be the first person to talk to the keyboard, in which case
1466  * it's patiently waiting to say "AA" to us to tell us it's up.
1467  * In theory it sends the AA in 300ms < n < 9s, but it's a pretty
1468  * good bet that we've already spent that long getting to that point,
1469  * so we'll only wait long enough for the communications electronics to
1470  * run.
1471  */
1472 static void
1473 kb8042_wait_poweron(struct kb8042 *kb8042)
1474 {
1475 	int cnt;
1476 	int ready;
1477 
1478 	/* wait for up to 250 ms for a response */
1479 	for (cnt = 0; cnt < 250; cnt++) {
1480 		ready = ddi_get8(kb8042->handle,
1481 		    kb8042->addr + I8042_INT_INPUT_AVAIL);
1482 		if (ready != 0)
1483 			break;
1484 		drv_usecwait(1000);
1485 	}
1486 
1487 	/*
1488 	 * If there's something pending, read and discard it.  If not,
1489 	 * assume things are OK anyway - maybe somebody else ate it
1490 	 * already.  (On a PC, the BIOS almost certainly did.)
1491 	 */
1492 	if (ready != 0) {
1493 		(void) ddi_get8(kb8042->handle,
1494 		    kb8042->addr + I8042_INT_INPUT_DATA);
1495 	}
1496 }
1497 
1498 static int
1499 kb8042_xlate_leds(int led)
1500 {
1501 	int res;
1502 
1503 	res = 0;
1504 
1505 	if (led & LED_NUM_LOCK)
1506 		res |= LED_NUM;
1507 	if (led & LED_SCROLL_LOCK)
1508 		res |= LED_SCR;
1509 	if (led & LED_CAPS_LOCK)
1510 		res |= LED_CAP;
1511 
1512 	return (res);
1513 }
1514 
1515 /*ARGSUSED*/
1516 static void
1517 kb8042_get_initial_leds(
1518     struct kb8042 *kb8042,
1519     int *initial_leds,
1520     int *initial_led_mask)
1521 {
1522 #if defined(__x86)
1523 	extern caddr_t	p0_va;
1524 	uint8_t		bios_kb_flag;
1525 
1526 	bios_kb_flag = p0_va[BIOS_KB_FLAG];
1527 
1528 	*initial_led_mask = LED_CAPS_LOCK | LED_NUM_LOCK | LED_SCROLL_LOCK;
1529 	*initial_leds = 0;
1530 	if (bios_kb_flag & BIOS_CAPS_STATE)
1531 		*initial_leds |= LED_CAPS_LOCK;
1532 	if (bios_kb_flag & BIOS_NUM_STATE)
1533 		*initial_leds |= LED_NUM_LOCK;
1534 	if (bios_kb_flag & BIOS_SCROLL_STATE)
1535 		*initial_leds |= LED_SCROLL_LOCK;
1536 #else
1537 	*initial_leds = 0;
1538 	*initial_led_mask = 0;
1539 #endif
1540 }
1541 
1542 static boolean_t
1543 kb8042_autorepeat_detect(
1544     struct kb8042 *kb8042,
1545     int key_pos,
1546     enum keystate state)
1547 {
1548 	if (state == KEY_RELEASED) {
1549 		if (kb8042->kb_old_key_pos == key_pos)
1550 			kb8042->kb_old_key_pos = 0;
1551 	} else {
1552 		if (kb8042->kb_old_key_pos == key_pos) {
1553 			return (B_TRUE);
1554 		}
1555 		kb8042->kb_old_key_pos = key_pos;
1556 	}
1557 	return (B_FALSE);
1558 }
1559 
1560 /* ARGSUSED */
1561 static void
1562 kb8042_type4_cmd(struct kb8042 *kb8042, int cmd)
1563 {
1564 	switch (cmd) {
1565 	case KBD_CMD_BELL:
1566 		(void) beeper_on(BEEP_TYPE4);
1567 		break;
1568 	case KBD_CMD_NOBELL:
1569 		(void) beeper_off();
1570 		break;
1571 	}
1572 }
1573 
1574 
1575 /*
1576  * This is a pass-thru routine to get a character at poll time.
1577  */
1578 static int
1579 kb8042_polled_getchar(cons_polledio_arg_t arg)
1580 {
1581 	struct kb8042	*kb8042;
1582 
1583 	kb8042 = (struct kb8042 *)arg;
1584 
1585 	return (kbtrans_getchar(kb8042->hw_kbtrans));
1586 }
1587 
1588 /*
1589  * This is a pass-thru routine to get a character at poll time.
1590  */
1591 static int
1592 kb8042_polled_ischar(cons_polledio_arg_t arg)
1593 {
1594 	struct kb8042	*kb8042;
1595 
1596 	kb8042 = (struct kb8042 *)arg;
1597 
1598 	return (kbtrans_ischar(kb8042->hw_kbtrans));
1599 }
1600