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