xref: /dragonfly/sys/kern/subr_prf.c (revision 25a2db75)
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  */
41 
42 #include "opt_ddb.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/msgbuf.h>
48 #include <sys/malloc.h>
49 #include <sys/proc.h>
50 #include <sys/priv.h>
51 #include <sys/tty.h>
52 #include <sys/tprintf.h>
53 #include <sys/stdint.h>
54 #include <sys/syslog.h>
55 #include <sys/cons.h>
56 #include <sys/uio.h>
57 #include <sys/sysctl.h>
58 #include <sys/lock.h>
59 #include <sys/ctype.h>
60 #include <sys/eventhandler.h>
61 #include <sys/kthread.h>
62 
63 #include <sys/thread2.h>
64 #include <sys/spinlock2.h>
65 
66 #ifdef DDB
67 #include <ddb/ddb.h>
68 #endif
69 
70 /*
71  * Note that stdarg.h and the ANSI style va_start macro is used for both
72  * ANSI and traditional C compilers.  We use the __ machine version to stay
73  * within the kernel header file set.
74  */
75 #include <machine/stdarg.h>
76 
77 #define TOCONS		0x01
78 #define TOTTY		0x02
79 #define TOLOG		0x04
80 #define TOWAKEUP	0x08
81 
82 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
83 #define MAXNBUF	(sizeof(intmax_t) * NBBY + 1)
84 
85 struct putchar_arg {
86 	int	flags;
87 	int	pri;
88 	struct	tty *tty;
89 };
90 
91 struct snprintf_arg {
92 	char	*str;
93 	size_t	remain;
94 };
95 
96 extern	int log_open;
97 
98 struct	tty *constty;			/* pointer to console "window" tty */
99 
100 static void  msglogchar(int c, int pri);
101 static void  msgaddchar(int c, void *dummy);
102 static void  kputchar (int ch, void *arg);
103 static char *ksprintn (char *nbuf, uintmax_t num, int base, int *lenp,
104 		       int upper);
105 static void  snprintf_func (int ch, void *arg);
106 
107 static int consintr = 1;		/* Ok to handle console interrupts? */
108 static int msgbufmapped;		/* Set when safe to use msgbuf */
109 static struct spinlock cons_spin = SPINLOCK_INITIALIZER(cons_spin);
110 static thread_t constty_td = NULL;
111 
112 int msgbuftrigger;
113 
114 static int      log_console_output = 1;
115 TUNABLE_INT("kern.log_console_output", &log_console_output);
116 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
117     &log_console_output, 0, "");
118 
119 static int unprivileged_read_msgbuf = 1;
120 SYSCTL_INT(_security, OID_AUTO, unprivileged_read_msgbuf, CTLFLAG_RW,
121     &unprivileged_read_msgbuf, 0,
122     "Unprivileged processes may read the kernel message buffer");
123 
124 /*
125  * Warn that a system table is full.
126  */
127 void
128 tablefull(const char *tab)
129 {
130 
131 	log(LOG_ERR, "%s: table is full\n", tab);
132 }
133 
134 /*
135  * Uprintf prints to the controlling terminal for the current process.
136  */
137 int
138 uprintf(const char *fmt, ...)
139 {
140 	struct proc *p = curproc;
141 	__va_list ap;
142 	struct putchar_arg pca;
143 	int retval = 0;
144 
145 	if (p && (p->p_flags & P_CONTROLT) && p->p_session->s_ttyvp) {
146 		__va_start(ap, fmt);
147 		pca.tty = p->p_session->s_ttyp;
148 		pca.flags = TOTTY;
149 
150 		retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
151 		__va_end(ap);
152 	}
153 	return (retval);
154 }
155 
156 tpr_t
157 tprintf_open(struct proc *p)
158 {
159 	if ((p->p_flags & P_CONTROLT) && p->p_session->s_ttyvp) {
160 		sess_hold(p->p_session);
161 		return ((tpr_t) p->p_session);
162 	}
163 	return (NULL);
164 }
165 
166 void
167 tprintf_close(tpr_t sess)
168 {
169 	if (sess)
170 		sess_rele((struct session *) sess);
171 }
172 
173 /*
174  * tprintf prints on the controlling terminal associated
175  * with the given session.
176  */
177 int
178 tprintf(tpr_t tpr, const char *fmt, ...)
179 {
180 	struct session *sess = (struct session *)tpr;
181 	struct tty *tp = NULL;
182 	int flags = TOLOG;
183 	__va_list ap;
184 	struct putchar_arg pca;
185 	int retval;
186 
187 	if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
188 		flags |= TOTTY;
189 		tp = sess->s_ttyp;
190 	}
191 	__va_start(ap, fmt);
192 	pca.tty = tp;
193 	pca.flags = flags;
194 	pca.pri = LOG_INFO;
195 	retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
196 	__va_end(ap);
197 	msgbuftrigger = 1;
198 	return (retval);
199 }
200 
201 /*
202  * Ttyprintf displays a message on a tty; it should be used only by
203  * the tty driver, or anything that knows the underlying tty will not
204  * be revoke(2)'d away.  Other callers should use tprintf.
205  */
206 int
207 ttyprintf(struct tty *tp, const char *fmt, ...)
208 {
209 	__va_list ap;
210 	struct putchar_arg pca;
211 	int retval;
212 
213 	__va_start(ap, fmt);
214 	pca.tty = tp;
215 	pca.flags = TOTTY;
216 	retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
217 	__va_end(ap);
218 	return (retval);
219 }
220 
221 /*
222  * Log writes to the log buffer, and guarantees not to sleep (so can be
223  * called by interrupt routines).  If there is no process reading the
224  * log yet, it writes to the console also.
225  */
226 int
227 log(int level, const char *fmt, ...)
228 {
229 	__va_list ap;
230 	int retval;
231 	struct putchar_arg pca;
232 
233 	pca.tty = NULL;
234 	pca.pri = level;
235 	pca.flags = log_open ? TOLOG : TOCONS;
236 
237 	__va_start(ap, fmt);
238 	retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
239 	__va_end(ap);
240 
241 	msgbuftrigger = 1;
242 	return (retval);
243 }
244 
245 #define CONSCHUNK 128
246 
247 void
248 log_console(struct uio *uio)
249 {
250 	int c, i, error, iovlen, nl;
251 	struct uio muio;
252 	struct iovec *miov = NULL;
253 	char *consbuffer;
254 	int pri;
255 
256 	if (!log_console_output)
257 		return;
258 
259 	pri = LOG_INFO | LOG_CONSOLE;
260 	muio = *uio;
261 	iovlen = uio->uio_iovcnt * sizeof (struct iovec);
262 	miov = kmalloc(iovlen, M_TEMP, M_WAITOK);
263 	consbuffer = kmalloc(CONSCHUNK, M_TEMP, M_WAITOK);
264 	bcopy((caddr_t)muio.uio_iov, (caddr_t)miov, iovlen);
265 	muio.uio_iov = miov;
266 	uio = &muio;
267 
268 	nl = 0;
269 	while (uio->uio_resid > 0) {
270 		c = (int)szmin(uio->uio_resid, CONSCHUNK);
271 		error = uiomove(consbuffer, (size_t)c, uio);
272 		if (error != 0)
273 			break;
274 		for (i = 0; i < c; i++) {
275 			msglogchar(consbuffer[i], pri);
276 			if (consbuffer[i] == '\n')
277 				nl = 1;
278 			else
279 				nl = 0;
280 		}
281 	}
282 	if (!nl)
283 		msglogchar('\n', pri);
284 	msgbuftrigger = 1;
285 	kfree(miov, M_TEMP);
286 	kfree(consbuffer, M_TEMP);
287 	return;
288 }
289 
290 /*
291  * Output to the console.
292  */
293 int
294 kprintf(const char *fmt, ...)
295 {
296 	__va_list ap;
297 	int savintr;
298 	struct putchar_arg pca;
299 	int retval;
300 
301 	savintr = consintr;		/* disable interrupts */
302 	consintr = 0;
303 	__va_start(ap, fmt);
304 	pca.tty = NULL;
305 	pca.flags = TOCONS | TOLOG;
306 	pca.pri = -1;
307 	retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
308 	__va_end(ap);
309 	if (!panicstr)
310 		msgbuftrigger = 1;
311 	consintr = savintr;		/* reenable interrupts */
312 	return (retval);
313 }
314 
315 int
316 kvprintf(const char *fmt, __va_list ap)
317 {
318 	int savintr;
319 	struct putchar_arg pca;
320 	int retval;
321 
322 	savintr = consintr;		/* disable interrupts */
323 	consintr = 0;
324 	pca.tty = NULL;
325 	pca.flags = TOCONS | TOLOG;
326 	pca.pri = -1;
327 	retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
328 	if (!panicstr)
329 		msgbuftrigger = 1;
330 	consintr = savintr;		/* reenable interrupts */
331 	return (retval);
332 }
333 
334 /*
335  * Limited rate kprintf.  The passed rate structure must be initialized
336  * with the desired reporting frequency.  A frequency of 0 will result in
337  * no output.
338  *
339  * count may be initialized to a negative number to allow an initial
340  * burst.
341  */
342 void
343 krateprintf(struct krate *rate, const char *fmt, ...)
344 {
345 	__va_list ap;
346 
347 	if (rate->ticks != (int)time_second) {
348 		rate->ticks = (int)time_second;
349 		if (rate->count > 0)
350 			rate->count = 0;
351 	}
352 	if (rate->count < rate->freq) {
353 		++rate->count;
354 		__va_start(ap, fmt);
355 		kvprintf(fmt, ap);
356 		__va_end(ap);
357 	}
358 }
359 
360 /*
361  * Print a character to the dmesg log, the console, and/or the user's
362  * terminal.
363  *
364  * NOTE: TOTTY does not require nonblocking operation, but TOCONS
365  * 	 and TOLOG do.  When we have a constty we still output to
366  *	 the real console but we have a monitoring thread which
367  *	 we wakeup which tracks the log.
368  */
369 static void
370 kputchar(int c, void *arg)
371 {
372 	struct putchar_arg *ap = (struct putchar_arg*) arg;
373 	int flags = ap->flags;
374 	struct tty *tp = ap->tty;
375 
376 	if (panicstr)
377 		constty = NULL;
378 	if ((flags & TOCONS) && tp == NULL && constty)
379 		flags |= TOLOG | TOWAKEUP;
380 	if ((flags & TOTTY) && tputchar(c, tp) < 0)
381 		ap->flags &= ~TOTTY;
382 	if ((flags & TOLOG))
383 		msglogchar(c, ap->pri);
384 	if ((flags & TOCONS) && c)
385 		cnputc(c);
386 	if (flags & TOWAKEUP)
387 		wakeup(constty_td);
388 }
389 
390 /*
391  * Scaled down version of sprintf(3).
392  */
393 int
394 ksprintf(char *buf, const char *cfmt, ...)
395 {
396 	int retval;
397 	__va_list ap;
398 
399 	__va_start(ap, cfmt);
400 	retval = kvcprintf(cfmt, NULL, buf, 10, ap);
401 	buf[retval] = '\0';
402 	__va_end(ap);
403 	return (retval);
404 }
405 
406 /*
407  * Scaled down version of vsprintf(3).
408  */
409 int
410 kvsprintf(char *buf, const char *cfmt, __va_list ap)
411 {
412 	int retval;
413 
414 	retval = kvcprintf(cfmt, NULL, buf, 10, ap);
415 	buf[retval] = '\0';
416 	return (retval);
417 }
418 
419 /*
420  * Scaled down version of snprintf(3).
421  */
422 int
423 ksnprintf(char *str, size_t size, const char *format, ...)
424 {
425 	int retval;
426 	__va_list ap;
427 
428 	__va_start(ap, format);
429 	retval = kvsnprintf(str, size, format, ap);
430 	__va_end(ap);
431 	return(retval);
432 }
433 
434 /*
435  * Scaled down version of vsnprintf(3).
436  */
437 int
438 kvsnprintf(char *str, size_t size, const char *format, __va_list ap)
439 {
440 	struct snprintf_arg info;
441 	int retval;
442 
443 	info.str = str;
444 	info.remain = size;
445 	retval = kvcprintf(format, snprintf_func, &info, 10, ap);
446 	if (info.remain >= 1)
447 		*info.str++ = '\0';
448 	return (retval);
449 }
450 
451 int
452 ksnrprintf(char *str, size_t size, int radix, const char *format, ...)
453 {
454 	int retval;
455 	__va_list ap;
456 
457 	__va_start(ap, format);
458 	retval = kvsnrprintf(str, size, radix, format, ap);
459 	__va_end(ap);
460 	return(retval);
461 }
462 
463 int
464 kvsnrprintf(char *str, size_t size, int radix, const char *format, __va_list ap)
465 {
466 	struct snprintf_arg info;
467 	int retval;
468 
469 	info.str = str;
470 	info.remain = size;
471 	retval = kvcprintf(format, snprintf_func, &info, radix, ap);
472 	if (info.remain >= 1)
473 		*info.str++ = '\0';
474 	return (retval);
475 }
476 
477 int
478 kvasnrprintf(char **strp, size_t size, int radix,
479 	     const char *format, __va_list ap)
480 {
481 	struct snprintf_arg info;
482 	int retval;
483 
484 	*strp = kmalloc(size, M_TEMP, M_WAITOK);
485 	info.str = *strp;
486 	info.remain = size;
487 	retval = kvcprintf(format, snprintf_func, &info, radix, ap);
488 	if (info.remain >= 1)
489 		*info.str++ = '\0';
490 	return (retval);
491 }
492 
493 void
494 kvasfree(char **strp)
495 {
496 	if (*strp) {
497 		kfree(*strp, M_TEMP);
498 		*strp = NULL;
499 	}
500 }
501 
502 static void
503 snprintf_func(int ch, void *arg)
504 {
505 	struct snprintf_arg *const info = arg;
506 
507 	if (info->remain >= 2) {
508 		*info->str++ = ch;
509 		info->remain--;
510 	}
511 }
512 
513 /*
514  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
515  * order; return an optional length and a pointer to the last character
516  * written in the buffer (i.e., the first character of the string).
517  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
518  */
519 static char *
520 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
521 {
522 	char *p, c;
523 
524 	p = nbuf;
525 	*p = '\0';
526 	do {
527 		c = hex2ascii(num % base);
528 		*++p = upper ? toupper(c) : c;
529 	} while (num /= base);
530 	if (lenp)
531 		*lenp = p - nbuf;
532 	return (p);
533 }
534 
535 /*
536  * Scaled down version of printf(3).
537  *
538  * Two additional formats:
539  *
540  * The format %b is supported to decode error registers.
541  * Its usage is:
542  *
543  *	kprintf("reg=%b\n", regval, "<base><arg>*");
544  *
545  * where <base> is the output base expressed as a control character, e.g.
546  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
547  * the first of which gives the bit number to be inspected (origin 1), and
548  * the next characters (up to a control character, i.e. a character <= 32),
549  * give the name of the register.  Thus:
550  *
551  *	kvcprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
552  *
553  * would produce output:
554  *
555  *	reg=3<BITTWO,BITONE>
556  */
557 
558 #define PCHAR(c) {int cc=(c); if(func) (*func)(cc,arg); else *d++=cc; retval++;}
559 
560 int
561 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg,
562 	  int radix, __va_list ap)
563 {
564 	char nbuf[MAXNBUF];
565 	char *d;
566 	const char *p, *percent, *q;
567 	int ch, n;
568 	uintmax_t num;
569 	int base, tmp, width, ladjust, sharpflag, neg, sign, dot;
570 	int cflag, hflag, jflag, lflag, qflag, tflag, zflag;
571 	int dwidth, upper;
572 	char padc;
573 	int retval = 0, stop = 0;
574 	int usespin;
575 
576 	/*
577 	 * Make a supreme effort to avoid reentrant panics or deadlocks.
578 	 *
579 	 * NOTE!  Do nothing that would access mycpu/gd/fs unless the
580 	 *	  function is the normal kputchar(), which allows us to
581 	 *	  use this function for very early debugging with a special
582 	 *	  function.
583 	 */
584 	if (func == kputchar) {
585 		if (mycpu->gd_flags & GDF_KPRINTF)
586 			return(0);
587 		atomic_set_long(&mycpu->gd_flags, GDF_KPRINTF);
588 	}
589 
590 	num = 0;
591 	if (!func)
592 		d = (char *) arg;
593 	else
594 		d = NULL;
595 
596 	if (fmt == NULL)
597 		fmt = "(fmt null)\n";
598 
599 	if (radix < 2 || radix > 36)
600 		radix = 10;
601 
602 	usespin = (func == kputchar &&
603 		   panic_cpu_gd != mycpu &&
604 		   (((struct putchar_arg *)arg)->flags & TOTTY) == 0);
605 	if (usespin) {
606 		crit_enter_hard();
607 		spin_lock(&cons_spin);
608 	}
609 
610 	for (;;) {
611 		padc = ' ';
612 		width = 0;
613 		while ((ch = (u_char)*fmt++) != '%' || stop) {
614 			if (ch == '\0')
615 				goto done;
616 			PCHAR(ch);
617 		}
618 		percent = fmt - 1;
619 		dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
620 		cflag = hflag = jflag = lflag = qflag = tflag = zflag = 0;
621 
622 reswitch:
623 		switch (ch = (u_char)*fmt++) {
624 		case '.':
625 			dot = 1;
626 			goto reswitch;
627 		case '#':
628 			sharpflag = 1;
629 			goto reswitch;
630 		case '+':
631 			sign = 1;
632 			goto reswitch;
633 		case '-':
634 			ladjust = 1;
635 			goto reswitch;
636 		case '%':
637 			PCHAR(ch);
638 			break;
639 		case '*':
640 			if (!dot) {
641 				width = __va_arg(ap, int);
642 				if (width < 0) {
643 					ladjust = !ladjust;
644 					width = -width;
645 				}
646 			} else {
647 				dwidth = __va_arg(ap, int);
648 			}
649 			goto reswitch;
650 		case '0':
651 			if (!dot) {
652 				padc = '0';
653 				goto reswitch;
654 			}
655 		case '1': case '2': case '3': case '4':
656 		case '5': case '6': case '7': case '8': case '9':
657 				for (n = 0;; ++fmt) {
658 					n = n * 10 + ch - '0';
659 					ch = *fmt;
660 					if (ch < '0' || ch > '9')
661 						break;
662 				}
663 			if (dot)
664 				dwidth = n;
665 			else
666 				width = n;
667 			goto reswitch;
668 		case 'b':
669 			num = (u_int)__va_arg(ap, int);
670 			p = __va_arg(ap, char *);
671 			for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
672 				PCHAR(*q--);
673 
674 			if (num == 0)
675 				break;
676 
677 			for (tmp = 0; *p;) {
678 				n = *p++;
679 				if (num & (1 << (n - 1))) {
680 					PCHAR(tmp ? ',' : '<');
681 					for (; (n = *p) > ' '; ++p)
682 						PCHAR(n);
683 					tmp = 1;
684 				} else
685 					for (; *p > ' '; ++p)
686 						continue;
687 			}
688 			if (tmp)
689 				PCHAR('>');
690 			break;
691 		case 'c':
692 			PCHAR(__va_arg(ap, int));
693 			break;
694 		case 'd':
695 		case 'i':
696 			base = 10;
697 			sign = 1;
698 			goto handle_sign;
699 		case 'h':
700 			if (hflag) {
701 				hflag = 0;
702 				cflag = 1;
703 			} else
704 				hflag = 1;
705 			goto reswitch;
706 		case 'j':
707 			jflag = 1;
708 			goto reswitch;
709 		case 'l':
710 			if (lflag) {
711 				lflag = 0;
712 				qflag = 1;
713 			} else
714 				lflag = 1;
715 			goto reswitch;
716 		case 'n':
717 			if (cflag)
718 				*(__va_arg(ap, char *)) = retval;
719 			else if (hflag)
720 				*(__va_arg(ap, short *)) = retval;
721 			else if (jflag)
722 				*(__va_arg(ap, intmax_t *)) = retval;
723 			else if (lflag)
724 				*(__va_arg(ap, long *)) = retval;
725 			else if (qflag)
726 				*(__va_arg(ap, quad_t *)) = retval;
727 			else
728 				*(__va_arg(ap, int *)) = retval;
729 			break;
730 		case 'o':
731 			base = 8;
732 			goto handle_nosign;
733 		case 'p':
734 			base = 16;
735 			sharpflag = (width == 0);
736 			sign = 0;
737 			num = (uintptr_t)__va_arg(ap, void *);
738 			goto number;
739 		case 'q':
740 			qflag = 1;
741 			goto reswitch;
742 		case 'r':
743 			base = radix;
744 			if (sign)
745 				goto handle_sign;
746 			goto handle_nosign;
747 		case 's':
748 			p = __va_arg(ap, char *);
749 			if (p == NULL)
750 				p = "(null)";
751 			if (!dot)
752 				n = strlen (p);
753 			else
754 				for (n = 0; n < dwidth && p[n]; n++)
755 					continue;
756 
757 			width -= n;
758 
759 			if (!ladjust && width > 0)
760 				while (width--)
761 					PCHAR(padc);
762 			while (n--)
763 				PCHAR(*p++);
764 			if (ladjust && width > 0)
765 				while (width--)
766 					PCHAR(padc);
767 			break;
768 		case 't':
769 			tflag = 1;
770 			goto reswitch;
771 		case 'u':
772 			base = 10;
773 			goto handle_nosign;
774 		case 'X':
775 			upper = 1;
776 			/* FALLTHROUGH */
777 		case 'x':
778 			base = 16;
779 			goto handle_nosign;
780 		case 'z':
781 			zflag = 1;
782 			goto reswitch;
783 handle_nosign:
784 			sign = 0;
785 			if (cflag)
786 				num = (u_char)__va_arg(ap, int);
787 			else if (hflag)
788 				num = (u_short)__va_arg(ap, int);
789 			else if (jflag)
790 				num = __va_arg(ap, uintmax_t);
791 			else if (lflag)
792 				num = __va_arg(ap, u_long);
793 			else if (qflag)
794 				num = __va_arg(ap, u_quad_t);
795 			else if (tflag)
796 				num = __va_arg(ap, ptrdiff_t);
797 			else if (zflag)
798 				num = __va_arg(ap, size_t);
799 			else
800 				num = __va_arg(ap, u_int);
801 			goto number;
802 handle_sign:
803 			if (cflag)
804 				num = (char)__va_arg(ap, int);
805 			else if (hflag)
806 				num = (short)__va_arg(ap, int);
807 			else if (jflag)
808 				num = __va_arg(ap, intmax_t);
809 			else if (lflag)
810 				num = __va_arg(ap, long);
811 			else if (qflag)
812 				num = __va_arg(ap, quad_t);
813 			else if (tflag)
814 				num = __va_arg(ap, ptrdiff_t);
815 			else if (zflag)
816 				num = __va_arg(ap, ssize_t);
817 			else
818 				num = __va_arg(ap, int);
819 number:
820 			if (sign && (intmax_t)num < 0) {
821 				neg = 1;
822 				num = -(intmax_t)num;
823 			}
824 			p = ksprintn(nbuf, num, base, &n, upper);
825 			tmp = 0;
826 			if (sharpflag && num != 0) {
827 				if (base == 8)
828 					tmp++;
829 				else if (base == 16)
830 					tmp += 2;
831 			}
832 			if (neg)
833 				tmp++;
834 
835 			if (!ladjust && padc == '0')
836 				dwidth = width - tmp;
837 			width -= tmp + imax(dwidth, n);
838 			dwidth -= n;
839 			if (!ladjust)
840 				while (width-- > 0)
841 					PCHAR(' ');
842 			if (neg)
843 				PCHAR('-');
844 			if (sharpflag && num != 0) {
845 				if (base == 8) {
846 					PCHAR('0');
847 				} else if (base == 16) {
848 					PCHAR('0');
849 					PCHAR('x');
850 				}
851 			}
852 			while (dwidth-- > 0)
853 				PCHAR('0');
854 
855 			while (*p)
856 				PCHAR(*p--);
857 
858 			if (ladjust)
859 				while (width-- > 0)
860 					PCHAR(' ');
861 
862 			break;
863 		default:
864 			while (percent < fmt)
865 				PCHAR(*percent++);
866 			/*
867 			 * Since we ignore an formatting argument it is no
868 			 * longer safe to obey the remaining formatting
869 			 * arguments as the arguments will no longer match
870 			 * the format specs.
871 			 */
872 			stop = 1;
873 			break;
874 		}
875 	}
876 done:
877 	/*
878 	 * Cleanup reentrancy issues.
879 	 */
880 	if (func == kputchar)
881 		atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
882 	if (usespin) {
883 		spin_unlock(&cons_spin);
884 		crit_exit_hard();
885 	}
886 	return (retval);
887 }
888 
889 #undef PCHAR
890 
891 /*
892  * Called from the panic code to try to get the console working
893  * again in case we paniced inside a kprintf().
894  */
895 void
896 kvcreinitspin(void)
897 {
898 	spin_init(&cons_spin);
899 	atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
900 }
901 
902 /*
903  * Console support thread for constty intercepts.  This is needed because
904  * console tty intercepts can block.  Instead of having kputchar() attempt
905  * to directly write to the console intercept we just force it to log
906  * and wakeup this baby to track and dump the log to constty.
907  */
908 static void
909 constty_daemon(void)
910 {
911 	int rindex = -1;
912 	int windex = -1;
913         struct msgbuf *mbp;
914 	struct tty *tp;
915 
916         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
917                               constty_td, SHUTDOWN_PRI_FIRST);
918         constty_td->td_flags |= TDF_SYSTHREAD;
919 
920         for (;;) {
921                 kproc_suspend_loop();
922 
923 		crit_enter();
924 		mbp = msgbufp;
925 		if (mbp == NULL || msgbufmapped == 0 ||
926 		    windex == mbp->msg_bufx) {
927 			tsleep(constty_td, 0, "waiting", hz*60);
928 			crit_exit();
929 			continue;
930 		}
931 		windex = mbp->msg_bufx;
932 		crit_exit();
933 
934 		/*
935 		 * Get message buf FIFO indices.  rindex is tracking.
936 		 */
937 		if ((tp = constty) == NULL) {
938 			rindex = mbp->msg_bufx;
939 			continue;
940 		}
941 
942 		/*
943 		 * Don't blow up if the message buffer is broken
944 		 */
945 		if (windex < 0 || windex >= mbp->msg_size)
946 			continue;
947 		if (rindex < 0 || rindex >= mbp->msg_size)
948 			rindex = windex;
949 
950 		/*
951 		 * And dump it.  If constty gets stuck will give up.
952 		 */
953 		while (rindex != windex) {
954 			if (tputchar((uint8_t)mbp->msg_ptr[rindex], tp) < 0) {
955 				constty = NULL;
956 				rindex = mbp->msg_bufx;
957 				break;
958 			}
959 			if (++rindex >= mbp->msg_size)
960 				rindex = 0;
961                         if (tp->t_outq.c_cc >= tp->t_ohiwat) {
962 				tsleep(constty_daemon, 0, "blocked", hz / 10);
963 				if (tp->t_outq.c_cc >= tp->t_ohiwat) {
964 					rindex = windex;
965 					break;
966 				}
967 			}
968 		}
969 	}
970 }
971 
972 static struct kproc_desc constty_kp = {
973         "consttyd",
974 	constty_daemon,
975         &constty_td
976 };
977 SYSINIT(bufdaemon, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY,
978         kproc_start, &constty_kp)
979 
980 /*
981  * Put character in log buffer with a particular priority.
982  *
983  * MPSAFE
984  */
985 static void
986 msglogchar(int c, int pri)
987 {
988 	static int lastpri = -1;
989 	static int dangling;
990 	char nbuf[MAXNBUF];
991 	char *p;
992 
993 	if (!msgbufmapped)
994 		return;
995 	if (c == '\0' || c == '\r')
996 		return;
997 	if (pri != -1 && pri != lastpri) {
998 		if (dangling) {
999 			msgaddchar('\n', NULL);
1000 			dangling = 0;
1001 		}
1002 		msgaddchar('<', NULL);
1003 		for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
1004 			msgaddchar(*p--, NULL);
1005 		msgaddchar('>', NULL);
1006 		lastpri = pri;
1007 	}
1008 	msgaddchar(c, NULL);
1009 	if (c == '\n') {
1010 		dangling = 0;
1011 		lastpri = -1;
1012 	} else {
1013 		dangling = 1;
1014 	}
1015 }
1016 
1017 /*
1018  * Put char in log buffer.   Make sure nothing blows up beyond repair if
1019  * we have an MP race.
1020  *
1021  * MPSAFE.
1022  */
1023 static void
1024 msgaddchar(int c, void *dummy)
1025 {
1026 	struct msgbuf *mbp;
1027 	int rindex;
1028 	int windex;
1029 
1030 	if (!msgbufmapped)
1031 		return;
1032 	mbp = msgbufp;
1033 	windex = mbp->msg_bufx;
1034 	mbp->msg_ptr[windex] = c;
1035 	if (++windex >= mbp->msg_size)
1036 		windex = 0;
1037 	rindex = mbp->msg_bufr;
1038 	if (windex == rindex) {
1039 		rindex += 32;
1040 		if (rindex >= mbp->msg_size)
1041 			rindex -= mbp->msg_size;
1042 		mbp->msg_bufr = rindex;
1043 	}
1044 	mbp->msg_bufx = windex;
1045 }
1046 
1047 static void
1048 msgbufcopy(struct msgbuf *oldp)
1049 {
1050 	int pos;
1051 
1052 	pos = oldp->msg_bufr;
1053 	while (pos != oldp->msg_bufx) {
1054 		msglogchar(oldp->msg_ptr[pos], -1);
1055 		if (++pos >= oldp->msg_size)
1056 			pos = 0;
1057 	}
1058 }
1059 
1060 void
1061 msgbufinit(void *ptr, size_t size)
1062 {
1063 	char *cp;
1064 	static struct msgbuf *oldp = NULL;
1065 
1066 	size -= sizeof(*msgbufp);
1067 	cp = (char *)ptr;
1068 	msgbufp = (struct msgbuf *) (cp + size);
1069 	if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
1070 	    msgbufp->msg_bufx >= size || msgbufp->msg_bufr >= size) {
1071 		bzero(cp, size);
1072 		bzero(msgbufp, sizeof(*msgbufp));
1073 		msgbufp->msg_magic = MSG_MAGIC;
1074 		msgbufp->msg_size = (char *)msgbufp - cp;
1075 	}
1076 	msgbufp->msg_ptr = cp;
1077 	if (msgbufmapped && oldp != msgbufp)
1078 		msgbufcopy(oldp);
1079 	msgbufmapped = 1;
1080 	oldp = msgbufp;
1081 }
1082 
1083 /* Sysctls for accessing/clearing the msgbuf */
1084 
1085 static int
1086 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1087 {
1088 	struct ucred *cred;
1089 	int error;
1090 
1091 	/*
1092 	 * Only wheel or root can access the message log.
1093 	 */
1094 	if (unprivileged_read_msgbuf == 0) {
1095 		KKASSERT(req->td->td_proc);
1096 		cred = req->td->td_proc->p_ucred;
1097 
1098 		if ((cred->cr_prison || groupmember(0, cred) == 0) &&
1099 		    priv_check(req->td, PRIV_ROOT) != 0
1100 		) {
1101 			return (EPERM);
1102 		}
1103 	}
1104 
1105 	/*
1106 	 * Unwind the buffer, so that it's linear (possibly starting with
1107 	 * some initial nulls).
1108 	 */
1109 	error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
1110 	    msgbufp->msg_size - msgbufp->msg_bufx, req);
1111 	if (error)
1112 		return (error);
1113 	if (msgbufp->msg_bufx > 0) {
1114 		error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
1115 		    msgbufp->msg_bufx, req);
1116 	}
1117 	return (error);
1118 }
1119 
1120 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
1121     0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1122 
1123 static int msgbuf_clear;
1124 
1125 static int
1126 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1127 {
1128 	int error;
1129 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1130 	if (!error && req->newptr) {
1131 		/* Clear the buffer and reset write pointer */
1132 		bzero(msgbufp->msg_ptr, msgbufp->msg_size);
1133 		msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
1134 		msgbuf_clear = 0;
1135 	}
1136 	return (error);
1137 }
1138 
1139 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1140     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
1141     sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
1142 
1143 #ifdef DDB
1144 
1145 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1146 {
1147 	int i, j;
1148 
1149 	if (!msgbufmapped) {
1150 		db_printf("msgbuf not mapped yet\n");
1151 		return;
1152 	}
1153 	db_printf("msgbufp = %p\n", msgbufp);
1154 	db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
1155 	    msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
1156 	    msgbufp->msg_bufx, msgbufp->msg_ptr);
1157 	for (i = 0; i < msgbufp->msg_size; i++) {
1158 		j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
1159 		db_printf("%c", msgbufp->msg_ptr[j]);
1160 	}
1161 	db_printf("\n");
1162 }
1163 
1164 #endif /* DDB */
1165 
1166 
1167 void
1168 hexdump(const void *ptr, int length, const char *hdr, int flags)
1169 {
1170 	int i, j, k;
1171 	int cols;
1172 	const unsigned char *cp;
1173 	char delim;
1174 
1175 	if ((flags & HD_DELIM_MASK) != 0)
1176 		delim = (flags & HD_DELIM_MASK) >> 8;
1177 	else
1178 		delim = ' ';
1179 
1180 	if ((flags & HD_COLUMN_MASK) != 0)
1181 		cols = flags & HD_COLUMN_MASK;
1182 	else
1183 		cols = 16;
1184 
1185 	cp = ptr;
1186 	for (i = 0; i < length; i+= cols) {
1187 		if (hdr != NULL)
1188 			kprintf("%s", hdr);
1189 
1190 		if ((flags & HD_OMIT_COUNT) == 0)
1191 			kprintf("%04x  ", i);
1192 
1193 		if ((flags & HD_OMIT_HEX) == 0) {
1194 			for (j = 0; j < cols; j++) {
1195 				k = i + j;
1196 				if (k < length)
1197 					kprintf("%c%02x", delim, cp[k]);
1198 				else
1199 					kprintf("   ");
1200 			}
1201 		}
1202 
1203 		if ((flags & HD_OMIT_CHARS) == 0) {
1204 			kprintf("  |");
1205 			for (j = 0; j < cols; j++) {
1206 				k = i + j;
1207 				if (k >= length)
1208 					kprintf(" ");
1209 				else if (cp[k] >= ' ' && cp[k] <= '~')
1210 					kprintf("%c", cp[k]);
1211 				else
1212 					kprintf(".");
1213 			}
1214 			kprintf("|");
1215 		}
1216 		kprintf("\n");
1217 	}
1218 }
1219