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