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