Home | History | Annotate | Line # | Download | only in kern
subr_prf.c revision 1.76.2.8
      1 /*	$NetBSD: subr_prf.c,v 1.76.2.8 2002/06/24 22:10:58 nathanw Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1986, 1988, 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * (c) UNIX System Laboratories, Inc.
      7  * All or some portions of this file are derived from material licensed
      8  * to the University of California by American Telephone and Telegraph
      9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     10  * the permission of UNIX System Laboratories, Inc.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the University of
     23  *	California, Berkeley and its contributors.
     24  * 4. Neither the name of the University nor the names of its contributors
     25  *    may be used to endorse or promote products derived from this software
     26  *    without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     38  * SUCH DAMAGE.
     39  *
     40  *	@(#)subr_prf.c	8.4 (Berkeley) 5/4/95
     41  */
     42 
     43 #include <sys/cdefs.h>
     44 __KERNEL_RCSID(0, "$NetBSD: subr_prf.c,v 1.76.2.8 2002/06/24 22:10:58 nathanw Exp $");
     45 
     46 #include "opt_ddb.h"
     47 #include "opt_ipkdb.h"
     48 #include "opt_kgdb.h"
     49 #include "opt_multiprocessor.h"
     50 
     51 #include <sys/param.h>
     52 #include <sys/stdint.h>
     53 #include <sys/systm.h>
     54 #include <sys/buf.h>
     55 #include <sys/reboot.h>
     56 #include <sys/msgbuf.h>
     57 #include <sys/lwp.h>
     58 #include <sys/proc.h>
     59 #include <sys/ioctl.h>
     60 #include <sys/vnode.h>
     61 #include <sys/file.h>
     62 #include <sys/tty.h>
     63 #include <sys/tprintf.h>
     64 #include <sys/syslog.h>
     65 #include <sys/malloc.h>
     66 #include <sys/lock.h>
     67 
     68 #include <dev/cons.h>
     69 
     70 #ifdef DDB
     71 #include <ddb/ddbvar.h>
     72 #include <machine/db_machdep.h>
     73 #include <ddb/db_command.h>
     74 #include <ddb/db_interface.h>
     75 #endif
     76 
     77 #ifdef IPKDB
     78 #include <ipkdb/ipkdb.h>
     79 #endif
     80 
     81 #if defined(MULTIPROCESSOR)
     82 struct simplelock kprintf_slock = SIMPLELOCK_INITIALIZER;
     83 
     84 /*
     85  * Use cpu_simple_lock() and cpu_simple_unlock().  These are the actual
     86  * atomic locking operations, and never attempt to print debugging
     87  * information.
     88  */
     89 #define	KPRINTF_MUTEX_ENTER(s)						\
     90 do {									\
     91 	(s) = splhigh();						\
     92 	__cpu_simple_lock(&kprintf_slock.lock_data);			\
     93 } while (0)
     94 
     95 #define	KPRINTF_MUTEX_EXIT(s)						\
     96 do {									\
     97 	__cpu_simple_unlock(&kprintf_slock.lock_data);			\
     98 	splx((s));							\
     99 } while (0)
    100 #else /* ! MULTIPROCESSOR */
    101 #define	KPRINTF_MUTEX_ENTER(s)	(s) = splhigh()
    102 #define	KPRINTF_MUTEX_EXIT(s)	splx((s))
    103 #endif /* MULTIPROCESSOR */
    104 
    105 /*
    106  * note that stdarg.h and the ansi style va_start macro is used for both
    107  * ansi and traditional c complers.
    108  * XXX: this requires that stdarg.h define: va_alist and va_dcl
    109  */
    110 #include <machine/stdarg.h>
    111 
    112 
    113 #ifdef KGDB
    114 #include <sys/kgdb.h>
    115 #include <machine/cpu.h>
    116 #endif
    117 #ifdef DDB
    118 #include <ddb/db_output.h>	/* db_printf, db_putchar prototypes */
    119 #endif
    120 
    121 
    122 /*
    123  * defines
    124  */
    125 
    126 /* flags for kprintf */
    127 #define TOCONS		0x01	/* to the console */
    128 #define TOTTY		0x02	/* to the process' tty */
    129 #define TOLOG		0x04	/* to the kernel message buffer */
    130 #define TOBUFONLY	0x08	/* to the buffer (only) [for snprintf] */
    131 #define TODDB		0x10	/* to ddb console */
    132 
    133 /* max size buffer kprintf needs to print quad_t [size in base 8 + \0] */
    134 #define KPRINTF_BUFSIZE		(sizeof(quad_t) * NBBY / 3 + 2)
    135 
    136 
    137 /*
    138  * local prototypes
    139  */
    140 
    141 static int	 kprintf __P((const char *, int, void *,
    142 				char *, va_list));
    143 static void	 putchar __P((int, int, struct tty *));
    144 static void	 klogpri __P((int));
    145 
    146 
    147 /*
    148  * globals
    149  */
    150 
    151 extern	struct tty *constty;	/* pointer to console "window" tty */
    152 extern	int log_open;	/* subr_log: is /dev/klog open? */
    153 const	char *panicstr; /* arg to first call to panic (used as a flag
    154 			   to indicate that panic has already been called). */
    155 long	panicstart, panicend;	/* position in the msgbuf of the start and
    156 				   end of the formatted panicstr. */
    157 int	doing_shutdown;	/* set to indicate shutdown in progress */
    158 
    159 /*
    160  * v_putc: routine to putc on virtual console
    161  *
    162  * the v_putc pointer can be used to redirect the console cnputc elsewhere
    163  * [e.g. to a "virtual console"].
    164  */
    165 
    166 void (*v_putc) __P((int)) = cnputc;	/* start with cnputc (normal cons) */
    167 
    168 
    169 /*
    170  * functions
    171  */
    172 
    173 /*
    174  * tablefull: warn that a system table is full
    175  */
    176 
    177 void
    178 tablefull(tab, hint)
    179 	const char *tab, *hint;
    180 {
    181 	if (hint)
    182 		log(LOG_ERR, "%s: table is full - %s\n", tab, hint);
    183 	else
    184 		log(LOG_ERR, "%s: table is full\n", tab);
    185 }
    186 
    187 /*
    188  * panic: handle an unresolvable fatal error
    189  *
    190  * prints "panic: <message>" and reboots.   if called twice (i.e. recursive
    191  * call) we avoid trying to sync the disk and just reboot (to avoid
    192  * recursive panics).
    193  */
    194 
    195 void
    196 #ifdef __STDC__
    197 panic(const char *fmt, ...)
    198 #else
    199 panic(fmt, va_alist)
    200 	char *fmt;
    201 	va_dcl
    202 #endif
    203 {
    204 	int bootopt;
    205 	va_list ap;
    206 
    207 	bootopt = RB_AUTOBOOT | RB_DUMP;
    208 	if (doing_shutdown)
    209 		bootopt |= RB_NOSYNC;
    210 	if (!panicstr)
    211 		panicstr = fmt;
    212 	doing_shutdown = 1;
    213 
    214 	if (msgbufenabled && msgbufp->msg_magic == MSG_MAGIC)
    215 		panicstart = msgbufp->msg_bufx;
    216 
    217 	va_start(ap, fmt);
    218 	printf("panic: ");
    219 	vprintf(fmt, ap);
    220 	printf("\n");
    221 	va_end(ap);
    222 
    223 	if (msgbufenabled && msgbufp->msg_magic == MSG_MAGIC)
    224 		panicend = msgbufp->msg_bufx;
    225 
    226 #ifdef IPKDB
    227 	ipkdb_panic();
    228 #endif
    229 #ifdef KGDB
    230 	kgdb_panic();
    231 #endif
    232 #ifdef KADB
    233 	if (boothowto & RB_KDB)
    234 		kdbpanic();
    235 #endif
    236 #ifdef DDB
    237 	if (db_onpanic)
    238 		Debugger();
    239 	else {
    240 		static int intrace = 0;
    241 
    242 		if (intrace==0) {
    243 			intrace=1;
    244 			printf("Begin traceback...\n");
    245 			db_stack_trace_print(
    246 			    (db_expr_t)__builtin_frame_address(0),
    247 			    TRUE, 65535, "", printf);
    248 			printf("End traceback...\n");
    249 			intrace=0;
    250 		} else
    251 			printf("Faulted in mid-traceback; aborting...");
    252 	}
    253 #endif
    254 	cpu_reboot(bootopt, NULL);
    255 }
    256 
    257 /*
    258  * kernel logging functions: log, logpri, addlog
    259  */
    260 
    261 /*
    262  * log: write to the log buffer
    263  *
    264  * => will not sleep [so safe to call from interrupt]
    265  * => will log to console if /dev/klog isn't open
    266  */
    267 
    268 void
    269 #ifdef __STDC__
    270 log(int level, const char *fmt, ...)
    271 #else
    272 log(level, fmt, va_alist)
    273 	int level;
    274 	char *fmt;
    275 	va_dcl
    276 #endif
    277 {
    278 	int s;
    279 	va_list ap;
    280 
    281 	KPRINTF_MUTEX_ENTER(s);
    282 
    283 	klogpri(level);		/* log the level first */
    284 	va_start(ap, fmt);
    285 	kprintf(fmt, TOLOG, NULL, NULL, ap);
    286 	va_end(ap);
    287 	if (!log_open) {
    288 		va_start(ap, fmt);
    289 		kprintf(fmt, TOCONS, NULL, NULL, ap);
    290 		va_end(ap);
    291 	}
    292 
    293 	KPRINTF_MUTEX_EXIT(s);
    294 
    295 	logwakeup();		/* wake up anyone waiting for log msgs */
    296 }
    297 
    298 /*
    299  * vlog: write to the log buffer [already have va_alist]
    300  */
    301 
    302 void
    303 vlog(level, fmt, ap)
    304 	int level;
    305 	const char *fmt;
    306 	va_list ap;
    307 {
    308 	int s;
    309 
    310 	KPRINTF_MUTEX_ENTER(s);
    311 
    312 	klogpri(level);		/* log the level first */
    313 	kprintf(fmt, TOLOG, NULL, NULL, ap);
    314 	if (!log_open)
    315 		kprintf(fmt, TOCONS, NULL, NULL, ap);
    316 
    317 	KPRINTF_MUTEX_EXIT(s);
    318 
    319 	logwakeup();		/* wake up anyone waiting for log msgs */
    320 }
    321 
    322 /*
    323  * logpri: log the priority level to the klog
    324  */
    325 
    326 void
    327 logpri(level)
    328 	int level;
    329 {
    330 	int s;
    331 
    332 	KPRINTF_MUTEX_ENTER(s);
    333 	klogpri(level);
    334 	KPRINTF_MUTEX_EXIT(s);
    335 }
    336 
    337 /*
    338  * Note: we must be in the mutex here!
    339  */
    340 static void
    341 klogpri(level)
    342 	int level;
    343 {
    344 	char *p;
    345 	char snbuf[KPRINTF_BUFSIZE];
    346 
    347 	putchar('<', TOLOG, NULL);
    348 	snprintf(snbuf, sizeof(snbuf), "%d", level);
    349 	for (p = snbuf ; *p ; p++)
    350 		putchar(*p, TOLOG, NULL);
    351 	putchar('>', TOLOG, NULL);
    352 }
    353 
    354 /*
    355  * addlog: add info to previous log message
    356  */
    357 
    358 void
    359 #ifdef __STDC__
    360 addlog(const char *fmt, ...)
    361 #else
    362 addlog(fmt, va_alist)
    363 	char *fmt;
    364 	va_dcl
    365 #endif
    366 {
    367 	int s;
    368 	va_list ap;
    369 
    370 	KPRINTF_MUTEX_ENTER(s);
    371 
    372 	va_start(ap, fmt);
    373 	kprintf(fmt, TOLOG, NULL, NULL, ap);
    374 	va_end(ap);
    375 	if (!log_open) {
    376 		va_start(ap, fmt);
    377 		kprintf(fmt, TOCONS, NULL, NULL, ap);
    378 		va_end(ap);
    379 	}
    380 
    381 	KPRINTF_MUTEX_EXIT(s);
    382 
    383 	logwakeup();
    384 }
    385 
    386 
    387 /*
    388  * putchar: print a single character on console or user terminal.
    389  *
    390  * => if console, then the last MSGBUFS chars are saved in msgbuf
    391  *	for inspection later (e.g. dmesg/syslog)
    392  * => we must already be in the mutex!
    393  */
    394 static void
    395 putchar(c, flags, tp)
    396 	int c;
    397 	int flags;
    398 	struct tty *tp;
    399 {
    400 	struct kern_msgbuf *mbp;
    401 
    402 	if (panicstr)
    403 		constty = NULL;
    404 	if ((flags & TOCONS) && tp == NULL && constty) {
    405 		tp = constty;
    406 		flags |= TOTTY;
    407 	}
    408 	if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
    409 	    (flags & TOCONS) && tp == constty)
    410 		constty = NULL;
    411 	if ((flags & TOLOG) &&
    412 	    c != '\0' && c != '\r' && c != 0177 && msgbufenabled) {
    413 		mbp = msgbufp;
    414 		if (mbp->msg_magic != MSG_MAGIC) {
    415 			/*
    416 			 * Arguably should panic or somehow notify the
    417 			 * user...  but how?  Panic may be too drastic,
    418 			 * and would obliterate the message being kicked
    419 			 * out (maybe a panic itself), and printf
    420 			 * would invoke us recursively.  Silently punt
    421 			 * for now.  If syslog is running, it should
    422 			 * notice.
    423 			 */
    424 			msgbufenabled = 0;
    425 		} else {
    426 			mbp->msg_bufc[mbp->msg_bufx++] = c;
    427 			if (mbp->msg_bufx < 0 || mbp->msg_bufx >= mbp->msg_bufs)
    428 				mbp->msg_bufx = 0;
    429 			/* If the buffer is full, keep the most recent data. */
    430 			if (mbp->msg_bufr == mbp->msg_bufx) {
    431 				 if (++mbp->msg_bufr >= mbp->msg_bufs)
    432 					mbp->msg_bufr = 0;
    433 			}
    434 		}
    435 	}
    436 	if ((flags & TOCONS) && constty == NULL && c != '\0')
    437 		(*v_putc)(c);
    438 #ifdef DDB
    439 	if (flags & TODDB)
    440 		db_putchar(c);
    441 #endif
    442 }
    443 
    444 
    445 /*
    446  * uprintf: print to the controlling tty of the current process
    447  *
    448  * => we may block if the tty queue is full
    449  * => no message is printed if the queue doesn't clear in a reasonable
    450  *	time
    451  */
    452 
    453 void
    454 #ifdef __STDC__
    455 uprintf(const char *fmt, ...)
    456 #else
    457 uprintf(fmt, va_alist)
    458 	char *fmt;
    459 	va_dcl
    460 #endif
    461 {
    462 	struct proc *p = curproc;
    463 	va_list ap;
    464 
    465 	if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
    466 		/* No mutex needed; going to process TTY. */
    467 		va_start(ap, fmt);
    468 		kprintf(fmt, TOTTY, p->p_session->s_ttyp, NULL, ap);
    469 		va_end(ap);
    470 	}
    471 }
    472 
    473 /*
    474  * tprintf functions: used to send messages to a specific process
    475  *
    476  * usage:
    477  *   get a tpr_t handle on a process "p" by using "tprintf_open(p)"
    478  *   use the handle when calling "tprintf"
    479  *   when done, do a "tprintf_close" to drop the handle
    480  */
    481 
    482 /*
    483  * tprintf_open: get a tprintf handle on a process "p"
    484  *
    485  * => returns NULL if process can't be printed to
    486  */
    487 
    488 tpr_t
    489 tprintf_open(p)
    490 	struct proc *p;
    491 {
    492 
    493 	if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
    494 		SESSHOLD(p->p_session);
    495 		return ((tpr_t) p->p_session);
    496 	}
    497 	return ((tpr_t) NULL);
    498 }
    499 
    500 /*
    501  * tprintf_close: dispose of a tprintf handle obtained with tprintf_open
    502  */
    503 
    504 void
    505 tprintf_close(sess)
    506 	tpr_t sess;
    507 {
    508 
    509 	if (sess)
    510 		SESSRELE((struct session *) sess);
    511 }
    512 
    513 /*
    514  * tprintf: given tprintf handle to a process [obtained with tprintf_open],
    515  * send a message to the controlling tty for that process.
    516  *
    517  * => also sends message to /dev/klog
    518  */
    519 void
    520 #ifdef __STDC__
    521 tprintf(tpr_t tpr, const char *fmt, ...)
    522 #else
    523 tprintf(tpr, fmt, va_alist)
    524 	tpr_t tpr;
    525 	char *fmt;
    526 	va_dcl
    527 #endif
    528 {
    529 	struct session *sess = (struct session *)tpr;
    530 	struct tty *tp = NULL;
    531 	int s, flags = TOLOG;
    532 	va_list ap;
    533 
    534 	if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
    535 		flags |= TOTTY;
    536 		tp = sess->s_ttyp;
    537 	}
    538 
    539 	KPRINTF_MUTEX_ENTER(s);
    540 
    541 	klogpri(LOG_INFO);
    542 	va_start(ap, fmt);
    543 	kprintf(fmt, flags, tp, NULL, ap);
    544 	va_end(ap);
    545 
    546 	KPRINTF_MUTEX_EXIT(s);
    547 
    548 	logwakeup();
    549 }
    550 
    551 
    552 /*
    553  * ttyprintf: send a message to a specific tty
    554  *
    555  * => should be used only by tty driver or anything that knows the
    556  *    underlying tty will not be revoked(2)'d away.  [otherwise,
    557  *    use tprintf]
    558  */
    559 void
    560 #ifdef __STDC__
    561 ttyprintf(struct tty *tp, const char *fmt, ...)
    562 #else
    563 ttyprintf(tp, fmt, va_alist)
    564 	struct tty *tp;
    565 	char *fmt;
    566 	va_dcl
    567 #endif
    568 {
    569 	va_list ap;
    570 
    571 	/* No mutex needed; going to process TTY. */
    572 	va_start(ap, fmt);
    573 	kprintf(fmt, TOTTY, tp, NULL, ap);
    574 	va_end(ap);
    575 }
    576 
    577 #ifdef DDB
    578 
    579 /*
    580  * db_printf: printf for DDB (via db_putchar)
    581  */
    582 
    583 void
    584 #ifdef __STDC__
    585 db_printf(const char *fmt, ...)
    586 #else
    587 db_printf(fmt, va_alist)
    588 	char *fmt;
    589 	va_dcl
    590 #endif
    591 {
    592 	va_list ap;
    593 
    594 	/* No mutex needed; DDB pauses all processors. */
    595 	va_start(ap, fmt);
    596 	kprintf(fmt, TODDB, NULL, NULL, ap);
    597 	va_end(ap);
    598 }
    599 
    600 void
    601 db_vprintf(fmt, ap)
    602 	const char *fmt;
    603 	va_list ap;
    604 {
    605 
    606 	/* No mutex needed; DDB pauses all processors. */
    607 	kprintf(fmt, TODDB, NULL, NULL, ap);
    608 }
    609 
    610 #endif /* DDB */
    611 
    612 
    613 /*
    614  * normal kernel printf functions: printf, vprintf, snprintf, vsnprintf
    615  */
    616 
    617 /*
    618  * printf: print a message to the console and the log
    619  */
    620 void
    621 #ifdef __STDC__
    622 printf(const char *fmt, ...)
    623 #else
    624 printf(fmt, va_alist)
    625 	char *fmt;
    626 	va_dcl
    627 #endif
    628 {
    629 	va_list ap;
    630 	int s;
    631 
    632 	KPRINTF_MUTEX_ENTER(s);
    633 
    634 	va_start(ap, fmt);
    635 	kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
    636 	va_end(ap);
    637 
    638 	KPRINTF_MUTEX_EXIT(s);
    639 
    640 	if (!panicstr)
    641 		logwakeup();
    642 }
    643 
    644 /*
    645  * vprintf: print a message to the console and the log [already have
    646  *	va_alist]
    647  */
    648 
    649 void
    650 vprintf(fmt, ap)
    651 	const char *fmt;
    652 	va_list ap;
    653 {
    654 	int s;
    655 
    656 	KPRINTF_MUTEX_ENTER(s);
    657 
    658 	kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
    659 
    660 	KPRINTF_MUTEX_EXIT(s);
    661 
    662 	if (!panicstr)
    663 		logwakeup();
    664 }
    665 
    666 /*
    667  * sprintf: print a message to a buffer
    668  */
    669 int
    670 #ifdef __STDC__
    671 sprintf(char *buf, const char *fmt, ...)
    672 #else
    673 sprintf(buf, fmt, va_alist)
    674         char *buf;
    675         const char *cfmt;
    676         va_dcl
    677 #endif
    678 {
    679 	int retval;
    680 	va_list ap;
    681 
    682 	va_start(ap, fmt);
    683 	retval = kprintf(fmt, TOBUFONLY, NULL, buf, ap);
    684 	va_end(ap);
    685 	*(buf + retval) = 0;	/* null terminate */
    686 	return(retval);
    687 }
    688 
    689 /*
    690  * vsprintf: print a message to a buffer [already have va_alist]
    691  */
    692 
    693 int
    694 vsprintf(buf, fmt, ap)
    695 	char *buf;
    696 	const char *fmt;
    697 	va_list ap;
    698 {
    699 	int retval;
    700 
    701 	retval = kprintf(fmt, TOBUFONLY, NULL, buf, ap);
    702 	*(buf + retval) = 0;	/* null terminate */
    703 	return (retval);
    704 }
    705 
    706 /*
    707  * snprintf: print a message to a buffer
    708  */
    709 int
    710 #ifdef __STDC__
    711 snprintf(char *buf, size_t size, const char *fmt, ...)
    712 #else
    713 snprintf(buf, size, fmt, va_alist)
    714         char *buf;
    715         size_t size;
    716         const char *cfmt;
    717         va_dcl
    718 #endif
    719 {
    720 	int retval;
    721 	va_list ap;
    722 	char *p;
    723 
    724 	if (size < 1)
    725 		return (-1);
    726 	p = buf + size - 1;
    727 	va_start(ap, fmt);
    728 	retval = kprintf(fmt, TOBUFONLY, &p, buf, ap);
    729 	va_end(ap);
    730 	*(p) = 0;	/* null terminate */
    731 	return(retval);
    732 }
    733 
    734 /*
    735  * vsnprintf: print a message to a buffer [already have va_alist]
    736  */
    737 int
    738 vsnprintf(buf, size, fmt, ap)
    739         char *buf;
    740         size_t size;
    741         const char *fmt;
    742         va_list ap;
    743 {
    744 	int retval;
    745 	char *p;
    746 
    747 	if (size < 1)
    748 		return (-1);
    749 	p = buf + size - 1;
    750 	retval = kprintf(fmt, TOBUFONLY, &p, buf, ap);
    751 	*(p) = 0;	/* null terminate */
    752 	return(retval);
    753 }
    754 
    755 /*
    756  * bitmask_snprintf: print an interpreted bitmask to a buffer
    757  *
    758  * => returns pointer to the buffer
    759  */
    760 char *
    761 bitmask_snprintf(val, p, buf, buflen)
    762 	u_quad_t val;
    763 	const char *p;
    764 	char *buf;
    765 	size_t buflen;
    766 {
    767 	char *bp, *q;
    768 	size_t left;
    769 	char *sbase, snbuf[KPRINTF_BUFSIZE];
    770 	int base, bit, ch, len, sep;
    771 	u_quad_t field;
    772 
    773 	bp = buf;
    774 	memset(buf, 0, buflen);
    775 
    776 	/*
    777 	 * Always leave room for the trailing NULL.
    778 	 */
    779 	left = buflen - 1;
    780 
    781 	/*
    782 	 * Print the value into the buffer.  Abort if there's not
    783 	 * enough room.
    784 	 */
    785 	if (buflen < KPRINTF_BUFSIZE)
    786 		return (buf);
    787 
    788 	ch = *p++;
    789 	base = ch != '\177' ? ch : *p++;
    790 	sbase = base == 8 ? "%qo" : base == 10 ? "%qd" : base == 16 ? "%qx" : 0;
    791 	if (sbase == 0)
    792 		return (buf);	/* punt if not oct, dec, or hex */
    793 
    794 	snprintf(snbuf, sizeof(snbuf), sbase, val);
    795 	for (q = snbuf ; *q ; q++) {
    796 		*bp++ = *q;
    797 		left--;
    798 	}
    799 
    800 	/*
    801 	 * If the value we printed was 0 and we're using the old-style format,
    802 	 * or if we don't have room for "<x>", we're done.
    803 	 */
    804 	if (((val == 0) && (ch != '\177')) || left < 3)
    805 		return (buf);
    806 
    807 #define PUTBYTE(b, c, l) do {	\
    808 	*(b)++ = (c);		\
    809 	if (--(l) == 0)		\
    810 		goto out;	\
    811 } while (0)
    812 #define PUTSTR(b, p, l) do {		\
    813 	int c;				\
    814 	while ((c = *(p)++) != 0) {	\
    815 		*(b)++ = c;		\
    816 		if (--(l) == 0)		\
    817 			goto out;	\
    818 	}				\
    819 } while (0)
    820 
    821 	/*
    822 	 * Chris Torek's new bitmask format is identified by a leading \177
    823 	 */
    824 	sep = '<';
    825 	if (ch != '\177') {
    826 		/* old (standard) format. */
    827 		for (;(bit = *p++) != 0;) {
    828 			if (val & (1 << (bit - 1))) {
    829 				PUTBYTE(bp, sep, left);
    830 				for (; (ch = *p) > ' '; ++p) {
    831 					PUTBYTE(bp, ch, left);
    832 				}
    833 				sep = ',';
    834 			} else
    835 				for (; *p > ' '; ++p)
    836 					continue;
    837 		}
    838 	} else {
    839 		/* new quad-capable format; also does fields. */
    840 		field = val;
    841 		while ((ch = *p++) != '\0') {
    842 			bit = *p++;	/* now 0-origin */
    843 			switch (ch) {
    844 			case 'b':
    845 				if (((u_int)(val >> bit) & 1) == 0)
    846 					goto skip;
    847 				PUTBYTE(bp, sep, left);
    848 				PUTSTR(bp, p, left);
    849 				sep = ',';
    850 				break;
    851 			case 'f':
    852 			case 'F':
    853 				len = *p++;	/* field length */
    854 				field = (val >> bit) & ((1ULL << len) - 1);
    855 				if (ch == 'F')	/* just extract */
    856 					break;
    857 				PUTBYTE(bp, sep, left);
    858 				sep = ',';
    859 				PUTSTR(bp, p, left);
    860 				PUTBYTE(bp, '=', left);
    861 				sprintf(snbuf, sbase, field);
    862 				q = snbuf; PUTSTR(bp, q, left);
    863 				break;
    864 			case '=':
    865 			case ':':
    866 				/*
    867 				 * Here "bit" is actually a value instead,
    868 				 * to be compared against the last field.
    869 				 * This only works for values in [0..255],
    870 				 * of course.
    871 				 */
    872 				if ((int)field != bit)
    873 					goto skip;
    874 				if (ch == '=')
    875 					PUTBYTE(bp, '=', left);
    876 				PUTSTR(bp, p, left);
    877 				break;
    878 			default:
    879 			skip:
    880 				while (*p++ != '\0')
    881 					continue;
    882 				break;
    883 			}
    884 		}
    885 	}
    886 	if (sep != '<')
    887 		PUTBYTE(bp, '>', left);
    888 
    889 out:
    890 	return (buf);
    891 
    892 #undef PUTBYTE
    893 #undef PUTSTR
    894 }
    895 
    896 /*
    897  * kprintf: scaled down version of printf(3).
    898  *
    899  * this version based on vfprintf() from libc which was derived from
    900  * software contributed to Berkeley by Chris Torek.
    901  *
    902  * NOTE: The kprintf mutex must be held if we're going TOBUF or TOCONS!
    903  */
    904 
    905 /*
    906  * macros for converting digits to letters and vice versa
    907  */
    908 #define	to_digit(c)	((c) - '0')
    909 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
    910 #define	to_char(n)	((n) + '0')
    911 
    912 /*
    913  * flags used during conversion.
    914  */
    915 #define	ALT		0x001		/* alternate form */
    916 #define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
    917 #define	LADJUST		0x004		/* left adjustment */
    918 #define	LONGDBL		0x008		/* long double; unimplemented */
    919 #define	LONGINT		0x010		/* long integer */
    920 #define	QUADINT		0x020		/* quad integer */
    921 #define	SHORTINT	0x040		/* short integer */
    922 #define	MAXINT		0x080		/* intmax_t */
    923 #define	PTRINT		0x100		/* intptr_t */
    924 #define	SIZEINT		0x200		/* size_t */
    925 #define	ZEROPAD		0x400		/* zero (as opposed to blank) pad */
    926 #define FPT		0x800		/* Floating point number */
    927 
    928 	/*
    929 	 * To extend shorts properly, we need both signed and unsigned
    930 	 * argument extraction methods.
    931 	 */
    932 #define	SARG() \
    933 	(flags&MAXINT ? va_arg(ap, intmax_t) : \
    934 	    flags&PTRINT ? va_arg(ap, intptr_t) : \
    935 	    flags&SIZEINT ? va_arg(ap, ssize_t) : /* XXX */ \
    936 	    flags&QUADINT ? va_arg(ap, quad_t) : \
    937 	    flags&LONGINT ? va_arg(ap, long) : \
    938 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
    939 	    (long)va_arg(ap, int))
    940 #define	UARG() \
    941 	(flags&MAXINT ? va_arg(ap, uintmax_t) : \
    942 	    flags&PTRINT ? va_arg(ap, uintptr_t) : \
    943 	    flags&SIZEINT ? va_arg(ap, size_t) : \
    944 	    flags&QUADINT ? va_arg(ap, u_quad_t) : \
    945 	    flags&LONGINT ? va_arg(ap, u_long) : \
    946 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
    947 	    (u_long)va_arg(ap, u_int))
    948 
    949 #define KPRINTF_PUTCHAR(C) {						\
    950 	if (oflags == TOBUFONLY) {					\
    951 		if ((vp != NULL) && (sbuf == tailp)) {			\
    952 			ret += 1;		/* indicate error */	\
    953 			goto overflow;					\
    954 		}							\
    955 		*sbuf++ = (C);						\
    956 	} else {							\
    957 		putchar((C), oflags, (struct tty *)vp);			\
    958 	}								\
    959 }
    960 
    961 /*
    962  * Guts of kernel printf.  Note, we already expect to be in a mutex!
    963  */
    964 static int
    965 kprintf(fmt0, oflags, vp, sbuf, ap)
    966 	const char *fmt0;
    967 	int oflags;
    968 	void *vp;
    969 	char *sbuf;
    970 	va_list ap;
    971 {
    972 	char *fmt;		/* format string */
    973 	int ch;			/* character from fmt */
    974 	int n;			/* handy integer (short term usage) */
    975 	char *cp;		/* handy char pointer (short term usage) */
    976 	int flags;		/* flags as above */
    977 	int ret;		/* return value accumulator */
    978 	int width;		/* width from format (%8d), or 0 */
    979 	int prec;		/* precision from format (%.3d), or -1 */
    980 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
    981 
    982 	u_quad_t _uquad;	/* integer arguments %[diouxX] */
    983 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
    984 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
    985 	int realsz;		/* field size expanded by dprec */
    986 	int size;		/* size of converted field or string */
    987 	char *xdigs;		/* digits for [xX] conversion */
    988 	char buf[KPRINTF_BUFSIZE]; /* space for %c, %[diouxX] */
    989 	char *tailp;		/* tail pointer for snprintf */
    990 
    991 	tailp = NULL;	/* XXX: shutup gcc */
    992 	if (oflags == TOBUFONLY && (vp != NULL))
    993 		tailp = *(char **)vp;
    994 
    995 	cp = NULL;	/* XXX: shutup gcc */
    996 	size = 0;	/* XXX: shutup gcc */
    997 
    998 	fmt = (char *)fmt0;
    999 	ret = 0;
   1000 
   1001 	xdigs = NULL;		/* XXX: shut up gcc warning */
   1002 
   1003 	/*
   1004 	 * Scan the format for conversions (`%' character).
   1005 	 */
   1006 	for (;;) {
   1007 		while (*fmt != '%' && *fmt) {
   1008 			ret++;
   1009 			KPRINTF_PUTCHAR(*fmt++);
   1010 		}
   1011 		if (*fmt == 0)
   1012 			goto done;
   1013 
   1014 		fmt++;		/* skip over '%' */
   1015 
   1016 		flags = 0;
   1017 		dprec = 0;
   1018 		width = 0;
   1019 		prec = -1;
   1020 		sign = '\0';
   1021 
   1022 rflag:		ch = *fmt++;
   1023 reswitch:	switch (ch) {
   1024 		case ' ':
   1025 			/*
   1026 			 * ``If the space and + flags both appear, the space
   1027 			 * flag will be ignored.''
   1028 			 *	-- ANSI X3J11
   1029 			 */
   1030 			if (!sign)
   1031 				sign = ' ';
   1032 			goto rflag;
   1033 		case '#':
   1034 			flags |= ALT;
   1035 			goto rflag;
   1036 		case '*':
   1037 			/*
   1038 			 * ``A negative field width argument is taken as a
   1039 			 * - flag followed by a positive field width.''
   1040 			 *	-- ANSI X3J11
   1041 			 * They don't exclude field widths read from args.
   1042 			 */
   1043 			if ((width = va_arg(ap, int)) >= 0)
   1044 				goto rflag;
   1045 			width = -width;
   1046 			/* FALLTHROUGH */
   1047 		case '-':
   1048 			flags |= LADJUST;
   1049 			goto rflag;
   1050 		case '+':
   1051 			sign = '+';
   1052 			goto rflag;
   1053 		case '.':
   1054 			if ((ch = *fmt++) == '*') {
   1055 				n = va_arg(ap, int);
   1056 				prec = n < 0 ? -1 : n;
   1057 				goto rflag;
   1058 			}
   1059 			n = 0;
   1060 			while (is_digit(ch)) {
   1061 				n = 10 * n + to_digit(ch);
   1062 				ch = *fmt++;
   1063 			}
   1064 			prec = n < 0 ? -1 : n;
   1065 			goto reswitch;
   1066 		case '0':
   1067 			/*
   1068 			 * ``Note that 0 is taken as a flag, not as the
   1069 			 * beginning of a field width.''
   1070 			 *	-- ANSI X3J11
   1071 			 */
   1072 			flags |= ZEROPAD;
   1073 			goto rflag;
   1074 		case '1': case '2': case '3': case '4':
   1075 		case '5': case '6': case '7': case '8': case '9':
   1076 			n = 0;
   1077 			do {
   1078 				n = 10 * n + to_digit(ch);
   1079 				ch = *fmt++;
   1080 			} while (is_digit(ch));
   1081 			width = n;
   1082 			goto reswitch;
   1083 		case 'h':
   1084 			flags |= SHORTINT;
   1085 			goto rflag;
   1086 		case 'j':
   1087 			flags |= MAXINT;
   1088 			goto rflag;
   1089 		case 'l':
   1090 			if (*fmt == 'l') {
   1091 				fmt++;
   1092 				flags |= QUADINT;
   1093 			} else {
   1094 				flags |= LONGINT;
   1095 			}
   1096 			goto rflag;
   1097 		case 'q':
   1098 			flags |= QUADINT;
   1099 			goto rflag;
   1100 		case 't':
   1101 			flags |= PTRINT;
   1102 			goto rflag;
   1103 		case 'z':
   1104 			flags |= SIZEINT;
   1105 			goto rflag;
   1106 		case 'c':
   1107 			*(cp = buf) = va_arg(ap, int);
   1108 			size = 1;
   1109 			sign = '\0';
   1110 			break;
   1111 		case 'D':
   1112 			flags |= LONGINT;
   1113 			/*FALLTHROUGH*/
   1114 		case 'd':
   1115 		case 'i':
   1116 			_uquad = SARG();
   1117 			if ((quad_t)_uquad < 0) {
   1118 				_uquad = -_uquad;
   1119 				sign = '-';
   1120 			}
   1121 			base = DEC;
   1122 			goto number;
   1123 		case 'n':
   1124 			if (flags & MAXINT)
   1125 				*va_arg(ap, intmax_t *) = ret;
   1126 			else if (flags & PTRINT)
   1127 				*va_arg(ap, intptr_t *) = ret;
   1128 			else if (flags & SIZEINT)
   1129 				*va_arg(ap, ssize_t *) = ret;
   1130 			else if (flags & QUADINT)
   1131 				*va_arg(ap, quad_t *) = ret;
   1132 			else if (flags & LONGINT)
   1133 				*va_arg(ap, long *) = ret;
   1134 			else if (flags & SHORTINT)
   1135 				*va_arg(ap, short *) = ret;
   1136 			else
   1137 				*va_arg(ap, int *) = ret;
   1138 			continue;	/* no output */
   1139 		case 'O':
   1140 			flags |= LONGINT;
   1141 			/*FALLTHROUGH*/
   1142 		case 'o':
   1143 			_uquad = UARG();
   1144 			base = OCT;
   1145 			goto nosign;
   1146 		case 'p':
   1147 			/*
   1148 			 * ``The argument shall be a pointer to void.  The
   1149 			 * value of the pointer is converted to a sequence
   1150 			 * of printable characters, in an implementation-
   1151 			 * defined manner.''
   1152 			 *	-- ANSI X3J11
   1153 			 */
   1154 			/* NOSTRICT */
   1155 			_uquad = (u_long)va_arg(ap, void *);
   1156 			base = HEX;
   1157 			xdigs = "0123456789abcdef";
   1158 			flags |= HEXPREFIX;
   1159 			ch = 'x';
   1160 			goto nosign;
   1161 		case 's':
   1162 			if ((cp = va_arg(ap, char *)) == NULL)
   1163 				cp = "(null)";
   1164 			if (prec >= 0) {
   1165 				/*
   1166 				 * can't use strlen; can only look for the
   1167 				 * NUL in the first `prec' characters, and
   1168 				 * strlen() will go further.
   1169 				 */
   1170 				char *p = memchr(cp, 0, prec);
   1171 
   1172 				if (p != NULL) {
   1173 					size = p - cp;
   1174 					if (size > prec)
   1175 						size = prec;
   1176 				} else
   1177 					size = prec;
   1178 			} else
   1179 				size = strlen(cp);
   1180 			sign = '\0';
   1181 			break;
   1182 		case 'U':
   1183 			flags |= LONGINT;
   1184 			/*FALLTHROUGH*/
   1185 		case 'u':
   1186 			_uquad = UARG();
   1187 			base = DEC;
   1188 			goto nosign;
   1189 		case 'X':
   1190 			xdigs = "0123456789ABCDEF";
   1191 			goto hex;
   1192 		case 'x':
   1193 			xdigs = "0123456789abcdef";
   1194 hex:			_uquad = UARG();
   1195 			base = HEX;
   1196 			/* leading 0x/X only if non-zero */
   1197 			if (flags & ALT && _uquad != 0)
   1198 				flags |= HEXPREFIX;
   1199 
   1200 			/* unsigned conversions */
   1201 nosign:			sign = '\0';
   1202 			/*
   1203 			 * ``... diouXx conversions ... if a precision is
   1204 			 * specified, the 0 flag will be ignored.''
   1205 			 *	-- ANSI X3J11
   1206 			 */
   1207 number:			if ((dprec = prec) >= 0)
   1208 				flags &= ~ZEROPAD;
   1209 
   1210 			/*
   1211 			 * ``The result of converting a zero value with an
   1212 			 * explicit precision of zero is no characters.''
   1213 			 *	-- ANSI X3J11
   1214 			 */
   1215 			cp = buf + KPRINTF_BUFSIZE;
   1216 			if (_uquad != 0 || prec != 0) {
   1217 				/*
   1218 				 * Unsigned mod is hard, and unsigned mod
   1219 				 * by a constant is easier than that by
   1220 				 * a variable; hence this switch.
   1221 				 */
   1222 				switch (base) {
   1223 				case OCT:
   1224 					do {
   1225 						*--cp = to_char(_uquad & 7);
   1226 						_uquad >>= 3;
   1227 					} while (_uquad);
   1228 					/* handle octal leading 0 */
   1229 					if (flags & ALT && *cp != '0')
   1230 						*--cp = '0';
   1231 					break;
   1232 
   1233 				case DEC:
   1234 					/* many numbers are 1 digit */
   1235 					while (_uquad >= 10) {
   1236 						*--cp = to_char(_uquad % 10);
   1237 						_uquad /= 10;
   1238 					}
   1239 					*--cp = to_char(_uquad);
   1240 					break;
   1241 
   1242 				case HEX:
   1243 					do {
   1244 						*--cp = xdigs[_uquad & 15];
   1245 						_uquad >>= 4;
   1246 					} while (_uquad);
   1247 					break;
   1248 
   1249 				default:
   1250 					cp = "bug in kprintf: bad base";
   1251 					size = strlen(cp);
   1252 					goto skipsize;
   1253 				}
   1254 			}
   1255 			size = buf + KPRINTF_BUFSIZE - cp;
   1256 		skipsize:
   1257 			break;
   1258 		default:	/* "%?" prints ?, unless ? is NUL */
   1259 			if (ch == '\0')
   1260 				goto done;
   1261 			/* pretend it was %c with argument ch */
   1262 			cp = buf;
   1263 			*cp = ch;
   1264 			size = 1;
   1265 			sign = '\0';
   1266 			break;
   1267 		}
   1268 
   1269 		/*
   1270 		 * All reasonable formats wind up here.  At this point, `cp'
   1271 		 * points to a string which (if not flags&LADJUST) should be
   1272 		 * padded out to `width' places.  If flags&ZEROPAD, it should
   1273 		 * first be prefixed by any sign or other prefix; otherwise,
   1274 		 * it should be blank padded before the prefix is emitted.
   1275 		 * After any left-hand padding and prefixing, emit zeroes
   1276 		 * required by a decimal [diouxX] precision, then print the
   1277 		 * string proper, then emit zeroes required by any leftover
   1278 		 * floating precision; finally, if LADJUST, pad with blanks.
   1279 		 *
   1280 		 * Compute actual size, so we know how much to pad.
   1281 		 * size excludes decimal prec; realsz includes it.
   1282 		 */
   1283 		realsz = dprec > size ? dprec : size;
   1284 		if (sign)
   1285 			realsz++;
   1286 		else if (flags & HEXPREFIX)
   1287 			realsz+= 2;
   1288 
   1289 		/* adjust ret */
   1290 		ret += width > realsz ? width : realsz;
   1291 
   1292 		/* right-adjusting blank padding */
   1293 		if ((flags & (LADJUST|ZEROPAD)) == 0) {
   1294 			n = width - realsz;
   1295 			while (n-- > 0)
   1296 				KPRINTF_PUTCHAR(' ');
   1297 		}
   1298 
   1299 		/* prefix */
   1300 		if (sign) {
   1301 			KPRINTF_PUTCHAR(sign);
   1302 		} else if (flags & HEXPREFIX) {
   1303 			KPRINTF_PUTCHAR('0');
   1304 			KPRINTF_PUTCHAR(ch);
   1305 		}
   1306 
   1307 		/* right-adjusting zero padding */
   1308 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) {
   1309 			n = width - realsz;
   1310 			while (n-- > 0)
   1311 				KPRINTF_PUTCHAR('0');
   1312 		}
   1313 
   1314 		/* leading zeroes from decimal precision */
   1315 		n = dprec - size;
   1316 		while (n-- > 0)
   1317 			KPRINTF_PUTCHAR('0');
   1318 
   1319 		/* the string or number proper */
   1320 		while (size--)
   1321 			KPRINTF_PUTCHAR(*cp++);
   1322 		/* left-adjusting padding (always blank) */
   1323 		if (flags & LADJUST) {
   1324 			n = width - realsz;
   1325 			while (n-- > 0)
   1326 				KPRINTF_PUTCHAR(' ');
   1327 		}
   1328 	}
   1329 
   1330 done:
   1331 	if ((oflags == TOBUFONLY) && (vp != NULL))
   1332 		*(char **)vp = sbuf;
   1333 overflow:
   1334 	return (ret);
   1335 	/* NOTREACHED */
   1336 }
   1337