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