xref: /freebsd/sys/kern/subr_prf.c (revision 390e8cc2974df1888369c06339ef8e0e92b312b6)
1 /*-
2  * Copyright (c) 1986, 1988, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)subr_prf.c	8.3 (Berkeley) 1/21/94
39  * $FreeBSD$
40  */
41 
42 #include "opt_ddb.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/sx.h>
49 #include <sys/kernel.h>
50 #include <sys/msgbuf.h>
51 #include <sys/malloc.h>
52 #include <sys/proc.h>
53 #include <sys/stddef.h>
54 #include <sys/sysctl.h>
55 #include <sys/tty.h>
56 #include <sys/syslog.h>
57 #include <sys/cons.h>
58 #include <sys/uio.h>
59 
60 #ifdef DDB
61 #include <ddb/ddb.h>
62 #endif
63 
64 /*
65  * Note that stdarg.h and the ANSI style va_start macro is used for both
66  * ANSI and traditional C compilers.
67  */
68 #include <machine/stdarg.h>
69 
70 #define TOCONS	0x01
71 #define TOTTY	0x02
72 #define TOLOG	0x04
73 
74 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
75 #define MAXNBUF	(sizeof(intmax_t) * NBBY + 1)
76 
77 struct putchar_arg {
78 	int	flags;
79 	int	pri;
80 	struct	tty *tty;
81 };
82 
83 struct snprintf_arg {
84 	char	*str;
85 	size_t	remain;
86 };
87 
88 extern	int log_open;
89 
90 struct	tty *constty;			/* pointer to console "window" tty */
91 
92 static void (*v_putc)(int) = cnputc;	/* routine to putc on virtual console */
93 static void  msglogchar(int c, int pri);
94 static void  msgaddchar(int c, void *dummy);
95 static u_int msgbufcksum(char *cp, size_t size, u_int cksum);
96 static void  putchar(int ch, void *arg);
97 static char *ksprintn(char *nbuf, uintmax_t num, int base, int *len);
98 static void  snprintf_func(int ch, void *arg);
99 
100 static int consintr = 1;		/* Ok to handle console interrupts? */
101 static int msgbufmapped;		/* Set when safe to use msgbuf */
102 int msgbuftrigger;
103 
104 static int      log_console_output = 1;
105 TUNABLE_INT("kern.log_console_output", &log_console_output);
106 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
107     &log_console_output, 0, "");
108 
109 /*
110  * Warn that a system table is full.
111  */
112 void
113 tablefull(const char *tab)
114 {
115 
116 	log(LOG_ERR, "%s: table is full\n", tab);
117 }
118 
119 /*
120  * Uprintf prints to the controlling terminal for the current process.
121  * It may block if the tty queue is overfull.  No message is printed if
122  * the queue does not clear in a reasonable time.
123  */
124 int
125 uprintf(const char *fmt, ...)
126 {
127 	struct thread *td = curthread;
128 	struct proc *p = td->td_proc;
129 	va_list ap;
130 	struct putchar_arg pca;
131 	int retval;
132 
133 	if (td == NULL || td == PCPU_GET(idlethread))
134 		return (0);
135 
136 	p = td->td_proc;
137 	PROC_LOCK(p);
138 	if ((p->p_flag & P_CONTROLT) == 0) {
139 		PROC_UNLOCK(p);
140 		return (0);
141 	}
142 	SESS_LOCK(p->p_session);
143 	pca.tty = p->p_session->s_ttyp;
144 	SESS_UNLOCK(p->p_session);
145 	PROC_UNLOCK(p);
146 	if (pca.tty == NULL)
147 		return (0);
148 	pca.flags = TOTTY;
149 	va_start(ap, fmt);
150 	retval = kvprintf(fmt, putchar, &pca, 10, ap);
151 	va_end(ap);
152 
153 	return (retval);
154 }
155 
156 /*
157  * tprintf prints on the controlling terminal associated
158  * with the given session, possibly to the log as well.
159  */
160 void
161 tprintf(struct proc *p, int pri, const char *fmt, ...)
162 {
163 	struct tty *tp = NULL;
164 	int flags = 0;
165 	va_list ap;
166 	struct putchar_arg pca;
167 	struct session *sess = NULL;
168 
169 	if (pri != -1)
170 		flags |= TOLOG;
171 	if (p != NULL) {
172 		PROC_LOCK(p);
173 		if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
174 			sess = p->p_session;
175 			SESS_LOCK(sess);
176 			PROC_UNLOCK(p);
177 			SESSHOLD(sess);
178 			tp = sess->s_ttyp;
179 			SESS_UNLOCK(sess);
180 			if (ttycheckoutq(tp, 0))
181 				flags |= TOTTY;
182 			else
183 				tp = NULL;
184 		} else
185 			PROC_UNLOCK(p);
186 	}
187 	pca.pri = pri;
188 	pca.tty = tp;
189 	pca.flags = flags;
190 	va_start(ap, fmt);
191 	kvprintf(fmt, putchar, &pca, 10, ap);
192 	va_end(ap);
193 	if (sess != NULL) {
194 		SESS_LOCK(sess);
195 		SESSRELE(sess);
196 		SESS_UNLOCK(sess);
197 	}
198 	msgbuftrigger = 1;
199 }
200 
201 /*
202  * Ttyprintf displays a message on a tty; it should be used only by
203  * the tty driver, or anything that knows the underlying tty will not
204  * be revoke(2)'d away.  Other callers should use tprintf.
205  */
206 int
207 ttyprintf(struct tty *tp, const char *fmt, ...)
208 {
209 	va_list ap;
210 	struct putchar_arg pca;
211 	int retval;
212 
213 	va_start(ap, fmt);
214 	pca.tty = tp;
215 	pca.flags = TOTTY;
216 	retval = kvprintf(fmt, putchar, &pca, 10, ap);
217 	va_end(ap);
218 	return (retval);
219 }
220 
221 /*
222  * Log writes to the log buffer, and guarantees not to sleep (so can be
223  * called by interrupt routines).  If there is no process reading the
224  * log yet, it writes to the console also.
225  */
226 void
227 log(int level, const char *fmt, ...)
228 {
229 	va_list ap;
230 	struct putchar_arg pca;
231 
232 	pca.tty = NULL;
233 	pca.pri = level;
234 	pca.flags = log_open ? TOLOG : TOCONS;
235 
236 	va_start(ap, fmt);
237 	kvprintf(fmt, putchar, &pca, 10, ap);
238 	va_end(ap);
239 
240 	msgbuftrigger = 1;
241 }
242 
243 #define CONSCHUNK 128
244 
245 void
246 log_console(struct uio *uio)
247 {
248 	int c, i, error, iovlen, nl;
249 	struct uio muio;
250 	struct iovec *miov = NULL;
251 	char *consbuffer;
252 	int pri;
253 
254 	if (!log_console_output)
255 		return;
256 
257 	pri = LOG_INFO | LOG_CONSOLE;
258 	muio = *uio;
259 	iovlen = uio->uio_iovcnt * sizeof (struct iovec);
260 	MALLOC(miov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
261 	MALLOC(consbuffer, char *, CONSCHUNK, M_TEMP, M_WAITOK);
262 	bcopy(muio.uio_iov, miov, iovlen);
263 	muio.uio_iov = miov;
264 	uio = &muio;
265 
266 	nl = 0;
267 	while (uio->uio_resid > 0) {
268 		c = imin(uio->uio_resid, CONSCHUNK);
269 		error = uiomove(consbuffer, c, uio);
270 		if (error != 0)
271 			break;
272 		for (i = 0; i < c; i++) {
273 			msglogchar(consbuffer[i], pri);
274 			if (consbuffer[i] == '\n')
275 				nl = 1;
276 			else
277 				nl = 0;
278 		}
279 	}
280 	if (!nl)
281 		msglogchar('\n', pri);
282 	msgbuftrigger = 1;
283 	FREE(miov, M_TEMP);
284 	FREE(consbuffer, M_TEMP);
285 	return;
286 }
287 
288 int
289 printf(const char *fmt, ...)
290 {
291 	va_list ap;
292 	int savintr;
293 	struct putchar_arg pca;
294 	int retval;
295 
296 	savintr = consintr;		/* disable interrupts */
297 	consintr = 0;
298 	va_start(ap, fmt);
299 	pca.tty = NULL;
300 	pca.flags = TOCONS | TOLOG;
301 	pca.pri = -1;
302 	retval = kvprintf(fmt, putchar, &pca, 10, ap);
303 	va_end(ap);
304 	if (!panicstr)
305 		msgbuftrigger = 1;
306 	consintr = savintr;		/* reenable interrupts */
307 	return (retval);
308 }
309 
310 int
311 vprintf(const char *fmt, va_list ap)
312 {
313 	int savintr;
314 	struct putchar_arg pca;
315 	int retval;
316 
317 	savintr = consintr;		/* disable interrupts */
318 	consintr = 0;
319 	pca.tty = NULL;
320 	pca.flags = TOCONS | TOLOG;
321 	pca.pri = -1;
322 	retval = kvprintf(fmt, putchar, &pca, 10, ap);
323 	if (!panicstr)
324 		msgbuftrigger = 1;
325 	consintr = savintr;		/* reenable interrupts */
326 	return (retval);
327 }
328 
329 /*
330  * Print a character on console or users terminal.  If destination is
331  * the console then the last bunch of characters are saved in msgbuf for
332  * inspection later.
333  */
334 static void
335 putchar(int c, void *arg)
336 {
337 	struct putchar_arg *ap = (struct putchar_arg*) arg;
338 	int flags = ap->flags;
339 	struct tty *tp = ap->tty;
340 	if (panicstr)
341 		constty = NULL;
342 	if ((flags & TOCONS) && tp == NULL && constty) {
343 		tp = constty;
344 		flags |= TOTTY;
345 	}
346 	if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
347 	    (flags & TOCONS) && tp == constty)
348 		constty = NULL;
349 	if ((flags & TOLOG))
350 		msglogchar(c, ap->pri);
351 	if ((flags & TOCONS) && constty == NULL && c != '\0')
352 		(*v_putc)(c);
353 }
354 
355 /*
356  * Scaled down version of sprintf(3).
357  */
358 int
359 sprintf(char *buf, const char *cfmt, ...)
360 {
361 	int retval;
362 	va_list ap;
363 
364 	va_start(ap, cfmt);
365 	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
366 	buf[retval] = '\0';
367 	va_end(ap);
368 	return (retval);
369 }
370 
371 /*
372  * Scaled down version of vsprintf(3).
373  */
374 int
375 vsprintf(char *buf, const char *cfmt, va_list ap)
376 {
377 	int retval;
378 
379 	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
380 	buf[retval] = '\0';
381 	return (retval);
382 }
383 
384 /*
385  * Scaled down version of snprintf(3).
386  */
387 int
388 snprintf(char *str, size_t size, const char *format, ...)
389 {
390 	int retval;
391 	va_list ap;
392 
393 	va_start(ap, format);
394 	retval = vsnprintf(str, size, format, ap);
395 	va_end(ap);
396 	return(retval);
397 }
398 
399 /*
400  * Scaled down version of vsnprintf(3).
401  */
402 int
403 vsnprintf(char *str, size_t size, const char *format, va_list ap)
404 {
405 	struct snprintf_arg info;
406 	int retval;
407 
408 	info.str = str;
409 	info.remain = size;
410 	retval = kvprintf(format, snprintf_func, &info, 10, ap);
411 	if (info.remain >= 1)
412 		*info.str++ = '\0';
413 	return (retval);
414 }
415 
416 /*
417  * Kernel version which takes radix argument vsnprintf(3).
418  */
419 int
420 vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
421 {
422 	struct snprintf_arg info;
423 	int retval;
424 
425 	info.str = str;
426 	info.remain = size;
427 	retval = kvprintf(format, snprintf_func, &info, radix, ap);
428 	if (info.remain >= 1)
429 		*info.str++ = '\0';
430 	return (retval);
431 }
432 
433 static void
434 snprintf_func(int ch, void *arg)
435 {
436 	struct snprintf_arg *const info = arg;
437 
438 	if (info->remain >= 2) {
439 		*info->str++ = ch;
440 		info->remain--;
441 	}
442 }
443 
444 /*
445  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
446  * order; return an optional length and a pointer to the last character
447  * written in the buffer (i.e., the first character of the string).
448  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
449  */
450 static char *
451 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp)
452 {
453 	char *p;
454 
455 	p = nbuf;
456 	*p = '\0';
457 	do {
458 		*++p = hex2ascii(num % base);
459 	} while (num /= base);
460 	if (lenp)
461 		*lenp = p - nbuf;
462 	return (p);
463 }
464 
465 /*
466  * Scaled down version of printf(3).
467  *
468  * Two additional formats:
469  *
470  * The format %b is supported to decode error registers.
471  * Its usage is:
472  *
473  *	printf("reg=%b\n", regval, "<base><arg>*");
474  *
475  * where <base> is the output base expressed as a control character, e.g.
476  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
477  * the first of which gives the bit number to be inspected (origin 1), and
478  * the next characters (up to a control character, i.e. a character <= 32),
479  * give the name of the register.  Thus:
480  *
481  *	kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
482  *
483  * would produce output:
484  *
485  *	reg=3<BITTWO,BITONE>
486  *
487  * XXX:  %D  -- Hexdump, takes pointer and separator string:
488  *		("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
489  *		("%*D", len, ptr, " " -> XX XX XX XX ...
490  */
491 int
492 kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
493 {
494 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
495 	char nbuf[MAXNBUF];
496 	char *d;
497 	const char *p, *percent, *q;
498 	u_char *up;
499 	int ch, n;
500 	uintmax_t num;
501 	int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
502 	int jflag, tflag, zflag;
503 	int dwidth;
504 	char padc;
505 	int retval = 0;
506 
507 	num = 0;
508 	if (!func)
509 		d = (char *) arg;
510 	else
511 		d = NULL;
512 
513 	if (fmt == NULL)
514 		fmt = "(fmt null)\n";
515 
516 	if (radix < 2 || radix > 36)
517 		radix = 10;
518 
519 	for (;;) {
520 		padc = ' ';
521 		width = 0;
522 		while ((ch = (u_char)*fmt++) != '%') {
523 			if (ch == '\0')
524 				return (retval);
525 			PCHAR(ch);
526 		}
527 		percent = fmt - 1;
528 		qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
529 		sign = 0; dot = 0; dwidth = 0;
530 		jflag = 0; tflag = 0; zflag = 0;
531 reswitch:	switch (ch = (u_char)*fmt++) {
532 		case '.':
533 			dot = 1;
534 			goto reswitch;
535 		case '#':
536 			sharpflag = 1;
537 			goto reswitch;
538 		case '+':
539 			sign = 1;
540 			goto reswitch;
541 		case '-':
542 			ladjust = 1;
543 			goto reswitch;
544 		case '%':
545 			PCHAR(ch);
546 			break;
547 		case '*':
548 			if (!dot) {
549 				width = va_arg(ap, int);
550 				if (width < 0) {
551 					ladjust = !ladjust;
552 					width = -width;
553 				}
554 			} else {
555 				dwidth = va_arg(ap, int);
556 			}
557 			goto reswitch;
558 		case '0':
559 			if (!dot) {
560 				padc = '0';
561 				goto reswitch;
562 			}
563 		case '1': case '2': case '3': case '4':
564 		case '5': case '6': case '7': case '8': case '9':
565 				for (n = 0;; ++fmt) {
566 					n = n * 10 + ch - '0';
567 					ch = *fmt;
568 					if (ch < '0' || ch > '9')
569 						break;
570 				}
571 			if (dot)
572 				dwidth = n;
573 			else
574 				width = n;
575 			goto reswitch;
576 		case 'b':
577 			num = (u_int)va_arg(ap, int);
578 			p = va_arg(ap, char *);
579 			for (q = ksprintn(nbuf, num, *p++, NULL); *q;)
580 				PCHAR(*q--);
581 
582 			if (num == 0)
583 				break;
584 
585 			for (tmp = 0; *p;) {
586 				n = *p++;
587 				if (num & (1 << (n - 1))) {
588 					PCHAR(tmp ? ',' : '<');
589 					for (; (n = *p) > ' '; ++p)
590 						PCHAR(n);
591 					tmp = 1;
592 				} else
593 					for (; *p > ' '; ++p)
594 						continue;
595 			}
596 			if (tmp)
597 				PCHAR('>');
598 			break;
599 		case 'c':
600 			PCHAR(va_arg(ap, int));
601 			break;
602 		case 'D':
603 			up = va_arg(ap, u_char *);
604 			p = va_arg(ap, char *);
605 			if (!width)
606 				width = 16;
607 			while(width--) {
608 				PCHAR(hex2ascii(*up >> 4));
609 				PCHAR(hex2ascii(*up & 0x0f));
610 				up++;
611 				if (width)
612 					for (q=p;*q;q++)
613 						PCHAR(*q);
614 			}
615 			break;
616 		case 'd':
617 		case 'i':
618 			base = 10;
619 			sign = 1;
620 			goto handle_sign;
621 		case 'j':
622 			jflag = 1;
623 			goto reswitch;
624 		case 'l':
625 			if (lflag) {
626 				lflag = 0;
627 				qflag = 1;
628 			} else
629 				lflag = 1;
630 			goto reswitch;
631 		case 'n':
632 			if (jflag)
633 				*(va_arg(ap, intmax_t *)) = retval;
634 			else if (qflag)
635 				*(va_arg(ap, quad_t *)) = retval;
636 			else if (lflag)
637 				*(va_arg(ap, long *)) = retval;
638 			else if (zflag)
639 				*(va_arg(ap, size_t *)) = retval;
640 			else
641 				*(va_arg(ap, int *)) = retval;
642 			break;
643 		case 'o':
644 			base = 8;
645 			goto handle_nosign;
646 		case 'p':
647 			base = 16;
648 			sharpflag = (width == 0);
649 			sign = 0;
650 			num = (uintptr_t)va_arg(ap, void *);
651 			goto number;
652 		case 'q':
653 			qflag = 1;
654 			goto reswitch;
655 		case 'r':
656 			base = radix;
657 			if (sign)
658 				goto handle_sign;
659 			goto handle_nosign;
660 		case 's':
661 			p = va_arg(ap, char *);
662 			if (p == NULL)
663 				p = "(null)";
664 			if (!dot)
665 				n = strlen (p);
666 			else
667 				for (n = 0; n < dwidth && p[n]; n++)
668 					continue;
669 
670 			width -= n;
671 
672 			if (!ladjust && width > 0)
673 				while (width--)
674 					PCHAR(padc);
675 			while (n--)
676 				PCHAR(*p++);
677 			if (ladjust && width > 0)
678 				while (width--)
679 					PCHAR(padc);
680 			break;
681 		case 't':
682 			tflag = 1;
683 			goto reswitch;
684 		case 'u':
685 			base = 10;
686 			goto handle_nosign;
687 		case 'x':
688 		case 'X':
689 			base = 16;
690 			goto handle_nosign;
691 		case 'y':
692 			base = 16;
693 			sign = 1;
694 			goto handle_sign;
695 		case 'z':
696 			zflag = 1;
697 			goto reswitch;
698 handle_nosign:
699 			sign = 0;
700 			if (jflag)
701 				num = va_arg(ap, uintmax_t);
702 			else if (qflag)
703 				num = va_arg(ap, u_quad_t);
704 			else if (tflag)
705 				num = va_arg(ap, ptrdiff_t);
706 			else if (lflag)
707 				num = va_arg(ap, u_long);
708 			else if (zflag)
709 				num = va_arg(ap, size_t);
710 			else
711 				num = va_arg(ap, u_int);
712 			goto number;
713 handle_sign:
714 			if (jflag)
715 				num = va_arg(ap, intmax_t);
716 			else if (qflag)
717 				num = va_arg(ap, quad_t);
718 			else if (tflag)
719 				num = va_arg(ap, ptrdiff_t);
720 			else if (lflag)
721 				num = va_arg(ap, long);
722 			else if (zflag)
723 				num = va_arg(ap, size_t);
724 			else
725 				num = va_arg(ap, int);
726 number:
727 			if (sign && (intmax_t)num < 0) {
728 				neg = 1;
729 				num = -(intmax_t)num;
730 			}
731 			p = ksprintn(nbuf, num, base, &tmp);
732 			if (sharpflag && num != 0) {
733 				if (base == 8)
734 					tmp++;
735 				else if (base == 16)
736 					tmp += 2;
737 			}
738 			if (neg)
739 				tmp++;
740 
741 			if (!ladjust && width && (width -= tmp) > 0)
742 				while (width--)
743 					PCHAR(padc);
744 			if (neg)
745 				PCHAR('-');
746 			if (sharpflag && num != 0) {
747 				if (base == 8) {
748 					PCHAR('0');
749 				} else if (base == 16) {
750 					PCHAR('0');
751 					PCHAR('x');
752 				}
753 			}
754 
755 			while (*p)
756 				PCHAR(*p--);
757 
758 			if (ladjust && width && (width -= tmp) > 0)
759 				while (width--)
760 					PCHAR(padc);
761 
762 			break;
763 		default:
764 			while (percent < fmt)
765 				PCHAR(*percent++);
766 			break;
767 		}
768 	}
769 #undef PCHAR
770 }
771 
772 /*
773  * Put character in log buffer with a particular priority.
774  */
775 static void
776 msglogchar(int c, int pri)
777 {
778 	static int lastpri = -1;
779 	static int dangling;
780 	char nbuf[MAXNBUF];
781 	char *p;
782 
783 	if (!msgbufmapped)
784 		return;
785 	if (c == '\0' || c == '\r')
786 		return;
787 	if (pri != -1 && pri != lastpri) {
788 		if (dangling) {
789 			msgaddchar('\n', NULL);
790 			dangling = 0;
791 		}
792 		msgaddchar('<', NULL);
793 		for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL); *p;)
794 			msgaddchar(*p--, NULL);
795 		msgaddchar('>', NULL);
796 		lastpri = pri;
797 	}
798 	msgaddchar(c, NULL);
799 	if (c == '\n') {
800 		dangling = 0;
801 		lastpri = -1;
802 	} else {
803 		dangling = 1;
804 	}
805 }
806 
807 /*
808  * Put char in log buffer
809  */
810 static void
811 msgaddchar(int c, void *dummy)
812 {
813 	struct msgbuf *mbp;
814 
815 	if (!msgbufmapped)
816 		return;
817 	mbp = msgbufp;
818 	mbp->msg_cksum += (u_char)c - (u_char)mbp->msg_ptr[mbp->msg_bufx];
819 	mbp->msg_ptr[mbp->msg_bufx++] = c;
820 	if (mbp->msg_bufx >= mbp->msg_size)
821 		mbp->msg_bufx = 0;
822 	/* If the buffer is full, keep the most recent data. */
823 	if (mbp->msg_bufr == mbp->msg_bufx) {
824 		if (++mbp->msg_bufr >= mbp->msg_size)
825 			mbp->msg_bufr = 0;
826 	}
827 }
828 
829 static void
830 msgbufcopy(struct msgbuf *oldp)
831 {
832 	int pos;
833 
834 	pos = oldp->msg_bufr;
835 	while (pos != oldp->msg_bufx) {
836 		msglogchar(oldp->msg_ptr[pos], -1);
837 		if (++pos >= oldp->msg_size)
838 			pos = 0;
839 	}
840 }
841 
842 void
843 msgbufinit(void *ptr, int size)
844 {
845 	char *cp;
846 	static struct msgbuf *oldp = NULL;
847 
848 	size -= sizeof(*msgbufp);
849 	cp = (char *)ptr;
850 	msgbufp = (struct msgbuf *) (cp + size);
851 	if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
852 	    msgbufp->msg_bufx >= size || msgbufp->msg_bufx < 0 ||
853 	    msgbufp->msg_bufr >= size || msgbufp->msg_bufr < 0 ||
854 	    msgbufcksum(cp, size, msgbufp->msg_cksum) != msgbufp->msg_cksum) {
855 		bzero(cp, size);
856 		bzero(msgbufp, sizeof(*msgbufp));
857 		msgbufp->msg_magic = MSG_MAGIC;
858 		msgbufp->msg_size = size;
859 	}
860 	msgbufp->msg_ptr = cp;
861 	if (msgbufmapped && oldp != msgbufp)
862 		msgbufcopy(oldp);
863 	msgbufmapped = 1;
864 	oldp = msgbufp;
865 }
866 
867 static u_int
868 msgbufcksum(char *cp, size_t size, u_int cksum)
869 {
870 	u_int sum;
871 	int i;
872 
873 	sum = 0;
874 	for (i = 0; i < size; i++)
875 		sum += (u_char)cp[i];
876 	if (sum != cksum)
877 		printf("msgbuf cksum mismatch (read %x, calc %x)\n", cksum,
878 		    sum);
879 
880 	return (sum);
881 }
882 
883 SYSCTL_DECL(_security_bsd);
884 
885 static int unprivileged_read_msgbuf = 1;
886 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_read_msgbuf,
887     CTLFLAG_RW, &unprivileged_read_msgbuf, 0,
888     "Unprivileged processes may read the kernel message buffer");
889 
890 /* Sysctls for accessing/clearing the msgbuf */
891 static int
892 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
893 {
894 	int error;
895 
896 	if (!unprivileged_read_msgbuf) {
897 		error = suser(req->td);
898 		if (error)
899 			return (error);
900 	}
901 
902 	/*
903 	 * Unwind the buffer, so that it's linear (possibly starting with
904 	 * some initial nulls).
905 	 */
906 	error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
907 	    msgbufp->msg_size - msgbufp->msg_bufx, req);
908 	if (error)
909 		return (error);
910 	if (msgbufp->msg_bufx > 0) {
911 		error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
912 		    msgbufp->msg_bufx, req);
913 	}
914 	return (error);
915 }
916 
917 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
918     0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
919 
920 static int msgbuf_clear;
921 
922 static int
923 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
924 {
925 	int error;
926 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
927 	if (!error && req->newptr) {
928 		/* Clear the buffer and reset write pointer */
929 		bzero(msgbufp->msg_ptr, msgbufp->msg_size);
930 		msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
931 		msgbufp->msg_cksum = 0;
932 		msgbuf_clear = 0;
933 	}
934 	return (error);
935 }
936 
937 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
938     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
939     sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
940 
941 #ifdef DDB
942 
943 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
944 {
945 	int i, j;
946 
947 	if (!msgbufmapped) {
948 		db_printf("msgbuf not mapped yet\n");
949 		return;
950 	}
951 	db_printf("msgbufp = %p\n", msgbufp);
952 	db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p, cksum= %d\n",
953 	    msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
954 	    msgbufp->msg_bufx, msgbufp->msg_ptr, msgbufp->msg_cksum);
955 	for (i = 0; i < msgbufp->msg_size; i++) {
956 		j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
957 		db_printf("%c", msgbufp->msg_ptr[j]);
958 	}
959 	db_printf("\n");
960 }
961 
962 #endif /* DDB */
963