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