Home | History | Annotate | Line # | Download | only in kern
subr_prf.c revision 1.78
      1 /*	$NetBSD: subr_prf.c,v 1.78 2001/04/30 21:29:45 kleink 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/stdint.h>
     49 #include <sys/systm.h>
     50 #include <sys/buf.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 #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;
    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	MAXINT		0x080		/* intmax_t */
    899 #define	PTRINT		0x100		/* intptr_t */
    900 #define	SIZEINT		0x200		/* size_t */
    901 #define	ZEROPAD		0x400		/* zero (as opposed to blank) pad */
    902 #define FPT		0x800		/* Floating point number */
    903 
    904 	/*
    905 	 * To extend shorts properly, we need both signed and unsigned
    906 	 * argument extraction methods.
    907 	 */
    908 #define	SARG() \
    909 	(flags&MAXINT ? va_arg(ap, intmax_t) : \
    910 	    flags&PTRINT ? va_arg(ap, intptr_t) : \
    911 	    flags&SIZEINT ? va_arg(ap, ssize_t) : /* XXX */ \
    912 	    flags&QUADINT ? va_arg(ap, quad_t) : \
    913 	    flags&LONGINT ? va_arg(ap, long) : \
    914 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
    915 	    (long)va_arg(ap, int))
    916 #define	UARG() \
    917 	(flags&MAXINT ? va_arg(ap, uintmax_t) : \
    918 	    flags&PTRINT ? va_arg(ap, uintptr_t) : \
    919 	    flags&SIZEINT ? va_arg(ap, size_t) : \
    920 	    flags&QUADINT ? va_arg(ap, u_quad_t) : \
    921 	    flags&LONGINT ? va_arg(ap, u_long) : \
    922 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
    923 	    (u_long)va_arg(ap, u_int))
    924 
    925 #define KPRINTF_PUTCHAR(C) {						\
    926 	if (oflags == TOBUFONLY) {					\
    927 		if ((vp != NULL) && (sbuf == tailp)) {			\
    928 			ret += 1;		/* indicate error */	\
    929 			goto overflow;					\
    930 		}							\
    931 		*sbuf++ = (C);						\
    932 	} else {							\
    933 		putchar((C), oflags, (struct tty *)vp);			\
    934 	}								\
    935 }
    936 
    937 /*
    938  * Guts of kernel printf.  Note, we already expect to be in a mutex!
    939  */
    940 static int
    941 kprintf(fmt0, oflags, vp, sbuf, ap)
    942 	const char *fmt0;
    943 	int oflags;
    944 	void *vp;
    945 	char *sbuf;
    946 	va_list ap;
    947 {
    948 	char *fmt;		/* format string */
    949 	int ch;			/* character from fmt */
    950 	int n;			/* handy integer (short term usage) */
    951 	char *cp;		/* handy char pointer (short term usage) */
    952 	int flags;		/* flags as above */
    953 	int ret;		/* return value accumulator */
    954 	int width;		/* width from format (%8d), or 0 */
    955 	int prec;		/* precision from format (%.3d), or -1 */
    956 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
    957 
    958 	u_quad_t _uquad;	/* integer arguments %[diouxX] */
    959 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
    960 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
    961 	int realsz;		/* field size expanded by dprec */
    962 	int size;		/* size of converted field or string */
    963 	char *xdigs;		/* digits for [xX] conversion */
    964 	char buf[KPRINTF_BUFSIZE]; /* space for %c, %[diouxX] */
    965 	char *tailp;		/* tail pointer for snprintf */
    966 
    967 	tailp = NULL;	/* XXX: shutup gcc */
    968 	if (oflags == TOBUFONLY && (vp != NULL))
    969 		tailp = *(char **)vp;
    970 
    971 	cp = NULL;	/* XXX: shutup gcc */
    972 	size = 0;	/* XXX: shutup gcc */
    973 
    974 	fmt = (char *)fmt0;
    975 	ret = 0;
    976 
    977 	xdigs = NULL;		/* XXX: shut up gcc warning */
    978 
    979 	/*
    980 	 * Scan the format for conversions (`%' character).
    981 	 */
    982 	for (;;) {
    983 		while (*fmt != '%' && *fmt) {
    984 			ret++;
    985 			KPRINTF_PUTCHAR(*fmt++);
    986 		}
    987 		if (*fmt == 0)
    988 			goto done;
    989 
    990 		fmt++;		/* skip over '%' */
    991 
    992 		flags = 0;
    993 		dprec = 0;
    994 		width = 0;
    995 		prec = -1;
    996 		sign = '\0';
    997 
    998 rflag:		ch = *fmt++;
    999 reswitch:	switch (ch) {
   1000 		case ' ':
   1001 			/*
   1002 			 * ``If the space and + flags both appear, the space
   1003 			 * flag will be ignored.''
   1004 			 *	-- ANSI X3J11
   1005 			 */
   1006 			if (!sign)
   1007 				sign = ' ';
   1008 			goto rflag;
   1009 		case '#':
   1010 			flags |= ALT;
   1011 			goto rflag;
   1012 		case '*':
   1013 			/*
   1014 			 * ``A negative field width argument is taken as a
   1015 			 * - flag followed by a positive field width.''
   1016 			 *	-- ANSI X3J11
   1017 			 * They don't exclude field widths read from args.
   1018 			 */
   1019 			if ((width = va_arg(ap, int)) >= 0)
   1020 				goto rflag;
   1021 			width = -width;
   1022 			/* FALLTHROUGH */
   1023 		case '-':
   1024 			flags |= LADJUST;
   1025 			goto rflag;
   1026 		case '+':
   1027 			sign = '+';
   1028 			goto rflag;
   1029 		case '.':
   1030 			if ((ch = *fmt++) == '*') {
   1031 				n = va_arg(ap, int);
   1032 				prec = n < 0 ? -1 : n;
   1033 				goto rflag;
   1034 			}
   1035 			n = 0;
   1036 			while (is_digit(ch)) {
   1037 				n = 10 * n + to_digit(ch);
   1038 				ch = *fmt++;
   1039 			}
   1040 			prec = n < 0 ? -1 : n;
   1041 			goto reswitch;
   1042 		case '0':
   1043 			/*
   1044 			 * ``Note that 0 is taken as a flag, not as the
   1045 			 * beginning of a field width.''
   1046 			 *	-- ANSI X3J11
   1047 			 */
   1048 			flags |= ZEROPAD;
   1049 			goto rflag;
   1050 		case '1': case '2': case '3': case '4':
   1051 		case '5': case '6': case '7': case '8': case '9':
   1052 			n = 0;
   1053 			do {
   1054 				n = 10 * n + to_digit(ch);
   1055 				ch = *fmt++;
   1056 			} while (is_digit(ch));
   1057 			width = n;
   1058 			goto reswitch;
   1059 		case 'h':
   1060 			flags |= SHORTINT;
   1061 			goto rflag;
   1062 		case 'j':
   1063 			flags |= MAXINT;
   1064 			goto rflag;
   1065 		case 'l':
   1066 			if (*fmt == 'l') {
   1067 				fmt++;
   1068 				flags |= QUADINT;
   1069 			} else {
   1070 				flags |= LONGINT;
   1071 			}
   1072 			goto rflag;
   1073 		case 'q':
   1074 			flags |= QUADINT;
   1075 			goto rflag;
   1076 		case 't':
   1077 			flags |= PTRINT;
   1078 			goto rflag;
   1079 		case 'z':
   1080 			flags |= SIZEINT;
   1081 			goto rflag;
   1082 		case 'c':
   1083 			*(cp = buf) = va_arg(ap, int);
   1084 			size = 1;
   1085 			sign = '\0';
   1086 			break;
   1087 		case 'D':
   1088 			flags |= LONGINT;
   1089 			/*FALLTHROUGH*/
   1090 		case 'd':
   1091 		case 'i':
   1092 			_uquad = SARG();
   1093 			if ((quad_t)_uquad < 0) {
   1094 				_uquad = -_uquad;
   1095 				sign = '-';
   1096 			}
   1097 			base = DEC;
   1098 			goto number;
   1099 		case 'n':
   1100 			if (flags & MAXINT)
   1101 				*va_arg(ap, intmax_t *) = ret;
   1102 			else if (flags & PTRINT)
   1103 				*va_arg(ap, intptr_t *) = ret;
   1104 			else if (flags & SIZEINT)
   1105 				*va_arg(ap, ssize_t *) = ret;
   1106 			else 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 			if (ch == '\0')
   1236 				goto done;
   1237 			/* pretend it was %c with argument ch */
   1238 			cp = buf;
   1239 			*cp = ch;
   1240 			size = 1;
   1241 			sign = '\0';
   1242 			break;
   1243 		}
   1244 
   1245 		/*
   1246 		 * All reasonable formats wind up here.  At this point, `cp'
   1247 		 * points to a string which (if not flags&LADJUST) should be
   1248 		 * padded out to `width' places.  If flags&ZEROPAD, it should
   1249 		 * first be prefixed by any sign or other prefix; otherwise,
   1250 		 * it should be blank padded before the prefix is emitted.
   1251 		 * After any left-hand padding and prefixing, emit zeroes
   1252 		 * required by a decimal [diouxX] precision, then print the
   1253 		 * string proper, then emit zeroes required by any leftover
   1254 		 * floating precision; finally, if LADJUST, pad with blanks.
   1255 		 *
   1256 		 * Compute actual size, so we know how much to pad.
   1257 		 * size excludes decimal prec; realsz includes it.
   1258 		 */
   1259 		realsz = dprec > size ? dprec : size;
   1260 		if (sign)
   1261 			realsz++;
   1262 		else if (flags & HEXPREFIX)
   1263 			realsz+= 2;
   1264 
   1265 		/* adjust ret */
   1266 		ret += width > realsz ? width : realsz;
   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 
   1306 done:
   1307 	if ((oflags == TOBUFONLY) && (vp != NULL))
   1308 		*(char **)vp = sbuf;
   1309 overflow:
   1310 	return (ret);
   1311 	/* NOTREACHED */
   1312 }
   1313