xref: /titanic_52/usr/src/uts/common/io/conskbd.c (revision 1959748cbddf37d4734c107dadfa449e076045e3)
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 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * Console kbd multiplexor driver for Sun.
31  * The console "zs" port is linked under us, with the "kbd" module pushed
32  * on top of it.
33  * Minor device 0 is what programs normally use.
34  * Minor device 1 is used to feed predigested keystrokes to the "workstation
35  * console" driver, which it is linked beneath.
36  *
37  *
38  *     This module can support multiple keyboards to be used simultaneously.
39  * and enable users to use at a time multiple keyboards connected to the
40  * same system. All the keyboards are linked under conskbd, and act as a
41  * keyboard with replicated keys.
42  *
43  *     The DIN keyboards of SUN, for exmple , type 3/4/5,  are supported via
44  * a two-level architecure. The lower one is one of serialport drivers, such
45  * as zs, se, and the upper is  "kb" STREAMS module. Currenly, the serialport
46  * drivers don't support polled I/O interfaces, we couldn't group the keyboard
47  * of this kind under conskbd. So we do as the follows:
48  *
49  *         A new ioctl CONSSETKBDTYPE interface between conskbd and lower
50  *     keyboard drivers is added. When conskbd receives I_LINK or I_PLINK
51  *     ioctl, it will send a CONSSETKBDTYPE ioctl to the driver which is
52  *     requesting to be linked under conskbd. If the lower driver does't
53  *     recognize this ioctl, the virtual keyboard will be disabled so that
54  *     only one keyboard instance could be linked under conskbd.
55  */
56 #define	KEYMAP_SIZE_VARIABLE
57 
58 #include <sys/types.h>
59 #include <sys/param.h>
60 #include <sys/stropts.h>
61 #include <sys/stream.h>
62 #include <sys/strsubr.h>
63 #include <sys/strsun.h>
64 #include <sys/conf.h>
65 #include <sys/stat.h>
66 #include <sys/errno.h>
67 #include <sys/modctl.h>
68 #include <sys/kbio.h>
69 #include <sys/ddi.h>
70 #include <sys/sunddi.h>
71 #include <sys/consdev.h>
72 #include <sys/note.h>
73 #include <sys/kmem.h>
74 #include <sys/kstat.h>
75 #include <sys/policy.h>
76 #include <sys/kbd.h>
77 #include <sys/kbtrans.h>
78 #include <sys/promif.h>
79 #include <sys/vuid_event.h>
80 #include <sys/conskbd.h>
81 #include <sys/beep.h>
82 
83 extern struct keyboard *kbtrans_usbkb_maptab_init(void);
84 extern void kbtrans_usbkb_maptab_fini(struct keyboard **);
85 extern int ddi_create_internal_pathname(dev_info_t *, char *, int, minor_t);
86 
87 /*
88  * Module linkage routines for the kernel
89  */
90 static int conskbd_attach(dev_info_t *, ddi_attach_cmd_t);
91 static int conskbd_detach(dev_info_t *, ddi_detach_cmd_t);
92 static int conskbd_info(dev_info_t *, ddi_info_cmd_t, void *, void **);
93 
94 /*
95  * STREAMS queue processing procedures
96  */
97 static void	conskbduwsrv(queue_t *);
98 static void	conskbdlwserv(queue_t *);
99 static void	conskbdlrput(queue_t *, mblk_t *);
100 static int	conskbdclose(queue_t *, int, cred_t *);
101 static int	conskbdopen(queue_t *, dev_t *, int, int, cred_t *);
102 
103 
104 /* STREAMS driver id and limit value struct */
105 static struct module_info conskbdm_info = {
106 	0,		/* mi_idnum */
107 	"conskbd",	/* mi_idname */
108 	0,		/* mi_minpsz */
109 	1024,		/* mi_maxpsz */
110 	2048,		/* mi_hiwat */
111 	128		/* mi_lowat */
112 };
113 
114 /*
115  * STREAMS queue processing procedure structures
116  */
117 /* upper read queue processing procedure structures */
118 static struct qinit conskbdurinit = {
119 	NULL,			/* qi_putp */
120 	(int (*)())NULL,	/* qi_srvp */
121 	conskbdopen,		/* qi_qopen */
122 	conskbdclose,		/* qi_qclose */
123 	(int (*)())NULL,	/* qi_qadmin */
124 	&conskbdm_info,		/* qi_minfo */
125 	NULL			/* qi_mstat */
126 };
127 
128 /* upper write queue processing procedures structuresi */
129 static struct qinit conskbduwinit = {
130 	(int (*)())putq,		/* qi_putp */
131 	(int (*)())conskbduwsrv,	/* qi_srvp */
132 	conskbdopen,			/* qi_qopen */
133 	conskbdclose,			/* qi_qclose */
134 	(int (*)())NULL,		/* qi_qadmin */
135 	&conskbdm_info,			/* qi_minfo */
136 	NULL				/* qi_mstat */
137 };
138 
139 /* lower read queue processing procedures structures */
140 static struct qinit conskbdlrinit = {
141 	(int (*)())conskbdlrput,	/* qi_putp */
142 	(int (*)())NULL,		/* qi_srvp */
143 	(int (*)())NULL,		/* qi_qopen */
144 	(int (*)())NULL,		/* qi_qclose */
145 	(int (*)())NULL,		/* qi_qadmin */
146 	&conskbdm_info,			/* qi_minfo */
147 	NULL				/* qi_mstat */
148 };
149 
150 /* lower write processing procedures structures */
151 static struct qinit conskbdlwinit = {
152 	putq,				/* qi_putp */
153 	(int (*)())conskbdlwserv,	/* qi_srvp */
154 	(int (*)())NULL,		/* qi_qopen */
155 	(int (*)())NULL,		/* qi_qclose */
156 	(int (*)())NULL,		/* qi_qadmin */
157 	&conskbdm_info,			/* qi_minfo */
158 	NULL				/* qi_mstat */
159 };
160 
161 /* STREAMS entity declaration structure */
162 static struct streamtab conskbd_str_info = {
163 	&conskbdurinit,		/* st_rdinit */
164 	&conskbduwinit,		/* st_wrinit */
165 	&conskbdlrinit,		/* st_muxrinit */
166 	&conskbdlwinit,		/* st_muxwinit */
167 };
168 
169 
170 /* Entry points structure */
171 static 	struct cb_ops cb_conskbd_ops = {
172 	nulldev,		/* cb_open */
173 	nulldev,		/* cb_close */
174 	nodev,			/* cb_strategy */
175 	nodev,			/* cb_print */
176 	nodev,			/* cb_dump */
177 	nodev,			/* cb_read */
178 	nodev,			/* cb_write */
179 	nodev,			/* cb_ioctl */
180 	nodev,			/* cb_devmap */
181 	nodev,			/* cb_mmap */
182 	nodev,			/* cb_segmap */
183 	nochpoll,		/* cb_chpoll */
184 	ddi_prop_op,		/* cb_prop_op */
185 	&conskbd_str_info,	/* cb_stream */
186 	D_MP | D_MTOUTPERIM | D_MTOCEXCL	/* cb_flag */
187 };
188 
189 
190 /*
191  * Device operations structure
192  */
193 static struct dev_ops conskbd_ops = {
194 	DEVO_REV,		/* devo_rev */
195 	0,			/* devo_refcnt */
196 	conskbd_info,		/* devo_getinfo */
197 	nulldev,		/* devo_identify */
198 	nulldev,		/* devo_probe */
199 	conskbd_attach,		/* devo_attach */
200 	conskbd_detach,		/* devo_detach */
201 	nodev,			/* devo_reset */
202 	&(cb_conskbd_ops),	/* devo_cb_ops */
203 	(struct bus_ops *)NULL,	/* devo_bus_ops */
204 	NULL			/* devo_power */
205 };
206 
207 /*
208  * Module linkage information for the kernel.
209  */
210 static struct modldrv modldrv = {
211 	&mod_driverops, /* Type of module.  This one is a pseudo driver */
212 	"conskbd multiplexer driver %I%",
213 	&conskbd_ops,	/* driver ops */
214 };
215 
216 /*
217  * Module linkage structure
218  */
219 static struct modlinkage modlinkage = {
220 	MODREV_1,	/* ml_rev */
221 	&modldrv,	/* ml_linkage */
222 	NULL		/* NULL terminates the list */
223 };
224 
225 /*
226  * Debug printing
227  */
228 #ifndef DPRINTF
229 #ifdef DEBUG
230 void	conskbd_dprintf(const char *fmt, ...);
231 #define	DPRINTF(l, m, args) \
232 	(((l) >= conskbd_errlevel) && ((m) & conskbd_errmask) ?	\
233 		conskbd_dprintf args :				\
234 		(void) 0)
235 
236 /*
237  * Severity levels for printing
238  */
239 #define	PRINT_L0	0	/* print every message */
240 #define	PRINT_L1	1	/* debug */
241 #define	PRINT_L2	2	/* quiet */
242 
243 /*
244  * Masks
245  */
246 #define	PRINT_MASK_ALL		0xFFFFFFFFU
247 uint_t	conskbd_errmask = PRINT_MASK_ALL;
248 uint_t	conskbd_errlevel = PRINT_L2;
249 
250 #else
251 #define	DPRINTF(l, m, args)	/* NOTHING */
252 #endif
253 #endif
254 
255 /*
256  * Module global data are protected by outer perimeter. Modifying
257  * these global data is executed in outer perimeter exclusively.
258  * Except in conskbdopen() and conskbdclose(), which are entered
259  * exclusively (Refer to D_MTOCEXCL flag), all changes for the
260  * global variables are protected by qwriter().
261  */
262 static	queue_t	*conskbd_regqueue; /* regular keyboard queue above us */
263 static	queue_t	*conskbd_consqueue; /* console queue above us */
264 
265 
266 static dev_info_t *conskbd_dip;		/* private copy of devinfo pointer */
267 static long	conskbd_idle_stamp;	/* seconds tstamp of latest keystroke */
268 static struct keyboard *conskbd_keyindex;
269 
270 /*
271  * Normally, kstats of type KSTAT_TYPE_NAMED have multiple elements.  In
272  * this case we use this type for a single element because the ioctl code
273  * for it knows how to handle mixed kernel/user data models.  Also, it
274  * will be easier to add new statistics later.
275  */
276 static struct {
277 	kstat_named_t idle_sec;		/* seconds since last keystroke */
278 } conskbd_kstat = {
279 	{ "idle_sec", KSTAT_DATA_LONG, }
280 };
281 
282 /*
283  * Local routines prototypes
284  */
285 static int conskbd_kstat_update(kstat_t *, int);
286 
287 static void conskbd_ioctl(queue_t *, mblk_t *);
288 static void conskbd_ioc_plink(queue_t *, mblk_t *);
289 static void conskbd_ioc_punlink(queue_t *, mblk_t *);
290 static void conskbd_legacy_kbd_ioctl(queue_t *, mblk_t *);
291 static void conskbd_virtual_kbd_ioctl(queue_t *, mblk_t *);
292 static mblk_t *conskbd_alloc_firm_event(int, int);
293 
294 static conskbd_pending_msg_t *conskbd_mux_find_msg(mblk_t *);
295 static void conskbd_mux_enqueue_msg(conskbd_pending_msg_t *);
296 static void conskbd_mux_dequeue_msg(conskbd_pending_msg_t *);
297 static void conskbd_link_lowque_virt(queue_t *, mblk_t *);
298 static void conskbd_link_lowque_legacy(queue_t *, mblk_t *);
299 
300 static void conskbd_handle_downstream_msg(queue_t *, mblk_t *);
301 static void conskbd_kioctype_complete(conskbd_lower_queue_t *, mblk_t *);
302 static void conskbd_kioctrans_complete(conskbd_lower_queue_t *, mblk_t *);
303 static void conskbd_kioclayout_complete(conskbd_lower_queue_t *, mblk_t *);
304 static void conskbd_kiocsled_complete(conskbd_lower_queue_t *, mblk_t *);
305 static void conskbd_mux_upstream_msg(conskbd_lower_queue_t *, mblk_t *);
306 static void conskbd_legacy_upstream_msg(conskbd_lower_queue_t *, mblk_t *);
307 static void conskbd_lqs_ack_complete(conskbd_lower_queue_t *, mblk_t *);
308 
309 static void conskbd_polledio_enter(cons_polledio_arg_t);
310 static void conskbd_polledio_exit(cons_polledio_arg_t);
311 static int  conskbd_polledio_ischar(cons_polledio_arg_t);
312 static int  conskbd_polledio_getchar(cons_polledio_arg_t);
313 static void conskbd_polledio_setled(struct kbtrans_hardware *, int);
314 
315 static void conskbd_streams_setled(struct kbtrans_hardware *, int);
316 static boolean_t conskbd_override_kbtrans(queue_t *, mblk_t *);
317 static boolean_t
318 conskbd_polled_keycheck(struct kbtrans_hardware *,
319 		kbtrans_key_t *, enum keystate *);
320 
321 /*
322  * Callbacks needed by kbtrans
323  */
324 static struct kbtrans_callbacks conskbd_callbacks = {
325 	conskbd_streams_setled,
326 	conskbd_polledio_setled,
327 	conskbd_polled_keycheck,
328 };
329 
330 /*
331  * Single private "global" lock for the few rare conditions
332  * we want single-threaded.
333  */
334 static	kmutex_t	conskbd_msgq_lock;
335 static	conskbd_pending_msg_t	*conskbd_msg_queue;
336 
337 /*
338  * The software state structure of virtual keyboard.
339  * Currently, only one virtual keyboard is supported.
340  */
341 static conskbd_state_t	conskbd = { 0 };
342 
343 /* This variable backs up the layout state for non-self-ID keyboards */
344 static int kbd_layout_bak = 0;
345 
346 /*
347  * _init()
348  *
349  * Description:
350  *      Driver initialization, called when driver is first loaded.
351  *      This is how access is initially given to all the static structures.
352  *
353  * Arguments:
354  *      None
355  *
356  * Returns:
357  *      ddi_soft_state_init() status, see ddi_soft_state_init(9f), or
358  *      mod_install() status, see mod_install(9f)
359  */
360 int
361 _init(void)
362 {
363 	int	error;
364 
365 	error = mod_install(&modlinkage);
366 	if (error != 0) {
367 		return (error);
368 	}
369 
370 	conskbd_keyindex = kbtrans_usbkb_maptab_init();
371 
372 	mutex_init(&conskbd_msgq_lock, NULL, MUTEX_DRIVER, NULL);
373 
374 	return (error);
375 
376 }	/* _init() */
377 
378 /*
379  * _fini()
380  *
381  * Description:
382  *      Module de-initialization, called when the driver is to be unloaded.
383  *
384  * Arguments:
385  *      None
386  *
387  * Returns:
388  *      mod_remove() status, see mod_remove(9f)
389  */
390 int
391 _fini(void)
392 {
393 	int	error;
394 
395 	error = mod_remove(&modlinkage);
396 	if (error != 0)
397 		return (error);
398 	mutex_destroy(&conskbd_msgq_lock);
399 	kbtrans_usbkb_maptab_fini(&conskbd_keyindex);
400 
401 	return (0);
402 
403 }	/* _fini() */
404 
405 /*
406  * _info()
407  *
408  * Description:
409  *      Module information, returns information about the driver.
410  *
411  * Arguments:
412  *      modinfo         *modinfop       Pointer to the opaque modinfo structure
413  *
414  * Returns:
415  *      mod_info() status, see mod_info(9f)
416  */
417 int
418 _info(struct modinfo *modinfop)
419 {
420 	return (mod_info(&modlinkage, modinfop));
421 
422 }	/* _info() */
423 
424 
425 /*
426  * conskbd_attach()
427  *
428  * Description:
429  * 	This routine creates two device nodes. One is the "kbd" node, which
430  * is used by user application programs(such as Xserver).The other is the
431  * "conskbd" node, which is an internal node. consconfig_dacf module will
432  * open this internal node, and link the conskbd under the wc (workstaion
433  * console).
434  *
435  * Arguments:
436  *      dev_info_t      *dip    Pointer to the device's dev_info struct
437  *      ddi_attach_cmd_t cmd    Attach command
438  *
439  * Returns:
440  *      DDI_SUCCESS             The driver was initialized properly
441  *      DDI_FAILURE             The driver couldn't be initialized properly
442  */
443 /*ARGSUSED*/
444 static int
445 conskbd_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
446 {
447 	kstat_t	*ksp;
448 
449 	switch (cmd) {
450 	case DDI_ATTACH:
451 		break;
452 
453 	default:
454 		return (DDI_FAILURE);
455 
456 	}
457 	if ((ddi_create_minor_node(devi, "kbd", S_IFCHR,
458 	    0, DDI_PSEUDO, NULL) == DDI_FAILURE) ||
459 	    (ddi_create_internal_pathname(devi, "conskbd", S_IFCHR,
460 	    1) == DDI_FAILURE)) {
461 		ddi_remove_minor_node(devi, NULL);
462 		return (DDI_FAILURE);
463 	}
464 	conskbd_dip = devi;
465 
466 	ksp = kstat_create("conskbd", 0, "activity", "misc", KSTAT_TYPE_NAMED,
467 	    sizeof (conskbd_kstat) / sizeof (kstat_named_t),
468 	    KSTAT_FLAG_VIRTUAL);
469 	if (ksp) {
470 		ksp->ks_data = (void *) &conskbd_kstat;
471 		ksp->ks_update = conskbd_kstat_update;
472 		kstat_install(ksp);
473 		conskbd_idle_stamp = gethrestime_sec();	/* initial value */
474 	}
475 
476 	conskbd.conskbd_layout = -1;	/* invalid layout */
477 	conskbd.conskbd_led_state = -1;
478 	conskbd.conskbd_bypassed = B_FALSE;
479 
480 	return (DDI_SUCCESS);
481 
482 }	/* conskbd_attach() */
483 
484 /*
485  * conskbd_detach()
486  *
487  * Description:
488  *      Detach an instance of the conskbd driver. In fact, the driver can not
489  * be detached.
490  *
491  * Arguments:
492  *      dev_info_t              *dip    Pointer to the device's dev_info struct
493  *      ddi_detach_cmd_t        cmd     Detach command
494  *
495  * Returns:
496  *      DDI_SUCCESS     The driver was detached
497  *      DDI_FAILURE     The driver couldn't be detached
498  */
499 /*ARGSUSED*/
500 static int
501 conskbd_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
502 {
503 	return (DDI_FAILURE);
504 
505 }	/* conskbd_detach() */
506 
507 /* ARGSUSED */
508 static int
509 conskbd_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
510 	void **result)
511 {
512 	register int error;
513 
514 	switch (infocmd) {
515 	case DDI_INFO_DEVT2DEVINFO:
516 		if (conskbd_dip == NULL) {
517 			error = DDI_FAILURE;
518 		} else {
519 			*result = (void *) conskbd_dip;
520 			error = DDI_SUCCESS;
521 		}
522 		break;
523 	case DDI_INFO_DEVT2INSTANCE:
524 		*result = (void *)0;
525 		error = DDI_SUCCESS;
526 		break;
527 	default:
528 		error = DDI_FAILURE;
529 	}
530 	return (error);
531 
532 }	/* conskbd_info() */
533 
534 /*ARGSUSED*/
535 static int
536 conskbdopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *crp)
537 {
538 	dev_t	unit;
539 	int	err;
540 
541 	unit = getminor(*devp);
542 
543 	if (unit == 0) {
544 		/*
545 		 * Opening "/dev/kbd".
546 		 */
547 		conskbd_regqueue = q;
548 		qprocson(q);
549 		return (0);
550 	} else if (unit != 1) {
551 		/* we don't do that under Bozo's Big Tent */
552 		return (ENODEV);
553 	}
554 
555 	/*
556 	 * Check if already initialized
557 	 */
558 	if (conskbd_consqueue != NULL)
559 		return (0);
560 
561 	/*
562 	 * Opening the device to be linked under the console.
563 	 */
564 	conskbd_consqueue = q;
565 
566 	/*
567 	 * initialize kbtrans module for conskbd
568 	 */
569 	err = kbtrans_streams_init(q, sflag, crp, (struct kbtrans_hardware *)
570 	    &conskbd, &conskbd_callbacks, &conskbd.conskbd_kbtrans, 0, 0);
571 	if (err != 0)
572 		return (err);
573 	kbtrans_streams_set_keyboard(conskbd.conskbd_kbtrans, KB_USB,
574 	    conskbd_keyindex);
575 
576 	conskbd.conskbd_polledio.cons_polledio_version = CONSPOLLEDIO_V1;
577 	conskbd.conskbd_polledio.cons_polledio_argument =
578 	    (cons_polledio_arg_t)&conskbd;
579 	conskbd.conskbd_polledio.cons_polledio_putchar = NULL;
580 	conskbd.conskbd_polledio.cons_polledio_getchar =
581 	    (int (*)(cons_polledio_arg_t)) conskbd_polledio_getchar;
582 	conskbd.conskbd_polledio.cons_polledio_ischar =
583 	    (boolean_t (*)(cons_polledio_arg_t))conskbd_polledio_ischar;
584 	conskbd.conskbd_polledio.cons_polledio_enter = conskbd_polledio_enter;
585 	conskbd.conskbd_polledio.cons_polledio_exit = conskbd_polledio_exit;
586 	qprocson(q);
587 
588 	return (0);
589 
590 }	/* conskbdopen() */
591 
592 
593 /*ARGSUSED*/
594 static int
595 conskbdclose(queue_t *q, int flag, cred_t *crp)
596 {
597 	if (q == conskbd_regqueue) {
598 
599 		conskbd_pending_msg_t	*pmsg, *prev, *next;
600 		mblk_t		*mp;
601 
602 		/* switch the input stream back to conskbd_consqueue */
603 		conskbd.conskbd_directio = B_FALSE;
604 
605 		kbtrans_streams_untimeout(conskbd.conskbd_kbtrans);
606 		kbtrans_streams_set_queue(conskbd.conskbd_kbtrans,
607 		    conskbd_consqueue);
608 		qprocsoff(q);
609 		conskbd_regqueue = NULL;
610 
611 		/*
612 		 * If there are any pending ioctls which conskbd hasn't
613 		 * responded to yet, remove them from conskbd_msg_queue.
614 		 * Otherwise, we might send the response to a nonexistent
615 		 * closed queue. Refer to: conskbd_mux_upstream_msg().
616 		 */
617 		for (prev = NULL, pmsg = conskbd_msg_queue; pmsg != NULL;
618 		    pmsg = next) {
619 			next = pmsg->kpm_next;
620 			if (pmsg->kpm_upper_queue == WR(q)) {
621 				if (prev == NULL)
622 					conskbd_msg_queue = next;
623 				else
624 					prev->kpm_next = next;
625 
626 				while (pmsg->kpm_resp_list != NULL) {
627 					mp = pmsg->kpm_resp_list;
628 					pmsg->kpm_resp_list = mp->b_next;
629 					mp->b_next = mp->b_prev = NULL;
630 					freemsg(mp);
631 				}
632 				mutex_destroy(&pmsg->kpm_lock);
633 				kmem_free(pmsg, sizeof (*pmsg));
634 			} else {
635 				prev = pmsg;
636 			}
637 		}
638 	} else if (q == conskbd_consqueue) {
639 		/*
640 		 * Well, this is probably a mistake, but we will permit you
641 		 * to close the path to the console if you really insist.
642 		 */
643 		qprocsoff(q);
644 		conskbd_consqueue = NULL;
645 	}
646 
647 	return (0);
648 
649 }	/* conskbdclose() */
650 
651 /*
652  * Service procedure for upper write queue.
653  *	To make sure the order of messages, we don't process any
654  * message in qi_putq() routine of upper write queue, instead the
655  * qi_putq() routine, which is a standard putq() routine, puts all
656  * messages into a queue, and lets the following service procedure
657  * deal with all messages.
658  * 	This routine is invoked when ioctl commands are send down
659  * by a consumer of the keyboard device, eg, when the keyboard
660  * consumer tries to determine the keyboard layout type, or sets
661  * the led states.
662  */
663 static void
664 conskbduwsrv(queue_t *q)
665 {
666 	mblk_t	*mp;
667 	queue_t	*oldq;
668 	enum kbtrans_message_response ret;
669 	struct copyresp *csp;
670 	struct freq_request *frqp;
671 	int error;
672 
673 	while ((mp = getq(q)) != NULL) {
674 
675 		/*
676 		 * if the virtual keyboard is supported
677 		 */
678 		if (conskbd.conskbd_bypassed == B_FALSE) {
679 
680 			if (conskbd_override_kbtrans(q, mp) == B_TRUE)
681 				continue;
682 			/*
683 			 * The conskbd driver is a psaudo driver. It has two
684 			 * devcice nodes, one is used by kernel, and the other
685 			 * is used by end-users. There are two STREAMS queues
686 			 * corresponding to the two device nodes, console queue
687 			 * and regular queue.
688 			 * In conskbd_override_kbtrans() routine, when receives
689 			 * KIOCSDIRECT ioctl, we need change the direction of
690 			 * keyboard input messages, and direct the input stream
691 			 * from keyboard into right queue. It causes this queue
692 			 * to be switched between regular queue and console
693 			 * queue. And here, in this routine, the in-parameter
694 			 * "q" can be any one of the two. Moreover, this module
695 			 * is executed in multithreaded environment, even if the
696 			 * q is switched to regular queue, it is possible that
697 			 * the in-parameter is still the console queue, and we
698 			 * need to return response to right queue.
699 			 * The response is sent to upstream by the kbtrans
700 			 * module. so we need to save the old queue, and wait
701 			 * kbtrans to proces message and to send response out,
702 			 * and then switch back to old queue.
703 			 */
704 			oldq = kbtrans_streams_get_queue(
705 			    conskbd.conskbd_kbtrans);
706 			kbtrans_streams_set_queue(
707 			    conskbd.conskbd_kbtrans, RD(q));
708 			ret = kbtrans_streams_message(
709 			    conskbd.conskbd_kbtrans, mp);
710 			kbtrans_streams_set_queue(
711 			    conskbd.conskbd_kbtrans, oldq);
712 
713 			switch (ret) {
714 				case KBTRANS_MESSAGE_HANDLED:
715 					continue;
716 				case KBTRANS_MESSAGE_NOT_HANDLED:
717 					break;
718 			}
719 		}
720 
721 		switch (mp->b_datap->db_type) {
722 
723 		case M_IOCTL:
724 			conskbd_ioctl(q, mp);
725 			break;
726 
727 		case M_FLUSH:
728 			if (*mp->b_rptr & FLUSHW) {
729 				flushq(q, FLUSHDATA);
730 			}
731 			/*
732 			 * here, if flush read queue, some key-up messages
733 			 * may be lost so that upper module or applications
734 			 * treat corresponding keys as being held down for
735 			 * ever.
736 			 */
737 			freemsg(mp);
738 			break;
739 
740 		case M_DATA:
741 			/*
742 			 * virtual keyboard doesn't support this interface.
743 			 * only when it is disabled, we pass the message
744 			 * down to lower queue.
745 			 */
746 			if ((conskbd.conskbd_bypassed) &&
747 			    (conskbd.conskbd_lqueue_nums > 0)) {
748 				if (putq(conskbd.conskbd_lqueue_list->
749 				    lqs_queue, mp) != 1)
750 					freemsg(mp);
751 			} else {
752 				freemsg(mp);
753 			}
754 			break;
755 
756 		case M_IOCDATA:
757 			/*
758 			 * Only deal with copyresp to KIOCSETFREQ
759 			 * transparent ioctl now
760 			 */
761 			csp = (struct copyresp *)mp->b_rptr;
762 			if (csp->cp_rval) {
763 				miocnak(q, mp, 0, EINVAL);
764 				break;
765 			}
766 
767 			error = 0;
768 			switch (csp->cp_cmd) {
769 			case KIOCSETFREQ:
770 				frqp = (struct freq_request *)mp->
771 				    b_cont->b_rptr;
772 
773 				switch (frqp->type) {
774 				case CONSOLE_BEEP:
775 					error = beeper_freq(BEEP_CONSOLE,
776 					    (int)frqp->freq);
777 						break;
778 
779 				case KBD_BEEP:
780 					error = beeper_freq(BEEP_TYPE4,
781 					    (int)frqp->freq);
782 						break;
783 
784 				default:
785 					error = 1;
786 				} /* frqp->type */
787 
788 				break;
789 
790 			default:
791 				error = 1;
792 			} /* csp->cp_cmd */
793 
794 			if (error == 0)
795 				miocack(q, mp, 0, 0);
796 			else
797 				miocnak(q, mp, 0, EINVAL);
798 
799 			break;
800 
801 		default:
802 			/*
803 			 * Pass an error message up.
804 			 */
805 			mp->b_datap->db_type = M_ERROR;
806 			if (mp->b_cont) {
807 				freemsg(mp->b_cont);
808 				mp->b_cont = NULL;
809 			}
810 			mp->b_rptr = mp->b_datap->db_base;
811 			mp->b_wptr = mp->b_rptr + sizeof (char);
812 			*mp->b_rptr = EINVAL;
813 			qreply(q, mp);
814 		}
815 	}	/* end of while */
816 
817 }	/* conskbduwsrv() */
818 
819 static void
820 conskbd_ioctl(queue_t *q, mblk_t *mp)
821 {
822 	struct	iocblk			*iocp;
823 	int	error = 0;
824 
825 	iocp = (struct iocblk *)mp->b_rptr;
826 
827 	switch (iocp->ioc_cmd) {
828 
829 	case I_LINK:
830 	case I_PLINK:
831 		if (conskbd.conskbd_bypassed == B_TRUE) {
832 		/*
833 		 * A legacy keyboard can NOT be connected to conskbd together
834 		 * with other keyboards. So when a legacy keyboard is already
835 		 * linked under conkbd, we just reject all others.
836 		 */
837 			miocnak(q, mp, 0, EAGAIN);
838 			break;
839 		}
840 		qwriter(q, mp, conskbd_ioc_plink, PERIM_OUTER);
841 		break;
842 
843 	case I_UNLINK:
844 	case I_PUNLINK:
845 		qwriter(q, mp, conskbd_ioc_punlink, PERIM_OUTER);
846 		break;
847 
848 	case KIOCSKABORTEN:
849 		/*
850 		 * Check if privileged
851 		 */
852 		if ((error = secpolicy_sys_config(iocp->ioc_cr, B_FALSE))) {
853 			miocnak(q, mp, 0, error);
854 			return;
855 		}
856 
857 		error = miocpullup(mp, sizeof (int));
858 		if (error != 0) {
859 			miocnak(q, mp, 0, error);
860 			return;
861 		}
862 
863 		abort_enable = *(int *)mp->b_cont->b_rptr;
864 		miocack(q, mp, 0, 0);
865 		break;
866 
867 	case KIOCSETFREQ:
868 		if (iocp->ioc_count != TRANSPARENT) {
869 			/*
870 			 * We don't support non-transparent ioctls,
871 			 * i.e. I_STR ioctls
872 			 */
873 			miocnak(q, mp, 0, EINVAL);
874 		} else {
875 			/* Transparent ioctl */
876 			mcopyin(mp, NULL, sizeof (struct freq_request), NULL);
877 			qreply(q, mp);
878 		}
879 		break;
880 
881 	default:
882 		if (conskbd.conskbd_bypassed == B_TRUE) {
883 			conskbd_legacy_kbd_ioctl(q, mp);
884 		} else {
885 			conskbd_virtual_kbd_ioctl(q, mp);
886 		}
887 	}
888 
889 }	/* conskbd_ioctl() */
890 
891 
892 static void
893 conskbd_virtual_kbd_ioctl(queue_t *q, mblk_t *mp)
894 {
895 	struct iocblk		*iocp;
896 	mblk_t			*datap;
897 	int			cmd;
898 	int			error = 0;
899 
900 	iocp = (struct iocblk *)mp->b_rptr;
901 
902 	switch (iocp->ioc_cmd) {
903 	case KIOCLAYOUT:
904 		if ((datap = allocb(sizeof (int), BPRI_HI)) == NULL) {
905 			miocnak(q, mp, 0, ENOMEM);
906 			break;
907 		}
908 
909 		if (conskbd.conskbd_layout == -1)
910 			*(int *)datap->b_wptr = KBTRANS_USBKB_DEFAULT_LAYOUT;
911 		else
912 			*(int *)datap->b_wptr = conskbd.conskbd_layout;
913 
914 		datap->b_wptr += sizeof (int);
915 		if (mp->b_cont)
916 			freemsg(mp->b_cont);
917 		mp->b_cont = datap;
918 		miocack(q, mp, sizeof (int), 0);
919 		break;
920 
921 	case KIOCSLAYOUT:
922 		if (iocp->ioc_count != TRANSPARENT) {
923 			miocnak(q, mp, 0, EINVAL);
924 			break;
925 		}
926 		kbd_layout_bak = conskbd.conskbd_layout;
927 		conskbd.conskbd_layout = *(intptr_t *)(mp->b_cont->b_rptr);
928 		if (conskbd.conskbd_layout != kbd_layout_bak) {
929 
930 			/* notify the upper of the change event */
931 			if ((datap = conskbd_alloc_firm_event(
932 			    KEYBOARD_LAYOUT_CHANGE,
933 			    conskbd.conskbd_layout)) != NULL) {
934 				if (conskbd.conskbd_directio) {
935 					putnext(conskbd_regqueue, datap);
936 				} else {
937 					freemsg(datap);
938 				}
939 			}
940 		}
941 		miocack(q, mp, 0, 0);
942 		break;
943 
944 	case CONSOPENPOLLEDIO:
945 		error = miocpullup(mp, sizeof (struct cons_polledio *));
946 		if (error != 0) {
947 			miocnak(q, mp, 0, error);
948 			break;
949 		}
950 		if (conskbd.conskbd_lqueue_list == NULL) {
951 			miocnak(q, mp, 0, EINVAL);
952 			break;
953 		}
954 		conskbd_handle_downstream_msg(q, mp);
955 		break;
956 
957 	case CONSCLOSEPOLLEDIO:
958 		if (conskbd.conskbd_lqueue_list == NULL) {
959 			miocnak(q, mp, 0, EINVAL);
960 			break;
961 		}
962 		conskbd_handle_downstream_msg(q, mp);
963 		break;
964 
965 	case CONSSETABORTENABLE:
966 		/*
967 		 * To enable combined STOP-A(or F1-A) to trap into kmdb,
968 		 * the lower physical keyboard drivers are always told not
969 		 * to parse abort sequence(refer to consconfig_dacf module).
970 		 * Instead, lower drivers always send all keydown & keyup
971 		 * messages up to conskbd, so that when key STOP(or F1) is
972 		 * pressed on one keyboard and key A is pressed on another
973 		 * keyboard, the system could trap into kmdb.
974 		 *
975 		 * When we by kbtrans_streams_message() invoked kbtrans to
976 		 * handle ioctls in conskbduwsrv() routine, kbtrans module
977 		 * already handle the message though it returned to us a
978 		 * KBTRANS_MESSAGE_NOT_HANDLED. For virtual keyboard, no
979 		 * special initialization or un-initialization is needed.
980 		 * So we just return ACK to upper module.
981 		 */
982 		miocack(q, mp, 0, 0);
983 		break;
984 
985 	case KIOCCMD:
986 		if (conskbd.conskbd_lqueue_list == NULL ||
987 		    mp->b_cont == NULL) {
988 			miocnak(q, mp, 0, EINVAL);
989 			break;
990 		}
991 		cmd = *(int *)mp->b_cont->b_rptr;
992 		if (cmd == KBD_CMD_GETLAYOUT) {
993 			freemsg(mp->b_cont);
994 			datap = allocb(sizeof (int), BPRI_HI);
995 			if (datap == NULL) {
996 				miocnak(q, mp, 0, ENOMEM);
997 				return;
998 			}
999 			if (conskbd.conskbd_layout == -1)
1000 				*(int *)datap->b_wptr =
1001 				    KBTRANS_USBKB_DEFAULT_LAYOUT;
1002 			else
1003 				*(int *)datap->b_wptr = conskbd.conskbd_layout;
1004 
1005 			mp->b_cont = datap;
1006 			miocack(q, mp, sizeof (int), 0);
1007 			return;
1008 		}
1009 		conskbd_handle_downstream_msg(q, mp);
1010 		break;
1011 
1012 	default:
1013 		miocnak(q, mp, 0, EINVAL);
1014 		break;
1015 	}
1016 
1017 }	/* conskbd_virtual_kbd_ioctl() */
1018 
1019 static void
1020 conskbd_legacy_kbd_ioctl(queue_t *q, mblk_t *mp)
1021 {
1022 	conskbd_lower_queue_t	*lq;
1023 	struct	iocblk		*iocp;
1024 	int	error = 0;
1025 
1026 	iocp = (struct iocblk *)mp->b_rptr;
1027 
1028 	ASSERT(conskbd.conskbd_lqueue_nums == 1);
1029 	switch (iocp->ioc_cmd) {
1030 
1031 	case KIOCGDIRECT: {
1032 		mblk_t *datap;
1033 
1034 		if ((datap = allocb(sizeof (int), BPRI_MED)) == NULL) {
1035 			miocnak(q, mp, 0, ENOMEM);
1036 			break;
1037 		}
1038 
1039 		*(int *)datap->b_wptr = conskbd.conskbd_directio;
1040 		datap->b_wptr += sizeof (int);
1041 		if (mp->b_cont != NULL) {
1042 			freemsg(mp->b_cont);
1043 			mp->b_cont = NULL;
1044 		}
1045 		mp->b_cont = datap;
1046 		miocack(q, mp, sizeof (int), 0);
1047 		break;
1048 	}
1049 
1050 	case KIOCSDIRECT:
1051 		error = miocpullup(mp, sizeof (int));
1052 		if (error != 0) {
1053 			miocnak(q, mp, 0, error);
1054 			break;
1055 		}
1056 		conskbd.conskbd_directio = *(int *)mp->b_cont->b_rptr;
1057 
1058 		/*
1059 		 * Pass this through, if there's something to pass
1060 		 * it through to, so the system keyboard can reset
1061 		 * itself.
1062 		 */
1063 		if (conskbd.conskbd_lqueue_nums > 0) {
1064 			lq = conskbd.conskbd_lqueue_list;
1065 			ASSERT(lq && lq->lqs_next == NULL);
1066 			if (putq(lq->lqs_queue, mp) != 1) {
1067 				miocnak(q, mp, 0, ENOMEM);
1068 				return;
1069 			}
1070 			break;
1071 		}
1072 
1073 		miocack(q, mp, 0, 0);
1074 		break;
1075 
1076 	default:
1077 		/*
1078 		 * Pass this through, if there's something to pass it
1079 		 * through to; otherwise, reject it.
1080 		 */
1081 		if (conskbd.conskbd_lqueue_nums > 0) {
1082 			lq = conskbd.conskbd_lqueue_list;
1083 			ASSERT(lq && lq->lqs_next == NULL);
1084 			if (putq(lq->lqs_queue, mp) != 1) {
1085 				miocnak(q, mp, 0, ENOMEM);
1086 				return;
1087 			}
1088 			break;
1089 		}
1090 
1091 		/* nobody below us; reject it */
1092 		miocnak(q, mp, 0, EINVAL);
1093 		break;
1094 	}
1095 
1096 }	/* conskbd_legacy_kbd_ioctl() */
1097 
1098 
1099 /*
1100  * Service procedure for lower write queue.
1101  * Puts things on the queue below us, if it lets us.
1102  */
1103 static void
1104 conskbdlwserv(queue_t *q)
1105 {
1106 	register mblk_t *mp;
1107 
1108 	while (canput(q->q_next) && (mp = getq(q)) != NULL)
1109 		putnext(q, mp);
1110 
1111 }	/* conskbdlwserv() */
1112 
1113 /*
1114  * Put procedure for lower read queue.
1115  * Pass everything up to minor device 0 if "directio" set, otherwise to minor
1116  * device 1.
1117  */
1118 static void
1119 conskbdlrput(queue_t *q, mblk_t *mp)
1120 {
1121 	conskbd_lower_queue_t	*lqs;
1122 	struct iocblk 	*iocp;
1123 	Firm_event	*fe;
1124 
1125 	DPRINTF(PRINT_L1, PRINT_MASK_ALL, ("conskbdlrput\n"));
1126 
1127 	switch (mp->b_datap->db_type) {
1128 
1129 	case M_FLUSH:
1130 		if (*mp->b_rptr == FLUSHR) {
1131 			flushq(q, FLUSHDATA);	/* XXX doesn't flush M_DELAY */
1132 			*mp->b_rptr &= ~FLUSHR;	/* it has been flushed */
1133 		}
1134 		if (*mp->b_rptr == FLUSHW) {
1135 			flushq(WR(q), FLUSHDATA);
1136 			qreply(q, mp);	/* give the read queues a crack at it */
1137 		} else
1138 			freemsg(mp);
1139 		break;
1140 
1141 	case M_DATA:
1142 		if (conskbd.conskbd_bypassed == B_FALSE) {
1143 
1144 			fe = (Firm_event *)mp->b_rptr;
1145 
1146 			/*
1147 			 * This is a workaround.
1148 			 *
1149 			 * According to HID specification, there are the
1150 			 * following keycode mapping between PS2 and USB,
1151 			 *
1152 			 *	PS2 AT-101 keycode(29)  --->    USB(49)
1153 			 *	PS2 AT-102 keycode(42)  --->    USB(50)
1154 			 *
1155 			 * However, the two keys, AT-101(29) and AT-102(42),
1156 			 * have the same scancode,0x2B, in PS2 scancode SET1
1157 			 * which we are using. The Kb8042 driver always
1158 			 * recognizes the two keys as PS2(29) so that we could
1159 			 * not know which is being pressed or released when we
1160 			 * receive scancode 0x2B. Fortunately, the two keys can
1161 			 * not co-exist in a specific layout. In other words,
1162 			 * in the table of keycode-to-symbol mapping, either
1163 			 * entry 49 or 50 is a hole. So, if we're processing a
1164 			 * keycode 49, we look at the entry for 49.  If it's
1165 			 * HOLE, remap the key to 50; If we're processing a 50,
1166 			 * look at the entry for 50.  If it's HOLE, we remap
1167 			 * the key to 49.
1168 			 */
1169 			if (fe->id == 49 || fe->id == 50) {
1170 				if (conskbd_keyindex->k_normal[50] == HOLE)
1171 					fe->id = 49;
1172 				else
1173 					fe->id = 50;
1174 			}
1175 
1176 			/*
1177 			 * Remember key state of each key of lower physical
1178 			 * keyboard. When a keyboard is umplumbed from conskbd,
1179 			 * we will check all key states. By then,  we will fake
1180 			 * a KEY_RELEASED message for each key in KEY_PRESSED
1181 			 * state. Otherwise, upper module will treat these keys
1182 			 * as held-down for ever.
1183 			 */
1184 			iocp = (struct iocblk *)mp->b_rptr;
1185 			lqs = (conskbd_lower_queue_t *)q->q_ptr;
1186 			if (fe->value)
1187 				lqs->lqs_key_state[fe->id] = KEY_PRESSED;
1188 			else
1189 				lqs->lqs_key_state[fe->id] = KEY_RELEASED;
1190 
1191 			kbtrans_streams_key(conskbd.conskbd_kbtrans,
1192 			    fe->id, fe->value ? KEY_PRESSED : KEY_RELEASED);
1193 			freemsg(mp);
1194 		} else {
1195 			if (conskbd.conskbd_directio)
1196 				putnext(conskbd_regqueue, mp);
1197 			else if (conskbd_consqueue != NULL)
1198 				putnext(conskbd_consqueue, mp);
1199 			else
1200 				freemsg(mp);
1201 		}
1202 		conskbd_idle_stamp = gethrestime_sec();
1203 		break;
1204 
1205 	case M_IOCACK:
1206 	case M_IOCNAK:
1207 		iocp = (struct iocblk *)mp->b_rptr;
1208 		lqs = (conskbd_lower_queue_t *)q->q_ptr;
1209 
1210 		DPRINTF(PRINT_L1, PRINT_MASK_ALL, ("conskbdlrput: "
1211 		    "ACK/NAK - cmd 0x%x\n", iocp->ioc_cmd));
1212 
1213 		conskbd_lqs_ack_complete(lqs, mp);
1214 		break;
1215 
1216 	case M_ERROR:
1217 	case M_HANGUP:
1218 	default:
1219 		freemsg(mp);	/* anything useful here? */
1220 		break;
1221 	}
1222 
1223 }	/* conskbdlrput() */
1224 
1225 
1226 /* ARGSUSED */
1227 static int
1228 conskbd_kstat_update(kstat_t *ksp, int rw)
1229 {
1230 	if (rw == KSTAT_WRITE)
1231 		return (EACCES);
1232 
1233 	conskbd_kstat.idle_sec.value.l = gethrestime_sec() - conskbd_idle_stamp;
1234 
1235 	return (0);
1236 
1237 }	/* conskbd_kstat_update() */
1238 
1239 /*
1240  * STREAMS architecuture provides guarantee that the ID of each
1241  * message, iocblk.ioc_id, in a stream is unique. The following
1242  * routine performes the task: When receive request from upstream,
1243  * it saves the request in a global link list, clones the request,
1244  * and then sends a copy of the request to each of lower queues
1245  * which are plumbed into conskbd. And then, when receives responses
1246  * from lower queues in conskbdlrput() routine, we can know the
1247  * request matching received responses by searching the global linked
1248  * list to find the request which has the same message ID of the
1249  * response. Then, when all lower queues response this request, we
1250  * give a response to upstreams based the following policy:
1251  * If any one of lower queues acks our reuqest, then we return ack
1252  * to upstreams; only if all lower queues nak our request, we return
1253  * nak to upstreams. If all responses are nak, the error number of
1254  * the first response is sent to upstream.
1255  */
1256 static void
1257 conskbd_handle_downstream_msg(queue_t *q, mblk_t *mp)
1258 {
1259 	conskbd_pending_msg_t	*msg;
1260 	conskbd_lower_queue_t	*lqs;
1261 	struct iocblk	*iocp;
1262 	mblk_t		*clonemp;
1263 	int		retry;
1264 
1265 	if (conskbd.conskbd_lqueue_nums == 0) {
1266 		miocnak(q, mp, 0, EINVAL);
1267 		return;
1268 	}
1269 
1270 	msg = (conskbd_pending_msg_t *)
1271 	    kmem_zalloc(sizeof (conskbd_pending_msg_t), KM_SLEEP);
1272 	mutex_init(&msg->kpm_lock, NULL, MUTEX_DRIVER, NULL);
1273 	lqs = conskbd.conskbd_lqueue_list;
1274 	iocp = (struct iocblk *)mp->b_rptr;
1275 
1276 	ASSERT(iocp->ioc_cmd == CONSOPENPOLLEDIO ||
1277 	    iocp->ioc_cmd == CONSCLOSEPOLLEDIO ||
1278 	    iocp->ioc_cmd == KIOCCMD);
1279 
1280 	msg->kpm_upper_queue = q;
1281 	msg->kpm_req_msg = mp;
1282 	msg->kpm_req_id = iocp->ioc_id;
1283 	msg->kpm_req_cmd = iocp->ioc_cmd;
1284 	msg->kpm_req_nums = conskbd.conskbd_lqueue_nums;
1285 	conskbd_mux_enqueue_msg(msg);
1286 
1287 	for (retry = 0, lqs = conskbd.conskbd_lqueue_list; lqs; ) {
1288 
1289 		/*
1290 		 * if a lower physical keyboard is not in polled I/O
1291 		 * mode, we couldn't send CONSCLOSEPOLLEDIO to it,
1292 		 * otherwise, system will panic.
1293 		 */
1294 		if (iocp->ioc_cmd == CONSCLOSEPOLLEDIO &&
1295 		    lqs->lqs_polledio == NULL) {
1296 			lqs = lqs->lqs_next;
1297 			msg->kpm_req_nums --;
1298 			retry = 0;
1299 			continue;
1300 		}
1301 
1302 		clonemp = copymsg(mp);
1303 		if (clonemp != NULL) {
1304 			if (putq(lqs->lqs_queue, clonemp) == 1) {
1305 				lqs = lqs->lqs_next;
1306 				retry = 0;
1307 				continue;
1308 			}
1309 
1310 			/*
1311 			 * failed to invoke putq(), retry.
1312 			 */
1313 			freemsg(clonemp);
1314 		}
1315 
1316 		/*
1317 		 * During testing it was observed that occasionally
1318 		 * copymsg() would fail during boot. The reason for
1319 		 * these failures is unknown. Since we really want
1320 		 * to successfully plumb up all the attached keyboards
1321 		 * during boot we do a best effort here by retrying
1322 		 * the copymsg() call in the hopes that it will
1323 		 * succeeded upon subsequent invocations.
1324 		 *
1325 		 * If all the calls to copymsg() fails, it will cause
1326 		 * the corresponding keyboard to be unavailable, or
1327 		 * or behave weirdly,
1328 		 *
1329 		 * 1) for CONSOPENPOLLEDIO
1330 		 *	if copymsg()fails, the corresponding keyboard
1331 		 *	is not available in polled I/O mode once
1332 		 *	entering kmdb;
1333 		 * 2) for CONSCLOSEPOLLEDIO
1334 		 *	if copymsg() fails, the corresponding keyboard
1335 		 *	is not available in normal mode once returning
1336 		 *	from kmdb;
1337 		 * 3) for KIOCCMD
1338 		 * 	3.1) for KBD_CMD_NOBELL
1339 		 * 		there's no beep in USB and PS2 keyboard,
1340 		 * 		this ioctl actually disables the beep on
1341 		 * 		system mainboard. Note that all the cloned
1342 		 * 		messages sent down to lower queues do the
1343 		 * 		same job for system mainboard. Therefore,
1344 		 * 		even if we fail to send this ioctl to most
1345 		 * 		of lower queues, the beep still would be
1346 		 * 		disabled. So, no trouble exists here.
1347 		 *	3.2) for others
1348 		 *		nothing;
1349 		 *
1350 		 * However, all cases could be resume next time when the
1351 		 * same request comes again.
1352 		 */
1353 		if (retry ++ >= 5) {
1354 			dev_t	devt;
1355 			char	path[MAXPATHLEN + 1];
1356 
1357 			devt = lqs->lqs_queue->q_stream->sd_vnode->v_rdev;
1358 			switch (iocp->ioc_cmd) {
1359 			case CONSOPENPOLLEDIO:
1360 				if (ddi_dev_pathname(devt, S_IFCHR,
1361 				    path) == DDI_SUCCESS)
1362 					cmn_err(CE_WARN, "conskbd: "
1363 					    "keyboard is not available"
1364 					    " for system debugging: %s",
1365 					    path);
1366 				break;
1367 
1368 			case CONSCLOSEPOLLEDIO:
1369 				if (ddi_dev_pathname(devt, S_IFCHR,
1370 				    path) == DDI_SUCCESS)
1371 					cmn_err(CE_WARN, "conskbd: "
1372 					    "keyboard is not available:"
1373 					    " %s", path);
1374 				break;
1375 
1376 			default:
1377 				break;
1378 			}
1379 			msg->kpm_req_nums --;
1380 			lqs = lqs->lqs_next;
1381 			retry = 0;
1382 		}
1383 	}
1384 
1385 	if (msg->kpm_req_nums == 0) {
1386 		conskbd_mux_dequeue_msg(msg);
1387 		kmem_free(msg, sizeof (*msg));
1388 		miocnak(q, mp, 0, ENOMEM);
1389 	}
1390 
1391 }	/* conskbd_handle_downstream_msg() */
1392 
1393 
1394 static void
1395 conskbd_ioc_plink(queue_t *q, mblk_t *mp)
1396 {
1397 	mblk_t		*req;
1398 	queue_t		*lowque;
1399 	struct linkblk		*linkp;
1400 	conskbd_lower_queue_t	*lqs;
1401 
1402 	lqs = kmem_zalloc(sizeof (*lqs), KM_SLEEP);
1403 	ASSERT(lqs->lqs_state == LQS_UNINITIALIZED);
1404 
1405 	linkp = (struct linkblk *)mp->b_cont->b_rptr;
1406 	lowque = linkp->l_qbot;
1407 
1408 	lqs->lqs_queue = lowque;
1409 	lqs->lqs_pending_plink = mp;
1410 	lqs->lqs_pending_queue = q;
1411 
1412 	req = mkiocb(CONSSETKBDTYPE);
1413 	if (req == NULL) {
1414 		miocnak(q, mp, 0, ENOMEM);
1415 		kmem_free(lqs, sizeof (*lqs));
1416 		return;
1417 	}
1418 
1419 	req->b_cont = allocb(sizeof (int), BPRI_MED);
1420 	if (req->b_cont == NULL) {
1421 		freemsg(req);
1422 		miocnak(q, mp, 0, ENOMEM);
1423 		kmem_free(lqs, sizeof (*lqs));
1424 		return;
1425 	}
1426 
1427 	lowque->q_ptr = lqs;
1428 	OTHERQ(lowque)->q_ptr = lqs;
1429 	*(int *)req->b_cont->b_wptr = KB_USB;
1430 	req->b_cont->b_wptr += sizeof (int);
1431 
1432 	lqs->lqs_state = LQS_KIOCTYPE_ACK_PENDING;
1433 
1434 	if (putq(lowque, req) != 1) {
1435 		freemsg(req);
1436 		miocnak(lqs->lqs_pending_queue,
1437 		    lqs->lqs_pending_plink, 0, ENOMEM);
1438 		lowque->q_ptr = NULL;
1439 		OTHERQ(lowque)->q_ptr = NULL;
1440 		kmem_free(lqs, sizeof (*lqs));
1441 	}
1442 
1443 }	/* conskbd_ioc_plink() */
1444 
1445 
1446 static void
1447 conskbd_ioc_punlink(queue_t *q, mblk_t *mp)
1448 {
1449 	int			index;
1450 	struct linkblk		*linkp;
1451 	conskbd_lower_queue_t	*lqs;
1452 	conskbd_lower_queue_t	*prev;
1453 
1454 	linkp = (struct linkblk *)mp->b_cont->b_rptr;
1455 	prev = conskbd.conskbd_lqueue_list;
1456 	for (lqs = prev; lqs; lqs = lqs->lqs_next) {
1457 		if (lqs->lqs_queue == linkp->l_qbot) {
1458 			if (prev == lqs)
1459 				conskbd.conskbd_lqueue_list =
1460 				    lqs->lqs_next;
1461 			else
1462 				prev->lqs_next = lqs->lqs_next;
1463 
1464 			lqs->lqs_queue->q_ptr =  NULL;
1465 			OTHERQ(lqs->lqs_queue)->q_ptr = NULL;
1466 			conskbd.conskbd_lqueue_nums --;
1467 			if (conskbd.conskbd_lqueue_nums == 0) {
1468 				kbd_layout_bak = conskbd.conskbd_layout;
1469 				conskbd.conskbd_layout = -1;
1470 			}
1471 
1472 			for (index = 0; index < KBTRANS_KEYNUMS_MAX; index ++) {
1473 				if (lqs->lqs_key_state[index] == KEY_PRESSED)
1474 					kbtrans_streams_key(
1475 					    conskbd.conskbd_kbtrans,
1476 					    index,
1477 					    KEY_RELEASED);
1478 			}
1479 
1480 			kmem_free(lqs, sizeof (*lqs));
1481 			miocack(q, mp, 0, 0);
1482 			return;
1483 		}
1484 		prev = lqs;
1485 	}
1486 	miocnak(q, mp, 0, EINVAL);
1487 
1488 }	/* conskbd_ioc_punlink() */
1489 
1490 /*
1491  * Every physical keyboard has a corresponding STREAMS queue. We call this
1492  * queue lower queue. Every lower queue has a state, refer to conskbd.h file
1493  * about "enum conskbd_lqs_state".
1494  * The following routine is used to handle response messages from lower queue.
1495  * When receiving ack/nak message from lower queue(s), the routine determines
1496  * the passage for it according to the current state of this lower queue.
1497  */
1498 static void
1499 conskbd_lqs_ack_complete(conskbd_lower_queue_t *lqs, mblk_t *mp)
1500 {
1501 	switch (lqs->lqs_state) {
1502 
1503 	/* S6: working in virtual keyboard mode, multi-keyboards are usable */
1504 	case LQS_INITIALIZED:
1505 		conskbd_mux_upstream_msg(lqs, mp);
1506 		break;
1507 
1508 	/* S5: working in legacy mode, only one keyboard is usable */
1509 	case LQS_INITIALIZED_LEGACY:
1510 		conskbd_legacy_upstream_msg(lqs, mp);
1511 		break;
1512 
1513 	/* S4: wait lower queue to acknowledge KIOCSLED/KIOCGLED  message */
1514 	case LQS_KIOCSLED_ACK_PENDING:
1515 		conskbd_kiocsled_complete(lqs, mp);
1516 		break;
1517 
1518 	/* S3: wait lower queue to acknowledge KIOCLAYOUT  message */
1519 	case LQS_KIOCLAYOUT_ACK_PENDING:
1520 		conskbd_kioclayout_complete(lqs, mp);
1521 		break;
1522 
1523 	/* S2: wait lower queue to acknowledge KIOCTRANS  message */
1524 	case LQS_KIOCTRANS_ACK_PENDING:
1525 		conskbd_kioctrans_complete(lqs, mp);
1526 		break;
1527 
1528 	/* S1: wait lower queue to acknowledge KIOCTYPE  message */
1529 	case LQS_KIOCTYPE_ACK_PENDING:
1530 		conskbd_kioctype_complete(lqs, mp);
1531 		break;
1532 
1533 	/* if reaching here, there must be a error */
1534 	default:
1535 		freemsg(mp);
1536 		cmn_err(CE_WARN, "conskbd: lqs_ack_complete() state error");
1537 		break;
1538 	}
1539 
1540 }	/* conskbd_lqs_ack_complete() */
1541 
1542 
1543 static void
1544 conskbd_kioctype_complete(conskbd_lower_queue_t *lqs, mblk_t *mp)
1545 {
1546 	struct iocblk	*iocp;
1547 	mblk_t		*req;
1548 	queue_t		*lowerque;
1549 	int		err = ENOMEM;
1550 
1551 	ASSERT(lqs->lqs_pending_plink);
1552 	ASSERT(lqs->lqs_state == LQS_KIOCTYPE_ACK_PENDING);
1553 
1554 	lowerque = lqs->lqs_queue;
1555 
1556 	switch (mp->b_datap->db_type) {
1557 	case M_IOCACK:
1558 		req = mkiocb(KIOCTRANS);
1559 		if (req == NULL) {
1560 			goto err_exit;
1561 		}
1562 
1563 		req->b_cont = allocb(sizeof (int), BPRI_MED);
1564 		if (req->b_cont == NULL) {
1565 			freemsg(req);
1566 			goto err_exit;
1567 		}
1568 
1569 		/* Set the translate mode to TR_UNTRANS_EVENT */
1570 		*(int *)req->b_cont->b_wptr = TR_UNTRANS_EVENT;
1571 		req->b_cont->b_wptr += sizeof (int);
1572 
1573 		/* Ready to handle the response to KIOCTRANS */
1574 		lqs->lqs_state = LQS_KIOCTRANS_ACK_PENDING;
1575 
1576 		if (putq(lowerque, req) != 1) {
1577 			freemsg(req);
1578 			goto err_exit;
1579 		}
1580 		freemsg(mp);
1581 		return;
1582 
1583 	case M_IOCNAK:
1584 		/*
1585 		 * The lower keyboard driver can't mimic USB keyboard,
1586 		 * that's say, the physical keyboard is an old one, such
1587 		 * as TYPE 3/4/5 one. In this case, the virtual keyboard
1588 		 * is disabled, and the data from lower keyboard driver
1589 		 * will bypass the conskbd module.
1590 		 */
1591 
1592 		/*
1593 		 * if there is any other keyborad already linked under the
1594 		 * conskbd, we reject the current one.
1595 		 */
1596 		if (conskbd.conskbd_lqueue_nums > 0) {
1597 			iocp = (struct iocblk *)mp->b_rptr;
1598 			err = iocp->ioc_error;
1599 			goto err_exit;
1600 		}
1601 
1602 		/*
1603 		 * link this keyboard under conskbd.
1604 		 */
1605 		qwriter(lowerque, mp, conskbd_link_lowque_legacy, PERIM_OUTER);
1606 		return;
1607 	}
1608 
1609 err_exit:
1610 	miocnak(lqs->lqs_pending_queue, lqs->lqs_pending_plink, 0, err);
1611 	lowerque->q_ptr = NULL;
1612 	OTHERQ(lowerque)->q_ptr = NULL;
1613 	kmem_free(lqs, sizeof (*lqs));
1614 	freemsg(mp);
1615 
1616 }	/* conskbd_kioctype_complete() */
1617 
1618 static void
1619 conskbd_kioctrans_complete(conskbd_lower_queue_t *lqs, mblk_t *mp)
1620 {
1621 	struct iocblk 	*iocp;
1622 	mblk_t		*req;
1623 	queue_t		*lowerque;
1624 	int		err = ENOMEM;
1625 
1626 	ASSERT(lqs->lqs_pending_plink != NULL);
1627 	ASSERT(lqs->lqs_state == LQS_KIOCTRANS_ACK_PENDING);
1628 
1629 	lowerque = lqs->lqs_queue;
1630 
1631 	switch (mp->b_datap->db_type) {
1632 	case M_IOCACK:
1633 		req = mkiocb(KIOCLAYOUT);
1634 		if (req == NULL) {
1635 			goto err_exit;
1636 		}
1637 
1638 		req->b_cont = allocb(sizeof (int), BPRI_MED);
1639 		if (req->b_cont == NULL) {
1640 			freemsg(req);
1641 			goto err_exit;
1642 		}
1643 
1644 		/* waiting for response to KIOCLAYOUT */
1645 		lqs->lqs_state = LQS_KIOCLAYOUT_ACK_PENDING;
1646 		if (putq(lqs->lqs_queue, req) != 1) {
1647 			freemsg(req);
1648 			goto err_exit;
1649 		}
1650 		freemsg(mp);
1651 		return;
1652 
1653 	case M_IOCNAK:
1654 		iocp = (struct iocblk *)mp->b_rptr;
1655 		err = iocp->ioc_error;
1656 		goto err_exit;
1657 	}
1658 
1659 err_exit:
1660 	miocnak(lqs->lqs_pending_queue, lqs->lqs_pending_plink, 0, err);
1661 	lowerque->q_ptr = NULL;
1662 	OTHERQ(lowerque)->q_ptr = NULL;
1663 	kmem_free(lqs, sizeof (*lqs));
1664 	freemsg(mp);
1665 
1666 }	/* conskbd_kioctrans_complete() */
1667 
1668 /*
1669  * Allocate a firm event
1670  */
1671 static mblk_t *
1672 conskbd_alloc_firm_event(int id, int value)
1673 {
1674 	mblk_t	*mb;
1675 	Firm_event *fe;
1676 
1677 	if ((mb = allocb(sizeof (Firm_event), BPRI_HI)) != NULL) {
1678 		fe = (Firm_event *)mb->b_wptr;
1679 		fe->id = id;
1680 		fe->pair_type = FE_PAIR_NONE;
1681 		fe->pair = NULL;
1682 		fe->value = value;
1683 		mb->b_wptr += sizeof (Firm_event);
1684 	}
1685 
1686 	return (mb);
1687 }
1688 
1689 static void
1690 conskbd_kioclayout_complete(conskbd_lower_queue_t *lqs, mblk_t *mp)
1691 {
1692 	mblk_t		*req;
1693 	int		layout;
1694 	boolean_t	fail;
1695 
1696 	ASSERT(lqs->lqs_pending_plink != NULL);
1697 	ASSERT(lqs->lqs_state == LQS_KIOCLAYOUT_ACK_PENDING);
1698 
1699 	switch (mp->b_datap->db_type) {
1700 	case M_IOCACK:
1701 		if (miocpullup(mp, sizeof (int)) == 0) {
1702 			layout = *(int *)mp->b_cont->b_rptr;
1703 			/*
1704 			 * We just accept the layout of the first keyboard
1705 			 * requesting to be linked under conskbd. If current
1706 			 * keyboard is the first one, and if we get right
1707 			 * layout from it, we set conskbd's layout
1708 			 */
1709 			if (layout != -1 && conskbd.conskbd_layout == -1) {
1710 				if (layout == 0) {
1711 					conskbd.conskbd_layout = kbd_layout_bak;
1712 				} else {
1713 					conskbd.conskbd_layout = layout;
1714 					if (layout == kbd_layout_bak) {
1715 						break;
1716 					}
1717 					if ((req = conskbd_alloc_firm_event(
1718 					    KEYBOARD_LAYOUT_CHANGE,
1719 					    layout)) != NULL) {
1720 						if (conskbd.conskbd_directio) {
1721 							putnext(
1722 							    conskbd_regqueue,
1723 							    req);
1724 						} else if (conskbd_consqueue
1725 						    != NULL) {
1726 							putnext(
1727 							    conskbd_consqueue,
1728 							    req);
1729 						} else {
1730 							freemsg(req);
1731 						}
1732 					}
1733 				}
1734 			}
1735 		}
1736 		break;
1737 
1738 
1739 	/* if fail, leave conskbd's layout as it is */
1740 	case M_IOCNAK:
1741 		break;
1742 	}
1743 
1744 	fail = B_TRUE;
1745 
1746 	if (conskbd.conskbd_led_state == -1)
1747 		req = mkiocb(KIOCGLED);
1748 	else
1749 		req = mkiocb(KIOCSLED);
1750 
1751 	if (req) {
1752 		req->b_cont = allocb(sizeof (uchar_t), BPRI_MED);
1753 		if (req->b_cont) {
1754 			if (conskbd.conskbd_led_state != -1) {
1755 				*(uchar_t *)req->b_cont->b_wptr =
1756 				    conskbd.conskbd_led_state;
1757 				req->b_cont->b_wptr += sizeof (uchar_t);
1758 			}
1759 
1760 			/* waiting for response to KIOCSLED */
1761 			lqs->lqs_state = LQS_KIOCSLED_ACK_PENDING;
1762 			if (putq(lqs->lqs_queue, req) == 1) {
1763 				fail = B_FALSE;
1764 			} else {
1765 				freemsg(req);
1766 			}
1767 
1768 		} else {
1769 			freemsg(req);
1770 		}
1771 	}
1772 
1773 	if (fail) {
1774 		/*
1775 		 * If fail to allocate KIOCSLED/KIOCGLED message or put
1776 		 * the message into lower queue, we immediately link
1777 		 * current keyboard under conskbd. Thus, even if fails
1778 		 * to set/get LED, this keyboard could be available.
1779 		 */
1780 		qwriter(lqs->lqs_queue,
1781 		    mp, conskbd_link_lowque_virt, PERIM_OUTER);
1782 	} else {
1783 		freemsg(mp);
1784 	}
1785 
1786 }	/* conskbd_kioclayout_complete() */
1787 
1788 
1789 static void
1790 conskbd_kiocsled_complete(conskbd_lower_queue_t *lqs, mblk_t *mp)
1791 {
1792 	int	led_state;
1793 
1794 	ASSERT(lqs->lqs_pending_plink != NULL);
1795 	ASSERT(lqs->lqs_state == LQS_KIOCSLED_ACK_PENDING);
1796 
1797 	if (conskbd.conskbd_led_state == -1) {
1798 		switch (mp->b_datap->db_type) {
1799 		case M_IOCACK:
1800 			if (miocpullup(mp, sizeof (uchar_t)) == 0) {
1801 				led_state = *(uchar_t *)mp->b_cont->b_rptr;
1802 				conskbd.conskbd_led_state = led_state;
1803 				kbtrans_streams_setled(conskbd.conskbd_kbtrans,
1804 				    led_state);
1805 			}
1806 			break;
1807 
1808 		/* if fail, leave conskbd's led_state as it is */
1809 		case M_IOCNAK:
1810 			break;
1811 		}
1812 	}
1813 
1814 	/*
1815 	 * Basically, failure of setting/getting LED is not a fatal
1816 	 * error, so we will plumb the lower queue into conskbd whether
1817 	 * setting/getting LED succeeds or fails.
1818 	 */
1819 	qwriter(lqs->lqs_queue, mp, conskbd_link_lowque_virt, PERIM_OUTER);
1820 
1821 }	/* conskbd_kiocsled_complete() */
1822 
1823 
1824 static void
1825 conskbd_mux_upstream_msg(conskbd_lower_queue_t *lqs, mblk_t *mp)
1826 {
1827 	conskbd_pending_msg_t	*msg;
1828 	struct iocblk		*iocp;
1829 	int			error;
1830 	dev_t			devt;
1831 	char			path[MAXPATHLEN + 1];
1832 
1833 	ASSERT(lqs->lqs_state == LQS_INITIALIZED);
1834 	msg = conskbd_mux_find_msg(mp);
1835 
1836 	if (!msg) {
1837 		/*
1838 		 * Here we discard the response if:
1839 		 *
1840 		 *   1. It's an KIOCSLED request; see conskbd_streams_setled().
1841 		 *   2. The application has already closed the upper stream;
1842 		 *		see conskbdclose()
1843 		 */
1844 		freemsg(mp);
1845 		return;
1846 	}
1847 
1848 	/*
1849 	 * We use the b_next field of mblk_t structure to link all
1850 	 * response coming from lower queues into a linkage list,
1851 	 * and make use of the b_prev field to save a pointer to
1852 	 * the lower queue from which the current response message
1853 	 * comes.
1854 	 */
1855 	ASSERT(mp->b_next == NULL && mp->b_prev == NULL);
1856 	mutex_enter(&msg->kpm_lock);
1857 	mp->b_next = msg->kpm_resp_list;
1858 	mp->b_prev = (mblk_t *)lqs;
1859 	msg->kpm_resp_list = mp;
1860 	msg->kpm_resp_nums ++;
1861 	mutex_exit(&msg->kpm_lock);
1862 
1863 	if (msg->kpm_resp_nums < msg->kpm_req_nums)
1864 		return;
1865 
1866 	ASSERT(msg->kpm_resp_nums == msg->kpm_req_nums);
1867 	ASSERT(mp == msg->kpm_resp_list);
1868 
1869 	conskbd_mux_dequeue_msg(msg);
1870 
1871 
1872 	/*
1873 	 * Here, we have the policy that, if any one lower queue ACK
1874 	 * our reuqest, then we return ACK to upstreams; only if all
1875 	 * lower queues NAK our request, we return NAK to upstreams.
1876 	 * if all responses are nak, the errno of the  first response
1877 	 * is sent to upstreams
1878 	 */
1879 	ASSERT(mp->b_rptr);
1880 	error = ((struct iocblk *)mp->b_rptr)->ioc_error;
1881 
1882 	switch (msg->kpm_req_cmd) {
1883 	case CONSOPENPOLLEDIO:
1884 		/*
1885 		 * Here, we can safely ignore the NAK message. If any one lower
1886 		 * queue returns NAK, the pointer to the corresponding polledio
1887 		 * structure will remain null, that's say lqs->lqs_polledio =
1888 		 * null. When we need to invoke polled I/O interface, we will
1889 		 * check if the pointer is null.
1890 		 */
1891 		for (mp = msg->kpm_resp_list; mp; ) {
1892 			cons_polledio_t		*polledio;
1893 
1894 			msg->kpm_resp_list = mp->b_next;
1895 			lqs = (conskbd_lower_queue_t *)mp->b_prev;
1896 			devt = lqs->lqs_queue->q_stream->sd_vnode->v_rdev;
1897 			if (mp->b_datap->db_type == M_IOCACK) {
1898 				polledio = *(struct cons_polledio **)
1899 				    mp->b_cont->b_rptr;
1900 				if (polledio->cons_polledio_version ==
1901 				    CONSPOLLEDIO_V1) {
1902 					lqs->lqs_polledio = polledio;
1903 					error = 0;
1904 				} else {
1905 					/*
1906 					 * USB and PS2 keyboard drivers should
1907 					 * use the same cons_polledio structure
1908 					 * as conskbd.
1909 					 */
1910 					if (ddi_dev_pathname(devt, S_IFCHR,
1911 					    path) == DDI_SUCCESS) {
1912 						cmn_err(CE_WARN, "keyboard "
1913 						    "driver does not support "
1914 						    "system debugging: %s",
1915 						    path);
1916 					}
1917 					error = EINVAL;
1918 				}
1919 			} else {
1920 				if (ddi_dev_pathname(devt, S_IFCHR, path) ==
1921 				    DDI_SUCCESS) {
1922 					cmn_err(CE_WARN, "conskbd: keyboard is"
1923 					    " not available for system"
1924 					    " debugging:  %s", path);
1925 				}
1926 			}
1927 			mp->b_next = NULL;
1928 			mp->b_prev = NULL;
1929 			freemsg(mp);
1930 			mp = msg->kpm_resp_list;
1931 		}
1932 
1933 		mp = msg->kpm_req_msg;
1934 		if (error == 0) {
1935 			*(struct cons_polledio **)mp->b_cont->b_rptr =
1936 			    &conskbd.conskbd_polledio;
1937 		}
1938 		break;
1939 
1940 	case CONSCLOSEPOLLEDIO:
1941 		for (mp = msg->kpm_resp_list; mp; ) {
1942 			msg->kpm_resp_list = mp->b_next;
1943 			lqs = (conskbd_lower_queue_t *)mp->b_prev;
1944 			if (mp->b_datap->db_type == M_IOCACK) {
1945 				lqs->lqs_polledio = NULL;
1946 				error = 0;
1947 			} else {
1948 				devt =
1949 				    lqs->lqs_queue->q_stream->sd_vnode->v_rdev;
1950 
1951 				if (ddi_dev_pathname(devt, S_IFCHR, path) ==
1952 				    DDI_SUCCESS) {
1953 					cmn_err(CE_WARN, "conskbd: keyboard is"
1954 					    " not available: %s", path);
1955 				}
1956 			}
1957 
1958 			mp->b_next = NULL;
1959 			mp->b_prev = NULL;
1960 			freemsg(mp);
1961 			mp = msg->kpm_resp_list;
1962 		}
1963 		break;
1964 
1965 	case KIOCCMD:
1966 		for (mp = msg->kpm_resp_list; mp; ) {
1967 			msg->kpm_resp_list = mp->b_next;
1968 
1969 			if (mp->b_datap->db_type == M_IOCACK)
1970 				error = 0;
1971 			mp->b_next = NULL;
1972 			mp->b_prev = NULL;
1973 			freemsg(mp);
1974 			mp = msg->kpm_resp_list;
1975 		}
1976 		break;
1977 
1978 	default:  /* it is impossible to reach here */
1979 		cmn_err(CE_WARN, "conskbd: unexpected ioctl reply");
1980 	}
1981 
1982 	mp = msg->kpm_req_msg;
1983 	if (error == 0) {
1984 		mp->b_datap->db_type = M_IOCACK;
1985 	} else {
1986 		mp->b_datap->db_type = M_IOCNAK;
1987 	}
1988 	iocp = (struct iocblk *)mp->b_rptr;
1989 	iocp->ioc_error = error;
1990 	qreply(msg->kpm_upper_queue, mp);
1991 	mutex_destroy(&msg->kpm_lock);
1992 	kmem_free(msg, sizeof (*msg));
1993 
1994 }	/* conskbd_mux_upstream_msg() */
1995 
1996 static void
1997 conskbd_link_lowque_legacy(queue_t *lowque, mblk_t *mp)
1998 {
1999 	conskbd_lower_queue_t *lqs;
2000 
2001 	freemsg(mp);
2002 
2003 	/*
2004 	 * Bypass the virutal keyboard for old hardware,
2005 	 * Now, only current legacy keyboard can be linked
2006 	 * under conskbd
2007 	 */
2008 	conskbd.conskbd_bypassed = B_TRUE;
2009 
2010 	/*
2011 	 * Link the lower queue under conskbd
2012 	 */
2013 	lqs = (conskbd_lower_queue_t *)lowque->q_ptr;
2014 	lqs->lqs_state = LQS_INITIALIZED_LEGACY;
2015 	lqs->lqs_next = conskbd.conskbd_lqueue_list;
2016 	conskbd.conskbd_lqueue_list = lqs;
2017 	conskbd.conskbd_lqueue_nums++;
2018 
2019 	mioc2ack(lqs->lqs_pending_plink, NULL, 0, 0);
2020 	qreply(lqs->lqs_pending_queue, lqs->lqs_pending_plink);
2021 
2022 }	/* conskbd_link_lowque_legacy() */
2023 
2024 static void
2025 conskbd_link_lowque_virt(queue_t *lowque, mblk_t *mp)
2026 {
2027 	int		index;
2028 	conskbd_lower_queue_t *lqs;
2029 
2030 	freemsg(mp);
2031 
2032 	lqs = (conskbd_lower_queue_t *)lowque->q_ptr;
2033 
2034 	ASSERT(lqs->lqs_queue == lowque);
2035 	ASSERT(lqs->lqs_pending_plink != NULL);
2036 
2037 	/*
2038 	 * Now, link the lower queue under conskbd
2039 	 */
2040 	for (index = 0; index < KBTRANS_KEYNUMS_MAX; index ++) {
2041 		lqs->lqs_key_state[index] = KEY_RELEASED;
2042 	}
2043 	lqs->lqs_next = conskbd.conskbd_lqueue_list;
2044 	lqs->lqs_state = LQS_INITIALIZED;
2045 	conskbd.conskbd_lqueue_nums++;
2046 	conskbd.conskbd_lqueue_list = lqs;
2047 	mioc2ack(lqs->lqs_pending_plink, NULL, 0, 0);
2048 	qreply(lqs->lqs_pending_queue, lqs->lqs_pending_plink);
2049 
2050 }	/* conskbd_link_lowque_virt() */
2051 
2052 /*ARGSUSED*/
2053 static void
2054 conskbd_legacy_upstream_msg(conskbd_lower_queue_t *lqs, mblk_t *mp)
2055 {
2056 	struct iocblk	*iocp;
2057 
2058 	ASSERT(lqs && lqs->lqs_state == LQS_INITIALIZED_LEGACY);
2059 
2060 	/*
2061 	 * We assume that all of the ioctls are headed to the
2062 	 * conskbd_regqueue if it is open.  We are intercepting a few ioctls
2063 	 * that we know belong to conskbd_consqueue, and sending them there.
2064 	 * Any other, new ioctls that have to be routed to conskbd_consqueue
2065 	 * should be added to this list.
2066 	 */
2067 	iocp = (struct iocblk *)mp->b_rptr;
2068 
2069 	if ((iocp->ioc_cmd == CONSOPENPOLLEDIO) ||
2070 	    (iocp->ioc_cmd == CONSCLOSEPOLLEDIO)) {
2071 
2072 		DPRINTF(PRINT_L1, PRINT_MASK_ALL,
2073 		    ("conskbd_legacy_upstream_msg: "
2074 		    "CONSOPEN/CLOSEPOLLEDIO ACK/NAK\n"));
2075 		putnext(conskbd_consqueue, mp);
2076 
2077 	} else if (conskbd_regqueue != NULL) {
2078 		DPRINTF(PRINT_L1, PRINT_MASK_ALL,
2079 		    ("conskbd_legacy_upstream_msg: conskbd_regqueue != NULL"));
2080 
2081 		putnext(conskbd_regqueue, mp);
2082 
2083 	} else if (conskbd_consqueue != NULL) {
2084 		DPRINTF(PRINT_L1, PRINT_MASK_ALL,
2085 		    ("conskbd_legacy_upstream_msg: conskbd_consqueue != NULL"));
2086 		putnext(conskbd_consqueue, mp);
2087 	} else {
2088 		/* if reached here, it must be a error */
2089 		cmn_err(CE_WARN,
2090 		    "kb:  no destination for IOCACK/IOCNAK!");
2091 		freemsg(mp);
2092 	}
2093 
2094 }	/* conskbd_legacy_upstream_msg() */
2095 
2096 /*
2097  * This routine is a callback routine for kbtrans module to set LED.
2098  * Kbtrans will invoke it in two cases:
2099  *
2100  * 1) application initiated request
2101  * 	A KIOCSLED ioctl is sent by an application. The ioctl will be
2102  * 	be prcoessed by queue service procedure conskbduwsrv(), which
2103  * 	in turn calls kbtrans to process the ioctl. Then kbtrans invokes
2104  * 	conskbd_streams_setled() to set LED, after that,  kbtrans will
2105  * 	return an ACK message to upper module.
2106  *
2107  * 2) Kbtrans initiated the request
2108  *	When conskbd works in TR_ASCII translation mode, if anyone of
2109  *	CapsLock, NumberLock and Compose keys is pressed, kbtrans need
2110  *	to set LED. In this case, there is no ioctl from upper module.
2111  *	There is no requirement to send response to somebody.
2112  *
2113  * In first case, kbtrans will send response to upper module; and in the
2114  * second, we don't need to send response. So conskbd_streams_setled()
2115  * has no return value.
2116  */
2117 static void
2118 conskbd_streams_setled(struct kbtrans_hardware *hw, int led_state)
2119 {
2120 	conskbd_state_t  *conskbdp = (conskbd_state_t *)hw;
2121 	conskbd_lower_queue_t *lqs;
2122 	mblk_t		*req;
2123 
2124 	ASSERT(&conskbd == conskbdp);
2125 
2126 	if (led_state == -1)
2127 		return;
2128 
2129 	conskbdp->conskbd_led_state = led_state;
2130 
2131 	/*
2132 	 * Basically, failing to set LED is not a fatal error, we just skip
2133 	 * it if this happens.
2134 	 */
2135 	for (lqs = conskbdp->conskbd_lqueue_list; lqs; lqs = lqs->lqs_next) {
2136 		req = mkiocb(KIOCSLED);
2137 
2138 		if (!req) {
2139 			continue;
2140 		}
2141 
2142 		req->b_cont = allocb(sizeof (uchar_t), BPRI_MED);
2143 		if (!req->b_cont) {
2144 			freemsg(req);
2145 			continue;
2146 		}
2147 		*(uchar_t *)req->b_cont->b_wptr = led_state;
2148 		req->b_cont->b_wptr += sizeof (uchar_t);
2149 		if (putq(lqs->lqs_queue, req) != 1)
2150 			freemsg(req);
2151 	}
2152 
2153 }	/* conskbd_streams_setled() */
2154 
2155 static void
2156 conskbd_polledio_setled(struct kbtrans_hardware *hw, int led_state)
2157 {
2158 	conskbd_state_t  *conskbdp = (conskbd_state_t *)hw;
2159 	struct cons_polledio		*cb;
2160 	conskbd_lower_queue_t	*lqs;
2161 
2162 	for (lqs = conskbdp->conskbd_lqueue_list; lqs; lqs = lqs->lqs_next) {
2163 		cb = lqs->lqs_polledio;
2164 		if ((cb != NULL) && (cb->cons_polledio_setled != NULL)) {
2165 			cb->cons_polledio_setled(cb->cons_polledio_argument,
2166 			    led_state);
2167 		}
2168 	}
2169 
2170 }	/* conskbd_polledio_setled() */
2171 
2172 static boolean_t
2173 conskbd_polled_keycheck(struct kbtrans_hardware *hw,
2174 		kbtrans_key_t *keycode, enum keystate *state)
2175 {
2176 	conskbd_state_t  *conskbdp = (conskbd_state_t *)hw;
2177 	struct cons_polledio 		*cb;
2178 	conskbd_lower_queue_t	*lqs;
2179 	boolean_t	ret = B_FALSE;
2180 
2181 	for (ret = B_FALSE, lqs = conskbdp->conskbd_lqueue_list; lqs != NULL;
2182 	    lqs = lqs->lqs_next) {
2183 		cb = lqs->lqs_polledio;
2184 		if ((cb != NULL) &&
2185 		    (cb->cons_polledio_keycheck != NULL)) {
2186 			ret = cb->cons_polledio_keycheck(
2187 			    cb->cons_polledio_argument, keycode, state);
2188 		}
2189 
2190 		/* Get a char from lower queue(hardware) ? */
2191 		if (ret == B_TRUE) {
2192 
2193 			/* A legacy keyboard ? */
2194 			if (conskbd.conskbd_bypassed == B_TRUE)
2195 				break;
2196 
2197 			/*
2198 			 * This is the PS2 scancode 0x2B -> USB(49) /
2199 			 * USB(50) keycode mapping workaround, for
2200 			 * polled mode.
2201 			 *
2202 			 * There are two possible USB keycode mappings
2203 			 * for PS2 scancode 0x2B and this workaround
2204 			 * makes sure that we use the USB keycode that
2205 			 * does not end up being mapped to a HOLE key
2206 			 * using the current keyboard translation
2207 			 * tables.
2208 			 *
2209 			 * See conskbdlrput() for a detailed
2210 			 * explanation of the problem.
2211 			 */
2212 			if (*keycode == 49 || *keycode == 50) {
2213 				if (conskbd_keyindex->k_normal[50] == HOLE)
2214 					*keycode = 49;
2215 				else
2216 					*keycode = 50;
2217 			}
2218 
2219 			break;
2220 		}
2221 	}
2222 
2223 	return (ret);
2224 
2225 }	/* conskbd_polled_keycheck() */
2226 
2227 static boolean_t
2228 conskbd_override_kbtrans(queue_t *q, mblk_t *mp)
2229 {
2230 	struct iocblk		*iocp;
2231 	int		directio;
2232 	int		error;
2233 
2234 	if (mp->b_datap->db_type != M_IOCTL)
2235 		return (B_FALSE);
2236 
2237 	iocp = (struct iocblk *)mp->b_rptr;
2238 
2239 	switch (iocp->ioc_cmd) {
2240 	case KIOCGDIRECT: {
2241 		/*
2242 		 * Don't let the kbtrans-based code see this; it will
2243 		 * respond incorrectly.
2244 		 */
2245 		register mblk_t *datap;
2246 
2247 		if ((datap = allocb((int)sizeof (int), BPRI_MED)) == NULL) {
2248 			miocnak(q, mp, 0, ENOMEM);
2249 			return (B_TRUE);
2250 		}
2251 
2252 		*(int *)datap->b_wptr = conskbd.conskbd_directio;
2253 		datap->b_wptr += sizeof (int);
2254 		if (mp->b_cont) {
2255 			freemsg(mp->b_cont);
2256 			mp->b_cont = NULL;
2257 		}
2258 		mp->b_cont = datap;
2259 		miocack(q, mp, sizeof (int), 0);
2260 		return (B_TRUE);
2261 	}
2262 
2263 	case KIOCSDIRECT:
2264 		/*
2265 		 * Peek at this, set our variables, and then let the kbtrans
2266 		 * based code see it and respond to it.
2267 		 */
2268 		error = miocpullup(mp, sizeof (int));
2269 		if (error != 0) {
2270 			return (B_FALSE);
2271 		}
2272 
2273 		directio = *(int *)mp->b_cont->b_rptr;
2274 		if (directio != 0 && directio != 1) {
2275 			miocnak(q, mp, 0, EINVAL);
2276 			return (B_TRUE);
2277 		}
2278 		conskbd.conskbd_directio = directio;
2279 
2280 		if (conskbd.conskbd_directio) {
2281 			kbtrans_streams_set_queue(
2282 			    conskbd.conskbd_kbtrans, conskbd_regqueue);
2283 		} else {
2284 			kbtrans_streams_set_queue(
2285 			    conskbd.conskbd_kbtrans, conskbd_consqueue);
2286 		}
2287 
2288 		/*
2289 		 * Let the kbtrans-based code see this and respond to it.
2290 		 */
2291 		return (B_FALSE);
2292 
2293 	default:
2294 		return (B_FALSE);
2295 	}
2296 
2297 }	/* conskbd_override_kbtrans() */
2298 
2299 
2300 static void
2301 conskbd_polledio_enter(cons_polledio_arg_t arg)
2302 {
2303 	conskbd_state_t		*conskbdp;
2304 	struct cons_polledio		*cb;
2305 	conskbd_lower_queue_t	*lqs;
2306 
2307 	conskbdp = (conskbd_state_t *)arg;
2308 	for (lqs = conskbdp->conskbd_lqueue_list; lqs; lqs = lqs->lqs_next) {
2309 		cb = lqs->lqs_polledio;
2310 		if ((cb != NULL) && (cb->cons_polledio_enter != NULL)) {
2311 			cb->cons_polledio_enter(cb->cons_polledio_argument);
2312 		}
2313 	}
2314 
2315 }	/* conskbd_polledio_enter() */
2316 
2317 static void
2318 conskbd_polledio_exit(cons_polledio_arg_t arg)
2319 {
2320 	conskbd_state_t		*conskbdp;
2321 	struct cons_polledio		*cb;
2322 	conskbd_lower_queue_t	*lqs;
2323 
2324 	conskbdp = (conskbd_state_t *)arg;
2325 	for (lqs = conskbdp->conskbd_lqueue_list; lqs; lqs = lqs->lqs_next) {
2326 		cb = lqs->lqs_polledio;
2327 		if ((cb != NULL) && (cb->cons_polledio_exit != NULL)) {
2328 			cb->cons_polledio_exit(cb->cons_polledio_argument);
2329 		}
2330 	}
2331 
2332 }	/* conskbd_polledio_exit() */
2333 
2334 static int
2335 conskbd_polledio_getchar(cons_polledio_arg_t arg)
2336 {
2337 	conskbd_state_t  *conskbdp;
2338 
2339 	conskbdp = (conskbd_state_t *)arg;
2340 
2341 	return (kbtrans_getchar(conskbdp->conskbd_kbtrans));
2342 
2343 }	/* conskbd_polledio_getchar() */
2344 
2345 static int
2346 conskbd_polledio_ischar(cons_polledio_arg_t arg)
2347 {
2348 	conskbd_state_t  *conskbdp;
2349 
2350 	conskbdp = (conskbd_state_t *)arg;
2351 
2352 	return (kbtrans_ischar(conskbdp->conskbd_kbtrans));
2353 
2354 }	/* conskbd_polledio_ischar() */
2355 
2356 
2357 static void
2358 conskbd_mux_enqueue_msg(conskbd_pending_msg_t *msg)
2359 {
2360 	mutex_enter(&conskbd_msgq_lock);
2361 	msg->kpm_next = conskbd_msg_queue;
2362 	conskbd_msg_queue = msg;
2363 	mutex_exit(&conskbd_msgq_lock);
2364 
2365 }	/* conskbd_mux_enqueue_msg() */
2366 
2367 /*
2368  * the messages in conskbd_msg_queue we just enqueue
2369  */
2370 static conskbd_pending_msg_t *
2371 conskbd_mux_find_msg(mblk_t *mp)
2372 {
2373 	conskbd_pending_msg_t	*msg;
2374 	struct iocblk		*iocp;
2375 	uint_t	id;
2376 
2377 	mutex_enter(&conskbd_msgq_lock);
2378 	msg = conskbd_msg_queue;
2379 
2380 	iocp = (struct iocblk *)mp->b_rptr;
2381 	ASSERT(iocp);
2382 	id = iocp->ioc_id;
2383 	while (msg && msg->kpm_req_id != id) {
2384 		msg = msg->kpm_next;
2385 	}
2386 	mutex_exit(&conskbd_msgq_lock);
2387 
2388 	return (msg);
2389 
2390 }	/* conskbd_mux_find_msg() */
2391 
2392 
2393 static void
2394 conskbd_mux_dequeue_msg(conskbd_pending_msg_t *msg)
2395 {
2396 	conskbd_pending_msg_t *prev;
2397 	conskbd_pending_msg_t *p;
2398 
2399 	mutex_enter(&conskbd_msgq_lock);
2400 	prev = conskbd_msg_queue;
2401 
2402 	for (p = prev; p != msg; p = p->kpm_next)
2403 		prev = p;
2404 	ASSERT(p && p == msg);
2405 	if (prev == p) {
2406 		conskbd_msg_queue = msg->kpm_next;
2407 	} else {
2408 		prev->kpm_next = p->kpm_next;
2409 	}
2410 	p->kpm_next = NULL;
2411 	mutex_exit(&conskbd_msgq_lock);
2412 
2413 }	/* conskbd_mux_dequeue_msg() */
2414 
2415 #ifdef DEBUG
2416 /*ARGSUSED*/
2417 void
2418 conskbd_dprintf(const char *fmt, ...)
2419 {
2420 	char buf[256];
2421 	va_list ap;
2422 
2423 	va_start(ap, fmt);
2424 	(void) vsprintf(buf, fmt, ap);
2425 	va_end(ap);
2426 
2427 	cmn_err(CE_CONT, "conskbd: %s", buf);
2428 
2429 }	/* conskbd_dprintf() */
2430 #endif
2431