xref: /freebsd/sys/kern/subr_prf.c (revision 4b2eaea43fec8e8792be611dea204071a10b655a)
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/stdint.h>
55 #include <sys/sysctl.h>
56 #include <sys/tty.h>
57 #include <sys/syslog.h>
58 #include <sys/cons.h>
59 #include <sys/uio.h>
60 
61 #ifdef DDB
62 #include <ddb/ddb.h>
63 #endif
64 
65 /*
66  * Note that stdarg.h and the ANSI style va_start macro is used for both
67  * ANSI and traditional C compilers.
68  */
69 #include <machine/stdarg.h>
70 
71 #define TOCONS	0x01
72 #define TOTTY	0x02
73 #define TOLOG	0x04
74 
75 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
76 #define MAXNBUF	(sizeof(intmax_t) * NBBY + 1)
77 
78 struct putchar_arg {
79 	int	flags;
80 	int	pri;
81 	struct	tty *tty;
82 };
83 
84 struct snprintf_arg {
85 	char	*str;
86 	size_t	remain;
87 };
88 
89 extern	int log_open;
90 
91 struct	tty *constty;			/* pointer to console "window" tty */
92 
93 static void (*v_putc)(int) = cnputc;	/* routine to putc on virtual console */
94 static void  msglogchar(int c, int pri);
95 static void  msgaddchar(int c, void *dummy);
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, shld = 0;
165 	va_list ap;
166 	struct putchar_arg pca;
167 	int retval;
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_LOCK(p->p_session);
175 			SESSHOLD(p->p_session);
176 			tp = p->p_session->s_ttyp;
177 			SESS_UNLOCK(p->p_session);
178 			PROC_UNLOCK(p);
179 			shld++;
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 	retval = kvprintf(fmt, putchar, &pca, 10, ap);
192 	va_end(ap);
193 	if (shld) {
194 		PROC_LOCK(p);
195 		SESS_LOCK(p->p_session);
196 		SESSRELE(p->p_session);
197 		SESS_UNLOCK(p->p_session);
198 		PROC_UNLOCK(p);
199 	}
200 	msgbuftrigger = 1;
201 }
202 
203 /*
204  * Ttyprintf displays a message on a tty; it should be used only by
205  * the tty driver, or anything that knows the underlying tty will not
206  * be revoke(2)'d away.  Other callers should use tprintf.
207  */
208 int
209 ttyprintf(struct tty *tp, const char *fmt, ...)
210 {
211 	va_list ap;
212 	struct putchar_arg pca;
213 	int retval;
214 
215 	va_start(ap, fmt);
216 	pca.tty = tp;
217 	pca.flags = TOTTY;
218 	retval = kvprintf(fmt, putchar, &pca, 10, ap);
219 	va_end(ap);
220 	return (retval);
221 }
222 
223 /*
224  * Log writes to the log buffer, and guarantees not to sleep (so can be
225  * called by interrupt routines).  If there is no process reading the
226  * log yet, it writes to the console also.
227  */
228 void
229 log(int level, const char *fmt, ...)
230 {
231 	va_list ap;
232 	int retval;
233 	struct putchar_arg pca;
234 
235 	pca.tty = NULL;
236 	pca.pri = level;
237 	pca.flags = log_open ? TOLOG : TOCONS;
238 
239 	va_start(ap, fmt);
240 	retval = kvprintf(fmt, putchar, &pca, 10, ap);
241 	va_end(ap);
242 
243 	msgbuftrigger = 1;
244 }
245 
246 #define CONSCHUNK 128
247 
248 void
249 log_console(struct uio *uio)
250 {
251 	int c, i, error, iovlen, nl;
252 	struct uio muio;
253 	struct iovec *miov = NULL;
254 	char *consbuffer;
255 	int pri;
256 
257 	if (!log_console_output)
258 		return;
259 
260 	pri = LOG_INFO | LOG_CONSOLE;
261 	muio = *uio;
262 	iovlen = uio->uio_iovcnt * sizeof (struct iovec);
263 	MALLOC(miov, struct iovec *, iovlen, M_TEMP, 0);
264 	MALLOC(consbuffer, char *, CONSCHUNK, M_TEMP, 0);
265 	bcopy(muio.uio_iov, miov, iovlen);
266 	muio.uio_iov = miov;
267 	uio = &muio;
268 
269 	nl = 0;
270 	while (uio->uio_resid > 0) {
271 		c = imin(uio->uio_resid, CONSCHUNK);
272 		error = uiomove(consbuffer, c, uio);
273 		if (error != 0)
274 			break;
275 		for (i = 0; i < c; i++) {
276 			msglogchar(consbuffer[i], pri);
277 			if (consbuffer[i] == '\n')
278 				nl = 1;
279 			else
280 				nl = 0;
281 		}
282 	}
283 	if (!nl)
284 		msglogchar('\n', pri);
285 	msgbuftrigger = 1;
286 	FREE(miov, M_TEMP);
287 	FREE(consbuffer, M_TEMP);
288 	return;
289 }
290 
291 int
292 printf(const char *fmt, ...)
293 {
294 	va_list ap;
295 	int savintr;
296 	struct putchar_arg pca;
297 	int retval;
298 
299 	savintr = consintr;		/* disable interrupts */
300 	consintr = 0;
301 	va_start(ap, fmt);
302 	pca.tty = NULL;
303 	pca.flags = TOCONS | TOLOG;
304 	pca.pri = -1;
305 	retval = kvprintf(fmt, putchar, &pca, 10, ap);
306 	va_end(ap);
307 	if (!panicstr)
308 		msgbuftrigger = 1;
309 	consintr = savintr;		/* reenable interrupts */
310 	return (retval);
311 }
312 
313 int
314 vprintf(const char *fmt, va_list ap)
315 {
316 	int savintr;
317 	struct putchar_arg pca;
318 	int retval;
319 
320 	savintr = consintr;		/* disable interrupts */
321 	consintr = 0;
322 	pca.tty = NULL;
323 	pca.flags = TOCONS | TOLOG;
324 	pca.pri = -1;
325 	retval = kvprintf(fmt, putchar, &pca, 10, ap);
326 	if (!panicstr)
327 		msgbuftrigger = 1;
328 	consintr = savintr;		/* reenable interrupts */
329 	return (retval);
330 }
331 
332 /*
333  * Print a character on console or users terminal.  If destination is
334  * the console then the last bunch of characters are saved in msgbuf for
335  * inspection later.
336  */
337 static void
338 putchar(int c, void *arg)
339 {
340 	struct putchar_arg *ap = (struct putchar_arg*) arg;
341 	int flags = ap->flags;
342 	struct tty *tp = ap->tty;
343 	if (panicstr)
344 		constty = NULL;
345 	if ((flags & TOCONS) && tp == NULL && constty) {
346 		tp = constty;
347 		flags |= TOTTY;
348 	}
349 	if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
350 	    (flags & TOCONS) && tp == constty)
351 		constty = NULL;
352 	if ((flags & TOLOG))
353 		msglogchar(c, ap->pri);
354 	if ((flags & TOCONS) && constty == NULL && c != '\0')
355 		(*v_putc)(c);
356 }
357 
358 /*
359  * Scaled down version of sprintf(3).
360  */
361 int
362 sprintf(char *buf, const char *cfmt, ...)
363 {
364 	int retval;
365 	va_list ap;
366 
367 	va_start(ap, cfmt);
368 	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
369 	buf[retval] = '\0';
370 	va_end(ap);
371 	return (retval);
372 }
373 
374 /*
375  * Scaled down version of vsprintf(3).
376  */
377 int
378 vsprintf(char *buf, const char *cfmt, va_list ap)
379 {
380 	int retval;
381 
382 	retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
383 	buf[retval] = '\0';
384 	return (retval);
385 }
386 
387 /*
388  * Scaled down version of snprintf(3).
389  */
390 int
391 snprintf(char *str, size_t size, const char *format, ...)
392 {
393 	int retval;
394 	va_list ap;
395 
396 	va_start(ap, format);
397 	retval = vsnprintf(str, size, format, ap);
398 	va_end(ap);
399 	return(retval);
400 }
401 
402 /*
403  * Scaled down version of vsnprintf(3).
404  */
405 int
406 vsnprintf(char *str, size_t size, const char *format, va_list ap)
407 {
408 	struct snprintf_arg info;
409 	int retval;
410 
411 	info.str = str;
412 	info.remain = size;
413 	retval = kvprintf(format, snprintf_func, &info, 10, ap);
414 	if (info.remain >= 1)
415 		*info.str++ = '\0';
416 	return (retval);
417 }
418 
419 static void
420 snprintf_func(int ch, void *arg)
421 {
422 	struct snprintf_arg *const info = arg;
423 
424 	if (info->remain >= 2) {
425 		*info->str++ = ch;
426 		info->remain--;
427 	}
428 }
429 
430 /*
431  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
432  * order; return an optional length and a pointer to the last character
433  * written in the buffer (i.e., the first character of the string).
434  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
435  */
436 static char *
437 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp)
438 {
439 	char *p;
440 
441 	p = nbuf;
442 	*p = '\0';
443 	do {
444 		*++p = hex2ascii(num % base);
445 	} while (num /= base);
446 	if (lenp)
447 		*lenp = p - nbuf;
448 	return (p);
449 }
450 
451 /*
452  * Scaled down version of printf(3).
453  *
454  * Two additional formats:
455  *
456  * The format %b is supported to decode error registers.
457  * Its usage is:
458  *
459  *	printf("reg=%b\n", regval, "<base><arg>*");
460  *
461  * where <base> is the output base expressed as a control character, e.g.
462  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
463  * the first of which gives the bit number to be inspected (origin 1), and
464  * the next characters (up to a control character, i.e. a character <= 32),
465  * give the name of the register.  Thus:
466  *
467  *	kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
468  *
469  * would produce output:
470  *
471  *	reg=3<BITTWO,BITONE>
472  *
473  * XXX:  %D  -- Hexdump, takes pointer and separator string:
474  *		("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
475  *		("%*D", len, ptr, " " -> XX XX XX XX ...
476  */
477 int
478 kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
479 {
480 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
481 	char nbuf[MAXNBUF];
482 	char *d;
483 	const char *p, *percent, *q;
484 	u_char *up;
485 	int ch, n;
486 	uintmax_t num;
487 	int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
488 	int jflag, tflag, zflag;
489 	int dwidth;
490 	char padc;
491 	int retval = 0;
492 
493 	num = 0;
494 	if (!func)
495 		d = (char *) arg;
496 	else
497 		d = NULL;
498 
499 	if (fmt == NULL)
500 		fmt = "(fmt null)\n";
501 
502 	if (radix < 2 || radix > 36)
503 		radix = 10;
504 
505 	for (;;) {
506 		padc = ' ';
507 		width = 0;
508 		while ((ch = (u_char)*fmt++) != '%') {
509 			if (ch == '\0')
510 				return (retval);
511 			PCHAR(ch);
512 		}
513 		percent = fmt - 1;
514 		qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
515 		sign = 0; dot = 0; dwidth = 0;
516 		jflag = 0; tflag = 0; zflag = 0;
517 reswitch:	switch (ch = (u_char)*fmt++) {
518 		case '.':
519 			dot = 1;
520 			goto reswitch;
521 		case '#':
522 			sharpflag = 1;
523 			goto reswitch;
524 		case '+':
525 			sign = 1;
526 			goto reswitch;
527 		case '-':
528 			ladjust = 1;
529 			goto reswitch;
530 		case '%':
531 			PCHAR(ch);
532 			break;
533 		case '*':
534 			if (!dot) {
535 				width = va_arg(ap, int);
536 				if (width < 0) {
537 					ladjust = !ladjust;
538 					width = -width;
539 				}
540 			} else {
541 				dwidth = va_arg(ap, int);
542 			}
543 			goto reswitch;
544 		case '0':
545 			if (!dot) {
546 				padc = '0';
547 				goto reswitch;
548 			}
549 		case '1': case '2': case '3': case '4':
550 		case '5': case '6': case '7': case '8': case '9':
551 				for (n = 0;; ++fmt) {
552 					n = n * 10 + ch - '0';
553 					ch = *fmt;
554 					if (ch < '0' || ch > '9')
555 						break;
556 				}
557 			if (dot)
558 				dwidth = n;
559 			else
560 				width = n;
561 			goto reswitch;
562 		case 'b':
563 			num = (u_int)va_arg(ap, int);
564 			p = va_arg(ap, char *);
565 			for (q = ksprintn(nbuf, num, *p++, NULL); *q;)
566 				PCHAR(*q--);
567 
568 			if (num == 0)
569 				break;
570 
571 			for (tmp = 0; *p;) {
572 				n = *p++;
573 				if (num & (1 << (n - 1))) {
574 					PCHAR(tmp ? ',' : '<');
575 					for (; (n = *p) > ' '; ++p)
576 						PCHAR(n);
577 					tmp = 1;
578 				} else
579 					for (; *p > ' '; ++p)
580 						continue;
581 			}
582 			if (tmp)
583 				PCHAR('>');
584 			break;
585 		case 'c':
586 			PCHAR(va_arg(ap, int));
587 			break;
588 		case 'D':
589 			up = va_arg(ap, u_char *);
590 			p = va_arg(ap, char *);
591 			if (!width)
592 				width = 16;
593 			while(width--) {
594 				PCHAR(hex2ascii(*up >> 4));
595 				PCHAR(hex2ascii(*up & 0x0f));
596 				up++;
597 				if (width)
598 					for (q=p;*q;q++)
599 						PCHAR(*q);
600 			}
601 			break;
602 		case 'd':
603 		case 'i':
604 			base = 10;
605 			sign = 1;
606 			goto handle_sign;
607 		case 'j':
608 			jflag = 1;
609 			goto reswitch;
610 		case 'l':
611 			if (lflag) {
612 				lflag = 0;
613 				qflag = 1;
614 			} else
615 				lflag = 1;
616 			goto reswitch;
617 		case 'n':
618 			if (jflag)
619 				*(va_arg(ap, intmax_t *)) = retval;
620 			else if (qflag)
621 				*(va_arg(ap, quad_t *)) = retval;
622 			else if (lflag)
623 				*(va_arg(ap, long *)) = retval;
624 			else if (zflag)
625 				*(va_arg(ap, size_t *)) = retval;
626 			else
627 				*(va_arg(ap, int *)) = retval;
628 			break;
629 		case 'o':
630 			base = 8;
631 			goto handle_nosign;
632 		case 'p':
633 			base = 16;
634 			sharpflag = (width == 0);
635 			sign = 0;
636 			num = (uintptr_t)va_arg(ap, void *);
637 			goto number;
638 		case 'q':
639 			qflag = 1;
640 			goto reswitch;
641 		case 'r':
642 			base = radix;
643 			if (sign)
644 				goto handle_sign;
645 			goto handle_nosign;
646 		case 's':
647 			p = va_arg(ap, char *);
648 			if (p == NULL)
649 				p = "(null)";
650 			if (!dot)
651 				n = strlen (p);
652 			else
653 				for (n = 0; n < dwidth && p[n]; n++)
654 					continue;
655 
656 			width -= n;
657 
658 			if (!ladjust && width > 0)
659 				while (width--)
660 					PCHAR(padc);
661 			while (n--)
662 				PCHAR(*p++);
663 			if (ladjust && width > 0)
664 				while (width--)
665 					PCHAR(padc);
666 			break;
667 		case 't':
668 			tflag = 1;
669 			goto reswitch;
670 			break;
671 		case 'u':
672 			base = 10;
673 			goto handle_nosign;
674 		case 'x':
675 		case 'X':
676 			base = 16;
677 			goto handle_nosign;
678 		case 'y':
679 			base = 16;
680 			sign = 1;
681 			goto handle_sign;
682 		case 'z':
683 			zflag = 1;
684 			goto reswitch;
685 handle_nosign:
686 			sign = 0;
687 			if (jflag)
688 				num = va_arg(ap, uintmax_t);
689 			else if (qflag)
690 				num = va_arg(ap, u_quad_t);
691 			else if (tflag)
692 				num = va_arg(ap, ptrdiff_t);
693 			else if (lflag)
694 				num = va_arg(ap, u_long);
695 			else if (zflag)
696 				num = va_arg(ap, size_t);
697 			else
698 				num = va_arg(ap, u_int);
699 			goto number;
700 handle_sign:
701 			if (jflag)
702 				num = va_arg(ap, intmax_t);
703 			else if (qflag)
704 				num = va_arg(ap, quad_t);
705 			else if (tflag)
706 				num = va_arg(ap, ptrdiff_t);
707 			else if (lflag)
708 				num = va_arg(ap, long);
709 			else if (zflag)
710 				num = va_arg(ap, size_t);
711 			else
712 				num = va_arg(ap, int);
713 number:
714 			if (sign && (intmax_t)num < 0) {
715 				neg = 1;
716 				num = -(intmax_t)num;
717 			}
718 			p = ksprintn(nbuf, num, base, &tmp);
719 			if (sharpflag && num != 0) {
720 				if (base == 8)
721 					tmp++;
722 				else if (base == 16)
723 					tmp += 2;
724 			}
725 			if (neg)
726 				tmp++;
727 
728 			if (!ladjust && width && (width -= tmp) > 0)
729 				while (width--)
730 					PCHAR(padc);
731 			if (neg)
732 				PCHAR('-');
733 			if (sharpflag && num != 0) {
734 				if (base == 8) {
735 					PCHAR('0');
736 				} else if (base == 16) {
737 					PCHAR('0');
738 					PCHAR('x');
739 				}
740 			}
741 
742 			while (*p)
743 				PCHAR(*p--);
744 
745 			if (ladjust && width && (width -= tmp) > 0)
746 				while (width--)
747 					PCHAR(padc);
748 
749 			break;
750 		default:
751 			while (percent < fmt)
752 				PCHAR(*percent++);
753 			break;
754 		}
755 	}
756 #undef PCHAR
757 }
758 
759 /*
760  * Put character in log buffer with a particular priority.
761  */
762 static void
763 msglogchar(int c, int pri)
764 {
765 	static int lastpri = -1;
766 	static int dangling;
767 	char nbuf[MAXNBUF];
768 	char *p;
769 
770 	if (!msgbufmapped)
771 		return;
772 	if (c == '\0' || c == '\r')
773 		return;
774 	if (pri != -1 && pri != lastpri) {
775 		if (dangling) {
776 			msgaddchar('\n', NULL);
777 			dangling = 0;
778 		}
779 		msgaddchar('<', NULL);
780 		for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL); *p;)
781 			msgaddchar(*p--, NULL);
782 		msgaddchar('>', NULL);
783 		lastpri = pri;
784 	}
785 	msgaddchar(c, NULL);
786 	if (c == '\n') {
787 		dangling = 0;
788 		lastpri = -1;
789 	} else {
790 		dangling = 1;
791 	}
792 }
793 
794 /*
795  * Put char in log buffer
796  */
797 static void
798 msgaddchar(int c, void *dummy)
799 {
800 	struct msgbuf *mbp;
801 
802 	if (!msgbufmapped)
803 		return;
804 	mbp = msgbufp;
805 	mbp->msg_ptr[mbp->msg_bufx++] = c;
806 	if (mbp->msg_bufx >= mbp->msg_size)
807 		mbp->msg_bufx = 0;
808 	/* If the buffer is full, keep the most recent data. */
809 	if (mbp->msg_bufr == mbp->msg_bufx) {
810 		if (++mbp->msg_bufr >= mbp->msg_size)
811 			mbp->msg_bufr = 0;
812 	}
813 }
814 
815 static void
816 msgbufcopy(struct msgbuf *oldp)
817 {
818 	int pos;
819 
820 	pos = oldp->msg_bufr;
821 	while (pos != oldp->msg_bufx) {
822 		msglogchar(oldp->msg_ptr[pos], -1);
823 		if (++pos >= oldp->msg_size)
824 			pos = 0;
825 	}
826 }
827 
828 void
829 msgbufinit(void *ptr, int size)
830 {
831 	char *cp;
832 	static struct msgbuf *oldp = NULL;
833 
834 	size -= sizeof(*msgbufp);
835 	cp = (char *)ptr;
836 	msgbufp = (struct msgbuf *) (cp + size);
837 	if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
838 	    msgbufp->msg_bufx >= size || msgbufp->msg_bufx < 0 ||
839 	    msgbufp->msg_bufr >= size || msgbufp->msg_bufr < 0) {
840 		bzero(cp, size);
841 		bzero(msgbufp, sizeof(*msgbufp));
842 		msgbufp->msg_magic = MSG_MAGIC;
843 		msgbufp->msg_size = (char *)msgbufp - cp;
844 	}
845 	msgbufp->msg_ptr = cp;
846 	if (msgbufmapped && oldp != msgbufp)
847 		msgbufcopy(oldp);
848 	msgbufmapped = 1;
849 	oldp = msgbufp;
850 }
851 
852 SYSCTL_DECL(_security_bsd);
853 
854 static int unprivileged_read_msgbuf = 1;
855 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_read_msgbuf,
856     CTLFLAG_RW, &unprivileged_read_msgbuf, 0,
857     "Unprivileged processes may read the kernel message buffer");
858 
859 /* Sysctls for accessing/clearing the msgbuf */
860 static int
861 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
862 {
863 	int error;
864 
865 	if (!unprivileged_read_msgbuf) {
866 		error = suser(req->td);
867 		if (error)
868 			return (error);
869 	}
870 
871 	/*
872 	 * Unwind the buffer, so that it's linear (possibly starting with
873 	 * some initial nulls).
874 	 */
875 	error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
876 	    msgbufp->msg_size - msgbufp->msg_bufx, req);
877 	if (error)
878 		return (error);
879 	if (msgbufp->msg_bufx > 0) {
880 		error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
881 		    msgbufp->msg_bufx, req);
882 	}
883 	return (error);
884 }
885 
886 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
887     0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
888 
889 static int msgbuf_clear;
890 
891 static int
892 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
893 {
894 	int error;
895 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
896 	if (!error && req->newptr) {
897 		/* Clear the buffer and reset write pointer */
898 		bzero(msgbufp->msg_ptr, msgbufp->msg_size);
899 		msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
900 		msgbuf_clear = 0;
901 	}
902 	return (error);
903 }
904 
905 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
906     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
907     sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
908 
909 #ifdef DDB
910 
911 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
912 {
913 	int i, j;
914 
915 	if (!msgbufmapped) {
916 		db_printf("msgbuf not mapped yet\n");
917 		return;
918 	}
919 	db_printf("msgbufp = %p\n", msgbufp);
920 	db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
921 	    msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
922 	    msgbufp->msg_bufx, msgbufp->msg_ptr);
923 	for (i = 0; i < msgbufp->msg_size; i++) {
924 		j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
925 		db_printf("%c", msgbufp->msg_ptr[j]);
926 	}
927 	db_printf("\n");
928 }
929 
930 #endif /* DDB */
931