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