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