Home | History | Annotate | Line # | Download | only in kern
subr_prf.c revision 1.46
      1 /*	$NetBSD: subr_prf.c,v 1.46 1997/11/15 09:27:33 ross 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.3 (Berkeley) 1/21/94
     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 		}
    315 	}
    316 	if ((flags & TOCONS) && constty == NULL && c != '\0')
    317 		(*v_putc)(c);
    318 #ifdef DDB
    319 	if (flags & TODDB)
    320 		db_putchar(c);
    321 #endif
    322 }
    323 
    324 
    325 /*
    326  * uprintf: print to the controlling tty of the current process
    327  *
    328  * => we may block if the tty queue is full
    329  * => no message is printed if the queue doesn't clear in a reasonable
    330  *	time
    331  */
    332 
    333 void
    334 #ifdef __STDC__
    335 uprintf(const char *fmt, ...)
    336 #else
    337 uprintf(fmt, va_alist)
    338 	char *fmt;
    339 	va_dcl
    340 #endif
    341 {
    342 	register struct proc *p = curproc;
    343 	va_list ap;
    344 
    345 	if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
    346 		va_start(ap, fmt);
    347 		kprintf(fmt, TOTTY, p->p_session->s_ttyp, NULL, ap);
    348 		va_end(ap);
    349 	}
    350 }
    351 
    352 /*
    353  * tprintf functions: used to send messages to a specific process
    354  *
    355  * usage:
    356  *   get a tpr_t handle on a process "p" by using "tprintf_open(p)"
    357  *   use the handle when calling "tprintf"
    358  *   when done, do a "tprintf_close" to drop the handle
    359  */
    360 
    361 /*
    362  * tprintf_open: get a tprintf handle on a process "p"
    363  *
    364  * => returns NULL if process can't be printed to
    365  */
    366 
    367 tpr_t
    368 tprintf_open(p)
    369 	register struct proc *p;
    370 {
    371 
    372 	if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
    373 		SESSHOLD(p->p_session);
    374 		return ((tpr_t) p->p_session);
    375 	}
    376 	return ((tpr_t) NULL);
    377 }
    378 
    379 /*
    380  * tprintf_close: dispose of a tprintf handle obtained with tprintf_open
    381  */
    382 
    383 void
    384 tprintf_close(sess)
    385 	tpr_t sess;
    386 {
    387 
    388 	if (sess)
    389 		SESSRELE((struct session *) sess);
    390 }
    391 
    392 /*
    393  * tprintf: given tprintf handle to a process [obtained with tprintf_open],
    394  * send a message to the controlling tty for that process.
    395  *
    396  * => also sends message to /dev/klog
    397  */
    398 void
    399 #ifdef __STDC__
    400 tprintf(tpr_t tpr, const char *fmt, ...)
    401 #else
    402 tprintf(tpr, fmt, va_alist)
    403 	tpr_t tpr;
    404 	char *fmt;
    405 	va_dcl
    406 #endif
    407 {
    408 	register struct session *sess = (struct session *)tpr;
    409 	struct tty *tp = NULL;
    410 	int flags = TOLOG;
    411 	va_list ap;
    412 
    413 	logpri(LOG_INFO);
    414 	if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
    415 		flags |= TOTTY;
    416 		tp = sess->s_ttyp;
    417 	}
    418 	va_start(ap, fmt);
    419 	kprintf(fmt, flags, tp, NULL, ap);
    420 	va_end(ap);
    421 	logwakeup();
    422 }
    423 
    424 
    425 /*
    426  * ttyprintf: send a message to a specific tty
    427  *
    428  * => should be used only by tty driver or anything that knows the
    429  *	underlying tty will not be revoked(2)'d away.  [otherwise,
    430  *	use tprintf]
    431  */
    432 void
    433 #ifdef __STDC__
    434 ttyprintf(struct tty *tp, const char *fmt, ...)
    435 #else
    436 ttyprintf(tp, fmt, va_alist)
    437 	struct tty *tp;
    438 	char *fmt;
    439 	va_dcl
    440 #endif
    441 {
    442 	va_list ap;
    443 
    444 	va_start(ap, fmt);
    445 	kprintf(fmt, TOTTY, tp, NULL, ap);
    446 	va_end(ap);
    447 }
    448 
    449 #ifdef DDB
    450 
    451 /*
    452  * db_printf: printf for DDB (via db_putchar)
    453  */
    454 
    455 void
    456 #ifdef __STDC__
    457 db_printf(const char *fmt, ...)
    458 #else
    459 db_printf(fmt, va_alist)
    460 	char *fmt;
    461 	va_dcl
    462 #endif
    463 {
    464 	va_list ap;
    465 
    466 	va_start(ap, fmt);
    467 	kprintf(fmt, TODDB, NULL, NULL, ap);
    468 	va_end(ap);
    469 }
    470 
    471 #endif /* DDB */
    472 
    473 
    474 /*
    475  * normal kernel printf functions: printf, vprintf, sprintf
    476  */
    477 
    478 /*
    479  * printf: print a message to the console and the log
    480  */
    481 void
    482 #ifdef __STDC__
    483 printf(const char *fmt, ...)
    484 #else
    485 printf(fmt, va_alist)
    486 	char *fmt;
    487 	va_dcl
    488 #endif
    489 {
    490 	va_list ap;
    491 	int savintr;
    492 
    493 	savintr = consintr;		/* disable interrupts */
    494 	consintr = 0;
    495 	va_start(ap, fmt);
    496 	kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
    497 	va_end(ap);
    498 	if (!panicstr)
    499 		logwakeup();
    500 	consintr = savintr;		/* reenable interrupts */
    501 }
    502 
    503 /*
    504  * vprintf: print a message to the console and the log [already have
    505  *	va_alist]
    506  */
    507 
    508 void
    509 vprintf(fmt, ap)
    510 	const char *fmt;
    511 	va_list ap;
    512 {
    513 	int savintr;
    514 
    515 	savintr = consintr;		/* disable interrupts */
    516 	consintr = 0;
    517 	kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
    518 	if (!panicstr)
    519 		logwakeup();
    520 	consintr = savintr;		/* reenable interrupts */
    521 }
    522 
    523 /*
    524  * sprintf: print a message to a buffer
    525  */
    526 int
    527 #ifdef __STDC__
    528 sprintf(char *buf, const char *fmt, ...)
    529 #else
    530 sprintf(buf, fmt, va_alist)
    531         char *buf;
    532         const char *cfmt;
    533         va_dcl
    534 #endif
    535 {
    536 	int retval;
    537 	va_list ap;
    538 
    539 	va_start(ap, fmt);
    540 	retval = kprintf(fmt, TOBUFONLY, NULL, buf, ap);
    541 	va_end(ap);
    542 	*(buf + retval) = 0;	/* null terminate */
    543 	return(retval);
    544 }
    545 
    546 /*
    547  * bitmask_snprintf: print a kernel-printf "%b" message to a buffer
    548  *
    549  * => returns pointer to the buffer
    550  * => XXX: useful vs. kernel %b?
    551  */
    552 char *
    553 bitmask_snprintf(ul, p, buf, buflen)
    554 	u_long ul;
    555 	const char *p;
    556 	char *buf;
    557 	size_t buflen;
    558 {
    559 	char *bp, *q;
    560 	size_t left;
    561 	register int n;
    562 	int tmp;
    563 	char snbuf[KPRINTF_BUFSIZE];
    564 
    565 	bp = buf;
    566 	bzero(buf, buflen);
    567 
    568 	/*
    569 	 * Always leave room for the trailing NULL.
    570 	 */
    571 	left = buflen - 1;
    572 
    573 	/*
    574 	 * Print the value into the buffer.  Abort if there's not
    575 	 * enough room.
    576 	 */
    577 	if (buflen < KPRINTF_BUFSIZE)
    578 		return (buf);
    579 
    580 	if (*p == 8)
    581 		sprintf(snbuf,"%lo", ul);
    582 	else if (*p == 10)
    583 		sprintf(snbuf, "%ld", ul);
    584 	else if (*p == 16)
    585 		sprintf(snbuf, "%lx", ul);
    586 	else
    587 		return(buf);	/* punt if not oct, dec, or hex */
    588 	p++;
    589 
    590 	for (q = snbuf ; *q ; q++) {
    591 		*bp++ = *q;
    592 		left--;
    593 	}
    594 
    595 	/*
    596 	 * If the value we printed was 0, or if we don't have room for
    597 	 * "<x>", we're done.
    598 	 */
    599 	if (ul == 0 || left < 3)
    600 		return (buf);
    601 
    602 #define PUTBYTE(b, c, l)	\
    603 	*(b)++ = (c);		\
    604 	if (--(l) == 0)		\
    605 		goto out;
    606 
    607 	for (tmp = 0; (n = *p++) != 0;) {
    608 		if (ul & (1 << (n - 1))) {
    609 			PUTBYTE(bp, tmp ? ',' : '<', left);
    610 				for (; (n = *p) > ' '; ++p) {
    611 					PUTBYTE(bp, n, left);
    612 				}
    613 				tmp = 1;
    614 		} else
    615 			for (; *p > ' '; ++p)
    616 				continue;
    617 	}
    618 	if (tmp)
    619 		*bp = '>';
    620 
    621 #undef PUTBYTE
    622 
    623  out:
    624 	return (buf);
    625 }
    626 
    627 /*
    628  * kprintf: scaled down version of printf(3).
    629  *
    630  * this version based on vfprintf() from libc which was derived from
    631  * software contributed to Berkeley by Chris Torek.
    632  *
    633  * Two additional formats:
    634  *
    635  * The format %b is supported to decode error registers.
    636  * Its usage is:
    637  *
    638  *	printf("reg=%b\n", regval, "<base><arg>*");
    639  *
    640  * where <base> is the output base expressed as a control character, e.g.
    641  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
    642  * the first of which gives the bit number to be inspected (origin 1), and
    643  * the next characters (up to a control character, i.e. a character <= 32),
    644  * give the name of the register.  Thus:
    645  *
    646  *	kprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
    647  *
    648  * would produce output:
    649  *
    650  *	reg=3<BITTWO,BITONE>
    651  *
    652  * The format %: passes an additional format string and argument list
    653  * recursively.  Its usage is:
    654  *
    655  * fn(char *fmt, ...)
    656  * {
    657  *	va_list ap;
    658  *	va_start(ap, fmt);
    659  *	printf("prefix: %: suffix\n", fmt, ap);
    660  *	va_end(ap);
    661  * }
    662  *
    663  * this is the actual printf innards
    664  *
    665  * This code is large and complicated...
    666  */
    667 
    668 /*
    669  * macros for converting digits to letters and vice versa
    670  */
    671 #define	to_digit(c)	((c) - '0')
    672 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
    673 #define	to_char(n)	((n) + '0')
    674 
    675 /*
    676  * flags used during conversion.
    677  */
    678 #define	ALT		0x001		/* alternate form */
    679 #define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
    680 #define	LADJUST		0x004		/* left adjustment */
    681 #define	LONGDBL		0x008		/* long double; unimplemented */
    682 #define	LONGINT		0x010		/* long integer */
    683 #define	QUADINT		0x020		/* quad integer */
    684 #define	SHORTINT	0x040		/* short integer */
    685 #define	ZEROPAD		0x080		/* zero (as opposed to blank) pad */
    686 #define FPT		0x100		/* Floating point number */
    687 
    688 	/*
    689 	 * To extend shorts properly, we need both signed and unsigned
    690 	 * argument extraction methods.
    691 	 */
    692 #define	SARG() \
    693 	(flags&QUADINT ? va_arg(ap, quad_t) : \
    694 	    flags&LONGINT ? va_arg(ap, long) : \
    695 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
    696 	    (long)va_arg(ap, int))
    697 #define	UARG() \
    698 	(flags&QUADINT ? va_arg(ap, u_quad_t) : \
    699 	    flags&LONGINT ? va_arg(ap, u_long) : \
    700 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
    701 	    (u_long)va_arg(ap, u_int))
    702 
    703 #define KPRINTF_PUTCHAR(C) \
    704 	(oflags == TOBUFONLY) ? *sbuf++ = (C) : putchar((C), oflags, tp);
    705 
    706 int
    707 kprintf(fmt0, oflags, tp, sbuf, ap)
    708 	const char *fmt0;
    709 	int oflags;
    710 	struct tty *tp;
    711 	char *sbuf;
    712 	va_list ap;
    713 {
    714 	char *fmt;		/* format string */
    715 	int ch;			/* character from fmt */
    716 	int n;			/* handy integer (short term usage) */
    717 	char *cp;		/* handy char pointer (short term usage) */
    718 	int flags;		/* flags as above */
    719 	int ret;		/* return value accumulator */
    720 	int width;		/* width from format (%8d), or 0 */
    721 	int prec;		/* precision from format (%.3d), or -1 */
    722 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
    723 
    724 	u_quad_t _uquad;	/* integer arguments %[diouxX] */
    725 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
    726 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
    727 	int realsz;		/* field size expanded by dprec */
    728 	int size;		/* size of converted field or string */
    729 	char *xdigs;		/* digits for [xX] conversion */
    730 	char buf[KPRINTF_BUFSIZE]; /* space for %c, %[diouxX] */
    731 
    732 	cp = NULL;	/* XXX: shutup gcc */
    733 	size = 0;	/* XXX: shutup gcc */
    734 
    735 	fmt = (char *)fmt0;
    736 	ret = 0;
    737 
    738 	xdigs = NULL;		/* XXX: shut up gcc warning */
    739 
    740 	/*
    741 	 * Scan the format for conversions (`%' character).
    742 	 */
    743 	for (;;) {
    744 		while (*fmt != '%' && *fmt) {
    745 			KPRINTF_PUTCHAR(*fmt++);
    746 			ret++;
    747 		}
    748 		if (*fmt == 0)
    749 			goto done;
    750 
    751 		fmt++;		/* skip over '%' */
    752 
    753 		flags = 0;
    754 		dprec = 0;
    755 		width = 0;
    756 		prec = -1;
    757 		sign = '\0';
    758 
    759 rflag:		ch = *fmt++;
    760 reswitch:	switch (ch) {
    761 		/* XXX: non-standard '%:' format */
    762 #ifndef __powerpc__
    763 #ifndef __alpha__
    764 		case ':':
    765 			if (oflags != TOBUFONLY) {
    766 				cp = va_arg(ap, char *);
    767 				kprintf(cp, oflags, tp,
    768 					NULL, va_arg(ap, va_list));
    769 			}
    770 			continue;	/* no output */
    771 #endif
    772 #endif
    773 		/* XXX: non-standard '%b' format */
    774 		case 'b': {
    775 			char *b, *z;
    776 			int tmp;
    777 			_uquad = va_arg(ap, int);
    778 			b = va_arg(ap, char *);
    779 			if (*b == 8)
    780 				sprintf(buf, "%qo", _uquad);
    781 			else if (*b == 10)
    782 				sprintf(buf, "%qd", _uquad);
    783 			else if (*b == 16)
    784 				sprintf(buf, "%qx", _uquad);
    785 			else
    786 				break;
    787 			b++;
    788 
    789 			z = buf;
    790 			while (*z) {
    791 				KPRINTF_PUTCHAR(*z++);
    792 				ret++;
    793 			}
    794 
    795 			if (_uquad) {
    796 				tmp = 0;
    797 				while ((n = *b++) != 0) {
    798 					if (_uquad & (1 << (n - 1))) {
    799 						KPRINTF_PUTCHAR(tmp ? ',':'<');
    800 						ret++;
    801 						while ((n = *b) > ' ') {
    802 							KPRINTF_PUTCHAR(n);
    803 							ret++;
    804 							b++;
    805 						}
    806 						tmp = 1;
    807 					} else {
    808 						while(*b > ' ')
    809 							b++;
    810 					}
    811 				}
    812 				if (tmp) {
    813 					KPRINTF_PUTCHAR('>');
    814 					ret++;
    815 				}
    816 			}
    817 			continue;	/* no output */
    818 		}
    819 
    820 #ifdef DDB
    821 		/* XXX: non-standard '%r' format (print int in db_radix) */
    822 		case 'r':
    823 			if ((oflags & TODDB) == 0)
    824 				goto default_case;
    825 
    826 			if (db_radix == 16)
    827 				goto case_z;	/* signed hex */
    828 			_uquad = SARG();
    829 			if ((quad_t)_uquad < 0) {
    830 				_uquad = -_uquad;
    831 				sign = '-';
    832 			}
    833 			base = (db_radix == 8) ? OCT : DEC;
    834 			goto number;
    835 
    836 
    837 		/* XXX: non-standard '%z' format ("signed hex", a "hex %i")*/
    838 		case 'z':
    839 		case_z:
    840 			if ((oflags & TODDB) == 0)
    841 				goto default_case;
    842 
    843 			xdigs = "0123456789abcdef";
    844 			ch = 'x';	/* the 'x' in '0x' (below) */
    845 			_uquad = SARG();
    846 			base = HEX;
    847 			/* leading 0x/X only if non-zero */
    848 			if (flags & ALT && _uquad != 0)
    849 				flags |= HEXPREFIX;
    850 			if ((quad_t)_uquad < 0) {
    851 				_uquad = -_uquad;
    852 				sign = '-';
    853 			}
    854 			goto number;
    855 #endif
    856 
    857 		case ' ':
    858 			/*
    859 			 * ``If the space and + flags both appear, the space
    860 			 * flag will be ignored.''
    861 			 *	-- ANSI X3J11
    862 			 */
    863 			if (!sign)
    864 				sign = ' ';
    865 			goto rflag;
    866 		case '#':
    867 			flags |= ALT;
    868 			goto rflag;
    869 		case '*':
    870 			/*
    871 			 * ``A negative field width argument is taken as a
    872 			 * - flag followed by a positive field width.''
    873 			 *	-- ANSI X3J11
    874 			 * They don't exclude field widths read from args.
    875 			 */
    876 			if ((width = va_arg(ap, int)) >= 0)
    877 				goto rflag;
    878 			width = -width;
    879 			/* FALLTHROUGH */
    880 		case '-':
    881 			flags |= LADJUST;
    882 			goto rflag;
    883 		case '+':
    884 			sign = '+';
    885 			goto rflag;
    886 		case '.':
    887 			if ((ch = *fmt++) == '*') {
    888 				n = va_arg(ap, int);
    889 				prec = n < 0 ? -1 : n;
    890 				goto rflag;
    891 			}
    892 			n = 0;
    893 			while (is_digit(ch)) {
    894 				n = 10 * n + to_digit(ch);
    895 				ch = *fmt++;
    896 			}
    897 			prec = n < 0 ? -1 : n;
    898 			goto reswitch;
    899 		case '0':
    900 			/*
    901 			 * ``Note that 0 is taken as a flag, not as the
    902 			 * beginning of a field width.''
    903 			 *	-- ANSI X3J11
    904 			 */
    905 			flags |= ZEROPAD;
    906 			goto rflag;
    907 		case '1': case '2': case '3': case '4':
    908 		case '5': case '6': case '7': case '8': case '9':
    909 			n = 0;
    910 			do {
    911 				n = 10 * n + to_digit(ch);
    912 				ch = *fmt++;
    913 			} while (is_digit(ch));
    914 			width = n;
    915 			goto reswitch;
    916 		case 'h':
    917 			flags |= SHORTINT;
    918 			goto rflag;
    919 		case 'l':
    920 			if (*fmt == 'l') {
    921 				fmt++;
    922 				flags |= QUADINT;
    923 			} else {
    924 				flags |= LONGINT;
    925 			}
    926 			goto rflag;
    927 		case 'q':
    928 			flags |= QUADINT;
    929 			goto rflag;
    930 		case 'c':
    931 			*(cp = buf) = va_arg(ap, int);
    932 			size = 1;
    933 			sign = '\0';
    934 			break;
    935 		case 'D':
    936 			flags |= LONGINT;
    937 			/*FALLTHROUGH*/
    938 		case 'd':
    939 		case 'i':
    940 			_uquad = SARG();
    941 			if ((quad_t)_uquad < 0) {
    942 				_uquad = -_uquad;
    943 				sign = '-';
    944 			}
    945 			base = DEC;
    946 			goto number;
    947 		case 'n':
    948 #ifdef DDB
    949 		/* XXX: non-standard '%n' format */
    950 		/*
    951 		 * XXX: HACK!   DDB wants '%n' to be a '%u' printed
    952 		 * in db_radix format.   this should die since '%n'
    953 		 * is already defined in standard printf to write
    954 		 * the number of chars printed so far to the arg (which
    955 		 * should be a pointer.
    956 		 */
    957 			if (oflags & TODDB) {
    958 				if (db_radix == 16)
    959 					ch = 'x';	/* convert to %x */
    960 				else if (db_radix == 8)
    961 					ch = 'o';	/* convert to %o */
    962 				else
    963 					ch = 'u';	/* convert to %u */
    964 
    965 				/* ... and start again */
    966 				goto reswitch;
    967 			}
    968 
    969 #endif
    970 			if (flags & QUADINT)
    971 				*va_arg(ap, quad_t *) = ret;
    972 			else if (flags & LONGINT)
    973 				*va_arg(ap, long *) = ret;
    974 			else if (flags & SHORTINT)
    975 				*va_arg(ap, short *) = ret;
    976 			else
    977 				*va_arg(ap, int *) = ret;
    978 			continue;	/* no output */
    979 		case 'O':
    980 			flags |= LONGINT;
    981 			/*FALLTHROUGH*/
    982 		case 'o':
    983 			_uquad = UARG();
    984 			base = OCT;
    985 			goto nosign;
    986 		case 'p':
    987 			/*
    988 			 * ``The argument shall be a pointer to void.  The
    989 			 * value of the pointer is converted to a sequence
    990 			 * of printable characters, in an implementation-
    991 			 * defined manner.''
    992 			 *	-- ANSI X3J11
    993 			 */
    994 			/* NOSTRICT */
    995 			_uquad = (u_long)va_arg(ap, void *);
    996 			base = HEX;
    997 			xdigs = "0123456789abcdef";
    998 			flags |= HEXPREFIX;
    999 			ch = 'x';
   1000 			goto nosign;
   1001 		case 's':
   1002 			if ((cp = va_arg(ap, char *)) == NULL)
   1003 				cp = "(null)";
   1004 			if (prec >= 0) {
   1005 				/*
   1006 				 * can't use strlen; can only look for the
   1007 				 * NUL in the first `prec' characters, and
   1008 				 * strlen() will go further.
   1009 				 */
   1010 				char *p = memchr(cp, 0, prec);
   1011 
   1012 				if (p != NULL) {
   1013 					size = p - cp;
   1014 					if (size > prec)
   1015 						size = prec;
   1016 				} else
   1017 					size = prec;
   1018 			} else
   1019 				size = strlen(cp);
   1020 			sign = '\0';
   1021 			break;
   1022 		case 'U':
   1023 			flags |= LONGINT;
   1024 			/*FALLTHROUGH*/
   1025 		case 'u':
   1026 			_uquad = UARG();
   1027 			base = DEC;
   1028 			goto nosign;
   1029 		case 'X':
   1030 			xdigs = "0123456789ABCDEF";
   1031 			goto hex;
   1032 		case 'x':
   1033 			xdigs = "0123456789abcdef";
   1034 hex:			_uquad = UARG();
   1035 			base = HEX;
   1036 			/* leading 0x/X only if non-zero */
   1037 			if (flags & ALT && _uquad != 0)
   1038 				flags |= HEXPREFIX;
   1039 
   1040 			/* unsigned conversions */
   1041 nosign:			sign = '\0';
   1042 			/*
   1043 			 * ``... diouXx conversions ... if a precision is
   1044 			 * specified, the 0 flag will be ignored.''
   1045 			 *	-- ANSI X3J11
   1046 			 */
   1047 number:			if ((dprec = prec) >= 0)
   1048 				flags &= ~ZEROPAD;
   1049 
   1050 			/*
   1051 			 * ``The result of converting a zero value with an
   1052 			 * explicit precision of zero is no characters.''
   1053 			 *	-- ANSI X3J11
   1054 			 */
   1055 			cp = buf + KPRINTF_BUFSIZE;
   1056 			if (_uquad != 0 || prec != 0) {
   1057 				/*
   1058 				 * Unsigned mod is hard, and unsigned mod
   1059 				 * by a constant is easier than that by
   1060 				 * a variable; hence this switch.
   1061 				 */
   1062 				switch (base) {
   1063 				case OCT:
   1064 					do {
   1065 						*--cp = to_char(_uquad & 7);
   1066 						_uquad >>= 3;
   1067 					} while (_uquad);
   1068 					/* handle octal leading 0 */
   1069 					if (flags & ALT && *cp != '0')
   1070 						*--cp = '0';
   1071 					break;
   1072 
   1073 				case DEC:
   1074 					/* many numbers are 1 digit */
   1075 					while (_uquad >= 10) {
   1076 						*--cp = to_char(_uquad % 10);
   1077 						_uquad /= 10;
   1078 					}
   1079 					*--cp = to_char(_uquad);
   1080 					break;
   1081 
   1082 				case HEX:
   1083 					do {
   1084 						*--cp = xdigs[_uquad & 15];
   1085 						_uquad >>= 4;
   1086 					} while (_uquad);
   1087 					break;
   1088 
   1089 				default:
   1090 					cp = "bug in kprintf: bad base";
   1091 					size = strlen(cp);
   1092 					goto skipsize;
   1093 				}
   1094 			}
   1095 			size = buf + KPRINTF_BUFSIZE - cp;
   1096 		skipsize:
   1097 			break;
   1098 		default:	/* "%?" prints ?, unless ? is NUL */
   1099 #ifdef DDB
   1100 		default_case:	/* DDB */
   1101 #endif
   1102 			if (ch == '\0')
   1103 				goto done;
   1104 			/* pretend it was %c with argument ch */
   1105 			cp = buf;
   1106 			*cp = ch;
   1107 			size = 1;
   1108 			sign = '\0';
   1109 			break;
   1110 		}
   1111 
   1112 		/*
   1113 		 * All reasonable formats wind up here.  At this point, `cp'
   1114 		 * points to a string which (if not flags&LADJUST) should be
   1115 		 * padded out to `width' places.  If flags&ZEROPAD, it should
   1116 		 * first be prefixed by any sign or other prefix; otherwise,
   1117 		 * it should be blank padded before the prefix is emitted.
   1118 		 * After any left-hand padding and prefixing, emit zeroes
   1119 		 * required by a decimal [diouxX] precision, then print the
   1120 		 * string proper, then emit zeroes required by any leftover
   1121 		 * floating precision; finally, if LADJUST, pad with blanks.
   1122 		 *
   1123 		 * Compute actual size, so we know how much to pad.
   1124 		 * size excludes decimal prec; realsz includes it.
   1125 		 */
   1126 		realsz = dprec > size ? dprec : size;
   1127 		if (sign)
   1128 			realsz++;
   1129 		else if (flags & HEXPREFIX)
   1130 			realsz+= 2;
   1131 
   1132 		/* right-adjusting blank padding */
   1133 		if ((flags & (LADJUST|ZEROPAD)) == 0) {
   1134 			n = width - realsz;
   1135 			while (n-- > 0)
   1136 				KPRINTF_PUTCHAR(' ');
   1137 		}
   1138 
   1139 		/* prefix */
   1140 		if (sign) {
   1141 			KPRINTF_PUTCHAR(sign);
   1142 		} else if (flags & HEXPREFIX) {
   1143 			KPRINTF_PUTCHAR('0');
   1144 			KPRINTF_PUTCHAR(ch);
   1145 		}
   1146 
   1147 		/* right-adjusting zero padding */
   1148 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) {
   1149 			n = width - realsz;
   1150 			while (n-- > 0)
   1151 				KPRINTF_PUTCHAR('0');
   1152 		}
   1153 
   1154 		/* leading zeroes from decimal precision */
   1155 		n = dprec - size;
   1156 		while (n-- > 0)
   1157 			KPRINTF_PUTCHAR('0');
   1158 
   1159 		/* the string or number proper */
   1160 		while (size--)
   1161 			KPRINTF_PUTCHAR(*cp++);
   1162 		/* left-adjusting padding (always blank) */
   1163 		if (flags & LADJUST) {
   1164 			n = width - realsz;
   1165 			while (n-- > 0)
   1166 				KPRINTF_PUTCHAR(' ');
   1167 		}
   1168 
   1169 		/* finally, adjust ret */
   1170 		ret += width > realsz ? width : realsz;
   1171 
   1172 	}
   1173 done:
   1174 	return (ret);
   1175 	/* NOTREACHED */
   1176 }
   1177