xref: /dflybsd-src/sys/kern/subr_prf.c (revision 2f8af9db97ed459e9c8eb19927a185f29b8b0d2e)
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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)subr_prf.c	8.3 (Berkeley) 1/21/94
35  * $FreeBSD: src/sys/kern/subr_prf.c,v 1.61.2.5 2002/08/31 18:22:08 dwmalone Exp $
36  */
37 
38 #include "opt_ddb.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/msgbuf.h>
44 #include <sys/malloc.h>
45 #include <sys/proc.h>
46 #include <sys/priv.h>
47 #include <sys/tty.h>
48 #include <sys/tprintf.h>
49 #include <sys/stdint.h>
50 #include <sys/syslog.h>
51 #include <sys/cons.h>
52 #include <sys/uio.h>
53 #include <sys/sysctl.h>
54 #include <sys/lock.h>
55 #include <sys/ctype.h>
56 #include <sys/eventhandler.h>
57 #include <sys/kthread.h>
58 #include <sys/cpu_topology.h>
59 
60 #include <sys/thread2.h>
61 #include <sys/spinlock2.h>
62 
63 #ifdef DDB
64 #include <ddb/ddb.h>
65 #endif
66 
67 /*
68  * Note that stdarg.h and the ANSI style va_start macro is used for both
69  * ANSI and traditional C compilers.  We use the __ machine version to stay
70  * within the kernel header file set.
71  */
72 #include <machine/stdarg.h>
73 
74 #define TOCONS		0x01
75 #define TOTTY		0x02
76 #define TOLOG		0x04
77 #define TOWAKEUP	0x08
78 #define TONOSPIN	0x10	/* avoid serialization */
79 
80 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
81 #define MAXNBUF	(sizeof(intmax_t) * NBBY + 1)
82 
83 struct putchar_arg {
84 	int	flags;
85 	int	pri;
86 	struct	tty *tty;
87 };
88 
89 struct snprintf_arg {
90 	char	*str;
91 	size_t	remain;
92 };
93 
94 extern	int log_open;
95 
96 struct	tty *constty;			/* pointer to console "window" tty */
97 
98 static void  msglogchar(int c, int pri);
99 static void  msgaddchar(int c, void *dummy);
100 static void  kputchar (int ch, void *arg);
101 static char *ksprintn (char *nbuf, uintmax_t num, int base, int *lenp,
102 		       int upper);
103 static void  snprintf_func (int ch, void *arg);
104 
105 static int consintr = 1;		/* Ok to handle console interrupts? */
106 static int msgbufmapped;		/* Set when safe to use msgbuf */
107 static struct spinlock cons_spin = SPINLOCK_INITIALIZER(cons_spin, "cons_spin");
108 static thread_t constty_td = NULL;
109 
110 int msgbuftrigger;
111 
112 static int      log_console_output = 1;
113 TUNABLE_INT("kern.log_console_output", &log_console_output);
114 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
115     &log_console_output, 0, "");
116 static int	kprintf_logging = TOLOG | TOCONS;
117 SYSCTL_INT(_kern, OID_AUTO, kprintf_logging, CTLFLAG_RW,
118     &kprintf_logging, 0, "");
119 
120 static int unprivileged_read_msgbuf = 1;
121 SYSCTL_INT(_security, OID_AUTO, unprivileged_read_msgbuf, CTLFLAG_RW,
122     &unprivileged_read_msgbuf, 0,
123     "Unprivileged processes may read the kernel message buffer");
124 
125 /*
126  * Warn that a system table is full.
127  */
128 void
129 tablefull(const char *tab)
130 {
131 
132 	log(LOG_ERR, "%s: table is full\n", tab);
133 }
134 
135 /*
136  * Uprintf prints to the controlling terminal for the current process.
137  */
138 int
139 uprintf(const char *fmt, ...)
140 {
141 	struct proc *p = curproc;
142 	__va_list ap;
143 	struct putchar_arg pca;
144 	int retval = 0;
145 
146 	if (p && (p->p_flags & P_CONTROLT) && p->p_session->s_ttyvp) {
147 		__va_start(ap, fmt);
148 		pca.tty = p->p_session->s_ttyp;
149 		pca.flags = TOTTY;
150 
151 		retval = kvcprintf(fmt, kputchar, &pca, ap);
152 		__va_end(ap);
153 	}
154 	return (retval);
155 }
156 
157 tpr_t
158 tprintf_open(struct proc *p)
159 {
160 	if ((p->p_flags & P_CONTROLT) && p->p_session->s_ttyvp) {
161 		sess_hold(p->p_session);
162 		return ((tpr_t) p->p_session);
163 	}
164 	return (NULL);
165 }
166 
167 void
168 tprintf_close(tpr_t sess)
169 {
170 	if (sess)
171 		sess_rele((struct session *) sess);
172 }
173 
174 /*
175  * tprintf prints on the controlling terminal associated
176  * with the given session.
177  */
178 int
179 tprintf(tpr_t tpr, const char *fmt, ...)
180 {
181 	struct session *sess = (struct session *)tpr;
182 	struct tty *tp = NULL;
183 	int flags = TOLOG;
184 	__va_list ap;
185 	struct putchar_arg pca;
186 	int retval;
187 
188 	if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
189 		flags |= TOTTY;
190 		tp = sess->s_ttyp;
191 	}
192 	__va_start(ap, fmt);
193 	pca.tty = tp;
194 	pca.flags = flags;
195 	pca.pri = LOG_INFO;
196 	retval = kvcprintf(fmt, kputchar, &pca, ap);
197 	__va_end(ap);
198 	msgbuftrigger = 1;
199 	return (retval);
200 }
201 
202 /*
203  * Ttyprintf displays a message on a tty; it should be used only by
204  * the tty driver, or anything that knows the underlying tty will not
205  * be revoke(2)'d away.  Other callers should use tprintf.
206  */
207 int
208 ttyprintf(struct tty *tp, const char *fmt, ...)
209 {
210 	__va_list ap;
211 	struct putchar_arg pca;
212 	int retval;
213 
214 	__va_start(ap, fmt);
215 	pca.tty = tp;
216 	pca.flags = TOTTY;
217 	retval = kvcprintf(fmt, kputchar, &pca, ap);
218 	__va_end(ap);
219 	return (retval);
220 }
221 
222 /*
223  * Log writes to the log buffer, and guarantees not to sleep (so can be
224  * called by interrupt routines).  If there is no process reading the
225  * log yet, it writes to the console also.
226  */
227 int
228 log(int level, const char *fmt, ...)
229 {
230 	__va_list ap;
231 	int retval;
232 	struct putchar_arg pca;
233 
234 	pca.tty = NULL;
235 	pca.pri = level;
236 	if ((kprintf_logging & TOCONS) == 0 || log_open)
237 		pca.flags = TOLOG;
238 	else
239 		pca.flags = TOCONS;
240 
241 	__va_start(ap, fmt);
242 	retval = kvcprintf(fmt, kputchar, &pca, ap);
243 	__va_end(ap);
244 
245 	msgbuftrigger = 1;
246 	return (retval);
247 }
248 
249 #define CONSCHUNK 128
250 
251 void
252 log_console(struct uio *uio)
253 {
254 	int c, i, error, iovlen, nl;
255 	struct uio muio;
256 	struct iovec *miov = NULL;
257 	char *consbuffer;
258 	int pri;
259 
260 	if (!log_console_output)
261 		return;
262 
263 	pri = LOG_INFO | LOG_CONSOLE;
264 	muio = *uio;
265 	iovlen = uio->uio_iovcnt * sizeof (struct iovec);
266 	miov = kmalloc(iovlen, M_TEMP, M_WAITOK);
267 	consbuffer = kmalloc(CONSCHUNK, M_TEMP, M_WAITOK);
268 	bcopy((caddr_t)muio.uio_iov, (caddr_t)miov, iovlen);
269 	muio.uio_iov = miov;
270 	uio = &muio;
271 
272 	nl = 0;
273 	while (uio->uio_resid > 0) {
274 		c = (int)szmin(uio->uio_resid, CONSCHUNK);
275 		error = uiomove(consbuffer, (size_t)c, uio);
276 		if (error != 0)
277 			break;
278 		for (i = 0; i < c; i++) {
279 			msglogchar(consbuffer[i], pri);
280 			if (consbuffer[i] == '\n')
281 				nl = 1;
282 			else
283 				nl = 0;
284 		}
285 	}
286 	if (!nl)
287 		msglogchar('\n', pri);
288 	msgbuftrigger = 1;
289 	kfree(miov, M_TEMP);
290 	kfree(consbuffer, M_TEMP);
291 	return;
292 }
293 
294 /*
295  * Output to the console.
296  */
297 int
298 kprintf(const char *fmt, ...)
299 {
300 	__va_list ap;
301 	int savintr;
302 	struct putchar_arg pca;
303 	int retval;
304 
305 	savintr = consintr;		/* disable interrupts */
306 	consintr = 0;
307 	__va_start(ap, fmt);
308 	pca.tty = NULL;
309 	pca.flags = kprintf_logging & ~TOTTY;
310 	pca.pri = -1;
311 	retval = kvcprintf(fmt, kputchar, &pca, ap);
312 	__va_end(ap);
313 	if (!panicstr)
314 		msgbuftrigger = 1;
315 	consintr = savintr;		/* reenable interrupts */
316 	return (retval);
317 }
318 
319 int
320 kvprintf(const char *fmt, __va_list ap)
321 {
322 	int savintr;
323 	struct putchar_arg pca;
324 	int retval;
325 
326 	savintr = consintr;		/* disable interrupts */
327 	consintr = 0;
328 	pca.tty = NULL;
329 	pca.flags = kprintf_logging & ~TOTTY;
330 	pca.pri = -1;
331 	retval = kvcprintf(fmt, kputchar, &pca, ap);
332 	if (!panicstr)
333 		msgbuftrigger = 1;
334 	consintr = savintr;		/* reenable interrupts */
335 	return (retval);
336 }
337 
338 /*
339  * Limited rate kprintf.  The passed rate structure must be initialized
340  * with the desired reporting frequency.  A frequency of 0 will result in
341  * no output.
342  *
343  * count may be initialized to a negative number to allow an initial
344  * burst.
345  */
346 void
347 krateprintf(struct krate *rate, const char *fmt, ...)
348 {
349 	__va_list ap;
350 
351 	if (rate->ticks != (int)time_uptime) {
352 		rate->ticks = (int)time_uptime;
353 		if (rate->count > 0)
354 			rate->count = 0;
355 	}
356 	if (rate->count < rate->freq) {
357 		++rate->count;
358 		__va_start(ap, fmt);
359 		kvprintf(fmt, ap);
360 		__va_end(ap);
361 	}
362 }
363 
364 /*
365  * Print a character to the dmesg log, the console, and/or the user's
366  * terminal.
367  *
368  * NOTE: TOTTY does not require nonblocking operation, but TOCONS
369  * 	 and TOLOG do.  When we have a constty we still output to
370  *	 the real console but we have a monitoring thread which
371  *	 we wakeup which tracks the log.
372  */
373 static void
374 kputchar(int c, void *arg)
375 {
376 	struct putchar_arg *ap = (struct putchar_arg*) arg;
377 	int flags = ap->flags;
378 	struct tty *tp = ap->tty;
379 
380 	if (panicstr)
381 		constty = NULL;
382 	if ((flags & TOCONS) && tp == NULL && constty)
383 		flags |= TOLOG | TOWAKEUP;
384 	if ((flags & TOTTY) && tputchar(c, tp) < 0)
385 		ap->flags &= ~TOTTY;
386 	if ((flags & TOLOG))
387 		msglogchar(c, ap->pri);
388 	if ((flags & TOCONS) && c)
389 		cnputc(c);
390 	if (flags & TOWAKEUP)
391 		wakeup(constty_td);
392 }
393 
394 /*
395  * Scaled down version of sprintf(3).
396  */
397 int
398 ksprintf(char *buf, const char *cfmt, ...)
399 {
400 	int retval;
401 	__va_list ap;
402 
403 	__va_start(ap, cfmt);
404 	retval = kvcprintf(cfmt, NULL, buf, ap);
405 	buf[retval] = '\0';
406 	__va_end(ap);
407 	return (retval);
408 }
409 
410 /*
411  * Scaled down version of vsprintf(3).
412  */
413 int
414 kvsprintf(char *buf, const char *cfmt, __va_list ap)
415 {
416 	int retval;
417 
418 	retval = kvcprintf(cfmt, NULL, buf, ap);
419 	buf[retval] = '\0';
420 	return (retval);
421 }
422 
423 /*
424  * Scaled down version of snprintf(3).
425  */
426 int
427 ksnprintf(char *str, size_t size, const char *format, ...)
428 {
429 	int retval;
430 	__va_list ap;
431 
432 	__va_start(ap, format);
433 	retval = kvsnprintf(str, size, format, ap);
434 	__va_end(ap);
435 	return(retval);
436 }
437 
438 /*
439  * Scaled down version of vsnprintf(3).
440  */
441 int
442 kvsnprintf(char *str, size_t size, const char *format, __va_list ap)
443 {
444 	struct snprintf_arg info;
445 	int retval;
446 
447 	info.str = str;
448 	info.remain = size;
449 	retval = kvcprintf(format, snprintf_func, &info, ap);
450 	if (info.remain >= 1)
451 		*info.str++ = '\0';
452 	return (retval);
453 }
454 
455 int
456 kvasnprintf(char **strp, size_t size, const char *format, __va_list ap)
457 {
458 	struct snprintf_arg info;
459 	int retval;
460 
461 	*strp = kmalloc(size, M_TEMP, M_WAITOK);
462 	info.str = *strp;
463 	info.remain = size;
464 	retval = kvcprintf(format, snprintf_func, &info, ap);
465 	if (info.remain >= 1)
466 		*info.str++ = '\0';
467 	return (retval);
468 }
469 
470 void
471 kvasfree(char **strp)
472 {
473 	if (*strp) {
474 		kfree(*strp, M_TEMP);
475 		*strp = NULL;
476 	}
477 }
478 
479 static void
480 snprintf_func(int ch, void *arg)
481 {
482 	struct snprintf_arg *const info = arg;
483 
484 	if (info->remain >= 2) {
485 		*info->str++ = ch;
486 		info->remain--;
487 	}
488 }
489 
490 /*
491  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
492  * order; return an optional length and a pointer to the last character
493  * written in the buffer (i.e., the first character of the string).
494  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
495  */
496 static char *
497 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
498 {
499 	char *p, c;
500 
501 	p = nbuf;
502 	*p = '\0';
503 	do {
504 		c = hex2ascii(num % base);
505 		*++p = upper ? toupper(c) : c;
506 	} while (num /= base);
507 	if (lenp)
508 		*lenp = p - nbuf;
509 	return (p);
510 }
511 
512 /*
513  * Scaled down version of printf(3).
514  *
515  * Two additional formats:
516  *
517  * The format %pb%i is supported to decode error registers.
518  * The use %b format is deprecated.
519  * Its usage is:
520  *
521  *	kprintf("reg=%pb%i\n", "<base><arg>*", regval);
522  *
523  * where <base> is the output base expressed as a control character, e.g.
524  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
525  * the first of which gives the bit number to be inspected (origin 1), and
526  * the next characters (up to a control character, i.e. a character <= 32),
527  * give the name of the register.  Thus:
528  *
529  *	kvcprintf("reg=%pb%i\n", "\10\2BITTWO\1BITONE\n", 3);
530  *
531  * would produce output:
532  *
533  *	reg=3<BITTWO,BITONE>
534  */
535 
536 #define PCHAR(c) {int cc=(c); if(func) (*func)(cc,arg); else *d++=cc; retval++;}
537 
538 int
539 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg, __va_list ap)
540 {
541 	char nbuf[MAXNBUF];
542 	char *d;
543 	const char *p, *percent, *q;
544 	int ch, n;
545 	uintmax_t num;
546 	int base, tmp, width, ladjust, sharpflag, spaceflag, neg, sign, dot;
547 	int cflag, hflag, jflag, lflag, qflag, tflag, zflag;
548 	int dwidth, upper;
549 	char padc;
550 	int retval = 0, stop = 0;
551 	int usespin;
552 
553 	/*
554 	 * Make a supreme effort to avoid reentrant panics or deadlocks.
555 	 *
556 	 * NOTE!  Do nothing that would access mycpu/gd/fs unless the
557 	 *	  function is the normal kputchar(), which allows us to
558 	 *	  use this function for very early debugging with a special
559 	 *	  function.
560 	 */
561 	if (func == kputchar) {
562 		if (mycpu->gd_flags & GDF_KPRINTF)
563 			return(0);
564 		atomic_set_long(&mycpu->gd_flags, GDF_KPRINTF);
565 	}
566 
567 	num = 0;
568 	if (!func)
569 		d = (char *) arg;
570 	else
571 		d = NULL;
572 
573 	if (fmt == NULL)
574 		fmt = "(fmt null)\n";
575 
576 	usespin = (func == kputchar &&
577 		   (kprintf_logging & TONOSPIN) == 0 &&
578 		   panic_cpu_gd != mycpu &&
579 		   (((struct putchar_arg *)arg)->flags & TOTTY) == 0);
580 	if (usespin) {
581 		crit_enter_hard();
582 		spin_lock(&cons_spin);
583 	}
584 
585 	for (;;) {
586 		padc = ' ';
587 		width = 0;
588 		while ((ch = (u_char)*fmt++) != '%' || stop) {
589 			if (ch == '\0')
590 				goto done;
591 			PCHAR(ch);
592 		}
593 		percent = fmt - 1;
594 		dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
595 		spaceflag = 0;
596 		cflag = hflag = jflag = lflag = qflag = tflag = zflag = 0;
597 
598 reswitch:
599 		switch (ch = (u_char)*fmt++) {
600 		case ' ':
601 			spaceflag = 1;
602 			goto reswitch;
603 		case '.':
604 			dot = 1;
605 			goto reswitch;
606 		case '#':
607 			sharpflag = 1;
608 			goto reswitch;
609 		case '+':
610 			sign = 1;
611 			goto reswitch;
612 		case '-':
613 			ladjust = 1;
614 			goto reswitch;
615 		case '%':
616 			PCHAR(ch);
617 			break;
618 		case '*':
619 			if (!dot) {
620 				width = __va_arg(ap, int);
621 				if (width < 0) {
622 					ladjust = !ladjust;
623 					width = -width;
624 				}
625 			} else {
626 				dwidth = __va_arg(ap, int);
627 			}
628 			goto reswitch;
629 		case '0':
630 			if (!dot) {
631 				padc = '0';
632 				goto reswitch;
633 			}
634 		case '1': case '2': case '3': case '4':
635 		case '5': case '6': case '7': case '8': case '9':
636 				for (n = 0;; ++fmt) {
637 					n = n * 10 + ch - '0';
638 					ch = *fmt;
639 					if (ch < '0' || ch > '9')
640 						break;
641 				}
642 			if (dot)
643 				dwidth = n;
644 			else
645 				width = n;
646 			goto reswitch;
647 		case 'b':
648 			num = (u_int)__va_arg(ap, int);
649 			p = __va_arg(ap, char *);
650 			for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
651 				PCHAR(*q--);
652 
653 			if (num == 0)
654 				break;
655 
656 			for (tmp = 0; *p;) {
657 				n = *p++;
658 				if (num & (1 << (n - 1))) {
659 					PCHAR(tmp ? ',' : '<');
660 					for (; (n = *p) > ' '; ++p)
661 						PCHAR(n);
662 					tmp = 1;
663 				} else
664 					for (; *p > ' '; ++p)
665 						continue;
666 			}
667 			if (tmp)
668 				PCHAR('>');
669 			break;
670 		case 'c':
671 			PCHAR(__va_arg(ap, int));
672 			break;
673 		case 'd':
674 		case 'i':
675 			base = 10;
676 			sign = 1;
677 			goto handle_sign;
678 		case 'h':
679 			if (hflag) {
680 				hflag = 0;
681 				cflag = 1;
682 			} else
683 				hflag = 1;
684 			goto reswitch;
685 		case 'j':
686 			jflag = 1;
687 			goto reswitch;
688 		case 'l':
689 			if (lflag) {
690 				lflag = 0;
691 				qflag = 1;
692 			} else
693 				lflag = 1;
694 			goto reswitch;
695 		case 'n':
696 			if (cflag)
697 				*(__va_arg(ap, char *)) = retval;
698 			else if (hflag)
699 				*(__va_arg(ap, short *)) = retval;
700 			else if (jflag)
701 				*(__va_arg(ap, intmax_t *)) = retval;
702 			else if (lflag)
703 				*(__va_arg(ap, long *)) = retval;
704 			else if (qflag)
705 				*(__va_arg(ap, quad_t *)) = retval;
706 			else
707 				*(__va_arg(ap, int *)) = retval;
708 			break;
709 		case 'o':
710 			base = 8;
711 			goto handle_nosign;
712 		case 'p':
713 			/* peek if this is a /b/ hiding as /p/ or not */
714 			if (fmt[0] == 'b' && fmt[1] == '%' && fmt[2] == 'i') {
715 				fmt += 3; /* consume "b%i" */
716 				p = __va_arg(ap, char *);
717 				num = (u_int)__va_arg(ap, int);
718 				for (q = ksprintn(nbuf, num, *p++, NULL, 0);*q;)
719 					PCHAR(*q--);
720 
721 				if (num == 0)
722 					break;
723 
724 				for (tmp = 0; *p;) {
725 					n = *p++;
726 					if (num & (1 << (n - 1))) {
727 						PCHAR(tmp ? ',' : '<');
728 						for (; (n = *p) > ' '; ++p)
729 							PCHAR(n);
730 						tmp = 1;
731 					} else {
732 						for (; *p > ' '; ++p)
733 							continue;
734 					}
735 				}
736 				if (tmp)
737 					PCHAR('>');
738 				break;
739 			}
740 			base = 16;
741 			sharpflag = (width == 0);
742 			sign = 0;
743 			num = (uintptr_t)__va_arg(ap, void *);
744 			goto number;
745 		case 'q':
746 			qflag = 1;
747 			goto reswitch;
748 		case 's':
749 			p = __va_arg(ap, char *);
750 			if (p == NULL)
751 				p = "(null)";
752 			if (!dot)
753 				n = strlen (p);
754 			else
755 				for (n = 0; n < dwidth && p[n]; n++)
756 					continue;
757 
758 			width -= n;
759 
760 			if (!ladjust && width > 0)
761 				while (width--)
762 					PCHAR(padc);
763 			while (n--)
764 				PCHAR(*p++);
765 			if (ladjust && width > 0)
766 				while (width--)
767 					PCHAR(padc);
768 			break;
769 		case 't':
770 			tflag = 1;
771 			goto reswitch;
772 		case 'u':
773 			base = 10;
774 			goto handle_nosign;
775 		case 'X':
776 			upper = 1;
777 			/* FALLTHROUGH */
778 		case 'x':
779 			base = 16;
780 			goto handle_nosign;
781 		case 'z':
782 			zflag = 1;
783 			goto reswitch;
784 handle_nosign:
785 			sign = 0;
786 			if (cflag)
787 				num = (u_char)__va_arg(ap, int);
788 			else if (hflag)
789 				num = (u_short)__va_arg(ap, int);
790 			else if (jflag)
791 				num = __va_arg(ap, uintmax_t);
792 			else if (lflag)
793 				num = __va_arg(ap, u_long);
794 			else if (qflag)
795 				num = __va_arg(ap, u_quad_t);
796 			else if (tflag)
797 				num = __va_arg(ap, ptrdiff_t);
798 			else if (zflag)
799 				num = __va_arg(ap, size_t);
800 			else
801 				num = __va_arg(ap, u_int);
802 			goto number;
803 handle_sign:
804 			if (cflag)
805 				num = (char)__va_arg(ap, int);
806 			else if (hflag)
807 				num = (short)__va_arg(ap, int);
808 			else if (jflag)
809 				num = __va_arg(ap, intmax_t);
810 			else if (lflag)
811 				num = __va_arg(ap, long);
812 			else if (qflag)
813 				num = __va_arg(ap, quad_t);
814 			else if (tflag)
815 				num = __va_arg(ap, ptrdiff_t);
816 			else if (zflag)
817 				num = __va_arg(ap, ssize_t);
818 			else
819 				num = __va_arg(ap, int);
820 number:
821 			if (sign && (intmax_t)num < 0) {
822 				neg = 1;
823 				num = -(intmax_t)num;
824 			}
825 			p = ksprintn(nbuf, num, base, &n, upper);
826 			tmp = 0;
827 			if (sharpflag && num != 0) {
828 				if (base == 8)
829 					tmp++;
830 				else if (base == 16)
831 					tmp += 2;
832 			}
833 			if (neg || (sign && spaceflag))
834 				tmp++;
835 
836 			if (!ladjust && padc == '0')
837 				dwidth = width - tmp;
838 			width -= tmp + imax(dwidth, n);
839 			dwidth -= n;
840 			if (!ladjust)
841 				while (width-- > 0)
842 					PCHAR(' ');
843 			if (neg) {
844 				PCHAR('-');
845 			} else if (sign && spaceflag) {
846 				PCHAR(' ');
847 			}
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, "kvcre");
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 	u_int rindex;
916 	u_int xindex;
917 	u_int n;
918         struct msgbuf *mbp;
919 	struct tty *tp;
920 
921         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
922                               constty_td, SHUTDOWN_PRI_FIRST);
923         constty_td->td_flags |= TDF_SYSTHREAD;
924 
925 	mbp = msgbufp;
926 	rindex = mbp->msg_bufr;		/* persistent loop variable */
927 	xindex = mbp->msg_bufx - 1;	/* anything different than bufx */
928 	cpu_ccfence();
929 
930         for (;;) {
931                 kproc_suspend_loop();
932 
933 		crit_enter();
934 		if (mbp != msgbufp)
935 			mbp = msgbufp;
936 		if (xindex == mbp->msg_bufx ||
937 		    mbp == NULL ||
938 		    msgbufmapped == 0) {
939 			tsleep(constty_td, 0, "waiting", hz*60);
940 			crit_exit();
941 			continue;
942 		}
943 		crit_exit();
944 
945 		/*
946 		 * Get message buf FIFO indices.  rindex is tracking.
947 		 */
948 		xindex = mbp->msg_bufx;
949 		cpu_ccfence();
950 		if ((tp = constty) == NULL) {
951 			rindex = xindex;
952 			continue;
953 		}
954 
955 		/*
956 		 * Check if the calculated bytes has rolled the whole
957 		 * message buffer.
958 		 */
959 		n = xindex - rindex;
960 		if (n > mbp->msg_size - 1024) {
961 			rindex = xindex - mbp->msg_size + 2048;
962 			n = xindex - rindex;
963 		}
964 
965 		/*
966 		 * And dump it.  If constty gets stuck will give up.
967 		 */
968 		while (rindex != xindex) {
969 			u_int ri = rindex % mbp->msg_size;
970 			if (tputchar((uint8_t)mbp->msg_ptr[ri], tp) < 0) {
971 				constty = NULL;
972 				rindex = xindex;
973 				break;
974 			}
975                         if (tp->t_outq.c_cc >= tp->t_ohiwat) {
976 				tsleep(constty_daemon, 0, "blocked", hz / 10);
977 				if (tp->t_outq.c_cc >= tp->t_ohiwat) {
978 					rindex = xindex;
979 					break;
980 				}
981 			}
982 			++rindex;
983 		}
984 	}
985 }
986 
987 static struct kproc_desc constty_kp = {
988         "consttyd",
989 	constty_daemon,
990         &constty_td
991 };
992 SYSINIT(bufdaemon, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY,
993         kproc_start, &constty_kp);
994 
995 /*
996  * Put character in log buffer with a particular priority.
997  *
998  * MPSAFE
999  */
1000 static void
1001 msglogchar(int c, int pri)
1002 {
1003 	static int lastpri = -1;
1004 	static int dangling;
1005 	char nbuf[MAXNBUF];
1006 	char *p;
1007 
1008 	if (!msgbufmapped)
1009 		return;
1010 	if (c == '\0' || c == '\r')
1011 		return;
1012 	if (pri != -1 && pri != lastpri) {
1013 		if (dangling) {
1014 			msgaddchar('\n', NULL);
1015 			dangling = 0;
1016 		}
1017 		msgaddchar('<', NULL);
1018 		for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
1019 			msgaddchar(*p--, NULL);
1020 		msgaddchar('>', NULL);
1021 		lastpri = pri;
1022 	}
1023 	msgaddchar(c, NULL);
1024 	if (c == '\n') {
1025 		dangling = 0;
1026 		lastpri = -1;
1027 	} else {
1028 		dangling = 1;
1029 	}
1030 }
1031 
1032 /*
1033  * Put char in log buffer.   Make sure nothing blows up beyond repair if
1034  * we have an MP race.
1035  *
1036  * MPSAFE.
1037  */
1038 static void
1039 msgaddchar(int c, void *dummy)
1040 {
1041 	struct msgbuf *mbp;
1042 	u_int lindex;
1043 	u_int rindex;
1044 	u_int xindex;
1045 	u_int n;
1046 
1047 	if (!msgbufmapped)
1048 		return;
1049 	mbp = msgbufp;
1050 	lindex = mbp->msg_bufl;
1051 	rindex = mbp->msg_bufr;
1052 	xindex = mbp->msg_bufx++;	/* Allow SMP race */
1053 	cpu_ccfence();
1054 
1055 	mbp->msg_ptr[xindex % mbp->msg_size] = c;
1056 	n = xindex - lindex;
1057 	if (n > mbp->msg_size - 1024) {
1058 		lindex = xindex - mbp->msg_size + 2048;
1059 		cpu_ccfence();
1060 		mbp->msg_bufl = lindex;
1061 	}
1062 	n = xindex - rindex;
1063 	if (n > mbp->msg_size - 1024) {
1064 		rindex = xindex - mbp->msg_size + 2048;
1065 		cpu_ccfence();
1066 		mbp->msg_bufr = rindex;
1067 	}
1068 }
1069 
1070 static void
1071 msgbufcopy(struct msgbuf *oldp)
1072 {
1073 	u_int rindex;
1074 	u_int xindex;
1075 	u_int n;
1076 
1077 	rindex = oldp->msg_bufr;
1078 	xindex = oldp->msg_bufx;
1079 	cpu_ccfence();
1080 
1081 	n = xindex - rindex;
1082 	if (n > oldp->msg_size - 1024)
1083 		rindex = xindex - oldp->msg_size + 2048;
1084 	while (rindex != xindex) {
1085 		msglogchar(oldp->msg_ptr[rindex % oldp->msg_size], -1);
1086 		++rindex;
1087 	}
1088 }
1089 
1090 void
1091 msgbufinit(void *ptr, size_t size)
1092 {
1093 	char *cp;
1094 	static struct msgbuf *oldp = NULL;
1095 
1096 	size -= sizeof(*msgbufp);
1097 	cp = (char *)ptr;
1098 	msgbufp = (struct msgbuf *) (cp + size);
1099 	if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size) {
1100 		bzero(cp, size);
1101 		bzero(msgbufp, sizeof(*msgbufp));
1102 		msgbufp->msg_magic = MSG_MAGIC;
1103 		msgbufp->msg_size = (char *)msgbufp - cp;
1104 	}
1105 	msgbufp->msg_ptr = cp;
1106 	if (msgbufmapped && oldp != msgbufp)
1107 		msgbufcopy(oldp);
1108 	cpu_mfence();
1109 	msgbufmapped = 1;
1110 	oldp = msgbufp;
1111 }
1112 
1113 /* Sysctls for accessing/clearing the msgbuf */
1114 
1115 static int
1116 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1117 {
1118         struct msgbuf *mbp;
1119 	struct ucred *cred;
1120 	int error;
1121 	u_int rindex_modulo;
1122 	u_int xindex_modulo;
1123 	u_int rindex;
1124 	u_int xindex;
1125 	u_int n;
1126 
1127 	/*
1128 	 * Only wheel or root can access the message log.
1129 	 */
1130 	if (unprivileged_read_msgbuf == 0) {
1131 		KKASSERT(req->td->td_proc);
1132 		cred = req->td->td_proc->p_ucred;
1133 
1134 		if ((cred->cr_prison || groupmember(0, cred) == 0) &&
1135 		    priv_check(req->td, PRIV_ROOT) != 0
1136 		) {
1137 			return (EPERM);
1138 		}
1139 	}
1140 
1141 	/*
1142 	 * Unwind the buffer, so that it's linear (possibly starting with
1143 	 * some initial nulls).
1144 	 *
1145 	 * We don't push the entire buffer like we did before because
1146 	 * bufr (and bufl) now advance in chunks when the fifo is full,
1147 	 * rather than one character.
1148 	 */
1149 	mbp = msgbufp;
1150 	rindex = mbp->msg_bufr;
1151 	xindex = mbp->msg_bufx;
1152 	n = xindex - rindex;
1153 	if (n > mbp->msg_size - 1024) {
1154 		rindex = xindex - mbp->msg_size + 2048;
1155 		n = xindex - rindex;
1156 	}
1157 	rindex_modulo = rindex % mbp->msg_size;
1158 	xindex_modulo = xindex % mbp->msg_size;
1159 
1160 	if (rindex_modulo < xindex_modulo) {
1161 		/*
1162 		 * Can handle in one linear section.
1163 		 */
1164 		error = sysctl_handle_opaque(oidp,
1165 					     mbp->msg_ptr + rindex_modulo,
1166 					     xindex_modulo - rindex_modulo,
1167 					     req);
1168 	} else if (rindex_modulo == xindex_modulo) {
1169 		/*
1170 		 * Empty buffer, just return a single newline
1171 		 */
1172 		error = sysctl_handle_opaque(oidp, "\n", 1, req);
1173 	} else if (n <= mbp->msg_size - rindex_modulo) {
1174 		/*
1175 		 * Can handle in one linear section.
1176 		 */
1177 		error = sysctl_handle_opaque(oidp,
1178 					     mbp->msg_ptr + rindex_modulo,
1179 					     n - rindex_modulo,
1180 					     req);
1181 	} else {
1182 		/*
1183 		 * Glue together two linear sections into one contiguous
1184 		 * output.
1185 		 */
1186 		error = sysctl_handle_opaque(oidp,
1187 					     mbp->msg_ptr + rindex_modulo,
1188 					     mbp->msg_size - rindex_modulo,
1189 					     req);
1190 		n -= mbp->msg_size - rindex_modulo;
1191 		if (error == 0)
1192 			error = sysctl_handle_opaque(oidp, mbp->msg_ptr,
1193 						     n, req);
1194 	}
1195 	return (error);
1196 }
1197 
1198 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
1199     0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1200 
1201 static int msgbuf_clear;
1202 
1203 static int
1204 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1205 {
1206 	int error;
1207 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1208 	if (!error && req->newptr) {
1209 		/* Clear the buffer and reset write pointer */
1210 		msgbufp->msg_bufr = msgbufp->msg_bufx;
1211 		msgbufp->msg_bufl = msgbufp->msg_bufx;
1212 		bzero(msgbufp->msg_ptr, msgbufp->msg_size);
1213 		msgbuf_clear = 0;
1214 	}
1215 	return (error);
1216 }
1217 
1218 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1219     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
1220     sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
1221 
1222 #ifdef DDB
1223 
1224 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1225 {
1226 	u_int rindex;
1227 	u_int i;
1228 	u_int j;
1229 
1230 	if (!msgbufmapped) {
1231 		db_printf("msgbuf not mapped yet\n");
1232 		return;
1233 	}
1234 	db_printf("msgbufp = %p\n", msgbufp);
1235 	db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
1236 		  msgbufp->msg_magic, msgbufp->msg_size,
1237 		  msgbufp->msg_bufr % msgbufp->msg_size,
1238 		  msgbufp->msg_bufx % msgbufp->msg_size,
1239 		  msgbufp->msg_ptr);
1240 
1241 	rindex = msgbufp->msg_bufr;
1242 	for (i = 0; i < msgbufp->msg_size; i++) {
1243 		j = (i + rindex) % msgbufp->msg_size;
1244 		db_printf("%c", msgbufp->msg_ptr[j]);
1245 	}
1246 	db_printf("\n");
1247 }
1248 
1249 #endif /* DDB */
1250 
1251 
1252 void
1253 hexdump(const void *ptr, int length, const char *hdr, int flags)
1254 {
1255 	int i, j, k;
1256 	int cols;
1257 	const unsigned char *cp;
1258 	char delim;
1259 
1260 	if ((flags & HD_DELIM_MASK) != 0)
1261 		delim = (flags & HD_DELIM_MASK) >> 8;
1262 	else
1263 		delim = ' ';
1264 
1265 	if ((flags & HD_COLUMN_MASK) != 0)
1266 		cols = flags & HD_COLUMN_MASK;
1267 	else
1268 		cols = 16;
1269 
1270 	cp = ptr;
1271 	for (i = 0; i < length; i+= cols) {
1272 		if (hdr != NULL)
1273 			kprintf("%s", hdr);
1274 
1275 		if ((flags & HD_OMIT_COUNT) == 0)
1276 			kprintf("%04x  ", i);
1277 
1278 		if ((flags & HD_OMIT_HEX) == 0) {
1279 			for (j = 0; j < cols; j++) {
1280 				k = i + j;
1281 				if (k < length)
1282 					kprintf("%c%02x", delim, cp[k]);
1283 				else
1284 					kprintf("   ");
1285 			}
1286 		}
1287 
1288 		if ((flags & HD_OMIT_CHARS) == 0) {
1289 			kprintf("  |");
1290 			for (j = 0; j < cols; j++) {
1291 				k = i + j;
1292 				if (k >= length)
1293 					kprintf(" ");
1294 				else if (cp[k] >= ' ' && cp[k] <= '~')
1295 					kprintf("%c", cp[k]);
1296 				else
1297 					kprintf(".");
1298 			}
1299 			kprintf("|");
1300 		}
1301 		kprintf("\n");
1302 	}
1303 }
1304 
1305 void
1306 kprint_cpuset(cpumask_t *mask)
1307 {
1308 	int i;
1309 	int b = -1;
1310 	int e = -1;
1311 	int more = 0;
1312 
1313 	kprintf("cpus(");
1314 	CPUSET_FOREACH(i, *mask) {
1315 		if (b < 0) {
1316 			b = i;
1317 			e = b + 1;
1318 			continue;
1319 		}
1320 		if (e == i) {
1321 			++e;
1322 			continue;
1323 		}
1324 		if (more)
1325 			kprintf(", ");
1326 		if (b == e - 1) {
1327 			kprintf("%d", b);
1328 		} else {
1329 			kprintf("%d-%d", b, e - 1);
1330 		}
1331 		more = 1;
1332 		b = i;
1333 		e = b + 1;
1334 	}
1335 	if (more)
1336 		kprintf(", ");
1337 	if (b >= 0) {
1338 		if (b == e - 1) {
1339 			kprintf("%d", b);
1340 		} else {
1341 			kprintf("%d-%d", b, e - 1);
1342 		}
1343 	}
1344 	kprintf(") ");
1345 }
1346