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