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