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