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