1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
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.3 (Berkeley) 1/21/94
37 */
38
39#include <sys/cdefs.h>
40__FBSDID("$FreeBSD$");
41
42#ifdef _KERNEL
43#include "opt_ddb.h"
44#include "opt_printf.h"
45#endif  /* _KERNEL */
46
47#include <sys/param.h>
48#ifdef _KERNEL
49#include <sys/systm.h>
50#include <sys/lock.h>
51#include <sys/kdb.h>
52#include <sys/mutex.h>
53#include <sys/sx.h>
54#include <sys/kernel.h>
55#include <sys/msgbuf.h>
56#include <sys/malloc.h>
57#include <sys/priv.h>
58#include <sys/proc.h>
59#include <sys/stddef.h>
60#include <sys/sysctl.h>
61#include <sys/tty.h>
62#include <sys/syslog.h>
63#include <sys/cons.h>
64#include <sys/uio.h>
65#endif
66#include <sys/ctype.h>
67#include <sys/sbuf.h>
68
69#ifdef DDB
70#include <ddb/ddb.h>
71#endif
72
73/*
74 * Note that stdarg.h and the ANSI style va_start macro is used for both
75 * ANSI and traditional C compilers.
76 */
77#ifdef _KERNEL
78#include <machine/stdarg.h>
79#else
80#include <stdarg.h>
81#endif
82
83/*
84 * This is needed for sbuf_putbuf() when compiled into userland.  Due to the
85 * shared nature of this file, it's the only place to put it.
86 */
87#ifndef _KERNEL
88#include <stdio.h>
89#endif
90
91#ifdef _KERNEL
92
93#define TOCONS	0x01
94#define TOTTY	0x02
95#define TOLOG	0x04
96
97/* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
98#define MAXNBUF	(sizeof(intmax_t) * NBBY + 1)
99
100struct putchar_arg {
101	int	flags;
102	int	pri;
103	struct	tty *tty;
104	char	*p_bufr;
105	size_t	n_bufr;
106	char	*p_next;
107	size_t	remain;
108};
109
110struct snprintf_arg {
111	char	*str;
112	size_t	remain;
113};
114
115extern	int log_open;
116
117static void  msglogchar(int c, int pri);
118static void  msglogstr(char *str, int pri, int filter_cr);
119static void  putchar(int ch, void *arg);
120static char *ksprintn(char *nbuf, uintmax_t num, int base, int *len, int upper);
121static void  snprintf_func(int ch, void *arg);
122
123static bool msgbufmapped;		/* Set when safe to use msgbuf */
124int msgbuftrigger;
125struct msgbuf *msgbufp;
126
127#ifndef BOOT_TAG_SZ
128#define	BOOT_TAG_SZ	32
129#endif
130#ifndef BOOT_TAG
131/* Tag used to mark the start of a boot in dmesg */
132#define	BOOT_TAG	"---<<BOOT>>---"
133#endif
134
135static char current_boot_tag[BOOT_TAG_SZ + 1] = BOOT_TAG;
136SYSCTL_STRING(_kern, OID_AUTO, boot_tag, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
137    current_boot_tag, 0, "Tag added to dmesg at start of boot");
138
139static int log_console_output = 1;
140SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RWTUN,
141    &log_console_output, 0, "Duplicate console output to the syslog");
142
143/*
144 * See the comment in log_console() below for more explanation of this.
145 */
146static int log_console_add_linefeed;
147SYSCTL_INT(_kern, OID_AUTO, log_console_add_linefeed, CTLFLAG_RWTUN,
148    &log_console_add_linefeed, 0, "log_console() adds extra newlines");
149
150static int always_console_output;
151SYSCTL_INT(_kern, OID_AUTO, always_console_output, CTLFLAG_RWTUN,
152    &always_console_output, 0, "Always output to console despite TIOCCONS");
153
154/*
155 * Warn that a system table is full.
156 */
157void
158tablefull(const char *tab)
159{
160
161	log(LOG_ERR, "%s: table is full\n", tab);
162}
163
164/*
165 * Uprintf prints to the controlling terminal for the current process.
166 */
167int
168uprintf(const char *fmt, ...)
169{
170	va_list ap;
171	struct putchar_arg pca;
172	struct proc *p;
173	struct thread *td;
174	int retval;
175
176	td = curthread;
177	if (TD_IS_IDLETHREAD(td))
178		return (0);
179
180	sx_slock(&proctree_lock);
181	p = td->td_proc;
182	PROC_LOCK(p);
183	if ((p->p_flag & P_CONTROLT) == 0) {
184		PROC_UNLOCK(p);
185		sx_sunlock(&proctree_lock);
186		return (0);
187	}
188	SESS_LOCK(p->p_session);
189	pca.tty = p->p_session->s_ttyp;
190	SESS_UNLOCK(p->p_session);
191	PROC_UNLOCK(p);
192	if (pca.tty == NULL) {
193		sx_sunlock(&proctree_lock);
194		return (0);
195	}
196	pca.flags = TOTTY;
197	pca.p_bufr = NULL;
198	va_start(ap, fmt);
199	tty_lock(pca.tty);
200	sx_sunlock(&proctree_lock);
201	retval = kvprintf(fmt, putchar, &pca, 10, ap);
202	tty_unlock(pca.tty);
203	va_end(ap);
204	return (retval);
205}
206
207/*
208 * tprintf and vtprintf print on the controlling terminal associated with the
209 * given session, possibly to the log as well.
210 */
211void
212tprintf(struct proc *p, int pri, const char *fmt, ...)
213{
214	va_list ap;
215
216	va_start(ap, fmt);
217	vtprintf(p, pri, fmt, ap);
218	va_end(ap);
219}
220
221void
222vtprintf(struct proc *p, int pri, const char *fmt, va_list ap)
223{
224	struct tty *tp = NULL;
225	int flags = 0;
226	struct putchar_arg pca;
227	struct session *sess = NULL;
228
229	sx_slock(&proctree_lock);
230	if (pri != -1)
231		flags |= TOLOG;
232	if (p != NULL) {
233		PROC_LOCK(p);
234		if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
235			sess = p->p_session;
236			sess_hold(sess);
237			PROC_UNLOCK(p);
238			tp = sess->s_ttyp;
239			if (tp != NULL && tty_checkoutq(tp))
240				flags |= TOTTY;
241			else
242				tp = NULL;
243		} else
244			PROC_UNLOCK(p);
245	}
246	pca.pri = pri;
247	pca.tty = tp;
248	pca.flags = flags;
249	pca.p_bufr = NULL;
250	if (pca.tty != NULL)
251		tty_lock(pca.tty);
252	sx_sunlock(&proctree_lock);
253	kvprintf(fmt, putchar, &pca, 10, ap);
254	if (pca.tty != NULL)
255		tty_unlock(pca.tty);
256	if (sess != NULL)
257		sess_release(sess);
258	msgbuftrigger = 1;
259}
260
261/*
262 * Ttyprintf displays a message on a tty; it should be used only by
263 * the tty driver, or anything that knows the underlying tty will not
264 * be revoke(2)'d away.  Other callers should use tprintf.
265 */
266int
267ttyprintf(struct tty *tp, const char *fmt, ...)
268{
269	va_list ap;
270	struct putchar_arg pca;
271	int retval;
272
273	va_start(ap, fmt);
274	pca.tty = tp;
275	pca.flags = TOTTY;
276	pca.p_bufr = NULL;
277	retval = kvprintf(fmt, putchar, &pca, 10, ap);
278	va_end(ap);
279	return (retval);
280}
281
282static int
283_vprintf(int level, int flags, const char *fmt, va_list ap)
284{
285	struct putchar_arg pca;
286	int retval;
287#ifdef PRINTF_BUFR_SIZE
288	char bufr[PRINTF_BUFR_SIZE];
289#endif
290
291	TSENTER();
292	pca.tty = NULL;
293	pca.pri = level;
294	pca.flags = flags;
295#ifdef PRINTF_BUFR_SIZE
296	pca.p_bufr = bufr;
297	pca.p_next = pca.p_bufr;
298	pca.n_bufr = sizeof(bufr);
299	pca.remain = sizeof(bufr);
300	*pca.p_next = '\0';
301#else
302	/* Don't buffer console output. */
303	pca.p_bufr = NULL;
304#endif
305
306	retval = kvprintf(fmt, putchar, &pca, 10, ap);
307
308#ifdef PRINTF_BUFR_SIZE
309	/* Write any buffered console/log output: */
310	if (*pca.p_bufr != '\0') {
311		if (pca.flags & TOLOG)
312			msglogstr(pca.p_bufr, level, /*filter_cr*/1);
313
314		if (pca.flags & TOCONS)
315			cnputs(pca.p_bufr);
316	}
317#endif
318
319	TSEXIT();
320	return (retval);
321}
322
323/*
324 * Log writes to the log buffer, and guarantees not to sleep (so can be
325 * called by interrupt routines).  If there is no process reading the
326 * log yet, it writes to the console also.
327 */
328void
329log(int level, const char *fmt, ...)
330{
331	va_list ap;
332
333	va_start(ap, fmt);
334	vlog(level, fmt, ap);
335	va_end(ap);
336}
337
338void
339vlog(int level, const char *fmt, va_list ap)
340{
341
342	(void)_vprintf(level, log_open ? TOLOG : TOCONS | TOLOG, fmt, ap);
343	msgbuftrigger = 1;
344}
345
346#define CONSCHUNK 128
347
348void
349log_console(struct uio *uio)
350{
351	int c, error, nl;
352	char *consbuffer;
353	int pri;
354
355	if (!log_console_output)
356		return;
357
358	pri = LOG_INFO | LOG_CONSOLE;
359	uio = cloneuio(uio);
360	consbuffer = malloc(CONSCHUNK, M_TEMP, M_WAITOK);
361
362	nl = 0;
363	while (uio->uio_resid > 0) {
364		c = imin(uio->uio_resid, CONSCHUNK - 1);
365		error = uiomove(consbuffer, c, uio);
366		if (error != 0)
367			break;
368		/* Make sure we're NUL-terminated */
369		consbuffer[c] = '\0';
370		if (consbuffer[c - 1] == '\n')
371			nl = 1;
372		else
373			nl = 0;
374		msglogstr(consbuffer, pri, /*filter_cr*/ 1);
375	}
376	/*
377	 * The previous behavior in log_console() is preserved when
378	 * log_console_add_linefeed is non-zero.  For that behavior, if an
379	 * individual console write came in that was not terminated with a
380	 * line feed, it would add a line feed.
381	 *
382	 * This results in different data in the message buffer than
383	 * appears on the system console (which doesn't add extra line feed
384	 * characters).
385	 *
386	 * A number of programs and rc scripts write a line feed, or a period
387	 * and a line feed when they have completed their operation.  On
388	 * the console, this looks seamless, but when displayed with
389	 * 'dmesg -a', you wind up with output that looks like this:
390	 *
391	 * Updating motd:
392	 * .
393	 *
394	 * On the console, it looks like this:
395	 * Updating motd:.
396	 *
397	 * We could add logic to detect that situation, or just not insert
398	 * the extra newlines.  Set the kern.log_console_add_linefeed
399	 * sysctl/tunable variable to get the old behavior.
400	 */
401	if (!nl && log_console_add_linefeed) {
402		consbuffer[0] = '\n';
403		consbuffer[1] = '\0';
404		msglogstr(consbuffer, pri, /*filter_cr*/ 1);
405	}
406	msgbuftrigger = 1;
407	free(uio, M_IOV);
408	free(consbuffer, M_TEMP);
409}
410
411int
412printf(const char *fmt, ...)
413{
414	va_list ap;
415	int retval;
416
417	va_start(ap, fmt);
418	retval = vprintf(fmt, ap);
419	va_end(ap);
420
421	return (retval);
422}
423
424int
425vprintf(const char *fmt, va_list ap)
426{
427	int retval;
428
429	retval = _vprintf(-1, TOCONS | TOLOG, fmt, ap);
430
431	if (!panicstr)
432		msgbuftrigger = 1;
433
434	return (retval);
435}
436
437static void
438prf_putbuf(char *bufr, int flags, int pri)
439{
440
441	if (flags & TOLOG)
442		msglogstr(bufr, pri, /*filter_cr*/1);
443
444	if (flags & TOCONS) {
445		if ((panicstr == NULL) && (constty != NULL))
446			msgbuf_addstr(&consmsgbuf, -1,
447			    bufr, /*filter_cr*/ 0);
448
449		if ((constty == NULL) ||(always_console_output))
450			cnputs(bufr);
451	}
452}
453
454static void
455putbuf(int c, struct putchar_arg *ap)
456{
457	/* Check if no console output buffer was provided. */
458	if (ap->p_bufr == NULL) {
459		/* Output direct to the console. */
460		if (ap->flags & TOCONS)
461			cnputc(c);
462
463		if (ap->flags & TOLOG)
464			msglogchar(c, ap->pri);
465	} else {
466		/* Buffer the character: */
467		*ap->p_next++ = c;
468		ap->remain--;
469
470		/* Always leave the buffer zero terminated. */
471		*ap->p_next = '\0';
472
473		/* Check if the buffer needs to be flushed. */
474		if (ap->remain == 2 || c == '\n') {
475			prf_putbuf(ap->p_bufr, ap->flags, ap->pri);
476
477			ap->p_next = ap->p_bufr;
478			ap->remain = ap->n_bufr;
479			*ap->p_next = '\0';
480		}
481
482		/*
483		 * Since we fill the buffer up one character at a time,
484		 * this should not happen.  We should always catch it when
485		 * ap->remain == 2 (if not sooner due to a newline), flush
486		 * the buffer and move on.  One way this could happen is
487		 * if someone sets PRINTF_BUFR_SIZE to 1 or something
488		 * similarly silly.
489		 */
490		KASSERT(ap->remain > 2, ("Bad buffer logic, remain = %zd",
491		    ap->remain));
492	}
493}
494
495/*
496 * Print a character on console or users terminal.  If destination is
497 * the console then the last bunch of characters are saved in msgbuf for
498 * inspection later.
499 */
500static void
501putchar(int c, void *arg)
502{
503	struct putchar_arg *ap = (struct putchar_arg*) arg;
504	struct tty *tp = ap->tty;
505	int flags = ap->flags;
506
507	/* Don't use the tty code after a panic or while in ddb. */
508	if (kdb_active) {
509		if (c != '\0')
510			cnputc(c);
511		return;
512	}
513
514	if ((flags & TOTTY) && tp != NULL && panicstr == NULL)
515		tty_putchar(tp, c);
516
517	if ((flags & (TOCONS | TOLOG)) && c != '\0')
518		putbuf(c, ap);
519}
520
521/*
522 * Scaled down version of sprintf(3).
523 */
524int
525sprintf(char *buf, const char *cfmt, ...)
526{
527	int retval;
528	va_list ap;
529
530	va_start(ap, cfmt);
531	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
532	buf[retval] = '\0';
533	va_end(ap);
534	return (retval);
535}
536
537/*
538 * Scaled down version of vsprintf(3).
539 */
540int
541vsprintf(char *buf, const char *cfmt, va_list ap)
542{
543	int retval;
544
545	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
546	buf[retval] = '\0';
547	return (retval);
548}
549
550/*
551 * Scaled down version of snprintf(3).
552 */
553int
554snprintf(char *str, size_t size, const char *format, ...)
555{
556	int retval;
557	va_list ap;
558
559	va_start(ap, format);
560	retval = vsnprintf(str, size, format, ap);
561	va_end(ap);
562	return(retval);
563}
564
565/*
566 * Scaled down version of vsnprintf(3).
567 */
568int
569vsnprintf(char *str, size_t size, const char *format, va_list ap)
570{
571	struct snprintf_arg info;
572	int retval;
573
574	info.str = str;
575	info.remain = size;
576	retval = kvprintf(format, snprintf_func, &info, 10, ap);
577	if (info.remain >= 1)
578		*info.str++ = '\0';
579	return (retval);
580}
581
582/*
583 * Kernel version which takes radix argument vsnprintf(3).
584 */
585int
586vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
587{
588	struct snprintf_arg info;
589	int retval;
590
591	info.str = str;
592	info.remain = size;
593	retval = kvprintf(format, snprintf_func, &info, radix, ap);
594	if (info.remain >= 1)
595		*info.str++ = '\0';
596	return (retval);
597}
598
599static void
600snprintf_func(int ch, void *arg)
601{
602	struct snprintf_arg *const info = arg;
603
604	if (info->remain >= 2) {
605		*info->str++ = ch;
606		info->remain--;
607	}
608}
609
610/*
611 * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
612 * order; return an optional length and a pointer to the last character
613 * written in the buffer (i.e., the first character of the string).
614 * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
615 */
616static char *
617ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
618{
619	char *p, c;
620
621	p = nbuf;
622	*p = '\0';
623	do {
624		c = hex2ascii(num % base);
625		*++p = upper ? toupper(c) : c;
626	} while (num /= base);
627	if (lenp)
628		*lenp = p - nbuf;
629	return (p);
630}
631
632/*
633 * Scaled down version of printf(3).
634 *
635 * Two additional formats:
636 *
637 * The format %b is supported to decode error registers.
638 * Its usage is:
639 *
640 *	printf("reg=%b\n", regval, "<base><arg>*");
641 *
642 * where <base> is the output base expressed as a control character, e.g.
643 * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
644 * the first of which gives the bit number to be inspected (origin 1), and
645 * the next characters (up to a control character, i.e. a character <= 32),
646 * give the name of the register.  Thus:
647 *
648 *	kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE");
649 *
650 * would produce output:
651 *
652 *	reg=3<BITTWO,BITONE>
653 *
654 * XXX:  %D  -- Hexdump, takes pointer and separator string:
655 *		("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
656 *		("%*D", len, ptr, " " -> XX XX XX XX ...
657 */
658int
659kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
660{
661#define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
662	char nbuf[MAXNBUF];
663	char *d;
664	const char *p, *percent, *q;
665	u_char *up;
666	int ch, n;
667	uintmax_t num;
668	int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
669	int cflag, hflag, jflag, tflag, zflag;
670	int bconv, dwidth, upper;
671	char padc;
672	int stop = 0, retval = 0;
673
674	num = 0;
675	q = NULL;
676	if (!func)
677		d = (char *) arg;
678	else
679		d = NULL;
680
681	if (fmt == NULL)
682		fmt = "(fmt null)\n";
683
684	if (radix < 2 || radix > 36)
685		radix = 10;
686
687	for (;;) {
688		padc = ' ';
689		width = 0;
690		while ((ch = (u_char)*fmt++) != '%' || stop) {
691			if (ch == '\0')
692				return (retval);
693			PCHAR(ch);
694		}
695		percent = fmt - 1;
696		qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
697		sign = 0; dot = 0; bconv = 0; dwidth = 0; upper = 0;
698		cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
699reswitch:	switch (ch = (u_char)*fmt++) {
700		case '.':
701			dot = 1;
702			goto reswitch;
703		case '#':
704			sharpflag = 1;
705			goto reswitch;
706		case '+':
707			sign = 1;
708			goto reswitch;
709		case '-':
710			ladjust = 1;
711			goto reswitch;
712		case '%':
713			PCHAR(ch);
714			break;
715		case '*':
716			if (!dot) {
717				width = va_arg(ap, int);
718				if (width < 0) {
719					ladjust = !ladjust;
720					width = -width;
721				}
722			} else {
723				dwidth = va_arg(ap, int);
724			}
725			goto reswitch;
726		case '0':
727			if (!dot) {
728				padc = '0';
729				goto reswitch;
730			}
731			/* FALLTHROUGH */
732		case '1': case '2': case '3': case '4':
733		case '5': case '6': case '7': case '8': case '9':
734				for (n = 0;; ++fmt) {
735					n = n * 10 + ch - '0';
736					ch = *fmt;
737					if (ch < '0' || ch > '9')
738						break;
739				}
740			if (dot)
741				dwidth = n;
742			else
743				width = n;
744			goto reswitch;
745		case 'b':
746			ladjust = 1;
747			bconv = 1;
748			goto handle_nosign;
749		case 'c':
750			width -= 1;
751
752			if (!ladjust && width > 0)
753				while (width--)
754					PCHAR(padc);
755			PCHAR(va_arg(ap, int));
756			if (ladjust && width > 0)
757				while (width--)
758					PCHAR(padc);
759			break;
760		case 'D':
761			up = va_arg(ap, u_char *);
762			p = va_arg(ap, char *);
763			if (!width)
764				width = 16;
765			while(width--) {
766				PCHAR(hex2ascii(*up >> 4));
767				PCHAR(hex2ascii(*up & 0x0f));
768				up++;
769				if (width)
770					for (q=p;*q;q++)
771						PCHAR(*q);
772			}
773			break;
774		case 'd':
775		case 'i':
776			base = 10;
777			sign = 1;
778			goto handle_sign;
779		case 'h':
780			if (hflag) {
781				hflag = 0;
782				cflag = 1;
783			} else
784				hflag = 1;
785			goto reswitch;
786		case 'j':
787			jflag = 1;
788			goto reswitch;
789		case 'l':
790			if (lflag) {
791				lflag = 0;
792				qflag = 1;
793			} else
794				lflag = 1;
795			goto reswitch;
796		case 'n':
797			if (jflag)
798				*(va_arg(ap, intmax_t *)) = retval;
799			else if (qflag)
800				*(va_arg(ap, quad_t *)) = retval;
801			else if (lflag)
802				*(va_arg(ap, long *)) = retval;
803			else if (zflag)
804				*(va_arg(ap, size_t *)) = retval;
805			else if (hflag)
806				*(va_arg(ap, short *)) = retval;
807			else if (cflag)
808				*(va_arg(ap, char *)) = retval;
809			else
810				*(va_arg(ap, int *)) = retval;
811			break;
812		case 'o':
813			base = 8;
814			goto handle_nosign;
815		case 'p':
816			base = 16;
817			sharpflag = (width == 0);
818			sign = 0;
819			num = (uintptr_t)va_arg(ap, void *);
820			goto number;
821		case 'q':
822			qflag = 1;
823			goto reswitch;
824		case 'r':
825			base = radix;
826			if (sign)
827				goto handle_sign;
828			goto handle_nosign;
829		case 's':
830			p = va_arg(ap, char *);
831			if (p == NULL)
832				p = "(null)";
833			if (!dot)
834				n = strlen (p);
835			else
836				for (n = 0; n < dwidth && p[n]; n++)
837					continue;
838
839			width -= n;
840
841			if (!ladjust && width > 0)
842				while (width--)
843					PCHAR(padc);
844			while (n--)
845				PCHAR(*p++);
846			if (ladjust && width > 0)
847				while (width--)
848					PCHAR(padc);
849			break;
850		case 't':
851			tflag = 1;
852			goto reswitch;
853		case 'u':
854			base = 10;
855			goto handle_nosign;
856		case 'X':
857			upper = 1;
858		case 'x':
859			base = 16;
860			goto handle_nosign;
861		case 'y':
862			base = 16;
863			sign = 1;
864			goto handle_sign;
865		case 'z':
866			zflag = 1;
867			goto reswitch;
868handle_nosign:
869			sign = 0;
870			if (jflag)
871				num = va_arg(ap, uintmax_t);
872			else if (qflag)
873				num = va_arg(ap, u_quad_t);
874			else if (tflag)
875				num = va_arg(ap, ptrdiff_t);
876			else if (lflag)
877				num = va_arg(ap, u_long);
878			else if (zflag)
879				num = va_arg(ap, size_t);
880			else if (hflag)
881				num = (u_short)va_arg(ap, int);
882			else if (cflag)
883				num = (u_char)va_arg(ap, int);
884			else
885				num = va_arg(ap, u_int);
886			if (bconv) {
887				q = va_arg(ap, char *);
888				base = *q++;
889			}
890			goto number;
891handle_sign:
892			if (jflag)
893				num = va_arg(ap, intmax_t);
894			else if (qflag)
895				num = va_arg(ap, quad_t);
896			else if (tflag)
897				num = va_arg(ap, ptrdiff_t);
898			else if (lflag)
899				num = va_arg(ap, long);
900			else if (zflag)
901				num = va_arg(ap, ssize_t);
902			else if (hflag)
903				num = (short)va_arg(ap, int);
904			else if (cflag)
905				num = (char)va_arg(ap, int);
906			else
907				num = va_arg(ap, int);
908number:
909			if (sign && (intmax_t)num < 0) {
910				neg = 1;
911				num = -(intmax_t)num;
912			}
913			p = ksprintn(nbuf, num, base, &n, upper);
914			tmp = 0;
915			if (sharpflag && num != 0) {
916				if (base == 8)
917					tmp++;
918				else if (base == 16)
919					tmp += 2;
920			}
921			if (neg)
922				tmp++;
923
924			if (!ladjust && padc == '0')
925				dwidth = width - tmp;
926			width -= tmp + imax(dwidth, n);
927			dwidth -= n;
928			if (!ladjust)
929				while (width-- > 0)
930					PCHAR(' ');
931			if (neg)
932				PCHAR('-');
933			if (sharpflag && num != 0) {
934				if (base == 8) {
935					PCHAR('0');
936				} else if (base == 16) {
937					PCHAR('0');
938					PCHAR('x');
939				}
940			}
941			while (dwidth-- > 0)
942				PCHAR('0');
943
944			while (*p)
945				PCHAR(*p--);
946
947			if (bconv && num != 0) {
948				/* %b conversion flag format. */
949				tmp = retval;
950				while (*q) {
951					n = *q++;
952					if (num & (1 << (n - 1))) {
953						PCHAR(retval != tmp ?
954						    ',' : '<');
955						for (; (n = *q) > ' '; ++q)
956							PCHAR(n);
957					} else
958						for (; *q > ' '; ++q)
959							continue;
960				}
961				if (retval != tmp) {
962					PCHAR('>');
963					width -= retval - tmp;
964				}
965			}
966
967			if (ladjust)
968				while (width-- > 0)
969					PCHAR(' ');
970
971			break;
972		default:
973			while (percent < fmt)
974				PCHAR(*percent++);
975			/*
976			 * Since we ignore a formatting argument it is no
977			 * longer safe to obey the remaining formatting
978			 * arguments as the arguments will no longer match
979			 * the format specs.
980			 */
981			stop = 1;
982			break;
983		}
984	}
985#undef PCHAR
986}
987
988/*
989 * Put character in log buffer with a particular priority.
990 */
991static void
992msglogchar(int c, int pri)
993{
994	static int lastpri = -1;
995	static int dangling;
996	char nbuf[MAXNBUF];
997	char *p;
998
999	if (!msgbufmapped)
1000		return;
1001	if (c == '\0' || c == '\r')
1002		return;
1003	if (pri != -1 && pri != lastpri) {
1004		if (dangling) {
1005			msgbuf_addchar(msgbufp, '\n');
1006			dangling = 0;
1007		}
1008		msgbuf_addchar(msgbufp, '<');
1009		for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
1010			msgbuf_addchar(msgbufp, *p--);
1011		msgbuf_addchar(msgbufp, '>');
1012		lastpri = pri;
1013	}
1014	msgbuf_addchar(msgbufp, c);
1015	if (c == '\n') {
1016		dangling = 0;
1017		lastpri = -1;
1018	} else {
1019		dangling = 1;
1020	}
1021}
1022
1023static void
1024msglogstr(char *str, int pri, int filter_cr)
1025{
1026	if (!msgbufmapped)
1027		return;
1028
1029	msgbuf_addstr(msgbufp, pri, str, filter_cr);
1030}
1031
1032void
1033msgbufinit(void *ptr, int size)
1034{
1035	char *cp;
1036	static struct msgbuf *oldp = NULL;
1037	bool print_boot_tag;
1038
1039	size -= sizeof(*msgbufp);
1040	cp = (char *)ptr;
1041	print_boot_tag = !msgbufmapped;
1042	/* Attempt to fetch kern.boot_tag tunable on first mapping */
1043	if (!msgbufmapped)
1044		TUNABLE_STR_FETCH("kern.boot_tag", current_boot_tag,
1045		    sizeof(current_boot_tag));
1046	msgbufp = (struct msgbuf *)(cp + size);
1047	msgbuf_reinit(msgbufp, cp, size);
1048	if (msgbufmapped && oldp != msgbufp)
1049		msgbuf_copy(oldp, msgbufp);
1050	msgbufmapped = true;
1051	if (print_boot_tag && *current_boot_tag != '\0')
1052		printf("%s\n", current_boot_tag);
1053	oldp = msgbufp;
1054}
1055
1056/* Sysctls for accessing/clearing the msgbuf */
1057static int
1058sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1059{
1060	char buf[128];
1061	u_int seq;
1062	int error, len;
1063
1064	error = priv_check(req->td, PRIV_MSGBUF);
1065	if (error)
1066		return (error);
1067
1068	/* Read the whole buffer, one chunk at a time. */
1069	mtx_lock(&msgbuf_lock);
1070	msgbuf_peekbytes(msgbufp, NULL, 0, &seq);
1071	for (;;) {
1072		len = msgbuf_peekbytes(msgbufp, buf, sizeof(buf), &seq);
1073		mtx_unlock(&msgbuf_lock);
1074		if (len == 0)
1075			return (SYSCTL_OUT(req, "", 1)); /* add nulterm */
1076
1077		error = sysctl_handle_opaque(oidp, buf, len, req);
1078		if (error)
1079			return (error);
1080
1081		mtx_lock(&msgbuf_lock);
1082	}
1083}
1084
1085SYSCTL_PROC(_kern, OID_AUTO, msgbuf,
1086    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1087    NULL, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1088
1089static int msgbuf_clearflag;
1090
1091static int
1092sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1093{
1094	int error;
1095	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1096	if (!error && req->newptr) {
1097		mtx_lock(&msgbuf_lock);
1098		msgbuf_clear(msgbufp);
1099		mtx_unlock(&msgbuf_lock);
1100		msgbuf_clearflag = 0;
1101	}
1102	return (error);
1103}
1104
1105SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1106    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE | CTLFLAG_MPSAFE,
1107    &msgbuf_clearflag, 0, sysctl_kern_msgbuf_clear, "I",
1108    "Clear kernel message buffer");
1109
1110#ifdef DDB
1111
1112DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1113{
1114	int i, j;
1115
1116	if (!msgbufmapped) {
1117		db_printf("msgbuf not mapped yet\n");
1118		return;
1119	}
1120	db_printf("msgbufp = %p\n", msgbufp);
1121	db_printf("magic = %x, size = %d, r= %u, w = %u, ptr = %p, cksum= %u\n",
1122	    msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_rseq,
1123	    msgbufp->msg_wseq, msgbufp->msg_ptr, msgbufp->msg_cksum);
1124	for (i = 0; i < msgbufp->msg_size && !db_pager_quit; i++) {
1125		j = MSGBUF_SEQ_TO_POS(msgbufp, i + msgbufp->msg_rseq);
1126		db_printf("%c", msgbufp->msg_ptr[j]);
1127	}
1128	db_printf("\n");
1129}
1130
1131#endif /* DDB */
1132
1133void
1134hexdump(const void *ptr, int length, const char *hdr, int flags)
1135{
1136	int i, j, k;
1137	int cols;
1138	const unsigned char *cp;
1139	char delim;
1140
1141	if ((flags & HD_DELIM_MASK) != 0)
1142		delim = (flags & HD_DELIM_MASK) >> 8;
1143	else
1144		delim = ' ';
1145
1146	if ((flags & HD_COLUMN_MASK) != 0)
1147		cols = flags & HD_COLUMN_MASK;
1148	else
1149		cols = 16;
1150
1151	cp = ptr;
1152	for (i = 0; i < length; i+= cols) {
1153		if (hdr != NULL)
1154			printf("%s", hdr);
1155
1156		if ((flags & HD_OMIT_COUNT) == 0)
1157			printf("%04x  ", i);
1158
1159		if ((flags & HD_OMIT_HEX) == 0) {
1160			for (j = 0; j < cols; j++) {
1161				k = i + j;
1162				if (k < length)
1163					printf("%c%02x", delim, cp[k]);
1164				else
1165					printf("   ");
1166			}
1167		}
1168
1169		if ((flags & HD_OMIT_CHARS) == 0) {
1170			printf("  |");
1171			for (j = 0; j < cols; j++) {
1172				k = i + j;
1173				if (k >= length)
1174					printf(" ");
1175				else if (cp[k] >= ' ' && cp[k] <= '~')
1176					printf("%c", cp[k]);
1177				else
1178					printf(".");
1179			}
1180			printf("|");
1181		}
1182		printf("\n");
1183	}
1184}
1185#endif /* _KERNEL */
1186
1187void
1188sbuf_hexdump(struct sbuf *sb, const void *ptr, int length, const char *hdr,
1189	     int flags)
1190{
1191	int i, j, k;
1192	int cols;
1193	const unsigned char *cp;
1194	char delim;
1195
1196	if ((flags & HD_DELIM_MASK) != 0)
1197		delim = (flags & HD_DELIM_MASK) >> 8;
1198	else
1199		delim = ' ';
1200
1201	if ((flags & HD_COLUMN_MASK) != 0)
1202		cols = flags & HD_COLUMN_MASK;
1203	else
1204		cols = 16;
1205
1206	cp = ptr;
1207	for (i = 0; i < length; i+= cols) {
1208		if (hdr != NULL)
1209			sbuf_printf(sb, "%s", hdr);
1210
1211		if ((flags & HD_OMIT_COUNT) == 0)
1212			sbuf_printf(sb, "%04x  ", i);
1213
1214		if ((flags & HD_OMIT_HEX) == 0) {
1215			for (j = 0; j < cols; j++) {
1216				k = i + j;
1217				if (k < length)
1218					sbuf_printf(sb, "%c%02x", delim, cp[k]);
1219				else
1220					sbuf_printf(sb, "   ");
1221			}
1222		}
1223
1224		if ((flags & HD_OMIT_CHARS) == 0) {
1225			sbuf_printf(sb, "  |");
1226			for (j = 0; j < cols; j++) {
1227				k = i + j;
1228				if (k >= length)
1229					sbuf_printf(sb, " ");
1230				else if (cp[k] >= ' ' && cp[k] <= '~')
1231					sbuf_printf(sb, "%c", cp[k]);
1232				else
1233					sbuf_printf(sb, ".");
1234			}
1235			sbuf_printf(sb, "|");
1236		}
1237		sbuf_printf(sb, "\n");
1238	}
1239}
1240
1241#ifdef _KERNEL
1242void
1243counted_warning(unsigned *counter, const char *msg)
1244{
1245	struct thread *td;
1246	unsigned c;
1247
1248	for (;;) {
1249		c = *counter;
1250		if (c == 0)
1251			break;
1252		if (atomic_cmpset_int(counter, c, c - 1)) {
1253			td = curthread;
1254			log(LOG_INFO, "pid %d (%s) %s%s\n",
1255			    td->td_proc->p_pid, td->td_name, msg,
1256			    c > 1 ? "" : " - not logging anymore");
1257			break;
1258		}
1259	}
1260}
1261#endif
1262
1263#ifdef _KERNEL
1264void
1265sbuf_putbuf(struct sbuf *sb)
1266{
1267
1268	prf_putbuf(sbuf_data(sb), TOLOG | TOCONS, -1);
1269}
1270#else
1271void
1272sbuf_putbuf(struct sbuf *sb)
1273{
1274
1275	printf("%s", sbuf_data(sb));
1276}
1277#endif
1278