xref: /dragonfly/sys/kern/subr_prf.c (revision 956939d5)
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: src/sys/kern/subr_prf.c,v 1.61.2.5 2002/08/31 18:22:08 dwmalone Exp $
40  * $DragonFly: src/sys/kern/subr_prf.c,v 1.21 2008/07/17 23:56:23 dillon Exp $
41  */
42 
43 #include "opt_ddb.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/msgbuf.h>
49 #include <sys/malloc.h>
50 #include <sys/proc.h>
51 #include <sys/priv.h>
52 #include <sys/tty.h>
53 #include <sys/tprintf.h>
54 #include <sys/stdint.h>
55 #include <sys/syslog.h>
56 #include <sys/cons.h>
57 #include <sys/uio.h>
58 #include <sys/sysctl.h>
59 #include <sys/lock.h>
60 #include <sys/ctype.h>
61 
62 #ifdef DDB
63 #include <ddb/ddb.h>
64 #endif
65 
66 /*
67  * Note that stdarg.h and the ANSI style va_start macro is used for both
68  * ANSI and traditional C compilers.  We use the __ machine version to stay
69  * within the kernel header file set.
70  */
71 #include <machine/stdarg.h>
72 
73 #define TOCONS	0x01
74 #define TOTTY	0x02
75 #define TOLOG	0x04
76 
77 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
78 #define MAXNBUF	(sizeof(intmax_t) * NBBY + 1)
79 
80 struct putchar_arg {
81 	int	flags;
82 	int	pri;
83 	struct	tty *tty;
84 };
85 
86 struct snprintf_arg {
87 	char	*str;
88 	size_t	remain;
89 };
90 
91 extern	int log_open;
92 
93 struct	tty *constty;			/* pointer to console "window" tty */
94 
95 static void (*v_putc)(int) = cnputc;	/* routine to putc on virtual console */
96 static void  msglogchar(int c, int pri);
97 static void  msgaddchar(int c, void *dummy);
98 static void  kputchar (int ch, void *arg);
99 static char *ksprintn (char *nbuf, uintmax_t num, int base, int *lenp,
100 		       int upper);
101 static void  snprintf_func (int ch, void *arg);
102 
103 static int consintr = 1;		/* Ok to handle console interrupts? */
104 static int msgbufmapped;		/* Set when safe to use msgbuf */
105 int msgbuftrigger;
106 
107 static int      log_console_output = 1;
108 TUNABLE_INT("kern.log_console_output", &log_console_output);
109 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
110     &log_console_output, 0, "");
111 
112 static int unprivileged_read_msgbuf = 1;
113 SYSCTL_INT(_security, OID_AUTO, unprivileged_read_msgbuf, CTLFLAG_RW,
114     &unprivileged_read_msgbuf, 0,
115     "Unprivileged processes may read the kernel message buffer");
116 
117 /*
118  * Warn that a system table is full.
119  */
120 void
121 tablefull(const char *tab)
122 {
123 
124 	log(LOG_ERR, "%s: table is full\n", tab);
125 }
126 
127 /*
128  * Uprintf prints to the controlling terminal for the current process.
129  */
130 int
131 uprintf(const char *fmt, ...)
132 {
133 	struct proc *p = curproc;
134 	__va_list ap;
135 	struct putchar_arg pca;
136 	int retval = 0;
137 
138 	if (p && p->p_flag & P_CONTROLT &&
139 	    p->p_session->s_ttyvp) {
140 		__va_start(ap, fmt);
141 		pca.tty = p->p_session->s_ttyp;
142 		pca.flags = TOTTY;
143 
144 		retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
145 		__va_end(ap);
146 	}
147 	return (retval);
148 }
149 
150 tpr_t
151 tprintf_open(struct proc *p)
152 {
153 
154 	if ((p->p_flag & P_CONTROLT) && p->p_session->s_ttyvp) {
155 		sess_hold(p->p_session);
156 		return ((tpr_t) p->p_session);
157 	}
158 	return ((tpr_t) NULL);
159 }
160 
161 void
162 tprintf_close(tpr_t sess)
163 {
164 	if (sess)
165 		sess_rele((struct session *) sess);
166 }
167 
168 /*
169  * tprintf prints on the controlling terminal associated
170  * with the given session.
171  */
172 int
173 tprintf(tpr_t tpr, const char *fmt, ...)
174 {
175 	struct session *sess = (struct session *)tpr;
176 	struct tty *tp = NULL;
177 	int flags = TOLOG;
178 	__va_list ap;
179 	struct putchar_arg pca;
180 	int retval;
181 
182 	if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
183 		flags |= TOTTY;
184 		tp = sess->s_ttyp;
185 	}
186 	__va_start(ap, fmt);
187 	pca.tty = tp;
188 	pca.flags = flags;
189 	pca.pri = LOG_INFO;
190 	retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
191 	__va_end(ap);
192 	msgbuftrigger = 1;
193 	return (retval);
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 = kvcprintf(fmt, kputchar, &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 int
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 = kvcprintf(fmt, kputchar, &pca, 10, ap);
234 	__va_end(ap);
235 
236 	msgbuftrigger = 1;
237 	return (retval);
238 }
239 
240 #define CONSCHUNK 128
241 
242 void
243 log_console(struct uio *uio)
244 {
245 	int c, i, error, iovlen, nl;
246 	struct uio muio;
247 	struct iovec *miov = NULL;
248 	char *consbuffer;
249 	int pri;
250 
251 	if (!log_console_output)
252 		return;
253 
254 	pri = LOG_INFO | LOG_CONSOLE;
255 	muio = *uio;
256 	iovlen = uio->uio_iovcnt * sizeof (struct iovec);
257 	MALLOC(miov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
258 	MALLOC(consbuffer, char *, CONSCHUNK, M_TEMP, M_WAITOK);
259 	bcopy((caddr_t)muio.uio_iov, (caddr_t)miov, iovlen);
260 	muio.uio_iov = miov;
261 	uio = &muio;
262 
263 	nl = 0;
264 	while (uio->uio_resid > 0) {
265 		c = (int)szmin(uio->uio_resid, CONSCHUNK);
266 		error = uiomove(consbuffer, (size_t)c, uio);
267 		if (error != 0)
268 			break;
269 		for (i = 0; i < c; i++) {
270 			msglogchar(consbuffer[i], pri);
271 			if (consbuffer[i] == '\n')
272 				nl = 1;
273 			else
274 				nl = 0;
275 		}
276 	}
277 	if (!nl)
278 		msglogchar('\n', pri);
279 	msgbuftrigger = 1;
280 	FREE(miov, M_TEMP);
281 	FREE(consbuffer, M_TEMP);
282 	return;
283 }
284 
285 /*
286  * Output to the console.
287  *
288  * NOT YET ENTIRELY MPSAFE
289  */
290 int
291 kprintf(const char *fmt, ...)
292 {
293 	__va_list ap;
294 	int savintr;
295 	struct putchar_arg pca;
296 	int retval;
297 
298 	savintr = consintr;		/* disable interrupts */
299 	consintr = 0;
300 	__va_start(ap, fmt);
301 	pca.tty = NULL;
302 	pca.flags = TOCONS | TOLOG;
303 	pca.pri = -1;
304 	cons_lock();
305 	retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
306 	cons_unlock();
307 	__va_end(ap);
308 	if (!panicstr)
309 		msgbuftrigger = 1;
310 	consintr = savintr;		/* reenable interrupts */
311 	return (retval);
312 }
313 
314 int
315 kvprintf(const char *fmt, __va_list ap)
316 {
317 	int savintr;
318 	struct putchar_arg pca;
319 	int retval;
320 
321 	savintr = consintr;		/* disable interrupts */
322 	consintr = 0;
323 	pca.tty = NULL;
324 	pca.flags = TOCONS | TOLOG;
325 	pca.pri = -1;
326 	cons_lock();
327 	retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
328 	cons_unlock();
329 	if (!panicstr)
330 		msgbuftrigger = 1;
331 	consintr = savintr;		/* reenable interrupts */
332 	return (retval);
333 }
334 
335 /*
336  * Limited rate kprintf.  The passed rate structure must be initialized
337  * with the desired reporting frequency.  A frequency of 0 will result in
338  * no output.
339  *
340  * count may be initialized to a negative number to allow an initial
341  * burst.
342  */
343 void
344 krateprintf(struct krate *rate, const char *fmt, ...)
345 {
346 	__va_list ap;
347 
348 	if (rate->ticks != (int)time_second) {
349 		rate->ticks = (int)time_second;
350 		if (rate->count > 0)
351 			rate->count = 0;
352 	}
353 	if (rate->count < rate->freq) {
354 		++rate->count;
355 		__va_start(ap, fmt);
356 		kvprintf(fmt, ap);
357 		__va_end(ap);
358 	}
359 }
360 
361 /*
362  * Print a character on console or users terminal.  If destination is
363  * the console then the last bunch of characters are saved in msgbuf for
364  * inspection later.
365  *
366  * NOT YET ENTIRELY MPSAFE, EVEN WHEN LOGGING JUST TO THE SYSCONSOLE.
367  */
368 static void
369 kputchar(int c, void *arg)
370 {
371 	struct putchar_arg *ap = (struct putchar_arg*) arg;
372 	int flags = ap->flags;
373 	struct tty *tp = ap->tty;
374 	if (panicstr)
375 		constty = NULL;
376 	if ((flags & TOCONS) && tp == NULL && constty) {
377 		tp = constty;
378 		flags |= TOTTY;
379 	}
380 	if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
381 	    (flags & TOCONS) && tp == constty)
382 		constty = NULL;
383 	if ((flags & TOLOG))
384 		msglogchar(c, ap->pri);
385 	if ((flags & TOCONS) && constty == NULL && c != '\0')
386 		(*v_putc)(c);
387 }
388 
389 /*
390  * Scaled down version of sprintf(3).
391  */
392 int
393 ksprintf(char *buf, const char *cfmt, ...)
394 {
395 	int retval;
396 	__va_list ap;
397 
398 	__va_start(ap, cfmt);
399 	retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
400 	buf[retval] = '\0';
401 	__va_end(ap);
402 	return (retval);
403 }
404 
405 /*
406  * Scaled down version of vsprintf(3).
407  */
408 int
409 kvsprintf(char *buf, const char *cfmt, __va_list ap)
410 {
411 	int retval;
412 
413 	retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
414 	buf[retval] = '\0';
415 	return (retval);
416 }
417 
418 /*
419  * Scaled down version of snprintf(3).
420  */
421 int
422 ksnprintf(char *str, size_t size, const char *format, ...)
423 {
424 	int retval;
425 	__va_list ap;
426 
427 	__va_start(ap, format);
428 	retval = kvsnprintf(str, size, format, ap);
429 	__va_end(ap);
430 	return(retval);
431 }
432 
433 /*
434  * Scaled down version of vsnprintf(3).
435  */
436 int
437 kvsnprintf(char *str, size_t size, const char *format, __va_list ap)
438 {
439 	struct snprintf_arg info;
440 	int retval;
441 
442 	info.str = str;
443 	info.remain = size;
444 	retval = kvcprintf(format, snprintf_func, &info, 10, ap);
445 	if (info.remain >= 1)
446 		*info.str++ = '\0';
447 	return (retval);
448 }
449 
450 int
451 ksnrprintf(char *str, size_t size, int radix, const char *format, ...)
452 {
453 	int retval;
454 	__va_list ap;
455 
456 	__va_start(ap, format);
457 	retval = kvsnrprintf(str, size, radix, format, ap);
458 	__va_end(ap);
459 	return(retval);
460 }
461 
462 int
463 kvsnrprintf(char *str, size_t size, int radix, const char *format, __va_list ap)
464 {
465 	struct snprintf_arg info;
466 	int retval;
467 
468 	info.str = str;
469 	info.remain = size;
470 	retval = kvcprintf(format, snprintf_func, &info, radix, ap);
471 	if (info.remain >= 1)
472 		*info.str++ = '\0';
473 	return (retval);
474 }
475 
476 int
477 kvasnrprintf(char **strp, size_t size, int radix,
478 	     const char *format, __va_list ap)
479 {
480 	struct snprintf_arg info;
481 	int retval;
482 
483 	*strp = kmalloc(size, M_TEMP, M_WAITOK);
484 	info.str = *strp;
485 	info.remain = size;
486 	retval = kvcprintf(format, snprintf_func, &info, radix, ap);
487 	if (info.remain >= 1)
488 		*info.str++ = '\0';
489 	return (retval);
490 }
491 
492 void
493 kvasfree(char **strp)
494 {
495 	if (*strp) {
496 		kfree(*strp, M_TEMP);
497 		*strp = NULL;
498 	}
499 }
500 
501 static void
502 snprintf_func(int ch, void *arg)
503 {
504 	struct snprintf_arg *const info = arg;
505 
506 	if (info->remain >= 2) {
507 		*info->str++ = ch;
508 		info->remain--;
509 	}
510 }
511 
512 /*
513  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
514  * order; return an optional length and a pointer to the last character
515  * written in the buffer (i.e., the first character of the string).
516  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
517  */
518 static char *
519 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
520 {
521 	char *p, c;
522 
523 	p = nbuf;
524 	*p = '\0';
525 	do {
526 		c = hex2ascii(num % base);
527 		*++p = upper ? toupper(c) : c;
528 	} while (num /= base);
529 	if (lenp)
530 		*lenp = p - nbuf;
531 	return (p);
532 }
533 
534 /*
535  * Scaled down version of printf(3).
536  *
537  * Two additional formats:
538  *
539  * The format %b is supported to decode error registers.
540  * Its usage is:
541  *
542  *	kprintf("reg=%b\n", regval, "<base><arg>*");
543  *
544  * where <base> is the output base expressed as a control character, e.g.
545  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
546  * the first of which gives the bit number to be inspected (origin 1), and
547  * the next characters (up to a control character, i.e. a character <= 32),
548  * give the name of the register.  Thus:
549  *
550  *	kvcprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
551  *
552  * would produce output:
553  *
554  *	reg=3<BITTWO,BITONE>
555  *
556  * XXX:  %D  -- Hexdump, takes pointer and separator string:
557  *		("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
558  *		("%*D", len, ptr, " " -> XX XX XX XX ...
559  */
560 int
561 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, __va_list ap)
562 {
563 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
564 	char nbuf[MAXNBUF];
565 	char *d;
566 	const char *p, *percent, *q;
567 	u_char *up;
568 	int ch, n;
569 	uintmax_t num;
570 	int base, tmp, width, ladjust, sharpflag, neg, sign, dot;
571 	int jflag, lflag, qflag, tflag, zflag;
572 	int dwidth, upper;
573 	char padc;
574 	int retval = 0, stop = 0;
575 
576 	num = 0;
577 	if (!func)
578 		d = (char *) arg;
579 	else
580 		d = NULL;
581 
582 	if (fmt == NULL)
583 		fmt = "(fmt null)\n";
584 
585 	if (radix < 2 || radix > 36)
586 		radix = 10;
587 
588 	for (;;) {
589 		padc = ' ';
590 		width = 0;
591 		while ((ch = (u_char)*fmt++) != '%' || stop) {
592 			if (ch == '\0')
593 				return (retval);
594 			PCHAR(ch);
595 		}
596 		percent = fmt - 1;
597 		dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
598 		jflag = lflag = qflag = tflag = zflag = 0;
599 
600 reswitch:
601 		switch (ch = (u_char)*fmt++) {
602 		case '.':
603 			dot = 1;
604 			goto reswitch;
605 		case '#':
606 			sharpflag = 1;
607 			goto reswitch;
608 		case '+':
609 			sign = 1;
610 			goto reswitch;
611 		case '-':
612 			ladjust = 1;
613 			goto reswitch;
614 		case '%':
615 			PCHAR(ch);
616 			break;
617 		case '*':
618 			if (!dot) {
619 				width = __va_arg(ap, int);
620 				if (width < 0) {
621 					ladjust = !ladjust;
622 					width = -width;
623 				}
624 			} else {
625 				dwidth = __va_arg(ap, int);
626 			}
627 			goto reswitch;
628 		case '0':
629 			if (!dot) {
630 				padc = '0';
631 				goto reswitch;
632 			}
633 		case '1': case '2': case '3': case '4':
634 		case '5': case '6': case '7': case '8': case '9':
635 				for (n = 0;; ++fmt) {
636 					n = n * 10 + ch - '0';
637 					ch = *fmt;
638 					if (ch < '0' || ch > '9')
639 						break;
640 				}
641 			if (dot)
642 				dwidth = n;
643 			else
644 				width = n;
645 			goto reswitch;
646 		case 'b':
647 			num = (u_int)__va_arg(ap, int);
648 			p = __va_arg(ap, char *);
649 			for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
650 				PCHAR(*q--);
651 
652 			if (num == 0)
653 				break;
654 
655 			for (tmp = 0; *p;) {
656 				n = *p++;
657 				if (num & (1 << (n - 1))) {
658 					PCHAR(tmp ? ',' : '<');
659 					for (; (n = *p) > ' '; ++p)
660 						PCHAR(n);
661 					tmp = 1;
662 				} else
663 					for (; *p > ' '; ++p)
664 						continue;
665 			}
666 			if (tmp)
667 				PCHAR('>');
668 			break;
669 		case 'c':
670 			PCHAR(__va_arg(ap, int));
671 			break;
672 		case 'D':
673 			up = __va_arg(ap, u_char *);
674 			p = __va_arg(ap, char *);
675 			if (!width)
676 				width = 16;
677 			while(width--) {
678 				PCHAR(hex2ascii(*up >> 4));
679 				PCHAR(hex2ascii(*up & 0x0f));
680 				up++;
681 				if (width)
682 					for (q=p;*q;q++)
683 						PCHAR(*q);
684 			}
685 			break;
686 		case 'd':
687 		case 'i':
688 			base = 10;
689 			sign = 1;
690 			goto handle_sign;
691 		case 'j':
692 			jflag = 1;
693 			goto reswitch;
694 		case 'l':
695 			if (lflag) {
696 				lflag = 0;
697 				qflag = 1;
698 			} else
699 				lflag = 1;
700 			goto reswitch;
701 		case 'n':
702 			if (jflag)
703 				*(__va_arg(ap, intmax_t *)) = retval;
704 			else if (lflag)
705 				*(__va_arg(ap, long *)) = retval;
706 			else if (qflag)
707 				*(__va_arg(ap, quad_t *)) = retval;
708 			else
709 				*(__va_arg(ap, int *)) = retval;
710 			break;
711 		case 'o':
712 			base = 8;
713 			goto handle_nosign;
714 		case 'p':
715 			base = 16;
716 			sharpflag = (width == 0);
717 			sign = 0;
718 			num = (uintptr_t)__va_arg(ap, void *);
719 			goto number;
720 		case 'q':
721 			qflag = 1;
722 			goto reswitch;
723 		case 'r':
724 			base = radix;
725 			if (sign)
726 				goto handle_sign;
727 			goto handle_nosign;
728 		case 's':
729 			p = __va_arg(ap, char *);
730 			if (p == NULL)
731 				p = "(null)";
732 			if (!dot)
733 				n = strlen (p);
734 			else
735 				for (n = 0; n < dwidth && p[n]; n++)
736 					continue;
737 
738 			width -= n;
739 
740 			if (!ladjust && width > 0)
741 				while (width--)
742 					PCHAR(padc);
743 			while (n--)
744 				PCHAR(*p++);
745 			if (ladjust && width > 0)
746 				while (width--)
747 					PCHAR(padc);
748 			break;
749 		case 't':
750 			tflag = 1;
751 			goto reswitch;
752 		case 'u':
753 			base = 10;
754 			goto handle_nosign;
755 		case 'X':
756 			upper = 1;
757 			/* FALLTHROUGH */
758 		case 'x':
759 			base = 16;
760 			goto handle_nosign;
761 		case 'z':
762 			zflag = 1;
763 			goto reswitch;
764 handle_nosign:
765 			sign = 0;
766 			if (jflag)
767 				num = __va_arg(ap, uintmax_t);
768 			else if (lflag)
769 				num = __va_arg(ap, u_long);
770 			else if (qflag)
771 				num = __va_arg(ap, u_quad_t);
772 			else if (tflag)
773 				num = __va_arg(ap, ptrdiff_t);
774 			else if (zflag)
775 				num = __va_arg(ap, size_t);
776 			else
777 				num = __va_arg(ap, u_int);
778 			goto number;
779 handle_sign:
780 			if (jflag)
781 				num = __va_arg(ap, intmax_t);
782 			else if (lflag)
783 				num = __va_arg(ap, long);
784 			else if (qflag)
785 				num = __va_arg(ap, quad_t);
786 			else if (tflag)
787 				num = __va_arg(ap, ptrdiff_t);
788 			else if (zflag)
789 				num = __va_arg(ap, ssize_t);
790 			else
791 				num = __va_arg(ap, int);
792 number:
793 			if (sign && (intmax_t)num < 0) {
794 				neg = 1;
795 				num = -(intmax_t)num;
796 			}
797 			p = ksprintn(nbuf, num, base, &tmp, upper);
798 			if (sharpflag && num != 0) {
799 				if (base == 8)
800 					tmp++;
801 				else if (base == 16)
802 					tmp += 2;
803 			}
804 			if (neg)
805 				tmp++;
806 
807 			if (!ladjust && padc != '0' && width &&
808 			    (width -= tmp) > 0) {
809 				while (width--)
810 					PCHAR(padc);
811 			}
812 			if (neg)
813 				PCHAR('-');
814 			if (sharpflag && num != 0) {
815 				if (base == 8) {
816 					PCHAR('0');
817 				} else if (base == 16) {
818 					PCHAR('0');
819 					PCHAR('x');
820 				}
821 			}
822 			if (!ladjust && width && (width -= tmp) > 0)
823 				while (width--)
824 					PCHAR(padc);
825 
826 			while (*p)
827 				PCHAR(*p--);
828 
829 			if (ladjust && width && (width -= tmp) > 0)
830 				while (width--)
831 					PCHAR(padc);
832 
833 			break;
834 		default:
835 			while (percent < fmt)
836 				PCHAR(*percent++);
837 			/*
838 			 * Since we ignore an formatting argument it is no
839 			 * longer safe to obey the remaining formatting
840 			 * arguments as the arguments will no longer match
841 			 * the format specs.
842 			 */
843 			stop = 1;
844 			break;
845 		}
846 	}
847 #undef PCHAR
848 }
849 
850 /*
851  * Put character in log buffer with a particular priority.
852  *
853  * MPSAFE
854  */
855 static void
856 msglogchar(int c, int pri)
857 {
858 	static int lastpri = -1;
859 	static int dangling;
860 	char nbuf[MAXNBUF];
861 	char *p;
862 
863 	if (!msgbufmapped)
864 		return;
865 	if (c == '\0' || c == '\r')
866 		return;
867 	if (pri != -1 && pri != lastpri) {
868 		if (dangling) {
869 			msgaddchar('\n', NULL);
870 			dangling = 0;
871 		}
872 		msgaddchar('<', NULL);
873 		for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
874 			msgaddchar(*p--, NULL);
875 		msgaddchar('>', NULL);
876 		lastpri = pri;
877 	}
878 	msgaddchar(c, NULL);
879 	if (c == '\n') {
880 		dangling = 0;
881 		lastpri = -1;
882 	} else {
883 		dangling = 1;
884 	}
885 }
886 
887 /*
888  * Put char in log buffer.   Make sure nothing blows up beyond repair if
889  * we have an MP race.
890  *
891  * MPSAFE.
892  */
893 static void
894 msgaddchar(int c, void *dummy)
895 {
896 	struct msgbuf *mbp;
897 	int rindex;
898 	int windex;
899 
900 	if (!msgbufmapped)
901 		return;
902 	mbp = msgbufp;
903 	windex = mbp->msg_bufx;
904 	mbp->msg_ptr[windex] = c;
905 	if (++windex >= mbp->msg_size)
906 		windex = 0;
907 	rindex = mbp->msg_bufr;
908 	if (windex == rindex) {
909 		rindex += 32;
910 		if (rindex >= mbp->msg_size)
911 			rindex -= mbp->msg_size;
912 		mbp->msg_bufr = rindex;
913 	}
914 	mbp->msg_bufx = windex;
915 }
916 
917 static void
918 msgbufcopy(struct msgbuf *oldp)
919 {
920 	int pos;
921 
922 	pos = oldp->msg_bufr;
923 	while (pos != oldp->msg_bufx) {
924 		msglogchar(oldp->msg_ptr[pos], -1);
925 		if (++pos >= oldp->msg_size)
926 			pos = 0;
927 	}
928 }
929 
930 void
931 msgbufinit(void *ptr, size_t size)
932 {
933 	char *cp;
934 	static struct msgbuf *oldp = NULL;
935 
936 	size -= sizeof(*msgbufp);
937 	cp = (char *)ptr;
938 	msgbufp = (struct msgbuf *) (cp + size);
939 	if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
940 	    msgbufp->msg_bufx >= size || msgbufp->msg_bufr >= size) {
941 		bzero(cp, size);
942 		bzero(msgbufp, sizeof(*msgbufp));
943 		msgbufp->msg_magic = MSG_MAGIC;
944 		msgbufp->msg_size = (char *)msgbufp - cp;
945 	}
946 	msgbufp->msg_ptr = cp;
947 	if (msgbufmapped && oldp != msgbufp)
948 		msgbufcopy(oldp);
949 	msgbufmapped = 1;
950 	oldp = msgbufp;
951 }
952 
953 /* Sysctls for accessing/clearing the msgbuf */
954 
955 static int
956 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
957 {
958 	struct ucred *cred;
959 	int error;
960 
961 	/*
962 	 * Only wheel or root can access the message log.
963 	 */
964 	if (unprivileged_read_msgbuf == 0) {
965 		KKASSERT(req->td->td_proc);
966 		cred = req->td->td_proc->p_ucred;
967 
968 		if ((cred->cr_prison || groupmember(0, cred) == 0) &&
969 		    priv_check(req->td, PRIV_ROOT) != 0
970 		) {
971 			return (EPERM);
972 		}
973 	}
974 
975 	/*
976 	 * Unwind the buffer, so that it's linear (possibly starting with
977 	 * some initial nulls).
978 	 */
979 	error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
980 	    msgbufp->msg_size - msgbufp->msg_bufx, req);
981 	if (error)
982 		return (error);
983 	if (msgbufp->msg_bufx > 0) {
984 		error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
985 		    msgbufp->msg_bufx, req);
986 	}
987 	return (error);
988 }
989 
990 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
991     0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
992 
993 static int msgbuf_clear;
994 
995 static int
996 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
997 {
998 	int error;
999 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1000 	if (!error && req->newptr) {
1001 		/* Clear the buffer and reset write pointer */
1002 		bzero(msgbufp->msg_ptr, msgbufp->msg_size);
1003 		msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
1004 		msgbuf_clear = 0;
1005 	}
1006 	return (error);
1007 }
1008 
1009 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1010     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
1011     sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
1012 
1013 #ifdef DDB
1014 
1015 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1016 {
1017 	int i, j;
1018 
1019 	if (!msgbufmapped) {
1020 		db_printf("msgbuf not mapped yet\n");
1021 		return;
1022 	}
1023 	db_printf("msgbufp = %p\n", msgbufp);
1024 	db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
1025 	    msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
1026 	    msgbufp->msg_bufx, msgbufp->msg_ptr);
1027 	for (i = 0; i < msgbufp->msg_size; i++) {
1028 		j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
1029 		db_printf("%c", msgbufp->msg_ptr[j]);
1030 	}
1031 	db_printf("\n");
1032 }
1033 
1034 #endif /* DDB */
1035