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