xref: /dflybsd-src/sys/kern/subr_prf.c (revision 636eca08bbf84bbb648c68d757be5ec1a2b86a72)
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  * XXX:  %D  -- Hexdump, takes pointer and separator string:
558  *		("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
559  *		("%*D", len, ptr, " " -> XX XX XX XX ...
560  */
561 
562 #define PCHAR(c) {int cc=(c); if(func) (*func)(cc,arg); else *d++=cc; retval++;}
563 
564 int
565 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg,
566 	  int radix, __va_list ap)
567 {
568 	char nbuf[MAXNBUF];
569 	char *d;
570 	const char *p, *percent, *q;
571 	int ch, n;
572 	uintmax_t num;
573 	int base, tmp, width, ladjust, sharpflag, neg, sign, dot;
574 	int cflag, hflag, jflag, lflag, qflag, tflag, zflag;
575 	int dwidth, upper;
576 	char padc;
577 	int retval = 0, stop = 0;
578 	int usespin;
579 
580 	/*
581 	 * Make a supreme effort to avoid reentrant panics or deadlocks.
582 	 *
583 	 * NOTE!  Do nothing that would access mycpu/gd/fs unless the
584 	 *	  function is the normal kputchar(), which allows us to
585 	 *	  use this function for very early debugging with a special
586 	 *	  function.
587 	 */
588 	if (func == kputchar) {
589 		if (mycpu->gd_flags & GDF_KPRINTF)
590 			return(0);
591 		atomic_set_long(&mycpu->gd_flags, GDF_KPRINTF);
592 	}
593 
594 	num = 0;
595 	if (!func)
596 		d = (char *) arg;
597 	else
598 		d = NULL;
599 
600 	if (fmt == NULL)
601 		fmt = "(fmt null)\n";
602 
603 	if (radix < 2 || radix > 36)
604 		radix = 10;
605 
606 	usespin = (func == kputchar &&
607 		   panic_cpu_gd != mycpu &&
608 		   (((struct putchar_arg *)arg)->flags & TOTTY) == 0);
609 	if (usespin) {
610 		crit_enter_hard();
611 		spin_lock(&cons_spin);
612 	}
613 
614 	for (;;) {
615 		padc = ' ';
616 		width = 0;
617 		while ((ch = (u_char)*fmt++) != '%' || stop) {
618 			if (ch == '\0')
619 				goto done;
620 			PCHAR(ch);
621 		}
622 		percent = fmt - 1;
623 		dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
624 		cflag = hflag = jflag = lflag = qflag = tflag = zflag = 0;
625 
626 reswitch:
627 		switch (ch = (u_char)*fmt++) {
628 		case '.':
629 			dot = 1;
630 			goto reswitch;
631 		case '#':
632 			sharpflag = 1;
633 			goto reswitch;
634 		case '+':
635 			sign = 1;
636 			goto reswitch;
637 		case '-':
638 			ladjust = 1;
639 			goto reswitch;
640 		case '%':
641 			PCHAR(ch);
642 			break;
643 		case '*':
644 			if (!dot) {
645 				width = __va_arg(ap, int);
646 				if (width < 0) {
647 					ladjust = !ladjust;
648 					width = -width;
649 				}
650 			} else {
651 				dwidth = __va_arg(ap, int);
652 			}
653 			goto reswitch;
654 		case '0':
655 			if (!dot) {
656 				padc = '0';
657 				goto reswitch;
658 			}
659 		case '1': case '2': case '3': case '4':
660 		case '5': case '6': case '7': case '8': case '9':
661 				for (n = 0;; ++fmt) {
662 					n = n * 10 + ch - '0';
663 					ch = *fmt;
664 					if (ch < '0' || ch > '9')
665 						break;
666 				}
667 			if (dot)
668 				dwidth = n;
669 			else
670 				width = n;
671 			goto reswitch;
672 		case 'b':
673 			num = (u_int)__va_arg(ap, int);
674 			p = __va_arg(ap, char *);
675 			for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
676 				PCHAR(*q--);
677 
678 			if (num == 0)
679 				break;
680 
681 			for (tmp = 0; *p;) {
682 				n = *p++;
683 				if (num & (1 << (n - 1))) {
684 					PCHAR(tmp ? ',' : '<');
685 					for (; (n = *p) > ' '; ++p)
686 						PCHAR(n);
687 					tmp = 1;
688 				} else
689 					for (; *p > ' '; ++p)
690 						continue;
691 			}
692 			if (tmp)
693 				PCHAR('>');
694 			break;
695 		case 'c':
696 			PCHAR(__va_arg(ap, int));
697 			break;
698 		case 'd':
699 		case 'i':
700 			base = 10;
701 			sign = 1;
702 			goto handle_sign;
703 		case 'h':
704 			if (hflag) {
705 				hflag = 0;
706 				cflag = 1;
707 			} else
708 				hflag = 1;
709 			goto reswitch;
710 		case 'j':
711 			jflag = 1;
712 			goto reswitch;
713 		case 'l':
714 			if (lflag) {
715 				lflag = 0;
716 				qflag = 1;
717 			} else
718 				lflag = 1;
719 			goto reswitch;
720 		case 'n':
721 			if (cflag)
722 				*(__va_arg(ap, char *)) = retval;
723 			else if (hflag)
724 				*(__va_arg(ap, short *)) = retval;
725 			else if (jflag)
726 				*(__va_arg(ap, intmax_t *)) = retval;
727 			else if (lflag)
728 				*(__va_arg(ap, long *)) = retval;
729 			else if (qflag)
730 				*(__va_arg(ap, quad_t *)) = retval;
731 			else
732 				*(__va_arg(ap, int *)) = retval;
733 			break;
734 		case 'o':
735 			base = 8;
736 			goto handle_nosign;
737 		case 'p':
738 			base = 16;
739 			sharpflag = (width == 0);
740 			sign = 0;
741 			num = (uintptr_t)__va_arg(ap, void *);
742 			goto number;
743 		case 'q':
744 			qflag = 1;
745 			goto reswitch;
746 		case 'r':
747 			base = radix;
748 			if (sign)
749 				goto handle_sign;
750 			goto handle_nosign;
751 		case 's':
752 			p = __va_arg(ap, char *);
753 			if (p == NULL)
754 				p = "(null)";
755 			if (!dot)
756 				n = strlen (p);
757 			else
758 				for (n = 0; n < dwidth && p[n]; n++)
759 					continue;
760 
761 			width -= n;
762 
763 			if (!ladjust && width > 0)
764 				while (width--)
765 					PCHAR(padc);
766 			while (n--)
767 				PCHAR(*p++);
768 			if (ladjust && width > 0)
769 				while (width--)
770 					PCHAR(padc);
771 			break;
772 		case 't':
773 			tflag = 1;
774 			goto reswitch;
775 		case 'u':
776 			base = 10;
777 			goto handle_nosign;
778 		case 'X':
779 			upper = 1;
780 			/* FALLTHROUGH */
781 		case 'x':
782 			base = 16;
783 			goto handle_nosign;
784 		case 'z':
785 			zflag = 1;
786 			goto reswitch;
787 handle_nosign:
788 			sign = 0;
789 			if (cflag)
790 				num = (u_char)__va_arg(ap, int);
791 			else if (hflag)
792 				num = (u_short)__va_arg(ap, int);
793 			else if (jflag)
794 				num = __va_arg(ap, uintmax_t);
795 			else if (lflag)
796 				num = __va_arg(ap, u_long);
797 			else if (qflag)
798 				num = __va_arg(ap, u_quad_t);
799 			else if (tflag)
800 				num = __va_arg(ap, ptrdiff_t);
801 			else if (zflag)
802 				num = __va_arg(ap, size_t);
803 			else
804 				num = __va_arg(ap, u_int);
805 			goto number;
806 handle_sign:
807 			if (cflag)
808 				num = (char)__va_arg(ap, int);
809 			else if (hflag)
810 				num = (short)__va_arg(ap, int);
811 			else if (jflag)
812 				num = __va_arg(ap, intmax_t);
813 			else if (lflag)
814 				num = __va_arg(ap, long);
815 			else if (qflag)
816 				num = __va_arg(ap, quad_t);
817 			else if (tflag)
818 				num = __va_arg(ap, ptrdiff_t);
819 			else if (zflag)
820 				num = __va_arg(ap, ssize_t);
821 			else
822 				num = __va_arg(ap, int);
823 number:
824 			if (sign && (intmax_t)num < 0) {
825 				neg = 1;
826 				num = -(intmax_t)num;
827 			}
828 			p = ksprintn(nbuf, num, base, &n, upper);
829 			tmp = 0;
830 			if (sharpflag && num != 0) {
831 				if (base == 8)
832 					tmp++;
833 				else if (base == 16)
834 					tmp += 2;
835 			}
836 			if (neg)
837 				tmp++;
838 
839 			if (!ladjust && padc == '0')
840 				dwidth = width - tmp;
841 			width -= tmp + imax(dwidth, n);
842 			dwidth -= n;
843 			if (!ladjust)
844 				while (width-- > 0)
845 					PCHAR(' ');
846 			if (neg)
847 				PCHAR('-');
848 			if (sharpflag && num != 0) {
849 				if (base == 8) {
850 					PCHAR('0');
851 				} else if (base == 16) {
852 					PCHAR('0');
853 					PCHAR('x');
854 				}
855 			}
856 			while (dwidth-- > 0)
857 				PCHAR('0');
858 
859 			while (*p)
860 				PCHAR(*p--);
861 
862 			if (ladjust)
863 				while (width-- > 0)
864 					PCHAR(' ');
865 
866 			break;
867 		default:
868 			while (percent < fmt)
869 				PCHAR(*percent++);
870 			/*
871 			 * Since we ignore an formatting argument it is no
872 			 * longer safe to obey the remaining formatting
873 			 * arguments as the arguments will no longer match
874 			 * the format specs.
875 			 */
876 			stop = 1;
877 			break;
878 		}
879 	}
880 done:
881 	/*
882 	 * Cleanup reentrancy issues.
883 	 */
884 	if (func == kputchar)
885 		atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
886 	if (usespin) {
887 		spin_unlock(&cons_spin);
888 		crit_exit_hard();
889 	}
890 	return (retval);
891 }
892 
893 #undef PCHAR
894 
895 /*
896  * Called from the panic code to try to get the console working
897  * again in case we paniced inside a kprintf().
898  */
899 void
900 kvcreinitspin(void)
901 {
902 	spin_init(&cons_spin);
903 	atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
904 }
905 
906 /*
907  * Console support thread for constty intercepts.  This is needed because
908  * console tty intercepts can block.  Instead of having kputchar() attempt
909  * to directly write to the console intercept we just force it to log
910  * and wakeup this baby to track and dump the log to constty.
911  */
912 static void
913 constty_daemon(void)
914 {
915 	int rindex = -1;
916 	int windex = -1;
917         struct msgbuf *mbp;
918 	struct tty *tp;
919 
920         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
921                               constty_td, SHUTDOWN_PRI_FIRST);
922         constty_td->td_flags |= TDF_SYSTHREAD;
923 
924         for (;;) {
925                 kproc_suspend_loop();
926 
927 		crit_enter();
928 		mbp = msgbufp;
929 		if (mbp == NULL || msgbufmapped == 0 ||
930 		    windex == mbp->msg_bufx) {
931 			tsleep(constty_td, 0, "waiting", hz*60);
932 			crit_exit();
933 			continue;
934 		}
935 		windex = mbp->msg_bufx;
936 		crit_exit();
937 
938 		/*
939 		 * Get message buf FIFO indices.  rindex is tracking.
940 		 */
941 		if ((tp = constty) == NULL) {
942 			rindex = mbp->msg_bufx;
943 			continue;
944 		}
945 
946 		/*
947 		 * Don't blow up if the message buffer is broken
948 		 */
949 		if (windex < 0 || windex >= mbp->msg_size)
950 			continue;
951 		if (rindex < 0 || rindex >= mbp->msg_size)
952 			rindex = windex;
953 
954 		/*
955 		 * And dump it.  If constty gets stuck will give up.
956 		 */
957 		while (rindex != windex) {
958 			if (tputchar((uint8_t)mbp->msg_ptr[rindex], tp) < 0) {
959 				constty = NULL;
960 				rindex = mbp->msg_bufx;
961 				break;
962 			}
963 			if (++rindex >= mbp->msg_size)
964 				rindex = 0;
965                         if (tp->t_outq.c_cc >= tp->t_ohiwat) {
966 				tsleep(constty_daemon, 0, "blocked", hz / 10);
967 				if (tp->t_outq.c_cc >= tp->t_ohiwat) {
968 					rindex = windex;
969 					break;
970 				}
971 			}
972 		}
973 	}
974 }
975 
976 static struct kproc_desc constty_kp = {
977         "consttyd",
978 	constty_daemon,
979         &constty_td
980 };
981 SYSINIT(bufdaemon, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY,
982         kproc_start, &constty_kp)
983 
984 /*
985  * Put character in log buffer with a particular priority.
986  *
987  * MPSAFE
988  */
989 static void
990 msglogchar(int c, int pri)
991 {
992 	static int lastpri = -1;
993 	static int dangling;
994 	char nbuf[MAXNBUF];
995 	char *p;
996 
997 	if (!msgbufmapped)
998 		return;
999 	if (c == '\0' || c == '\r')
1000 		return;
1001 	if (pri != -1 && pri != lastpri) {
1002 		if (dangling) {
1003 			msgaddchar('\n', NULL);
1004 			dangling = 0;
1005 		}
1006 		msgaddchar('<', NULL);
1007 		for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
1008 			msgaddchar(*p--, NULL);
1009 		msgaddchar('>', NULL);
1010 		lastpri = pri;
1011 	}
1012 	msgaddchar(c, NULL);
1013 	if (c == '\n') {
1014 		dangling = 0;
1015 		lastpri = -1;
1016 	} else {
1017 		dangling = 1;
1018 	}
1019 }
1020 
1021 /*
1022  * Put char in log buffer.   Make sure nothing blows up beyond repair if
1023  * we have an MP race.
1024  *
1025  * MPSAFE.
1026  */
1027 static void
1028 msgaddchar(int c, void *dummy)
1029 {
1030 	struct msgbuf *mbp;
1031 	int rindex;
1032 	int windex;
1033 
1034 	if (!msgbufmapped)
1035 		return;
1036 	mbp = msgbufp;
1037 	windex = mbp->msg_bufx;
1038 	mbp->msg_ptr[windex] = c;
1039 	if (++windex >= mbp->msg_size)
1040 		windex = 0;
1041 	rindex = mbp->msg_bufr;
1042 	if (windex == rindex) {
1043 		rindex += 32;
1044 		if (rindex >= mbp->msg_size)
1045 			rindex -= mbp->msg_size;
1046 		mbp->msg_bufr = rindex;
1047 	}
1048 	mbp->msg_bufx = windex;
1049 }
1050 
1051 static void
1052 msgbufcopy(struct msgbuf *oldp)
1053 {
1054 	int pos;
1055 
1056 	pos = oldp->msg_bufr;
1057 	while (pos != oldp->msg_bufx) {
1058 		msglogchar(oldp->msg_ptr[pos], -1);
1059 		if (++pos >= oldp->msg_size)
1060 			pos = 0;
1061 	}
1062 }
1063 
1064 void
1065 msgbufinit(void *ptr, size_t size)
1066 {
1067 	char *cp;
1068 	static struct msgbuf *oldp = NULL;
1069 
1070 	size -= sizeof(*msgbufp);
1071 	cp = (char *)ptr;
1072 	msgbufp = (struct msgbuf *) (cp + size);
1073 	if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
1074 	    msgbufp->msg_bufx >= size || msgbufp->msg_bufr >= size) {
1075 		bzero(cp, size);
1076 		bzero(msgbufp, sizeof(*msgbufp));
1077 		msgbufp->msg_magic = MSG_MAGIC;
1078 		msgbufp->msg_size = (char *)msgbufp - cp;
1079 	}
1080 	msgbufp->msg_ptr = cp;
1081 	if (msgbufmapped && oldp != msgbufp)
1082 		msgbufcopy(oldp);
1083 	msgbufmapped = 1;
1084 	oldp = msgbufp;
1085 }
1086 
1087 /* Sysctls for accessing/clearing the msgbuf */
1088 
1089 static int
1090 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1091 {
1092 	struct ucred *cred;
1093 	int error;
1094 
1095 	/*
1096 	 * Only wheel or root can access the message log.
1097 	 */
1098 	if (unprivileged_read_msgbuf == 0) {
1099 		KKASSERT(req->td->td_proc);
1100 		cred = req->td->td_proc->p_ucred;
1101 
1102 		if ((cred->cr_prison || groupmember(0, cred) == 0) &&
1103 		    priv_check(req->td, PRIV_ROOT) != 0
1104 		) {
1105 			return (EPERM);
1106 		}
1107 	}
1108 
1109 	/*
1110 	 * Unwind the buffer, so that it's linear (possibly starting with
1111 	 * some initial nulls).
1112 	 */
1113 	error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
1114 	    msgbufp->msg_size - msgbufp->msg_bufx, req);
1115 	if (error)
1116 		return (error);
1117 	if (msgbufp->msg_bufx > 0) {
1118 		error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
1119 		    msgbufp->msg_bufx, req);
1120 	}
1121 	return (error);
1122 }
1123 
1124 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
1125     0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1126 
1127 static int msgbuf_clear;
1128 
1129 static int
1130 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1131 {
1132 	int error;
1133 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1134 	if (!error && req->newptr) {
1135 		/* Clear the buffer and reset write pointer */
1136 		bzero(msgbufp->msg_ptr, msgbufp->msg_size);
1137 		msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
1138 		msgbuf_clear = 0;
1139 	}
1140 	return (error);
1141 }
1142 
1143 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1144     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
1145     sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
1146 
1147 #ifdef DDB
1148 
1149 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1150 {
1151 	int i, j;
1152 
1153 	if (!msgbufmapped) {
1154 		db_printf("msgbuf not mapped yet\n");
1155 		return;
1156 	}
1157 	db_printf("msgbufp = %p\n", msgbufp);
1158 	db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
1159 	    msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
1160 	    msgbufp->msg_bufx, msgbufp->msg_ptr);
1161 	for (i = 0; i < msgbufp->msg_size; i++) {
1162 		j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
1163 		db_printf("%c", msgbufp->msg_ptr[j]);
1164 	}
1165 	db_printf("\n");
1166 }
1167 
1168 #endif /* DDB */
1169 
1170 
1171 void
1172 hexdump(const void *ptr, int length, const char *hdr, int flags)
1173 {
1174 	int i, j, k;
1175 	int cols;
1176 	const unsigned char *cp;
1177 	char delim;
1178 
1179 	if ((flags & HD_DELIM_MASK) != 0)
1180 		delim = (flags & HD_DELIM_MASK) >> 8;
1181 	else
1182 		delim = ' ';
1183 
1184 	if ((flags & HD_COLUMN_MASK) != 0)
1185 		cols = flags & HD_COLUMN_MASK;
1186 	else
1187 		cols = 16;
1188 
1189 	cp = ptr;
1190 	for (i = 0; i < length; i+= cols) {
1191 		if (hdr != NULL)
1192 			kprintf("%s", hdr);
1193 
1194 		if ((flags & HD_OMIT_COUNT) == 0)
1195 			kprintf("%04x  ", i);
1196 
1197 		if ((flags & HD_OMIT_HEX) == 0) {
1198 			for (j = 0; j < cols; j++) {
1199 				k = i + j;
1200 				if (k < length)
1201 					kprintf("%c%02x", delim, cp[k]);
1202 				else
1203 					kprintf("   ");
1204 			}
1205 		}
1206 
1207 		if ((flags & HD_OMIT_CHARS) == 0) {
1208 			kprintf("  |");
1209 			for (j = 0; j < cols; j++) {
1210 				k = i + j;
1211 				if (k >= length)
1212 					kprintf(" ");
1213 				else if (cp[k] >= ' ' && cp[k] <= '~')
1214 					kprintf("%c", cp[k]);
1215 				else
1216 					kprintf(".");
1217 			}
1218 			kprintf("|");
1219 		}
1220 		kprintf("\n");
1221 	}
1222 }
1223