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