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