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