Home | History | Annotate | Line # | Download | only in kern
subr_prf.c revision 1.172
      1 /*	$NetBSD: subr_prf.c,v 1.172 2018/06/30 17:15:01 jmcneill 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. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)subr_prf.c	8.4 (Berkeley) 5/4/95
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: subr_prf.c,v 1.172 2018/06/30 17:15:01 jmcneill Exp $");
     41 
     42 #ifdef _KERNEL_OPT
     43 #include "opt_ddb.h"
     44 #include "opt_ipkdb.h"
     45 #include "opt_kgdb.h"
     46 #include "opt_dump.h"
     47 #include "opt_rnd_printf.h"
     48 #endif
     49 
     50 #include <sys/param.h>
     51 #include <sys/stdint.h>
     52 #include <sys/systm.h>
     53 #include <sys/buf.h>
     54 #include <sys/device.h>
     55 #include <sys/reboot.h>
     56 #include <sys/msgbuf.h>
     57 #include <sys/proc.h>
     58 #include <sys/ioctl.h>
     59 #include <sys/vnode.h>
     60 #include <sys/file.h>
     61 #include <sys/tty.h>
     62 #include <sys/tprintf.h>
     63 #include <sys/spldebug.h>
     64 #include <sys/syslog.h>
     65 #include <sys/kprintf.h>
     66 #include <sys/atomic.h>
     67 #include <sys/kernel.h>
     68 #include <sys/cpu.h>
     69 #include <sys/sha2.h>
     70 #include <sys/rndsource.h>
     71 #include <sys/timetc.h>
     72 
     73 #include <dev/cons.h>
     74 
     75 #include <net/if.h>
     76 
     77 #ifdef IPKDB
     78 #include <ipkdb/ipkdb.h>
     79 #endif
     80 
     81 static kmutex_t kprintf_mtx;
     82 static bool kprintf_inited = false;
     83 
     84 #ifdef KGDB
     85 #include <sys/kgdb.h>
     86 #endif
     87 
     88 #ifdef DDB
     89 #include <ddb/ddbvar.h>		/* db_panic */
     90 #include <ddb/db_output.h>	/* db_printf, db_putchar prototypes */
     91 #endif
     92 
     93 
     94 /*
     95  * defines
     96  */
     97 #define KLOG_PRI	0x80000000
     98 
     99 
    100 /*
    101  * local prototypes
    102  */
    103 
    104 static void	 putchar(int, int, struct tty *);
    105 
    106 
    107 /*
    108  * globals
    109  */
    110 
    111 extern	struct tty *constty;	/* pointer to console "window" tty */
    112 extern	int log_open;	/* subr_log: is /dev/klog open? */
    113 extern	krndsource_t	rnd_printf_source;
    114 const	char *panicstr; /* arg to first call to panic (used as a flag
    115 			   to indicate that panic has already been called). */
    116 struct cpu_info *paniccpu;	/* cpu that first paniced */
    117 long	panicstart, panicend;	/* position in the msgbuf of the start and
    118 				   end of the formatted panicstr. */
    119 int	doing_shutdown;	/* set to indicate shutdown in progress */
    120 
    121 #ifdef RND_PRINTF
    122 static bool kprintf_inited_callout = false;
    123 static SHA512_CTX kprnd_sha;
    124 static uint8_t kprnd_accum[SHA512_DIGEST_LENGTH];
    125 static int kprnd_added;
    126 
    127 static struct callout kprnd_callout;
    128 #endif
    129 
    130 #ifndef	DUMP_ON_PANIC
    131 #define	DUMP_ON_PANIC	1
    132 #endif
    133 int	dumponpanic = DUMP_ON_PANIC;
    134 
    135 /*
    136  * v_putc: routine to putc on virtual console
    137  *
    138  * the v_putc pointer can be used to redirect the console cnputc elsewhere
    139  * [e.g. to a "virtual console"].
    140  */
    141 
    142 void (*v_putc)(int) = cnputc;	/* start with cnputc (normal cons) */
    143 void (*v_flush)(void) = cnflush;	/* start with cnflush (normal cons) */
    144 
    145 const char hexdigits[] = "0123456789abcdef";
    146 const char HEXDIGITS[] = "0123456789ABCDEF";
    147 
    148 
    149 /*
    150  * functions
    151  */
    152 
    153 #ifdef RND_PRINTF
    154 static void kprintf_rnd_get(size_t bytes, void *priv)
    155 {
    156 	if (kprnd_added)  {
    157 		KASSERT(kprintf_inited);
    158 		if (mutex_tryenter(&kprintf_mtx)) {
    159 			SHA512_Final(kprnd_accum, &kprnd_sha);
    160 			rnd_add_data(&rnd_printf_source,
    161 				     kprnd_accum, sizeof(kprnd_accum), 0);
    162 			kprnd_added = 0;
    163 			/* This, we must do, since we called _Final. */
    164 			SHA512_Init(&kprnd_sha);
    165 			/* This is optional but seems useful. */
    166 			SHA512_Update(&kprnd_sha, kprnd_accum,
    167 				      sizeof(kprnd_accum));
    168 			mutex_exit(&kprintf_mtx);
    169 		}
    170 	}
    171 }
    172 
    173 static void kprintf_rnd_callout(void *arg)
    174 {
    175 	kprintf_rnd_get(0, NULL);
    176 	callout_schedule(&kprnd_callout, hz);
    177 }
    178 
    179 #endif
    180 
    181 /*
    182  * Locking is inited fairly early in MI bootstrap.  Before that
    183  * prints are done unlocked.  But that doesn't really matter,
    184  * since nothing can preempt us before interrupts are enabled.
    185  */
    186 void
    187 kprintf_init(void)
    188 {
    189 
    190 	KASSERT(!kprintf_inited && cold); /* not foolproof, but ... */
    191 #ifdef RND_PRINTF
    192 	SHA512_Init(&kprnd_sha);
    193 #endif
    194 	mutex_init(&kprintf_mtx, MUTEX_DEFAULT, IPL_HIGH);
    195 	kprintf_inited = true;
    196 }
    197 
    198 #ifdef RND_PRINTF
    199 void
    200 kprintf_init_callout(void)
    201 {
    202 	KASSERT(!kprintf_inited_callout);
    203 	callout_init(&kprnd_callout, CALLOUT_MPSAFE);
    204 	callout_setfunc(&kprnd_callout, kprintf_rnd_callout, NULL);
    205 	callout_schedule(&kprnd_callout, hz);
    206 	kprintf_inited_callout = true;
    207 }
    208 #endif
    209 
    210 void
    211 kprintf_lock(void)
    212 {
    213 
    214 	if (__predict_true(kprintf_inited))
    215 		mutex_enter(&kprintf_mtx);
    216 }
    217 
    218 void
    219 kprintf_unlock(void)
    220 {
    221 
    222 	if (__predict_true(kprintf_inited)) {
    223 		/* assert kprintf wasn't somehow inited while we were in */
    224 		KASSERT(mutex_owned(&kprintf_mtx));
    225 		mutex_exit(&kprintf_mtx);
    226 	}
    227 }
    228 
    229 /*
    230  * twiddle: spin a little propellor on the console.
    231  */
    232 
    233 void
    234 twiddle(void)
    235 {
    236 	static const char twiddle_chars[] = "|/-\\";
    237 	static int pos;
    238 
    239 	kprintf_lock();
    240 
    241 	putchar(twiddle_chars[pos++ & 3], TOCONS, NULL);
    242 	putchar('\b', TOCONS, NULL);
    243 
    244 	kprintf_unlock();
    245 }
    246 
    247 /*
    248  * panic: handle an unresolvable fatal error
    249  *
    250  * prints "panic: <message>" and reboots.   if called twice (i.e. recursive
    251  * call) we avoid trying to dump and just reboot (to avoid recursive panics).
    252  */
    253 
    254 void
    255 panic(const char *fmt, ...)
    256 {
    257 	va_list ap;
    258 
    259 	va_start(ap, fmt);
    260 	vpanic(fmt, ap);
    261 	va_end(ap);
    262 }
    263 
    264 void
    265 vpanic(const char *fmt, va_list ap)
    266 {
    267 	CPU_INFO_ITERATOR cii;
    268 	struct cpu_info *ci, *oci;
    269 	int bootopt;
    270 	static char scratchstr[384]; /* stores panic message */
    271 
    272 	spldebug_stop();
    273 
    274 	if (lwp0.l_cpu && curlwp) {
    275 		/*
    276 		 * Disable preemption.  If already panicing on another CPU, sit
    277 		 * here and spin until the system is rebooted.  Allow the CPU that
    278 		 * first paniced to panic again.
    279 		 */
    280 		kpreempt_disable();
    281 		ci = curcpu();
    282 		oci = atomic_cas_ptr((void *)&paniccpu, NULL, ci);
    283 		if (oci != NULL && oci != ci) {
    284 			/* Give interrupts a chance to try and prevent deadlock. */
    285 			for (;;) {
    286 #ifndef _RUMPKERNEL /* XXXpooka: temporary build fix, see kern/40505 */
    287 				DELAY(10);
    288 #endif /* _RUMPKERNEL */
    289 			}
    290 		}
    291 
    292 		/*
    293 		 * Convert the current thread to a bound thread and prevent all
    294 		 * CPUs from scheduling unbound jobs.  Do so without taking any
    295 		 * locks.
    296 		 */
    297 		curlwp->l_pflag |= LP_BOUND;
    298 		for (CPU_INFO_FOREACH(cii, ci)) {
    299 			ci->ci_schedstate.spc_flags |= SPCF_OFFLINE;
    300 		}
    301 	}
    302 
    303 	bootopt = RB_AUTOBOOT | RB_NOSYNC;
    304 	if (!doing_shutdown) {
    305 		if (dumponpanic)
    306 			bootopt |= RB_DUMP;
    307 	} else
    308 		printf("Skipping crash dump on recursive panic\n");
    309 
    310 	doing_shutdown = 1;
    311 
    312 	if (logenabled(msgbufp))
    313 		panicstart = msgbufp->msg_bufx;
    314 
    315 	printf("panic: ");
    316 	if (panicstr == NULL) {
    317 		/* first time in panic - store fmt first for precaution */
    318 		panicstr = fmt;
    319 
    320 		vsnprintf(scratchstr, sizeof(scratchstr), fmt, ap);
    321 		printf("%s", scratchstr);
    322 		panicstr = scratchstr;
    323 	} else {
    324 		vprintf(fmt, ap);
    325 	}
    326 	printf("\n");
    327 
    328 	if (logenabled(msgbufp))
    329 		panicend = msgbufp->msg_bufx;
    330 
    331 #ifdef IPKDB
    332 	ipkdb_panic();
    333 #endif
    334 #ifdef KGDB
    335 	kgdb_panic();
    336 #endif
    337 #ifdef KADB
    338 	if (boothowto & RB_KDB)
    339 		kdbpanic();
    340 #endif
    341 #ifdef DDB
    342 	db_panic();
    343 #endif
    344 	cpu_reboot(bootopt, NULL);
    345 }
    346 
    347 /*
    348  * kernel logging functions: log, logpri, addlog
    349  */
    350 
    351 /*
    352  * log: write to the log buffer
    353  *
    354  * => will not sleep [so safe to call from interrupt]
    355  * => will log to console if /dev/klog isn't open
    356  */
    357 
    358 void
    359 log(int level, const char *fmt, ...)
    360 {
    361 	va_list ap;
    362 
    363 	kprintf_lock();
    364 
    365 	klogpri(level);		/* log the level first */
    366 	va_start(ap, fmt);
    367 	kprintf(fmt, TOLOG, NULL, NULL, ap);
    368 	va_end(ap);
    369 	if (!log_open) {
    370 		va_start(ap, fmt);
    371 		kprintf(fmt, TOCONS, NULL, NULL, ap);
    372 		va_end(ap);
    373 	}
    374 
    375 	kprintf_unlock();
    376 
    377 	logwakeup();		/* wake up anyone waiting for log msgs */
    378 }
    379 
    380 /*
    381  * vlog: write to the log buffer [already have va_list]
    382  */
    383 
    384 void
    385 vlog(int level, const char *fmt, va_list ap)
    386 {
    387 	va_list cap;
    388 
    389 	va_copy(cap, ap);
    390 	kprintf_lock();
    391 
    392 	klogpri(level);		/* log the level first */
    393 	kprintf(fmt, TOLOG, NULL, NULL, ap);
    394 	if (!log_open)
    395 		kprintf(fmt, TOCONS, NULL, NULL, cap);
    396 
    397 	kprintf_unlock();
    398 	va_end(cap);
    399 
    400 	logwakeup();		/* wake up anyone waiting for log msgs */
    401 }
    402 
    403 /*
    404  * logpri: log the priority level to the klog
    405  */
    406 
    407 void
    408 logpri(int level)
    409 {
    410 
    411 	kprintf_lock();
    412 	klogpri(level);
    413 	kprintf_unlock();
    414 }
    415 
    416 /*
    417  * Note: we must be in the mutex here!
    418  */
    419 void
    420 klogpri(int level)
    421 {
    422 	KASSERT((level & KLOG_PRI) == 0);
    423 
    424 	putchar(level | KLOG_PRI, TOLOG, NULL);
    425 }
    426 
    427 /*
    428  * addlog: add info to previous log message
    429  */
    430 
    431 void
    432 addlog(const char *fmt, ...)
    433 {
    434 	va_list ap;
    435 
    436 	kprintf_lock();
    437 
    438 	va_start(ap, fmt);
    439 	kprintf(fmt, TOLOG, NULL, NULL, ap);
    440 	va_end(ap);
    441 	if (!log_open) {
    442 		va_start(ap, fmt);
    443 		kprintf(fmt, TOCONS, NULL, NULL, ap);
    444 		va_end(ap);
    445 	}
    446 
    447 	kprintf_unlock();
    448 
    449 	logwakeup();
    450 }
    451 
    452 static void
    453 putone(int c, int flags, struct tty *tp)
    454 {
    455 	if (panicstr)
    456 		constty = NULL;
    457 
    458 	if ((flags & TOCONS) && tp == NULL && constty) {
    459 		tp = constty;
    460 		flags |= TOTTY;
    461 	}
    462 	if ((flags & TOTTY) && tp &&
    463 	    tputchar(c, flags, tp) < 0 &&
    464 	    (flags & TOCONS) && tp == constty)
    465 		constty = NULL;
    466 	if ((flags & TOLOG) &&
    467 	    c != '\0' && c != '\r' && c != 0177)
    468 	    	logputchar(c);
    469 	if ((flags & TOCONS) && constty == NULL && c != '\0')
    470 		(*v_putc)(c);
    471 }
    472 
    473 static void
    474 putlogpri(int level)
    475 {
    476 	char *p;
    477 	char snbuf[KPRINTF_BUFSIZE];
    478 
    479 	putone('<', TOLOG, NULL);
    480 	snprintf(snbuf, sizeof(snbuf), "%d", level);
    481 	for (p = snbuf ; *p ; p++)
    482 		putone(*p, TOLOG, NULL);
    483 	putone('>', TOLOG, NULL);
    484 }
    485 
    486 #ifndef KLOG_NOTIMESTAMP
    487 static int needtstamp = 1;
    488 int log_ts_prec = 7;
    489 
    490 static void
    491 addtstamp(int flags, struct tty *tp)
    492 {
    493 	char buf[64];
    494 	struct timespec ts;
    495 	int n, prec;
    496 	long fsec;
    497 
    498 	prec = log_ts_prec;
    499 	if (prec < 0) {
    500 		prec = 0;
    501 		log_ts_prec = prec;
    502 	} else if (prec > 9) {
    503 		prec = 9;
    504 		log_ts_prec = prec;
    505 	}
    506 
    507 	if (cold)
    508 		tc_ticktock();
    509 
    510 	getnanouptime(&ts);
    511 
    512 	for (n = prec, fsec = ts.tv_nsec; n < 8; n++)
    513 		fsec /= 10;
    514 	if (n < 9)
    515 		fsec = (fsec / 10) + ((fsec % 10) >= 5);
    516 
    517 	n = snprintf(buf, sizeof(buf), "[% 4jd.%.*ld] ",
    518 	    (intmax_t)ts.tv_sec, prec, fsec);
    519 
    520 	for (int i = 0; i < n; i++)
    521 		putone(buf[i], flags, tp);
    522 }
    523 #endif
    524 
    525 /*
    526  * putchar: print a single character on console or user terminal.
    527  *
    528  * => if console, then the last MSGBUFS chars are saved in msgbuf
    529  *	for inspection later (e.g. dmesg/syslog)
    530  * => we must already be in the mutex!
    531  */
    532 static void
    533 putchar(int c, int flags, struct tty *tp)
    534 {
    535 	if (c & KLOG_PRI) {
    536 		putlogpri(c & ~KLOG_PRI);
    537 		return;
    538 	}
    539 
    540 #ifndef KLOG_NOTIMESTAMP
    541 	if (c != '\0' && c != '\n' && needtstamp) {
    542 		addtstamp(flags, tp);
    543 		needtstamp = 0;
    544 	}
    545 
    546 	if (c == '\n')
    547 		needtstamp = 1;
    548 #endif
    549 	putone(c, flags, tp);
    550 
    551 #ifdef DDB
    552 	if (flags & TODDB) {
    553 		db_putchar(c);
    554 		return;
    555 	}
    556 #endif
    557 
    558 #ifdef RND_PRINTF
    559 	if (__predict_true(kprintf_inited)) {
    560 		static uint8_t rbuf[SHA512_BLOCK_LENGTH];
    561 		static int cursor;
    562 
    563 		rbuf[cursor] = c;
    564 		if (cursor == sizeof(rbuf) - 1) {
    565 			SHA512_Update(&kprnd_sha, rbuf, sizeof(rbuf));
    566 			kprnd_added++;
    567 			cursor = 0;
    568 		} else {
    569 			cursor++;
    570 		}
    571 	}
    572 #endif
    573 }
    574 
    575 /*
    576  * tablefull: warn that a system table is full
    577  */
    578 
    579 void
    580 tablefull(const char *tab, const char *hint)
    581 {
    582 	if (hint)
    583 		log(LOG_ERR, "%s: table is full - %s\n", tab, hint);
    584 	else
    585 		log(LOG_ERR, "%s: table is full\n", tab);
    586 }
    587 
    588 
    589 /*
    590  * uprintf: print to the controlling tty of the current process
    591  *
    592  * => we may block if the tty queue is full
    593  * => no message is printed if the queue doesn't clear in a reasonable
    594  *	time
    595  */
    596 
    597 void
    598 uprintf(const char *fmt, ...)
    599 {
    600 	struct proc *p = curproc;
    601 	va_list ap;
    602 
    603 	/* mutex_enter(proc_lock); XXXSMP */
    604 
    605 	if (p->p_lflag & PL_CONTROLT && p->p_session->s_ttyvp) {
    606 		/* No mutex needed; going to process TTY. */
    607 		va_start(ap, fmt);
    608 		kprintf(fmt, TOTTY, p->p_session->s_ttyp, NULL, ap);
    609 		va_end(ap);
    610 	}
    611 
    612 	/* mutex_exit(proc_lock); XXXSMP */
    613 }
    614 
    615 void
    616 uprintf_locked(const char *fmt, ...)
    617 {
    618 	struct proc *p = curproc;
    619 	va_list ap;
    620 
    621 	if (p->p_lflag & PL_CONTROLT && p->p_session->s_ttyvp) {
    622 		/* No mutex needed; going to process TTY. */
    623 		va_start(ap, fmt);
    624 		kprintf(fmt, TOTTY, p->p_session->s_ttyp, NULL, ap);
    625 		va_end(ap);
    626 	}
    627 }
    628 
    629 /*
    630  * tprintf functions: used to send messages to a specific process
    631  *
    632  * usage:
    633  *   get a tpr_t handle on a process "p" by using "tprintf_open(p)"
    634  *   use the handle when calling "tprintf"
    635  *   when done, do a "tprintf_close" to drop the handle
    636  */
    637 
    638 /*
    639  * tprintf_open: get a tprintf handle on a process "p"
    640  *
    641  * => returns NULL if process can't be printed to
    642  */
    643 
    644 tpr_t
    645 tprintf_open(struct proc *p)
    646 {
    647 	tpr_t cookie;
    648 
    649 	cookie = NULL;
    650 
    651 	mutex_enter(proc_lock);
    652 	if (p->p_lflag & PL_CONTROLT && p->p_session->s_ttyvp) {
    653 		proc_sesshold(p->p_session);
    654 		cookie = (tpr_t)p->p_session;
    655 	}
    656 	mutex_exit(proc_lock);
    657 
    658 	return cookie;
    659 }
    660 
    661 /*
    662  * tprintf_close: dispose of a tprintf handle obtained with tprintf_open
    663  */
    664 
    665 void
    666 tprintf_close(tpr_t sess)
    667 {
    668 
    669 	if (sess) {
    670 		mutex_enter(proc_lock);
    671 		/* Releases proc_lock. */
    672 		proc_sessrele((struct session *)sess);
    673 	}
    674 }
    675 
    676 /*
    677  * tprintf: given tprintf handle to a process [obtained with tprintf_open],
    678  * send a message to the controlling tty for that process.
    679  *
    680  * => also sends message to /dev/klog
    681  */
    682 void
    683 tprintf(tpr_t tpr, const char *fmt, ...)
    684 {
    685 	struct session *sess = (struct session *)tpr;
    686 	struct tty *tp = NULL;
    687 	int flags = TOLOG;
    688 	va_list ap;
    689 
    690 	/* mutex_enter(proc_lock); XXXSMP */
    691 	if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
    692 		flags |= TOTTY;
    693 		tp = sess->s_ttyp;
    694 	}
    695 
    696 	kprintf_lock();
    697 
    698 	klogpri(LOG_INFO);
    699 	va_start(ap, fmt);
    700 	kprintf(fmt, flags, tp, NULL, ap);
    701 	va_end(ap);
    702 
    703 	kprintf_unlock();
    704 	/* mutex_exit(proc_lock);	XXXSMP */
    705 
    706 	logwakeup();
    707 }
    708 
    709 
    710 /*
    711  * ttyprintf: send a message to a specific tty
    712  *
    713  * => should be used only by tty driver or anything that knows the
    714  *    underlying tty will not be revoked(2)'d away.  [otherwise,
    715  *    use tprintf]
    716  */
    717 void
    718 ttyprintf(struct tty *tp, const char *fmt, ...)
    719 {
    720 	va_list ap;
    721 
    722 	/* No mutex needed; going to process TTY. */
    723 	va_start(ap, fmt);
    724 	kprintf(fmt, TOTTY, tp, NULL, ap);
    725 	va_end(ap);
    726 }
    727 
    728 #ifdef DDB
    729 
    730 /*
    731  * db_printf: printf for DDB (via db_putchar)
    732  */
    733 
    734 void
    735 db_printf(const char *fmt, ...)
    736 {
    737 	va_list ap;
    738 
    739 	/* No mutex needed; DDB pauses all processors. */
    740 	va_start(ap, fmt);
    741 	kprintf(fmt, TODDB, NULL, NULL, ap);
    742 	va_end(ap);
    743 
    744 	if (db_tee_msgbuf) {
    745 		va_start(ap, fmt);
    746 		kprintf(fmt, TOLOG, NULL, NULL, ap);
    747 		va_end(ap);
    748 	}
    749 }
    750 
    751 void
    752 db_vprintf(const char *fmt, va_list ap)
    753 {
    754 	va_list cap;
    755 
    756 	va_copy(cap, ap);
    757 	/* No mutex needed; DDB pauses all processors. */
    758 	kprintf(fmt, TODDB, NULL, NULL, ap);
    759 	if (db_tee_msgbuf)
    760 		kprintf(fmt, TOLOG, NULL, NULL, cap);
    761 	va_end(cap);
    762 }
    763 
    764 #endif /* DDB */
    765 
    766 static void
    767 kprintf_internal(const char *fmt, int oflags, void *vp, char *sbuf, ...)
    768 {
    769 	va_list ap;
    770 
    771 	va_start(ap, sbuf);
    772 	(void)kprintf(fmt, oflags, vp, sbuf, ap);
    773 	va_end(ap);
    774 }
    775 
    776 /*
    777  * Device autoconfiguration printf routines.  These change their
    778  * behavior based on the AB_* flags in boothowto.  If AB_SILENT
    779  * is set, messages never go to the console (but they still always
    780  * go to the log).  AB_VERBOSE overrides AB_SILENT.
    781  */
    782 
    783 /*
    784  * aprint_normal: Send to console unless AB_QUIET.  Always goes
    785  * to the log.
    786  */
    787 static void
    788 aprint_normal_internal(const char *prefix, const char *fmt, va_list ap)
    789 {
    790 	int flags = TOLOG;
    791 
    792 	if ((boothowto & (AB_SILENT|AB_QUIET)) == 0 ||
    793 	    (boothowto & AB_VERBOSE) != 0)
    794 		flags |= TOCONS;
    795 
    796 	kprintf_lock();
    797 
    798 	if (prefix)
    799 		kprintf_internal("%s: ", flags, NULL, NULL, prefix);
    800 	kprintf(fmt, flags, NULL, NULL, ap);
    801 
    802 	kprintf_unlock();
    803 
    804 	if (!panicstr)
    805 		logwakeup();
    806 }
    807 
    808 void
    809 aprint_normal(const char *fmt, ...)
    810 {
    811 	va_list ap;
    812 
    813 	va_start(ap, fmt);
    814 	aprint_normal_internal(NULL, fmt, ap);
    815 	va_end(ap);
    816 }
    817 
    818 void
    819 aprint_normal_dev(device_t dv, const char *fmt, ...)
    820 {
    821 	va_list ap;
    822 
    823 	va_start(ap, fmt);
    824 	aprint_normal_internal(device_xname(dv), fmt, ap);
    825 	va_end(ap);
    826 }
    827 
    828 void
    829 aprint_normal_ifnet(struct ifnet *ifp, const char *fmt, ...)
    830 {
    831 	va_list ap;
    832 
    833 	va_start(ap, fmt);
    834 	aprint_normal_internal(ifp->if_xname, fmt, ap);
    835 	va_end(ap);
    836 }
    837 
    838 /*
    839  * aprint_error: Send to console unless AB_QUIET.  Always goes
    840  * to the log.  Also counts the number of times called so other
    841  * parts of the kernel can report the number of errors during a
    842  * given phase of system startup.
    843  */
    844 static int aprint_error_count;
    845 
    846 int
    847 aprint_get_error_count(void)
    848 {
    849 	int count;
    850 
    851 	kprintf_lock();
    852 
    853 	count = aprint_error_count;
    854 	aprint_error_count = 0;
    855 
    856 	kprintf_unlock();
    857 
    858 	return (count);
    859 }
    860 
    861 static void
    862 aprint_error_internal(const char *prefix, const char *fmt, va_list ap)
    863 {
    864 	int flags = TOLOG;
    865 
    866 	if ((boothowto & (AB_SILENT|AB_QUIET)) == 0 ||
    867 	    (boothowto & AB_VERBOSE) != 0)
    868 		flags |= TOCONS;
    869 
    870 	kprintf_lock();
    871 
    872 	aprint_error_count++;
    873 
    874 	if (prefix)
    875 		kprintf_internal("%s: ", flags, NULL, NULL, prefix);
    876 	kprintf_internal("autoconfiguration error: ", TOLOG, NULL, NULL);
    877 	kprintf(fmt, flags, NULL, NULL, ap);
    878 
    879 	kprintf_unlock();
    880 
    881 	if (!panicstr)
    882 		logwakeup();
    883 }
    884 
    885 void
    886 aprint_error(const char *fmt, ...)
    887 {
    888 	va_list ap;
    889 
    890 	va_start(ap, fmt);
    891 	aprint_error_internal(NULL, fmt, ap);
    892 	va_end(ap);
    893 }
    894 
    895 void
    896 aprint_error_dev(device_t dv, const char *fmt, ...)
    897 {
    898 	va_list ap;
    899 
    900 	va_start(ap, fmt);
    901 	aprint_error_internal(device_xname(dv), fmt, ap);
    902 	va_end(ap);
    903 }
    904 
    905 void
    906 aprint_error_ifnet(struct ifnet *ifp, const char *fmt, ...)
    907 {
    908 	va_list ap;
    909 
    910 	va_start(ap, fmt);
    911 	aprint_error_internal(ifp->if_xname, fmt, ap);
    912 	va_end(ap);
    913 }
    914 
    915 /*
    916  * aprint_naive: Send to console only if AB_QUIET.  Never goes
    917  * to the log.
    918  */
    919 static void
    920 aprint_naive_internal(const char *prefix, const char *fmt, va_list ap)
    921 {
    922 	if ((boothowto & (AB_QUIET|AB_SILENT|AB_VERBOSE)) != AB_QUIET)
    923 		return;
    924 
    925 	kprintf_lock();
    926 
    927 	if (prefix)
    928 		kprintf_internal("%s: ", TOCONS, NULL, NULL, prefix);
    929 	kprintf(fmt, TOCONS, NULL, NULL, ap);
    930 
    931 	kprintf_unlock();
    932 }
    933 
    934 void
    935 aprint_naive(const char *fmt, ...)
    936 {
    937 	va_list ap;
    938 
    939 	va_start(ap, fmt);
    940 	aprint_naive_internal(NULL, fmt, ap);
    941 	va_end(ap);
    942 }
    943 
    944 void
    945 aprint_naive_dev(device_t dv, const char *fmt, ...)
    946 {
    947 	va_list ap;
    948 
    949 	va_start(ap, fmt);
    950 	aprint_naive_internal(device_xname(dv), fmt, ap);
    951 	va_end(ap);
    952 }
    953 
    954 void
    955 aprint_naive_ifnet(struct ifnet *ifp, const char *fmt, ...)
    956 {
    957 	va_list ap;
    958 
    959 	va_start(ap, fmt);
    960 	aprint_naive_internal(ifp->if_xname, fmt, ap);
    961 	va_end(ap);
    962 }
    963 
    964 /*
    965  * aprint_verbose: Send to console only if AB_VERBOSE.  Always
    966  * goes to the log.
    967  */
    968 static void
    969 aprint_verbose_internal(const char *prefix, const char *fmt, va_list ap)
    970 {
    971 	int flags = TOLOG;
    972 
    973 	if (boothowto & AB_VERBOSE)
    974 		flags |= TOCONS;
    975 
    976 	kprintf_lock();
    977 
    978 	if (prefix)
    979 		kprintf_internal("%s: ", flags, NULL, NULL, prefix);
    980 	kprintf(fmt, flags, NULL, NULL, ap);
    981 
    982 	kprintf_unlock();
    983 
    984 	if (!panicstr)
    985 		logwakeup();
    986 }
    987 
    988 void
    989 aprint_verbose(const char *fmt, ...)
    990 {
    991 	va_list ap;
    992 
    993 	va_start(ap, fmt);
    994 	aprint_verbose_internal(NULL, fmt, ap);
    995 	va_end(ap);
    996 }
    997 
    998 void
    999 aprint_verbose_dev(device_t dv, const char *fmt, ...)
   1000 {
   1001 	va_list ap;
   1002 
   1003 	va_start(ap, fmt);
   1004 	aprint_verbose_internal(device_xname(dv), fmt, ap);
   1005 	va_end(ap);
   1006 }
   1007 
   1008 void
   1009 aprint_verbose_ifnet(struct ifnet *ifp, const char *fmt, ...)
   1010 {
   1011 	va_list ap;
   1012 
   1013 	va_start(ap, fmt);
   1014 	aprint_verbose_internal(ifp->if_xname, fmt, ap);
   1015 	va_end(ap);
   1016 }
   1017 
   1018 /*
   1019  * aprint_debug: Send to console and log only if AB_DEBUG.
   1020  */
   1021 static void
   1022 aprint_debug_internal(const char *prefix, const char *fmt, va_list ap)
   1023 {
   1024 	if ((boothowto & AB_DEBUG) == 0)
   1025 		return;
   1026 
   1027 	kprintf_lock();
   1028 
   1029 	if (prefix)
   1030 		kprintf_internal("%s: ", TOCONS | TOLOG, NULL, NULL, prefix);
   1031 	kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
   1032 
   1033 	kprintf_unlock();
   1034 }
   1035 
   1036 void
   1037 aprint_debug(const char *fmt, ...)
   1038 {
   1039 	va_list ap;
   1040 
   1041 	va_start(ap, fmt);
   1042 	aprint_debug_internal(NULL, fmt, ap);
   1043 	va_end(ap);
   1044 }
   1045 
   1046 void
   1047 aprint_debug_dev(device_t dv, const char *fmt, ...)
   1048 {
   1049 	va_list ap;
   1050 
   1051 	va_start(ap, fmt);
   1052 	aprint_debug_internal(device_xname(dv), fmt, ap);
   1053 	va_end(ap);
   1054 }
   1055 
   1056 void
   1057 aprint_debug_ifnet(struct ifnet *ifp, const char *fmt, ...)
   1058 {
   1059 	va_list ap;
   1060 
   1061 	va_start(ap, fmt);
   1062 	aprint_debug_internal(ifp->if_xname, fmt, ap);
   1063 	va_end(ap);
   1064 }
   1065 
   1066 void
   1067 printf_tolog(const char *fmt, ...)
   1068 {
   1069 	va_list ap;
   1070 
   1071 	kprintf_lock();
   1072 
   1073 	va_start(ap, fmt);
   1074 	kprintf(fmt, TOLOG, NULL, NULL, ap);
   1075 	va_end(ap);
   1076 
   1077 	kprintf_unlock();
   1078 }
   1079 
   1080 /*
   1081  * printf_nolog: Like printf(), but does not send message to the log.
   1082  */
   1083 
   1084 void
   1085 printf_nolog(const char *fmt, ...)
   1086 {
   1087 	va_list ap;
   1088 
   1089 	kprintf_lock();
   1090 
   1091 	va_start(ap, fmt);
   1092 	kprintf(fmt, TOCONS, NULL, NULL, ap);
   1093 	va_end(ap);
   1094 
   1095 	kprintf_unlock();
   1096 }
   1097 
   1098 /*
   1099  * normal kernel printf functions: printf, vprintf, snprintf, vsnprintf
   1100  */
   1101 
   1102 /*
   1103  * printf: print a message to the console and the log
   1104  */
   1105 void
   1106 printf(const char *fmt, ...)
   1107 {
   1108 	va_list ap;
   1109 
   1110 	kprintf_lock();
   1111 
   1112 	va_start(ap, fmt);
   1113 	kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
   1114 	va_end(ap);
   1115 
   1116 	kprintf_unlock();
   1117 
   1118 	if (!panicstr)
   1119 		logwakeup();
   1120 }
   1121 
   1122 /*
   1123  * vprintf: print a message to the console and the log [already have
   1124  *	va_list]
   1125  */
   1126 
   1127 void
   1128 vprintf(const char *fmt, va_list ap)
   1129 {
   1130 	kprintf_lock();
   1131 
   1132 	kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
   1133 
   1134 	kprintf_unlock();
   1135 
   1136 	if (!panicstr)
   1137 		logwakeup();
   1138 }
   1139 
   1140 /*
   1141  * snprintf: print a message to a buffer
   1142  */
   1143 int
   1144 snprintf(char *bf, size_t size, const char *fmt, ...)
   1145 {
   1146 	int retval;
   1147 	va_list ap;
   1148 
   1149 	va_start(ap, fmt);
   1150 	retval = vsnprintf(bf, size, fmt, ap);
   1151 	va_end(ap);
   1152 
   1153 	return retval;
   1154 }
   1155 
   1156 /*
   1157  * vsnprintf: print a message to a buffer [already have va_list]
   1158  */
   1159 int
   1160 vsnprintf(char *bf, size_t size, const char *fmt, va_list ap)
   1161 {
   1162 	int retval;
   1163 	char *p;
   1164 
   1165 	p = bf + size;
   1166 	retval = kprintf(fmt, TOBUFONLY, &p, bf, ap);
   1167 	if (bf && size > 0) {
   1168 		/* nul terminate */
   1169 		if (size <= (size_t)retval)
   1170 			bf[size - 1] = '\0';
   1171 		else
   1172 			bf[retval] = '\0';
   1173 	}
   1174 	return retval;
   1175 }
   1176 
   1177 /*
   1178  * kprintf: scaled down version of printf(3).
   1179  *
   1180  * this version based on vfprintf() from libc which was derived from
   1181  * software contributed to Berkeley by Chris Torek.
   1182  *
   1183  * NOTE: The kprintf mutex must be held if we're going TOBUF or TOCONS!
   1184  */
   1185 
   1186 /*
   1187  * macros for converting digits to letters and vice versa
   1188  */
   1189 #define	to_digit(c)	((c) - '0')
   1190 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
   1191 #define	to_char(n)	((n) + '0')
   1192 
   1193 /*
   1194  * flags used during conversion.
   1195  */
   1196 #define	ALT		0x001		/* alternate form */
   1197 #define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
   1198 #define	LADJUST		0x004		/* left adjustment */
   1199 #define	LONGDBL		0x008		/* long double; unimplemented */
   1200 #define	LONGINT		0x010		/* long integer */
   1201 #define	QUADINT		0x020		/* quad integer */
   1202 #define	SHORTINT	0x040		/* short integer */
   1203 #define	MAXINT		0x080		/* intmax_t */
   1204 #define	PTRINT		0x100		/* intptr_t */
   1205 #define	SIZEINT		0x200		/* size_t */
   1206 #define	ZEROPAD		0x400		/* zero (as opposed to blank) pad */
   1207 #define FPT		0x800		/* Floating point number */
   1208 
   1209 	/*
   1210 	 * To extend shorts properly, we need both signed and unsigned
   1211 	 * argument extraction methods.
   1212 	 */
   1213 #define	SARG() \
   1214 	(flags&MAXINT ? va_arg(ap, intmax_t) : \
   1215 	    flags&PTRINT ? va_arg(ap, intptr_t) : \
   1216 	    flags&SIZEINT ? va_arg(ap, ssize_t) : /* XXX */ \
   1217 	    flags&QUADINT ? va_arg(ap, quad_t) : \
   1218 	    flags&LONGINT ? va_arg(ap, long) : \
   1219 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
   1220 	    (long)va_arg(ap, int))
   1221 #define	UARG() \
   1222 	(flags&MAXINT ? va_arg(ap, uintmax_t) : \
   1223 	    flags&PTRINT ? va_arg(ap, uintptr_t) : \
   1224 	    flags&SIZEINT ? va_arg(ap, size_t) : \
   1225 	    flags&QUADINT ? va_arg(ap, u_quad_t) : \
   1226 	    flags&LONGINT ? va_arg(ap, u_long) : \
   1227 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
   1228 	    (u_long)va_arg(ap, u_int))
   1229 
   1230 #define KPRINTF_PUTCHAR(C) {						\
   1231 	if (oflags == TOBUFONLY) {					\
   1232 		if (sbuf && ((vp == NULL) || (sbuf < tailp))) 		\
   1233 			*sbuf++ = (C);					\
   1234 	} else {							\
   1235 		putchar((C), oflags, vp);				\
   1236 	}								\
   1237 }
   1238 
   1239 void
   1240 device_printf(device_t dev, const char *fmt, ...)
   1241 {
   1242 	va_list ap;
   1243 
   1244 	va_start(ap, fmt);
   1245 	printf("%s: ", device_xname(dev));
   1246 	vprintf(fmt, ap);
   1247 	va_end(ap);
   1248 	return;
   1249 }
   1250 
   1251 /*
   1252  * Guts of kernel printf.  Note, we already expect to be in a mutex!
   1253  */
   1254 int
   1255 kprintf(const char *fmt0, int oflags, void *vp, char *sbuf, va_list ap)
   1256 {
   1257 	const char *fmt;	/* format string */
   1258 	int ch;			/* character from fmt */
   1259 	int n;			/* handy integer (short term usage) */
   1260 	char *cp;		/* handy char pointer (short term usage) */
   1261 	int flags;		/* flags as above */
   1262 	int ret;		/* return value accumulator */
   1263 	int width;		/* width from format (%8d), or 0 */
   1264 	int prec;		/* precision from format (%.3d), or -1 */
   1265 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
   1266 
   1267 	u_quad_t _uquad;	/* integer arguments %[diouxX] */
   1268 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
   1269 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
   1270 	int realsz;		/* field size expanded by dprec */
   1271 	int size;		/* size of converted field or string */
   1272 	const char *xdigs;	/* digits for [xX] conversion */
   1273 	char bf[KPRINTF_BUFSIZE]; /* space for %c, %[diouxX] */
   1274 	char *tailp;		/* tail pointer for snprintf */
   1275 
   1276 	if (oflags == TOBUFONLY && (vp != NULL))
   1277 		tailp = *(char **)vp;
   1278 	else
   1279 		tailp = NULL;
   1280 
   1281 	cp = NULL;	/* XXX: shutup gcc */
   1282 	size = 0;	/* XXX: shutup gcc */
   1283 
   1284 	fmt = fmt0;
   1285 	ret = 0;
   1286 
   1287 	xdigs = NULL;		/* XXX: shut up gcc warning */
   1288 
   1289 	/*
   1290 	 * Scan the format for conversions (`%' character).
   1291 	 */
   1292 	for (;;) {
   1293 		for (; *fmt != '%' && *fmt; fmt++) {
   1294 			ret++;
   1295 			KPRINTF_PUTCHAR(*fmt);
   1296 		}
   1297 		if (*fmt == 0)
   1298 			goto done;
   1299 
   1300 		fmt++;		/* skip over '%' */
   1301 
   1302 		flags = 0;
   1303 		dprec = 0;
   1304 		width = 0;
   1305 		prec = -1;
   1306 		sign = '\0';
   1307 
   1308 rflag:		ch = *fmt++;
   1309 reswitch:	switch (ch) {
   1310 		case ' ':
   1311 			/*
   1312 			 * ``If the space and + flags both appear, the space
   1313 			 * flag will be ignored.''
   1314 			 *	-- ANSI X3J11
   1315 			 */
   1316 			if (!sign)
   1317 				sign = ' ';
   1318 			goto rflag;
   1319 		case '#':
   1320 			flags |= ALT;
   1321 			goto rflag;
   1322 		case '*':
   1323 			/*
   1324 			 * ``A negative field width argument is taken as a
   1325 			 * - flag followed by a positive field width.''
   1326 			 *	-- ANSI X3J11
   1327 			 * They don't exclude field widths read from args.
   1328 			 */
   1329 			if ((width = va_arg(ap, int)) >= 0)
   1330 				goto rflag;
   1331 			width = -width;
   1332 			/* FALLTHROUGH */
   1333 		case '-':
   1334 			flags |= LADJUST;
   1335 			goto rflag;
   1336 		case '+':
   1337 			sign = '+';
   1338 			goto rflag;
   1339 		case '.':
   1340 			if ((ch = *fmt++) == '*') {
   1341 				n = va_arg(ap, int);
   1342 				prec = n < 0 ? -1 : n;
   1343 				goto rflag;
   1344 			}
   1345 			n = 0;
   1346 			while (is_digit(ch)) {
   1347 				n = 10 * n + to_digit(ch);
   1348 				ch = *fmt++;
   1349 			}
   1350 			prec = n < 0 ? -1 : n;
   1351 			goto reswitch;
   1352 		case '0':
   1353 			/*
   1354 			 * ``Note that 0 is taken as a flag, not as the
   1355 			 * beginning of a field width.''
   1356 			 *	-- ANSI X3J11
   1357 			 */
   1358 			flags |= ZEROPAD;
   1359 			goto rflag;
   1360 		case '1': case '2': case '3': case '4':
   1361 		case '5': case '6': case '7': case '8': case '9':
   1362 			n = 0;
   1363 			do {
   1364 				n = 10 * n + to_digit(ch);
   1365 				ch = *fmt++;
   1366 			} while (is_digit(ch));
   1367 			width = n;
   1368 			goto reswitch;
   1369 		case 'h':
   1370 			flags |= SHORTINT;
   1371 			goto rflag;
   1372 		case 'j':
   1373 			flags |= MAXINT;
   1374 			goto rflag;
   1375 		case 'l':
   1376 			if (*fmt == 'l') {
   1377 				fmt++;
   1378 				flags |= QUADINT;
   1379 			} else {
   1380 				flags |= LONGINT;
   1381 			}
   1382 			goto rflag;
   1383 		case 'q':
   1384 			flags |= QUADINT;
   1385 			goto rflag;
   1386 		case 't':
   1387 			flags |= PTRINT;
   1388 			goto rflag;
   1389 		case 'z':
   1390 			flags |= SIZEINT;
   1391 			goto rflag;
   1392 		case 'c':
   1393 			*(cp = bf) = va_arg(ap, int);
   1394 			size = 1;
   1395 			sign = '\0';
   1396 			break;
   1397 		case 'D':
   1398 			flags |= LONGINT;
   1399 			/*FALLTHROUGH*/
   1400 		case 'd':
   1401 		case 'i':
   1402 			_uquad = SARG();
   1403 			if ((quad_t)_uquad < 0) {
   1404 				_uquad = -_uquad;
   1405 				sign = '-';
   1406 			}
   1407 			base = DEC;
   1408 			goto number;
   1409 		case 'n':
   1410 			if (flags & MAXINT)
   1411 				*va_arg(ap, intmax_t *) = ret;
   1412 			else if (flags & PTRINT)
   1413 				*va_arg(ap, intptr_t *) = ret;
   1414 			else if (flags & SIZEINT)
   1415 				*va_arg(ap, ssize_t *) = ret;
   1416 			else if (flags & QUADINT)
   1417 				*va_arg(ap, quad_t *) = ret;
   1418 			else if (flags & LONGINT)
   1419 				*va_arg(ap, long *) = ret;
   1420 			else if (flags & SHORTINT)
   1421 				*va_arg(ap, short *) = ret;
   1422 			else
   1423 				*va_arg(ap, int *) = ret;
   1424 			continue;	/* no output */
   1425 		case 'O':
   1426 			flags |= LONGINT;
   1427 			/*FALLTHROUGH*/
   1428 		case 'o':
   1429 			_uquad = UARG();
   1430 			base = OCT;
   1431 			goto nosign;
   1432 		case 'p':
   1433 			/*
   1434 			 * ``The argument shall be a pointer to void.  The
   1435 			 * value of the pointer is converted to a sequence
   1436 			 * of printable characters, in an implementation-
   1437 			 * defined manner.''
   1438 			 *	-- ANSI X3J11
   1439 			 */
   1440 			/* NOSTRICT */
   1441 			_uquad = (u_long)va_arg(ap, void *);
   1442 			base = HEX;
   1443 			xdigs = hexdigits;
   1444 			flags |= HEXPREFIX;
   1445 			ch = 'x';
   1446 			goto nosign;
   1447 		case 's':
   1448 			if ((cp = va_arg(ap, char *)) == NULL)
   1449 				/*XXXUNCONST*/
   1450 				cp = __UNCONST("(null)");
   1451 			if (prec >= 0) {
   1452 				/*
   1453 				 * can't use strlen; can only look for the
   1454 				 * NUL in the first `prec' characters, and
   1455 				 * strlen() will go further.
   1456 				 */
   1457 				char *p = memchr(cp, 0, prec);
   1458 
   1459 				if (p != NULL) {
   1460 					size = p - cp;
   1461 					if (size > prec)
   1462 						size = prec;
   1463 				} else
   1464 					size = prec;
   1465 			} else
   1466 				size = strlen(cp);
   1467 			sign = '\0';
   1468 			break;
   1469 		case 'U':
   1470 			flags |= LONGINT;
   1471 			/*FALLTHROUGH*/
   1472 		case 'u':
   1473 			_uquad = UARG();
   1474 			base = DEC;
   1475 			goto nosign;
   1476 		case 'X':
   1477 			xdigs = HEXDIGITS;
   1478 			goto hex;
   1479 		case 'x':
   1480 			xdigs = hexdigits;
   1481 hex:			_uquad = UARG();
   1482 			base = HEX;
   1483 			/* leading 0x/X only if non-zero */
   1484 			if (flags & ALT && _uquad != 0)
   1485 				flags |= HEXPREFIX;
   1486 
   1487 			/* unsigned conversions */
   1488 nosign:			sign = '\0';
   1489 			/*
   1490 			 * ``... diouXx conversions ... if a precision is
   1491 			 * specified, the 0 flag will be ignored.''
   1492 			 *	-- ANSI X3J11
   1493 			 */
   1494 number:			if ((dprec = prec) >= 0)
   1495 				flags &= ~ZEROPAD;
   1496 
   1497 			/*
   1498 			 * ``The result of converting a zero value with an
   1499 			 * explicit precision of zero is no characters.''
   1500 			 *	-- ANSI X3J11
   1501 			 */
   1502 			cp = bf + KPRINTF_BUFSIZE;
   1503 			if (_uquad != 0 || prec != 0) {
   1504 				/*
   1505 				 * Unsigned mod is hard, and unsigned mod
   1506 				 * by a constant is easier than that by
   1507 				 * a variable; hence this switch.
   1508 				 */
   1509 				switch (base) {
   1510 				case OCT:
   1511 					do {
   1512 						*--cp = to_char(_uquad & 7);
   1513 						_uquad >>= 3;
   1514 					} while (_uquad);
   1515 					/* handle octal leading 0 */
   1516 					if (flags & ALT && *cp != '0')
   1517 						*--cp = '0';
   1518 					break;
   1519 
   1520 				case DEC:
   1521 					/* many numbers are 1 digit */
   1522 					while (_uquad >= 10) {
   1523 						*--cp = to_char(_uquad % 10);
   1524 						_uquad /= 10;
   1525 					}
   1526 					*--cp = to_char(_uquad);
   1527 					break;
   1528 
   1529 				case HEX:
   1530 					do {
   1531 						*--cp = xdigs[_uquad & 15];
   1532 						_uquad >>= 4;
   1533 					} while (_uquad);
   1534 					break;
   1535 
   1536 				default:
   1537 					/*XXXUNCONST*/
   1538 					cp = __UNCONST("bug in kprintf: bad base");
   1539 					size = strlen(cp);
   1540 					goto skipsize;
   1541 				}
   1542 			}
   1543 			size = bf + KPRINTF_BUFSIZE - cp;
   1544 		skipsize:
   1545 			break;
   1546 		default:	/* "%?" prints ?, unless ? is NUL */
   1547 			if (ch == '\0')
   1548 				goto done;
   1549 			/* pretend it was %c with argument ch */
   1550 			cp = bf;
   1551 			*cp = ch;
   1552 			size = 1;
   1553 			sign = '\0';
   1554 			break;
   1555 		}
   1556 
   1557 		/*
   1558 		 * All reasonable formats wind up here.  At this point, `cp'
   1559 		 * points to a string which (if not flags&LADJUST) should be
   1560 		 * padded out to `width' places.  If flags&ZEROPAD, it should
   1561 		 * first be prefixed by any sign or other prefix; otherwise,
   1562 		 * it should be blank padded before the prefix is emitted.
   1563 		 * After any left-hand padding and prefixing, emit zeroes
   1564 		 * required by a decimal [diouxX] precision, then print the
   1565 		 * string proper, then emit zeroes required by any leftover
   1566 		 * floating precision; finally, if LADJUST, pad with blanks.
   1567 		 *
   1568 		 * Compute actual size, so we know how much to pad.
   1569 		 * size excludes decimal prec; realsz includes it.
   1570 		 */
   1571 		realsz = dprec > size ? dprec : size;
   1572 		if (sign)
   1573 			realsz++;
   1574 		else if (flags & HEXPREFIX)
   1575 			realsz+= 2;
   1576 
   1577 		/* adjust ret */
   1578 		ret += width > realsz ? width : realsz;
   1579 
   1580 		/* right-adjusting blank padding */
   1581 		if ((flags & (LADJUST|ZEROPAD)) == 0) {
   1582 			n = width - realsz;
   1583 			while (n-- > 0)
   1584 				KPRINTF_PUTCHAR(' ');
   1585 		}
   1586 
   1587 		/* prefix */
   1588 		if (sign) {
   1589 			KPRINTF_PUTCHAR(sign);
   1590 		} else if (flags & HEXPREFIX) {
   1591 			KPRINTF_PUTCHAR('0');
   1592 			KPRINTF_PUTCHAR(ch);
   1593 		}
   1594 
   1595 		/* right-adjusting zero padding */
   1596 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) {
   1597 			n = width - realsz;
   1598 			while (n-- > 0)
   1599 				KPRINTF_PUTCHAR('0');
   1600 		}
   1601 
   1602 		/* leading zeroes from decimal precision */
   1603 		n = dprec - size;
   1604 		while (n-- > 0)
   1605 			KPRINTF_PUTCHAR('0');
   1606 
   1607 		/* the string or number proper */
   1608 		for (; size--; cp++)
   1609 			KPRINTF_PUTCHAR(*cp);
   1610 		/* left-adjusting padding (always blank) */
   1611 		if (flags & LADJUST) {
   1612 			n = width - realsz;
   1613 			while (n-- > 0)
   1614 				KPRINTF_PUTCHAR(' ');
   1615 		}
   1616 	}
   1617 
   1618 done:
   1619 	if ((oflags == TOBUFONLY) && (vp != NULL))
   1620 		*(char **)vp = sbuf;
   1621 	(*v_flush)();
   1622 
   1623 #ifdef RND_PRINTF
   1624 	if (!cold) {
   1625 		struct timespec ts;
   1626 		(void)nanotime(&ts);
   1627 		SHA512_Update(&kprnd_sha, (char *)&ts, sizeof(ts));
   1628 	}
   1629 #endif
   1630 	return ret;
   1631 }
   1632