xref: /titanic_50/usr/src/uts/common/io/conskbd.c (revision ff3124eff995e6cd8ebd8c6543648e0670920034)
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 2008 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(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, 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 	case KIOCMKTONE:
987 		if (conskbd.conskbd_lqueue_list == NULL ||
988 		    mp->b_cont == NULL) {
989 			miocnak(q, mp, 0, EINVAL);
990 			break;
991 		}
992 		cmd = *(int *)mp->b_cont->b_rptr;
993 		if (cmd == KBD_CMD_GETLAYOUT) {
994 			freemsg(mp->b_cont);
995 			datap = allocb(sizeof (int), BPRI_HI);
996 			if (datap == NULL) {
997 				miocnak(q, mp, 0, ENOMEM);
998 				return;
999 			}
1000 			if (conskbd.conskbd_layout == -1)
1001 				*(int *)datap->b_wptr =
1002 				    KBTRANS_USBKB_DEFAULT_LAYOUT;
1003 			else
1004 				*(int *)datap->b_wptr = conskbd.conskbd_layout;
1005 
1006 			mp->b_cont = datap;
1007 			miocack(q, mp, sizeof (int), 0);
1008 			return;
1009 		}
1010 		conskbd_handle_downstream_msg(q, mp);
1011 		break;
1012 
1013 	default:
1014 		miocnak(q, mp, 0, EINVAL);
1015 		break;
1016 	}
1017 
1018 }	/* conskbd_virtual_kbd_ioctl() */
1019 
1020 static void
1021 conskbd_legacy_kbd_ioctl(queue_t *q, mblk_t *mp)
1022 {
1023 	conskbd_lower_queue_t	*lq;
1024 	struct	iocblk		*iocp;
1025 	int	error = 0;
1026 
1027 	iocp = (struct iocblk *)mp->b_rptr;
1028 
1029 	ASSERT(conskbd.conskbd_lqueue_nums == 1);
1030 	switch (iocp->ioc_cmd) {
1031 
1032 	case KIOCGDIRECT: {
1033 		mblk_t *datap;
1034 
1035 		if ((datap = allocb(sizeof (int), BPRI_MED)) == NULL) {
1036 			miocnak(q, mp, 0, ENOMEM);
1037 			break;
1038 		}
1039 
1040 		*(int *)datap->b_wptr = conskbd.conskbd_directio;
1041 		datap->b_wptr += sizeof (int);
1042 		if (mp->b_cont != NULL) {
1043 			freemsg(mp->b_cont);
1044 			mp->b_cont = NULL;
1045 		}
1046 		mp->b_cont = datap;
1047 		miocack(q, mp, sizeof (int), 0);
1048 		break;
1049 	}
1050 
1051 	case KIOCSDIRECT:
1052 		error = miocpullup(mp, sizeof (int));
1053 		if (error != 0) {
1054 			miocnak(q, mp, 0, error);
1055 			break;
1056 		}
1057 		conskbd.conskbd_directio = *(int *)mp->b_cont->b_rptr;
1058 
1059 		/*
1060 		 * Pass this through, if there's something to pass
1061 		 * it through to, so the system keyboard can reset
1062 		 * itself.
1063 		 */
1064 		if (conskbd.conskbd_lqueue_nums > 0) {
1065 			lq = conskbd.conskbd_lqueue_list;
1066 			ASSERT(lq && lq->lqs_next == NULL);
1067 			if (putq(lq->lqs_queue, mp) != 1) {
1068 				miocnak(q, mp, 0, ENOMEM);
1069 				return;
1070 			}
1071 			break;
1072 		}
1073 
1074 		miocack(q, mp, 0, 0);
1075 		break;
1076 
1077 	default:
1078 		/*
1079 		 * Pass this through, if there's something to pass it
1080 		 * through to; otherwise, reject it.
1081 		 */
1082 		if (conskbd.conskbd_lqueue_nums > 0) {
1083 			lq = conskbd.conskbd_lqueue_list;
1084 			ASSERT(lq && lq->lqs_next == NULL);
1085 			if (putq(lq->lqs_queue, mp) != 1) {
1086 				miocnak(q, mp, 0, ENOMEM);
1087 				return;
1088 			}
1089 			break;
1090 		}
1091 
1092 		/* nobody below us; reject it */
1093 		miocnak(q, mp, 0, EINVAL);
1094 		break;
1095 	}
1096 
1097 }	/* conskbd_legacy_kbd_ioctl() */
1098 
1099 
1100 /*
1101  * Service procedure for lower write queue.
1102  * Puts things on the queue below us, if it lets us.
1103  */
1104 static void
1105 conskbdlwserv(queue_t *q)
1106 {
1107 	register mblk_t *mp;
1108 
1109 	while (canput(q->q_next) && (mp = getq(q)) != NULL)
1110 		putnext(q, mp);
1111 
1112 }	/* conskbdlwserv() */
1113 
1114 /*
1115  * Put procedure for lower read queue.
1116  * Pass everything up to minor device 0 if "directio" set, otherwise to minor
1117  * device 1.
1118  */
1119 static void
1120 conskbdlrput(queue_t *q, mblk_t *mp)
1121 {
1122 	conskbd_lower_queue_t	*lqs;
1123 	struct iocblk 	*iocp;
1124 	Firm_event	*fe;
1125 
1126 	DPRINTF(PRINT_L1, PRINT_MASK_ALL, ("conskbdlrput\n"));
1127 
1128 	switch (mp->b_datap->db_type) {
1129 
1130 	case M_FLUSH:
1131 		if (*mp->b_rptr == FLUSHR) {
1132 			flushq(q, FLUSHDATA);	/* XXX doesn't flush M_DELAY */
1133 			*mp->b_rptr &= ~FLUSHR;	/* it has been flushed */
1134 		}
1135 		if (*mp->b_rptr == FLUSHW) {
1136 			flushq(WR(q), FLUSHDATA);
1137 			qreply(q, mp);	/* give the read queues a crack at it */
1138 		} else
1139 			freemsg(mp);
1140 		break;
1141 
1142 	case M_DATA:
1143 		if (conskbd.conskbd_bypassed == B_FALSE) {
1144 
1145 			fe = (Firm_event *)mp->b_rptr;
1146 
1147 			/*
1148 			 * This is a workaround.
1149 			 *
1150 			 * According to HID specification, there are the
1151 			 * following keycode mapping between PS2 and USB,
1152 			 *
1153 			 *	PS2 AT-101 keycode(29)  --->    USB(49)
1154 			 *	PS2 AT-102 keycode(42)  --->    USB(50)
1155 			 *
1156 			 * However, the two keys, AT-101(29) and AT-102(42),
1157 			 * have the same scancode,0x2B, in PS2 scancode SET1
1158 			 * which we are using. The Kb8042 driver always
1159 			 * recognizes the two keys as PS2(29) so that we could
1160 			 * not know which is being pressed or released when we
1161 			 * receive scancode 0x2B. Fortunately, the two keys can
1162 			 * not co-exist in a specific layout. In other words,
1163 			 * in the table of keycode-to-symbol mapping, either
1164 			 * entry 49 or 50 is a hole. So, if we're processing a
1165 			 * keycode 49, we look at the entry for 49.  If it's
1166 			 * HOLE, remap the key to 50; If we're processing a 50,
1167 			 * look at the entry for 50.  If it's HOLE, we remap
1168 			 * the key to 49.
1169 			 */
1170 			if (fe->id == 49 || fe->id == 50) {
1171 				if (conskbd_keyindex->k_normal[50] == HOLE)
1172 					fe->id = 49;
1173 				else
1174 					fe->id = 50;
1175 			}
1176 
1177 			/*
1178 			 * Remember key state of each key of lower physical
1179 			 * keyboard. When a keyboard is umplumbed from conskbd,
1180 			 * we will check all key states. By then,  we will fake
1181 			 * a KEY_RELEASED message for each key in KEY_PRESSED
1182 			 * state. Otherwise, upper module will treat these keys
1183 			 * as held-down for ever.
1184 			 */
1185 			iocp = (struct iocblk *)mp->b_rptr;
1186 			lqs = (conskbd_lower_queue_t *)q->q_ptr;
1187 			if (fe->value)
1188 				lqs->lqs_key_state[fe->id] = KEY_PRESSED;
1189 			else
1190 				lqs->lqs_key_state[fe->id] = KEY_RELEASED;
1191 
1192 			kbtrans_streams_key(conskbd.conskbd_kbtrans,
1193 			    fe->id, fe->value ? KEY_PRESSED : KEY_RELEASED);
1194 			freemsg(mp);
1195 		} else {
1196 			if (conskbd.conskbd_directio)
1197 				putnext(conskbd_regqueue, mp);
1198 			else if (conskbd_consqueue != NULL)
1199 				putnext(conskbd_consqueue, mp);
1200 			else
1201 				freemsg(mp);
1202 		}
1203 		conskbd_idle_stamp = gethrestime_sec();
1204 		break;
1205 
1206 	case M_IOCACK:
1207 	case M_IOCNAK:
1208 		iocp = (struct iocblk *)mp->b_rptr;
1209 		lqs = (conskbd_lower_queue_t *)q->q_ptr;
1210 
1211 		DPRINTF(PRINT_L1, PRINT_MASK_ALL, ("conskbdlrput: "
1212 		    "ACK/NAK - cmd 0x%x\n", iocp->ioc_cmd));
1213 
1214 		conskbd_lqs_ack_complete(lqs, mp);
1215 		break;
1216 
1217 	case M_ERROR:
1218 	case M_HANGUP:
1219 	default:
1220 		freemsg(mp);	/* anything useful here? */
1221 		break;
1222 	}
1223 
1224 }	/* conskbdlrput() */
1225 
1226 
1227 /* ARGSUSED */
1228 static int
1229 conskbd_kstat_update(kstat_t *ksp, int rw)
1230 {
1231 	if (rw == KSTAT_WRITE)
1232 		return (EACCES);
1233 
1234 	conskbd_kstat.idle_sec.value.l = gethrestime_sec() - conskbd_idle_stamp;
1235 
1236 	return (0);
1237 
1238 }	/* conskbd_kstat_update() */
1239 
1240 /*
1241  * STREAMS architecuture provides guarantee that the ID of each
1242  * message, iocblk.ioc_id, in a stream is unique. The following
1243  * routine performes the task: When receive request from upstream,
1244  * it saves the request in a global link list, clones the request,
1245  * and then sends a copy of the request to each of lower queues
1246  * which are plumbed into conskbd. And then, when receives responses
1247  * from lower queues in conskbdlrput() routine, we can know the
1248  * request matching received responses by searching the global linked
1249  * list to find the request which has the same message ID of the
1250  * response. Then, when all lower queues response this request, we
1251  * give a response to upstreams based the following policy:
1252  * If any one of lower queues acks our reuqest, then we return ack
1253  * to upstreams; only if all lower queues nak our request, we return
1254  * nak to upstreams. If all responses are nak, the error number of
1255  * the first response is sent to upstream.
1256  */
1257 static void
1258 conskbd_handle_downstream_msg(queue_t *q, mblk_t *mp)
1259 {
1260 	conskbd_pending_msg_t	*msg;
1261 	conskbd_lower_queue_t	*lqs;
1262 	struct iocblk	*iocp;
1263 	mblk_t		*clonemp;
1264 	int		retry;
1265 
1266 	if (conskbd.conskbd_lqueue_nums == 0) {
1267 		miocnak(q, mp, 0, EINVAL);
1268 		return;
1269 	}
1270 
1271 	msg = (conskbd_pending_msg_t *)
1272 	    kmem_zalloc(sizeof (conskbd_pending_msg_t), KM_SLEEP);
1273 	mutex_init(&msg->kpm_lock, NULL, MUTEX_DRIVER, NULL);
1274 	lqs = conskbd.conskbd_lqueue_list;
1275 	iocp = (struct iocblk *)mp->b_rptr;
1276 
1277 	ASSERT(iocp->ioc_cmd == CONSOPENPOLLEDIO ||
1278 	    iocp->ioc_cmd == CONSCLOSEPOLLEDIO ||
1279 	    iocp->ioc_cmd == KIOCCMD ||
1280 	    iocp->ioc_cmd == KIOCMKTONE);
1281 
1282 	msg->kpm_upper_queue = q;
1283 	msg->kpm_req_msg = mp;
1284 	msg->kpm_req_id = iocp->ioc_id;
1285 	msg->kpm_req_cmd = iocp->ioc_cmd;
1286 	msg->kpm_req_nums = conskbd.conskbd_lqueue_nums;
1287 	conskbd_mux_enqueue_msg(msg);
1288 
1289 	for (retry = 0, lqs = conskbd.conskbd_lqueue_list; lqs; ) {
1290 
1291 		/*
1292 		 * if a lower physical keyboard is not in polled I/O
1293 		 * mode, we couldn't send CONSCLOSEPOLLEDIO to it,
1294 		 * otherwise, system will panic.
1295 		 */
1296 		if (iocp->ioc_cmd == CONSCLOSEPOLLEDIO &&
1297 		    lqs->lqs_polledio == NULL) {
1298 			lqs = lqs->lqs_next;
1299 			msg->kpm_req_nums --;
1300 			retry = 0;
1301 			continue;
1302 		}
1303 
1304 		clonemp = copymsg(mp);
1305 		if (clonemp != NULL) {
1306 			if (putq(lqs->lqs_queue, clonemp) == 1) {
1307 				lqs = lqs->lqs_next;
1308 				retry = 0;
1309 				continue;
1310 			}
1311 
1312 			/*
1313 			 * failed to invoke putq(), retry.
1314 			 */
1315 			freemsg(clonemp);
1316 		}
1317 
1318 		/*
1319 		 * During testing it was observed that occasionally
1320 		 * copymsg() would fail during boot. The reason for
1321 		 * these failures is unknown. Since we really want
1322 		 * to successfully plumb up all the attached keyboards
1323 		 * during boot we do a best effort here by retrying
1324 		 * the copymsg() call in the hopes that it will
1325 		 * succeeded upon subsequent invocations.
1326 		 *
1327 		 * If all the calls to copymsg() fails, it will cause
1328 		 * the corresponding keyboard to be unavailable, or
1329 		 * or behave weirdly,
1330 		 *
1331 		 * 1) for CONSOPENPOLLEDIO
1332 		 *	if copymsg()fails, the corresponding keyboard
1333 		 *	is not available in polled I/O mode once
1334 		 *	entering kmdb;
1335 		 * 2) for CONSCLOSEPOLLEDIO
1336 		 *	if copymsg() fails, the corresponding keyboard
1337 		 *	is not available in normal mode once returning
1338 		 *	from kmdb;
1339 		 * 3) for KIOCCMD
1340 		 * 	3.1) for KBD_CMD_NOBELL
1341 		 * 		there's no beep in USB and PS2 keyboard,
1342 		 * 		this ioctl actually disables the beep on
1343 		 * 		system mainboard. Note that all the cloned
1344 		 * 		messages sent down to lower queues do the
1345 		 * 		same job for system mainboard. Therefore,
1346 		 * 		even if we fail to send this ioctl to most
1347 		 * 		of lower queues, the beep still would be
1348 		 * 		disabled. So, no trouble exists here.
1349 		 *	3.2) for others
1350 		 *		nothing;
1351 		 *
1352 		 * However, all cases could be resume next time when the
1353 		 * same request comes again.
1354 		 */
1355 		if (retry ++ >= 5) {
1356 			dev_t	devt;
1357 			char	path[MAXPATHLEN + 1];
1358 
1359 			devt = lqs->lqs_queue->q_stream->sd_vnode->v_rdev;
1360 			switch (iocp->ioc_cmd) {
1361 			case CONSOPENPOLLEDIO:
1362 				if (ddi_dev_pathname(devt, S_IFCHR,
1363 				    path) == DDI_SUCCESS)
1364 					cmn_err(CE_WARN, "conskbd: "
1365 					    "keyboard is not available"
1366 					    " for system debugging: %s",
1367 					    path);
1368 				break;
1369 
1370 			case CONSCLOSEPOLLEDIO:
1371 				if (ddi_dev_pathname(devt, S_IFCHR,
1372 				    path) == DDI_SUCCESS)
1373 					cmn_err(CE_WARN, "conskbd: "
1374 					    "keyboard is not available:"
1375 					    " %s", path);
1376 				break;
1377 
1378 			default:
1379 				break;
1380 			}
1381 			msg->kpm_req_nums --;
1382 			lqs = lqs->lqs_next;
1383 			retry = 0;
1384 		}
1385 	}
1386 
1387 	if (msg->kpm_req_nums == 0) {
1388 		conskbd_mux_dequeue_msg(msg);
1389 		kmem_free(msg, sizeof (*msg));
1390 		miocnak(q, mp, 0, ENOMEM);
1391 	}
1392 
1393 }	/* conskbd_handle_downstream_msg() */
1394 
1395 
1396 static void
1397 conskbd_ioc_plink(queue_t *q, mblk_t *mp)
1398 {
1399 	mblk_t		*req;
1400 	queue_t		*lowque;
1401 	struct linkblk		*linkp;
1402 	conskbd_lower_queue_t	*lqs;
1403 
1404 	lqs = kmem_zalloc(sizeof (*lqs), KM_SLEEP);
1405 	ASSERT(lqs->lqs_state == LQS_UNINITIALIZED);
1406 
1407 	linkp = (struct linkblk *)mp->b_cont->b_rptr;
1408 	lowque = linkp->l_qbot;
1409 
1410 	lqs->lqs_queue = lowque;
1411 	lqs->lqs_pending_plink = mp;
1412 	lqs->lqs_pending_queue = q;
1413 
1414 	req = mkiocb(CONSSETKBDTYPE);
1415 	if (req == NULL) {
1416 		miocnak(q, mp, 0, ENOMEM);
1417 		kmem_free(lqs, sizeof (*lqs));
1418 		return;
1419 	}
1420 
1421 	req->b_cont = allocb(sizeof (int), BPRI_MED);
1422 	if (req->b_cont == NULL) {
1423 		freemsg(req);
1424 		miocnak(q, mp, 0, ENOMEM);
1425 		kmem_free(lqs, sizeof (*lqs));
1426 		return;
1427 	}
1428 
1429 	lowque->q_ptr = lqs;
1430 	OTHERQ(lowque)->q_ptr = lqs;
1431 	*(int *)req->b_cont->b_wptr = KB_USB;
1432 	req->b_cont->b_wptr += sizeof (int);
1433 
1434 	lqs->lqs_state = LQS_KIOCTYPE_ACK_PENDING;
1435 
1436 	if (putq(lowque, req) != 1) {
1437 		freemsg(req);
1438 		miocnak(lqs->lqs_pending_queue,
1439 		    lqs->lqs_pending_plink, 0, ENOMEM);
1440 		lowque->q_ptr = NULL;
1441 		OTHERQ(lowque)->q_ptr = NULL;
1442 		kmem_free(lqs, sizeof (*lqs));
1443 	}
1444 
1445 }	/* conskbd_ioc_plink() */
1446 
1447 
1448 static void
1449 conskbd_ioc_punlink(queue_t *q, mblk_t *mp)
1450 {
1451 	int			index;
1452 	struct linkblk		*linkp;
1453 	conskbd_lower_queue_t	*lqs;
1454 	conskbd_lower_queue_t	*prev;
1455 
1456 	linkp = (struct linkblk *)mp->b_cont->b_rptr;
1457 	prev = conskbd.conskbd_lqueue_list;
1458 	for (lqs = prev; lqs; lqs = lqs->lqs_next) {
1459 		if (lqs->lqs_queue == linkp->l_qbot) {
1460 			if (prev == lqs)
1461 				conskbd.conskbd_lqueue_list =
1462 				    lqs->lqs_next;
1463 			else
1464 				prev->lqs_next = lqs->lqs_next;
1465 
1466 			lqs->lqs_queue->q_ptr =  NULL;
1467 			OTHERQ(lqs->lqs_queue)->q_ptr = NULL;
1468 			conskbd.conskbd_lqueue_nums --;
1469 			if (conskbd.conskbd_lqueue_nums == 0) {
1470 				kbd_layout_bak = conskbd.conskbd_layout;
1471 				conskbd.conskbd_layout = -1;
1472 			}
1473 
1474 			for (index = 0; index < KBTRANS_KEYNUMS_MAX; index ++) {
1475 				if (lqs->lqs_key_state[index] == KEY_PRESSED)
1476 					kbtrans_streams_key(
1477 					    conskbd.conskbd_kbtrans,
1478 					    index,
1479 					    KEY_RELEASED);
1480 			}
1481 
1482 			kmem_free(lqs, sizeof (*lqs));
1483 			miocack(q, mp, 0, 0);
1484 			return;
1485 		}
1486 		prev = lqs;
1487 	}
1488 	miocnak(q, mp, 0, EINVAL);
1489 
1490 }	/* conskbd_ioc_punlink() */
1491 
1492 /*
1493  * Every physical keyboard has a corresponding STREAMS queue. We call this
1494  * queue lower queue. Every lower queue has a state, refer to conskbd.h file
1495  * about "enum conskbd_lqs_state".
1496  * The following routine is used to handle response messages from lower queue.
1497  * When receiving ack/nak message from lower queue(s), the routine determines
1498  * the passage for it according to the current state of this lower queue.
1499  */
1500 static void
1501 conskbd_lqs_ack_complete(conskbd_lower_queue_t *lqs, mblk_t *mp)
1502 {
1503 	switch (lqs->lqs_state) {
1504 
1505 	/* S6: working in virtual keyboard mode, multi-keyboards are usable */
1506 	case LQS_INITIALIZED:
1507 		conskbd_mux_upstream_msg(lqs, mp);
1508 		break;
1509 
1510 	/* S5: working in legacy mode, only one keyboard is usable */
1511 	case LQS_INITIALIZED_LEGACY:
1512 		conskbd_legacy_upstream_msg(lqs, mp);
1513 		break;
1514 
1515 	/* S4: wait lower queue to acknowledge KIOCSLED/KIOCGLED  message */
1516 	case LQS_KIOCSLED_ACK_PENDING:
1517 		conskbd_kiocsled_complete(lqs, mp);
1518 		break;
1519 
1520 	/* S3: wait lower queue to acknowledge KIOCLAYOUT  message */
1521 	case LQS_KIOCLAYOUT_ACK_PENDING:
1522 		conskbd_kioclayout_complete(lqs, mp);
1523 		break;
1524 
1525 	/* S2: wait lower queue to acknowledge KIOCTRANS  message */
1526 	case LQS_KIOCTRANS_ACK_PENDING:
1527 		conskbd_kioctrans_complete(lqs, mp);
1528 		break;
1529 
1530 	/* S1: wait lower queue to acknowledge KIOCTYPE  message */
1531 	case LQS_KIOCTYPE_ACK_PENDING:
1532 		conskbd_kioctype_complete(lqs, mp);
1533 		break;
1534 
1535 	/* if reaching here, there must be a error */
1536 	default:
1537 		freemsg(mp);
1538 		cmn_err(CE_WARN, "conskbd: lqs_ack_complete() state error");
1539 		break;
1540 	}
1541 
1542 }	/* conskbd_lqs_ack_complete() */
1543 
1544 
1545 static void
1546 conskbd_kioctype_complete(conskbd_lower_queue_t *lqs, mblk_t *mp)
1547 {
1548 	struct iocblk	*iocp;
1549 	mblk_t		*req;
1550 	queue_t		*lowerque;
1551 	int		err = ENOMEM;
1552 
1553 	ASSERT(lqs->lqs_pending_plink);
1554 	ASSERT(lqs->lqs_state == LQS_KIOCTYPE_ACK_PENDING);
1555 
1556 	lowerque = lqs->lqs_queue;
1557 
1558 	switch (mp->b_datap->db_type) {
1559 	case M_IOCACK:
1560 		req = mkiocb(KIOCTRANS);
1561 		if (req == NULL) {
1562 			goto err_exit;
1563 		}
1564 
1565 		req->b_cont = allocb(sizeof (int), BPRI_MED);
1566 		if (req->b_cont == NULL) {
1567 			freemsg(req);
1568 			goto err_exit;
1569 		}
1570 
1571 		/* Set the translate mode to TR_UNTRANS_EVENT */
1572 		*(int *)req->b_cont->b_wptr = TR_UNTRANS_EVENT;
1573 		req->b_cont->b_wptr += sizeof (int);
1574 
1575 		/* Ready to handle the response to KIOCTRANS */
1576 		lqs->lqs_state = LQS_KIOCTRANS_ACK_PENDING;
1577 
1578 		if (putq(lowerque, req) != 1) {
1579 			freemsg(req);
1580 			goto err_exit;
1581 		}
1582 		freemsg(mp);
1583 		return;
1584 
1585 	case M_IOCNAK:
1586 		/*
1587 		 * The lower keyboard driver can't mimic USB keyboard,
1588 		 * that's say, the physical keyboard is an old one, such
1589 		 * as TYPE 3/4/5 one. In this case, the virtual keyboard
1590 		 * is disabled, and the data from lower keyboard driver
1591 		 * will bypass the conskbd module.
1592 		 */
1593 
1594 		/*
1595 		 * if there is any other keyborad already linked under the
1596 		 * conskbd, we reject the current one.
1597 		 */
1598 		if (conskbd.conskbd_lqueue_nums > 0) {
1599 			iocp = (struct iocblk *)mp->b_rptr;
1600 			err = iocp->ioc_error;
1601 			goto err_exit;
1602 		}
1603 
1604 		/*
1605 		 * link this keyboard under conskbd.
1606 		 */
1607 		qwriter(lowerque, mp, conskbd_link_lowque_legacy, PERIM_OUTER);
1608 		return;
1609 	}
1610 
1611 err_exit:
1612 	miocnak(lqs->lqs_pending_queue, lqs->lqs_pending_plink, 0, err);
1613 	lowerque->q_ptr = NULL;
1614 	OTHERQ(lowerque)->q_ptr = NULL;
1615 	kmem_free(lqs, sizeof (*lqs));
1616 	freemsg(mp);
1617 
1618 }	/* conskbd_kioctype_complete() */
1619 
1620 static void
1621 conskbd_kioctrans_complete(conskbd_lower_queue_t *lqs, mblk_t *mp)
1622 {
1623 	struct iocblk 	*iocp;
1624 	mblk_t		*req;
1625 	queue_t		*lowerque;
1626 	int		err = ENOMEM;
1627 
1628 	ASSERT(lqs->lqs_pending_plink != NULL);
1629 	ASSERT(lqs->lqs_state == LQS_KIOCTRANS_ACK_PENDING);
1630 
1631 	lowerque = lqs->lqs_queue;
1632 
1633 	switch (mp->b_datap->db_type) {
1634 	case M_IOCACK:
1635 		req = mkiocb(KIOCLAYOUT);
1636 		if (req == NULL) {
1637 			goto err_exit;
1638 		}
1639 
1640 		req->b_cont = allocb(sizeof (int), BPRI_MED);
1641 		if (req->b_cont == NULL) {
1642 			freemsg(req);
1643 			goto err_exit;
1644 		}
1645 
1646 		/* waiting for response to KIOCLAYOUT */
1647 		lqs->lqs_state = LQS_KIOCLAYOUT_ACK_PENDING;
1648 		if (putq(lqs->lqs_queue, req) != 1) {
1649 			freemsg(req);
1650 			goto err_exit;
1651 		}
1652 		freemsg(mp);
1653 		return;
1654 
1655 	case M_IOCNAK:
1656 		iocp = (struct iocblk *)mp->b_rptr;
1657 		err = iocp->ioc_error;
1658 		goto err_exit;
1659 	}
1660 
1661 err_exit:
1662 	miocnak(lqs->lqs_pending_queue, lqs->lqs_pending_plink, 0, err);
1663 	lowerque->q_ptr = NULL;
1664 	OTHERQ(lowerque)->q_ptr = NULL;
1665 	kmem_free(lqs, sizeof (*lqs));
1666 	freemsg(mp);
1667 
1668 }	/* conskbd_kioctrans_complete() */
1669 
1670 /*
1671  * Allocate a firm event
1672  */
1673 static mblk_t *
1674 conskbd_alloc_firm_event(ushort_t id, int value)
1675 {
1676 	mblk_t	*mb;
1677 	Firm_event *fe;
1678 
1679 	if ((mb = allocb(sizeof (Firm_event), BPRI_HI)) != NULL) {
1680 		fe = (Firm_event *)mb->b_wptr;
1681 		fe->id = id;
1682 		fe->pair_type = FE_PAIR_NONE;
1683 		fe->pair = NULL;
1684 		fe->value = value;
1685 		mb->b_wptr += sizeof (Firm_event);
1686 	}
1687 
1688 	return (mb);
1689 }
1690 
1691 static void
1692 conskbd_kioclayout_complete(conskbd_lower_queue_t *lqs, mblk_t *mp)
1693 {
1694 	mblk_t		*req;
1695 	int		layout;
1696 	boolean_t	fail;
1697 
1698 	ASSERT(lqs->lqs_pending_plink != NULL);
1699 	ASSERT(lqs->lqs_state == LQS_KIOCLAYOUT_ACK_PENDING);
1700 
1701 	switch (mp->b_datap->db_type) {
1702 	case M_IOCACK:
1703 		if (miocpullup(mp, sizeof (int)) == 0) {
1704 			layout = *(int *)mp->b_cont->b_rptr;
1705 			/*
1706 			 * We just accept the layout of the first keyboard
1707 			 * requesting to be linked under conskbd. If current
1708 			 * keyboard is the first one, and if we get right
1709 			 * layout from it, we set conskbd's layout
1710 			 */
1711 			if (layout != -1 && conskbd.conskbd_layout == -1) {
1712 				if (layout == 0) {
1713 					conskbd.conskbd_layout = kbd_layout_bak;
1714 				} else {
1715 					conskbd.conskbd_layout = layout;
1716 					if (layout == kbd_layout_bak) {
1717 						break;
1718 					}
1719 					if ((req = conskbd_alloc_firm_event(
1720 					    KEYBOARD_LAYOUT_CHANGE,
1721 					    layout)) != NULL) {
1722 						if (conskbd.conskbd_directio) {
1723 							putnext(
1724 							    conskbd_regqueue,
1725 							    req);
1726 						} else if (conskbd_consqueue
1727 						    != NULL) {
1728 							putnext(
1729 							    conskbd_consqueue,
1730 							    req);
1731 						} else {
1732 							freemsg(req);
1733 						}
1734 					}
1735 				}
1736 			}
1737 		}
1738 		break;
1739 
1740 
1741 	/* if fail, leave conskbd's layout as it is */
1742 	case M_IOCNAK:
1743 		break;
1744 	}
1745 
1746 	fail = B_TRUE;
1747 
1748 	if (conskbd.conskbd_led_state == -1)
1749 		req = mkiocb(KIOCGLED);
1750 	else
1751 		req = mkiocb(KIOCSLED);
1752 
1753 	if (req) {
1754 		req->b_cont = allocb(sizeof (uchar_t), BPRI_MED);
1755 		if (req->b_cont) {
1756 			if (conskbd.conskbd_led_state != -1) {
1757 				*(uchar_t *)req->b_cont->b_wptr =
1758 				    conskbd.conskbd_led_state;
1759 				req->b_cont->b_wptr += sizeof (uchar_t);
1760 			}
1761 
1762 			/* waiting for response to KIOCSLED */
1763 			lqs->lqs_state = LQS_KIOCSLED_ACK_PENDING;
1764 			if (putq(lqs->lqs_queue, req) == 1) {
1765 				fail = B_FALSE;
1766 			} else {
1767 				freemsg(req);
1768 			}
1769 
1770 		} else {
1771 			freemsg(req);
1772 		}
1773 	}
1774 
1775 	if (fail) {
1776 		/*
1777 		 * If fail to allocate KIOCSLED/KIOCGLED message or put
1778 		 * the message into lower queue, we immediately link
1779 		 * current keyboard under conskbd. Thus, even if fails
1780 		 * to set/get LED, this keyboard could be available.
1781 		 */
1782 		qwriter(lqs->lqs_queue,
1783 		    mp, conskbd_link_lowque_virt, PERIM_OUTER);
1784 	} else {
1785 		freemsg(mp);
1786 	}
1787 
1788 }	/* conskbd_kioclayout_complete() */
1789 
1790 
1791 static void
1792 conskbd_kiocsled_complete(conskbd_lower_queue_t *lqs, mblk_t *mp)
1793 {
1794 	int	led_state;
1795 
1796 	ASSERT(lqs->lqs_pending_plink != NULL);
1797 	ASSERT(lqs->lqs_state == LQS_KIOCSLED_ACK_PENDING);
1798 
1799 	if (conskbd.conskbd_led_state == -1) {
1800 		switch (mp->b_datap->db_type) {
1801 		case M_IOCACK:
1802 			if (miocpullup(mp, sizeof (uchar_t)) == 0) {
1803 				led_state = *(uchar_t *)mp->b_cont->b_rptr;
1804 				conskbd.conskbd_led_state = led_state;
1805 				kbtrans_streams_setled(conskbd.conskbd_kbtrans,
1806 				    led_state);
1807 			}
1808 			break;
1809 
1810 		/* if fail, leave conskbd's led_state as it is */
1811 		case M_IOCNAK:
1812 			break;
1813 		}
1814 	}
1815 
1816 	/*
1817 	 * Basically, failure of setting/getting LED is not a fatal
1818 	 * error, so we will plumb the lower queue into conskbd whether
1819 	 * setting/getting LED succeeds or fails.
1820 	 */
1821 	qwriter(lqs->lqs_queue, mp, conskbd_link_lowque_virt, PERIM_OUTER);
1822 
1823 }	/* conskbd_kiocsled_complete() */
1824 
1825 
1826 static void
1827 conskbd_mux_upstream_msg(conskbd_lower_queue_t *lqs, mblk_t *mp)
1828 {
1829 	conskbd_pending_msg_t	*msg;
1830 	struct iocblk		*iocp;
1831 	int			error;
1832 	dev_t			devt;
1833 	char			path[MAXPATHLEN + 1];
1834 
1835 	ASSERT(lqs->lqs_state == LQS_INITIALIZED);
1836 	msg = conskbd_mux_find_msg(mp);
1837 
1838 	if (!msg) {
1839 		/*
1840 		 * Here we discard the response if:
1841 		 *
1842 		 *   1. It's an KIOCSLED request; see conskbd_streams_setled().
1843 		 *   2. The application has already closed the upper stream;
1844 		 *		see conskbdclose()
1845 		 */
1846 		freemsg(mp);
1847 		return;
1848 	}
1849 
1850 	/*
1851 	 * We use the b_next field of mblk_t structure to link all
1852 	 * response coming from lower queues into a linkage list,
1853 	 * and make use of the b_prev field to save a pointer to
1854 	 * the lower queue from which the current response message
1855 	 * comes.
1856 	 */
1857 	ASSERT(mp->b_next == NULL && mp->b_prev == NULL);
1858 	mutex_enter(&msg->kpm_lock);
1859 	mp->b_next = msg->kpm_resp_list;
1860 	mp->b_prev = (mblk_t *)lqs;
1861 	msg->kpm_resp_list = mp;
1862 	msg->kpm_resp_nums ++;
1863 
1864 	if (msg->kpm_resp_nums < msg->kpm_req_nums) {
1865 		mutex_exit(&msg->kpm_lock);
1866 		return;
1867 	}
1868 
1869 	ASSERT(msg->kpm_resp_nums == msg->kpm_req_nums);
1870 	ASSERT(mp == msg->kpm_resp_list);
1871 
1872 	mutex_exit(&msg->kpm_lock);
1873 
1874 	conskbd_mux_dequeue_msg(msg);
1875 
1876 
1877 	/*
1878 	 * Here, we have the policy that, if any one lower queue ACK
1879 	 * our reuqest, then we return ACK to upstreams; only if all
1880 	 * lower queues NAK our request, we return NAK to upstreams.
1881 	 * if all responses are nak, the errno of the  first response
1882 	 * is sent to upstreams
1883 	 */
1884 	ASSERT(mp->b_rptr);
1885 	error = ((struct iocblk *)mp->b_rptr)->ioc_error;
1886 
1887 	switch (msg->kpm_req_cmd) {
1888 	case CONSOPENPOLLEDIO:
1889 		/*
1890 		 * Here, we can safely ignore the NAK message. If any one lower
1891 		 * queue returns NAK, the pointer to the corresponding polledio
1892 		 * structure will remain null, that's say lqs->lqs_polledio =
1893 		 * null. When we need to invoke polled I/O interface, we will
1894 		 * check if the pointer is null.
1895 		 */
1896 		for (mp = msg->kpm_resp_list; mp; ) {
1897 			cons_polledio_t		*polledio;
1898 
1899 			msg->kpm_resp_list = mp->b_next;
1900 			lqs = (conskbd_lower_queue_t *)mp->b_prev;
1901 			devt = lqs->lqs_queue->q_stream->sd_vnode->v_rdev;
1902 			if (mp->b_datap->db_type == M_IOCACK) {
1903 				polledio = *(struct cons_polledio **)
1904 				    mp->b_cont->b_rptr;
1905 				if (polledio->cons_polledio_version ==
1906 				    CONSPOLLEDIO_V1) {
1907 					lqs->lqs_polledio = polledio;
1908 					error = 0;
1909 				} else {
1910 					/*
1911 					 * USB and PS2 keyboard drivers should
1912 					 * use the same cons_polledio structure
1913 					 * as conskbd.
1914 					 */
1915 					if (ddi_dev_pathname(devt, S_IFCHR,
1916 					    path) == DDI_SUCCESS) {
1917 						cmn_err(CE_WARN, "keyboard "
1918 						    "driver does not support "
1919 						    "system debugging: %s",
1920 						    path);
1921 					}
1922 					error = EINVAL;
1923 				}
1924 			} else {
1925 				if (ddi_dev_pathname(devt, S_IFCHR, path) ==
1926 				    DDI_SUCCESS) {
1927 					cmn_err(CE_WARN, "conskbd: keyboard is"
1928 					    " not available for system"
1929 					    " debugging:  %s", path);
1930 				}
1931 			}
1932 			mp->b_next = NULL;
1933 			mp->b_prev = NULL;
1934 			freemsg(mp);
1935 			mp = msg->kpm_resp_list;
1936 		}
1937 
1938 		mp = msg->kpm_req_msg;
1939 		if (error == 0) {
1940 			*(struct cons_polledio **)mp->b_cont->b_rptr =
1941 			    &conskbd.conskbd_polledio;
1942 		}
1943 		break;
1944 
1945 	case CONSCLOSEPOLLEDIO:
1946 		for (mp = msg->kpm_resp_list; mp; ) {
1947 			msg->kpm_resp_list = mp->b_next;
1948 			lqs = (conskbd_lower_queue_t *)mp->b_prev;
1949 			if (mp->b_datap->db_type == M_IOCACK) {
1950 				lqs->lqs_polledio = NULL;
1951 				error = 0;
1952 			} else {
1953 				devt =
1954 				    lqs->lqs_queue->q_stream->sd_vnode->v_rdev;
1955 
1956 				if (ddi_dev_pathname(devt, S_IFCHR, path) ==
1957 				    DDI_SUCCESS) {
1958 					cmn_err(CE_WARN, "conskbd: keyboard is"
1959 					    " not available: %s", path);
1960 				}
1961 			}
1962 
1963 			mp->b_next = NULL;
1964 			mp->b_prev = NULL;
1965 			freemsg(mp);
1966 			mp = msg->kpm_resp_list;
1967 		}
1968 		break;
1969 
1970 	case KIOCCMD:
1971 	case KIOCMKTONE:
1972 		for (mp = msg->kpm_resp_list; mp; ) {
1973 			msg->kpm_resp_list = mp->b_next;
1974 
1975 			if (mp->b_datap->db_type == M_IOCACK)
1976 				error = 0;
1977 			mp->b_next = NULL;
1978 			mp->b_prev = NULL;
1979 			freemsg(mp);
1980 			mp = msg->kpm_resp_list;
1981 		}
1982 		break;
1983 
1984 	default:  /* it is impossible to reach here */
1985 		cmn_err(CE_WARN, "conskbd: unexpected ioctl reply");
1986 	}
1987 
1988 	mp = msg->kpm_req_msg;
1989 	if (error == 0) {
1990 		mp->b_datap->db_type = M_IOCACK;
1991 	} else {
1992 		mp->b_datap->db_type = M_IOCNAK;
1993 	}
1994 	iocp = (struct iocblk *)mp->b_rptr;
1995 	iocp->ioc_error = error;
1996 	qreply(msg->kpm_upper_queue, mp);
1997 	mutex_destroy(&msg->kpm_lock);
1998 	kmem_free(msg, sizeof (*msg));
1999 
2000 }	/* conskbd_mux_upstream_msg() */
2001 
2002 static void
2003 conskbd_link_lowque_legacy(queue_t *lowque, mblk_t *mp)
2004 {
2005 	conskbd_lower_queue_t *lqs;
2006 
2007 	freemsg(mp);
2008 
2009 	/*
2010 	 * Bypass the virutal keyboard for old hardware,
2011 	 * Now, only current legacy keyboard can be linked
2012 	 * under conskbd
2013 	 */
2014 	conskbd.conskbd_bypassed = B_TRUE;
2015 
2016 	/*
2017 	 * Link the lower queue under conskbd
2018 	 */
2019 	lqs = (conskbd_lower_queue_t *)lowque->q_ptr;
2020 	lqs->lqs_state = LQS_INITIALIZED_LEGACY;
2021 	lqs->lqs_next = conskbd.conskbd_lqueue_list;
2022 	conskbd.conskbd_lqueue_list = lqs;
2023 	conskbd.conskbd_lqueue_nums++;
2024 
2025 	mioc2ack(lqs->lqs_pending_plink, NULL, 0, 0);
2026 	qreply(lqs->lqs_pending_queue, lqs->lqs_pending_plink);
2027 
2028 }	/* conskbd_link_lowque_legacy() */
2029 
2030 static void
2031 conskbd_link_lowque_virt(queue_t *lowque, mblk_t *mp)
2032 {
2033 	int		index;
2034 	conskbd_lower_queue_t *lqs;
2035 
2036 	freemsg(mp);
2037 
2038 	lqs = (conskbd_lower_queue_t *)lowque->q_ptr;
2039 
2040 	ASSERT(lqs->lqs_queue == lowque);
2041 	ASSERT(lqs->lqs_pending_plink != NULL);
2042 
2043 	/*
2044 	 * Now, link the lower queue under conskbd
2045 	 */
2046 	for (index = 0; index < KBTRANS_KEYNUMS_MAX; index ++) {
2047 		lqs->lqs_key_state[index] = KEY_RELEASED;
2048 	}
2049 	lqs->lqs_next = conskbd.conskbd_lqueue_list;
2050 	lqs->lqs_state = LQS_INITIALIZED;
2051 	conskbd.conskbd_lqueue_nums++;
2052 	conskbd.conskbd_lqueue_list = lqs;
2053 	mioc2ack(lqs->lqs_pending_plink, NULL, 0, 0);
2054 	qreply(lqs->lqs_pending_queue, lqs->lqs_pending_plink);
2055 
2056 }	/* conskbd_link_lowque_virt() */
2057 
2058 /*ARGSUSED*/
2059 static void
2060 conskbd_legacy_upstream_msg(conskbd_lower_queue_t *lqs, mblk_t *mp)
2061 {
2062 	struct iocblk	*iocp;
2063 
2064 	ASSERT(lqs && lqs->lqs_state == LQS_INITIALIZED_LEGACY);
2065 
2066 	/*
2067 	 * We assume that all of the ioctls are headed to the
2068 	 * conskbd_regqueue if it is open.  We are intercepting a few ioctls
2069 	 * that we know belong to conskbd_consqueue, and sending them there.
2070 	 * Any other, new ioctls that have to be routed to conskbd_consqueue
2071 	 * should be added to this list.
2072 	 */
2073 	iocp = (struct iocblk *)mp->b_rptr;
2074 
2075 	if ((iocp->ioc_cmd == CONSOPENPOLLEDIO) ||
2076 	    (iocp->ioc_cmd == CONSCLOSEPOLLEDIO)) {
2077 
2078 		DPRINTF(PRINT_L1, PRINT_MASK_ALL,
2079 		    ("conskbd_legacy_upstream_msg: "
2080 		    "CONSOPEN/CLOSEPOLLEDIO ACK/NAK\n"));
2081 		putnext(conskbd_consqueue, mp);
2082 
2083 	} else if (conskbd_regqueue != NULL) {
2084 		DPRINTF(PRINT_L1, PRINT_MASK_ALL,
2085 		    ("conskbd_legacy_upstream_msg: conskbd_regqueue != NULL"));
2086 
2087 		putnext(conskbd_regqueue, mp);
2088 
2089 	} else if (conskbd_consqueue != NULL) {
2090 		DPRINTF(PRINT_L1, PRINT_MASK_ALL,
2091 		    ("conskbd_legacy_upstream_msg: conskbd_consqueue != NULL"));
2092 		putnext(conskbd_consqueue, mp);
2093 	} else {
2094 		/* if reached here, it must be a error */
2095 		cmn_err(CE_WARN,
2096 		    "kb:  no destination for IOCACK/IOCNAK!");
2097 		freemsg(mp);
2098 	}
2099 
2100 }	/* conskbd_legacy_upstream_msg() */
2101 
2102 /*
2103  * This routine is a callback routine for kbtrans module to set LED.
2104  * Kbtrans will invoke it in two cases:
2105  *
2106  * 1) application initiated request
2107  * 	A KIOCSLED ioctl is sent by an application. The ioctl will be
2108  * 	be prcoessed by queue service procedure conskbduwsrv(), which
2109  * 	in turn calls kbtrans to process the ioctl. Then kbtrans invokes
2110  * 	conskbd_streams_setled() to set LED, after that,  kbtrans will
2111  * 	return an ACK message to upper module.
2112  *
2113  * 2) Kbtrans initiated the request
2114  *	When conskbd works in TR_ASCII translation mode, if anyone of
2115  *	CapsLock, NumberLock and Compose keys is pressed, kbtrans need
2116  *	to set LED. In this case, there is no ioctl from upper module.
2117  *	There is no requirement to send response to somebody.
2118  *
2119  * In first case, kbtrans will send response to upper module; and in the
2120  * second, we don't need to send response. So conskbd_streams_setled()
2121  * has no return value.
2122  */
2123 static void
2124 conskbd_streams_setled(struct kbtrans_hardware *hw, int led_state)
2125 {
2126 	conskbd_state_t  *conskbdp = (conskbd_state_t *)hw;
2127 	conskbd_lower_queue_t *lqs;
2128 	mblk_t		*req;
2129 
2130 	ASSERT(&conskbd == conskbdp);
2131 
2132 	if (led_state == -1)
2133 		return;
2134 
2135 	conskbdp->conskbd_led_state = led_state;
2136 
2137 	/*
2138 	 * Basically, failing to set LED is not a fatal error, we just skip
2139 	 * it if this happens.
2140 	 */
2141 	for (lqs = conskbdp->conskbd_lqueue_list; lqs; lqs = lqs->lqs_next) {
2142 		req = mkiocb(KIOCSLED);
2143 
2144 		if (!req) {
2145 			continue;
2146 		}
2147 
2148 		req->b_cont = allocb(sizeof (uchar_t), BPRI_MED);
2149 		if (!req->b_cont) {
2150 			freemsg(req);
2151 			continue;
2152 		}
2153 		*(uchar_t *)req->b_cont->b_wptr = led_state;
2154 		req->b_cont->b_wptr += sizeof (uchar_t);
2155 		if (putq(lqs->lqs_queue, req) != 1)
2156 			freemsg(req);
2157 	}
2158 
2159 }	/* conskbd_streams_setled() */
2160 
2161 static void
2162 conskbd_polledio_setled(struct kbtrans_hardware *hw, int led_state)
2163 {
2164 	conskbd_state_t  *conskbdp = (conskbd_state_t *)hw;
2165 	struct cons_polledio		*cb;
2166 	conskbd_lower_queue_t	*lqs;
2167 
2168 	for (lqs = conskbdp->conskbd_lqueue_list; lqs; lqs = lqs->lqs_next) {
2169 		cb = lqs->lqs_polledio;
2170 		if ((cb != NULL) && (cb->cons_polledio_setled != NULL)) {
2171 			cb->cons_polledio_setled(cb->cons_polledio_argument,
2172 			    led_state);
2173 		}
2174 	}
2175 
2176 }	/* conskbd_polledio_setled() */
2177 
2178 static boolean_t
2179 conskbd_polled_keycheck(struct kbtrans_hardware *hw,
2180 		kbtrans_key_t *keycode, enum keystate *state)
2181 {
2182 	conskbd_state_t  *conskbdp = (conskbd_state_t *)hw;
2183 	struct cons_polledio 		*cb;
2184 	conskbd_lower_queue_t	*lqs;
2185 	boolean_t	ret = B_FALSE;
2186 
2187 	for (ret = B_FALSE, lqs = conskbdp->conskbd_lqueue_list; lqs != NULL;
2188 	    lqs = lqs->lqs_next) {
2189 		cb = lqs->lqs_polledio;
2190 		if ((cb != NULL) &&
2191 		    (cb->cons_polledio_keycheck != NULL)) {
2192 			ret = cb->cons_polledio_keycheck(
2193 			    cb->cons_polledio_argument, keycode, state);
2194 		}
2195 
2196 		/* Get a char from lower queue(hardware) ? */
2197 		if (ret == B_TRUE) {
2198 
2199 			/* A legacy keyboard ? */
2200 			if (conskbd.conskbd_bypassed == B_TRUE)
2201 				break;
2202 
2203 			/*
2204 			 * This is the PS2 scancode 0x2B -> USB(49) /
2205 			 * USB(50) keycode mapping workaround, for
2206 			 * polled mode.
2207 			 *
2208 			 * There are two possible USB keycode mappings
2209 			 * for PS2 scancode 0x2B and this workaround
2210 			 * makes sure that we use the USB keycode that
2211 			 * does not end up being mapped to a HOLE key
2212 			 * using the current keyboard translation
2213 			 * tables.
2214 			 *
2215 			 * See conskbdlrput() for a detailed
2216 			 * explanation of the problem.
2217 			 */
2218 			if (*keycode == 49 || *keycode == 50) {
2219 				if (conskbd_keyindex->k_normal[50] == HOLE)
2220 					*keycode = 49;
2221 				else
2222 					*keycode = 50;
2223 			}
2224 
2225 			break;
2226 		}
2227 	}
2228 
2229 	return (ret);
2230 
2231 }	/* conskbd_polled_keycheck() */
2232 
2233 static boolean_t
2234 conskbd_override_kbtrans(queue_t *q, mblk_t *mp)
2235 {
2236 	struct iocblk		*iocp;
2237 	int		directio;
2238 	int		error;
2239 
2240 	if (mp->b_datap->db_type != M_IOCTL)
2241 		return (B_FALSE);
2242 
2243 	iocp = (struct iocblk *)mp->b_rptr;
2244 
2245 	switch (iocp->ioc_cmd) {
2246 	case KIOCGDIRECT: {
2247 		/*
2248 		 * Don't let the kbtrans-based code see this; it will
2249 		 * respond incorrectly.
2250 		 */
2251 		register mblk_t *datap;
2252 
2253 		if ((datap = allocb((int)sizeof (int), BPRI_MED)) == NULL) {
2254 			miocnak(q, mp, 0, ENOMEM);
2255 			return (B_TRUE);
2256 		}
2257 
2258 		*(int *)datap->b_wptr = conskbd.conskbd_directio;
2259 		datap->b_wptr += sizeof (int);
2260 		if (mp->b_cont) {
2261 			freemsg(mp->b_cont);
2262 			mp->b_cont = NULL;
2263 		}
2264 		mp->b_cont = datap;
2265 		miocack(q, mp, sizeof (int), 0);
2266 		return (B_TRUE);
2267 	}
2268 
2269 	case KIOCSDIRECT:
2270 		/*
2271 		 * Peek at this, set our variables, and then let the kbtrans
2272 		 * based code see it and respond to it.
2273 		 */
2274 		error = miocpullup(mp, sizeof (int));
2275 		if (error != 0) {
2276 			return (B_FALSE);
2277 		}
2278 
2279 		directio = *(int *)mp->b_cont->b_rptr;
2280 		if (directio != 0 && directio != 1) {
2281 			miocnak(q, mp, 0, EINVAL);
2282 			return (B_TRUE);
2283 		}
2284 		conskbd.conskbd_directio = directio;
2285 
2286 		if (conskbd.conskbd_directio) {
2287 			kbtrans_streams_set_queue(
2288 			    conskbd.conskbd_kbtrans, conskbd_regqueue);
2289 		} else {
2290 			kbtrans_streams_set_queue(
2291 			    conskbd.conskbd_kbtrans, conskbd_consqueue);
2292 		}
2293 
2294 		/*
2295 		 * Let the kbtrans-based code see this and respond to it.
2296 		 */
2297 		return (B_FALSE);
2298 
2299 	default:
2300 		return (B_FALSE);
2301 	}
2302 
2303 }	/* conskbd_override_kbtrans() */
2304 
2305 
2306 static void
2307 conskbd_polledio_enter(cons_polledio_arg_t arg)
2308 {
2309 	conskbd_state_t		*conskbdp;
2310 	struct cons_polledio		*cb;
2311 	conskbd_lower_queue_t	*lqs;
2312 
2313 	conskbdp = (conskbd_state_t *)arg;
2314 	for (lqs = conskbdp->conskbd_lqueue_list; lqs; lqs = lqs->lqs_next) {
2315 		cb = lqs->lqs_polledio;
2316 		if ((cb != NULL) && (cb->cons_polledio_enter != NULL)) {
2317 			cb->cons_polledio_enter(cb->cons_polledio_argument);
2318 		}
2319 	}
2320 
2321 }	/* conskbd_polledio_enter() */
2322 
2323 static void
2324 conskbd_polledio_exit(cons_polledio_arg_t arg)
2325 {
2326 	conskbd_state_t		*conskbdp;
2327 	struct cons_polledio		*cb;
2328 	conskbd_lower_queue_t	*lqs;
2329 
2330 	conskbdp = (conskbd_state_t *)arg;
2331 	for (lqs = conskbdp->conskbd_lqueue_list; lqs; lqs = lqs->lqs_next) {
2332 		cb = lqs->lqs_polledio;
2333 		if ((cb != NULL) && (cb->cons_polledio_exit != NULL)) {
2334 			cb->cons_polledio_exit(cb->cons_polledio_argument);
2335 		}
2336 	}
2337 
2338 }	/* conskbd_polledio_exit() */
2339 
2340 static int
2341 conskbd_polledio_getchar(cons_polledio_arg_t arg)
2342 {
2343 	conskbd_state_t  *conskbdp;
2344 
2345 	conskbdp = (conskbd_state_t *)arg;
2346 
2347 	return (kbtrans_getchar(conskbdp->conskbd_kbtrans));
2348 
2349 }	/* conskbd_polledio_getchar() */
2350 
2351 static int
2352 conskbd_polledio_ischar(cons_polledio_arg_t arg)
2353 {
2354 	conskbd_state_t  *conskbdp;
2355 
2356 	conskbdp = (conskbd_state_t *)arg;
2357 
2358 	return (kbtrans_ischar(conskbdp->conskbd_kbtrans));
2359 
2360 }	/* conskbd_polledio_ischar() */
2361 
2362 
2363 static void
2364 conskbd_mux_enqueue_msg(conskbd_pending_msg_t *msg)
2365 {
2366 	mutex_enter(&conskbd_msgq_lock);
2367 	msg->kpm_next = conskbd_msg_queue;
2368 	conskbd_msg_queue = msg;
2369 	mutex_exit(&conskbd_msgq_lock);
2370 
2371 }	/* conskbd_mux_enqueue_msg() */
2372 
2373 /*
2374  * the messages in conskbd_msg_queue we just enqueue
2375  */
2376 static conskbd_pending_msg_t *
2377 conskbd_mux_find_msg(mblk_t *mp)
2378 {
2379 	conskbd_pending_msg_t	*msg;
2380 	struct iocblk		*iocp;
2381 	uint_t	id;
2382 
2383 	mutex_enter(&conskbd_msgq_lock);
2384 	msg = conskbd_msg_queue;
2385 
2386 	iocp = (struct iocblk *)mp->b_rptr;
2387 	ASSERT(iocp);
2388 	id = iocp->ioc_id;
2389 	while (msg && msg->kpm_req_id != id) {
2390 		msg = msg->kpm_next;
2391 	}
2392 	mutex_exit(&conskbd_msgq_lock);
2393 
2394 	return (msg);
2395 
2396 }	/* conskbd_mux_find_msg() */
2397 
2398 
2399 static void
2400 conskbd_mux_dequeue_msg(conskbd_pending_msg_t *msg)
2401 {
2402 	conskbd_pending_msg_t *prev;
2403 	conskbd_pending_msg_t *p;
2404 
2405 	mutex_enter(&conskbd_msgq_lock);
2406 	prev = conskbd_msg_queue;
2407 
2408 	for (p = prev; p && p != msg; p = p->kpm_next)
2409 		prev = p;
2410 
2411 	ASSERT(p && p == msg);
2412 
2413 	if (prev == p) {
2414 		conskbd_msg_queue = msg->kpm_next;
2415 	} else {
2416 		prev->kpm_next = p->kpm_next;
2417 	}
2418 	p->kpm_next = NULL;
2419 	mutex_exit(&conskbd_msgq_lock);
2420 
2421 }	/* conskbd_mux_dequeue_msg() */
2422 
2423 #ifdef DEBUG
2424 /*ARGSUSED*/
2425 void
2426 conskbd_dprintf(const char *fmt, ...)
2427 {
2428 	char buf[256];
2429 	va_list ap;
2430 
2431 	va_start(ap, fmt);
2432 	(void) vsprintf(buf, fmt, ap);
2433 	va_end(ap);
2434 
2435 	cmn_err(CE_CONT, "conskbd: %s", buf);
2436 
2437 }	/* conskbd_dprintf() */
2438 #endif
2439