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