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.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
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 $
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>
52 #include <sys/tprintf.h>
53 #include <sys/stdint.h>
54 #include <sys/syslog.h>
57 #include <sys/sysctl.h>
59 #include <sys/ctype.h>
60 #include <sys/eventhandler.h>
61 #include <sys/kthread.h>
63 #include <sys/thread2.h>
64 #include <sys/spinlock2.h>
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.
75 #include <machine/stdarg.h>
82 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
83 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
98 struct tty *constty; /* pointer to console "window" tty */
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,
105 static void snprintf_func (int ch, void *arg);
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;
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, "");
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");
125 * Warn that a system table is full.
128 tablefull(const char *tab)
131 log(LOG_ERR, "%s: table is full\n", tab);
135 * Uprintf prints to the controlling terminal for the current process.
138 uprintf(const char *fmt, ...)
140 struct proc *p = curproc;
142 struct putchar_arg pca;
145 if (p && (p->p_flags & P_CONTROLT) && p->p_session->s_ttyvp) {
147 pca.tty = p->p_session->s_ttyp;
150 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
157 tprintf_open(struct proc *p)
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);
167 tprintf_close(tpr_t sess)
170 sess_rele((struct session *) sess);
174 * tprintf prints on the controlling terminal associated
175 * with the given session.
178 tprintf(tpr_t tpr, const char *fmt, ...)
180 struct session *sess = (struct session *)tpr;
181 struct tty *tp = NULL;
184 struct putchar_arg pca;
187 if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
195 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
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.
207 ttyprintf(struct tty *tp, const char *fmt, ...)
210 struct putchar_arg pca;
216 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
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.
227 log(int level, const char *fmt, ...)
231 struct putchar_arg pca;
235 pca.flags = log_open ? TOLOG : TOCONS;
238 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
245 #define CONSCHUNK 128
248 log_console(struct uio *uio)
250 int c, i, error, iovlen, nl;
252 struct iovec *miov = NULL;
256 if (!log_console_output)
259 pri = LOG_INFO | LOG_CONSOLE;
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);
269 while (uio->uio_resid > 0) {
270 c = (int)szmin(uio->uio_resid, CONSCHUNK);
271 error = uiomove(consbuffer, (size_t)c, uio);
274 for (i = 0; i < c; i++) {
275 msglogchar(consbuffer[i], pri);
276 if (consbuffer[i] == '\n')
283 msglogchar('\n', pri);
286 kfree(consbuffer, M_TEMP);
291 * Output to the console.
294 kprintf(const char *fmt, ...)
298 struct putchar_arg pca;
301 savintr = consintr; /* disable interrupts */
305 pca.flags = TOCONS | TOLOG;
307 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
311 consintr = savintr; /* reenable interrupts */
316 kvprintf(const char *fmt, __va_list ap)
319 struct putchar_arg pca;
322 savintr = consintr; /* disable interrupts */
325 pca.flags = TOCONS | TOLOG;
327 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
330 consintr = savintr; /* reenable interrupts */
335 * Limited rate kprintf. The passed rate structure must be initialized
336 * with the desired reporting frequency. A frequency of 0 will result in
339 * count may be initialized to a negative number to allow an initial
343 krateprintf(struct krate *rate, const char *fmt, ...)
347 if (rate->ticks != (int)time_second) {
348 rate->ticks = (int)time_second;
352 if (rate->count < rate->freq) {
361 * Print a character to the dmesg log, the console, and/or the user's
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.
370 kputchar(int c, void *arg)
372 struct putchar_arg *ap = (struct putchar_arg*) arg;
373 int flags = ap->flags;
374 struct tty *tp = ap->tty;
378 if ((flags & TOCONS) && tp == NULL && constty)
379 flags |= TOLOG | TOWAKEUP;
380 if ((flags & TOTTY) && tputchar(c, tp) < 0)
383 msglogchar(c, ap->pri);
384 if ((flags & TOCONS) && c)
386 if (flags & TOWAKEUP)
391 * Scaled down version of sprintf(3).
394 ksprintf(char *buf, const char *cfmt, ...)
399 __va_start(ap, cfmt);
400 retval = kvcprintf(cfmt, NULL, buf, 10, ap);
407 * Scaled down version of vsprintf(3).
410 kvsprintf(char *buf, const char *cfmt, __va_list ap)
414 retval = kvcprintf(cfmt, NULL, buf, 10, ap);
420 * Scaled down version of snprintf(3).
423 ksnprintf(char *str, size_t size, const char *format, ...)
428 __va_start(ap, format);
429 retval = kvsnprintf(str, size, format, ap);
435 * Scaled down version of vsnprintf(3).
438 kvsnprintf(char *str, size_t size, const char *format, __va_list ap)
440 struct snprintf_arg info;
445 retval = kvcprintf(format, snprintf_func, &info, 10, ap);
446 if (info.remain >= 1)
452 ksnrprintf(char *str, size_t size, int radix, const char *format, ...)
457 __va_start(ap, format);
458 retval = kvsnrprintf(str, size, radix, format, ap);
464 kvsnrprintf(char *str, size_t size, int radix, const char *format, __va_list ap)
466 struct snprintf_arg info;
471 retval = kvcprintf(format, snprintf_func, &info, radix, ap);
472 if (info.remain >= 1)
478 kvasnrprintf(char **strp, size_t size, int radix,
479 const char *format, __va_list ap)
481 struct snprintf_arg info;
484 *strp = kmalloc(size, M_TEMP, M_WAITOK);
487 retval = kvcprintf(format, snprintf_func, &info, radix, ap);
488 if (info.remain >= 1)
494 kvasfree(char **strp)
497 kfree(*strp, M_TEMP);
503 snprintf_func(int ch, void *arg)
505 struct snprintf_arg *const info = arg;
507 if (info->remain >= 2) {
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.
520 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
527 c = hex2ascii(num % base);
528 *++p = upper ? toupper(c) : c;
529 } while (num /= base);
536 * Scaled down version of printf(3).
538 * Two additional formats:
540 * The format %b is supported to decode error registers.
543 * kprintf("reg=%b\n", regval, "<base><arg>*");
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:
551 * kvcprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
553 * would produce output:
555 * reg=3<BITTWO,BITONE>
558 #define PCHAR(c) {int cc=(c); if(func) (*func)(cc,arg); else *d++=cc; retval++;}
561 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg,
562 int radix, __va_list ap)
566 const char *p, *percent, *q;
569 int base, tmp, width, ladjust, sharpflag, neg, sign, dot;
570 int cflag, hflag, jflag, lflag, qflag, tflag, zflag;
573 int retval = 0, stop = 0;
577 * Make a supreme effort to avoid reentrant panics or deadlocks.
579 * NOTE! Do nothing that would access mycpu/gd/fs unless the
580 * function is the normal kputchar(), which allows us to
581 * use this function for very early debugging with a special
584 if (func == kputchar) {
585 if (mycpu->gd_flags & GDF_KPRINTF)
587 atomic_set_long(&mycpu->gd_flags, GDF_KPRINTF);
597 fmt = "(fmt null)\n";
599 if (radix < 2 || radix > 36)
602 usespin = (func == kputchar &&
603 panic_cpu_gd != mycpu &&
604 (((struct putchar_arg *)arg)->flags & TOTTY) == 0);
607 spin_lock(&cons_spin);
613 while ((ch = (u_char)*fmt++) != '%' || stop) {
619 dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
620 cflag = hflag = jflag = lflag = qflag = tflag = zflag = 0;
623 switch (ch = (u_char)*fmt++) {
641 width = __va_arg(ap, int);
647 dwidth = __va_arg(ap, int);
655 case '1': case '2': case '3': case '4':
656 case '5': case '6': case '7': case '8': case '9':
657 for (n = 0;; ++fmt) {
658 n = n * 10 + ch - '0';
660 if (ch < '0' || ch > '9')
669 num = (u_int)__va_arg(ap, int);
670 p = __va_arg(ap, char *);
671 for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
679 if (num & (1 << (n - 1))) {
680 PCHAR(tmp ? ',' : '<');
681 for (; (n = *p) > ' '; ++p)
685 for (; *p > ' '; ++p)
692 PCHAR(__va_arg(ap, int));
718 *(__va_arg(ap, char *)) = retval;
720 *(__va_arg(ap, short *)) = retval;
722 *(__va_arg(ap, intmax_t *)) = retval;
724 *(__va_arg(ap, long *)) = retval;
726 *(__va_arg(ap, quad_t *)) = retval;
728 *(__va_arg(ap, int *)) = retval;
735 sharpflag = (width == 0);
737 num = (uintptr_t)__va_arg(ap, void *);
748 p = __va_arg(ap, char *);
754 for (n = 0; n < dwidth && p[n]; n++)
759 if (!ladjust && width > 0)
764 if (ladjust && width > 0)
786 num = (u_char)__va_arg(ap, int);
788 num = (u_short)__va_arg(ap, int);
790 num = __va_arg(ap, uintmax_t);
792 num = __va_arg(ap, u_long);
794 num = __va_arg(ap, u_quad_t);
796 num = __va_arg(ap, ptrdiff_t);
798 num = __va_arg(ap, size_t);
800 num = __va_arg(ap, u_int);
804 num = (char)__va_arg(ap, int);
806 num = (short)__va_arg(ap, int);
808 num = __va_arg(ap, intmax_t);
810 num = __va_arg(ap, long);
812 num = __va_arg(ap, quad_t);
814 num = __va_arg(ap, ptrdiff_t);
816 num = __va_arg(ap, ssize_t);
818 num = __va_arg(ap, int);
820 if (sign && (intmax_t)num < 0) {
822 num = -(intmax_t)num;
824 p = ksprintn(nbuf, num, base, &n, upper);
826 if (sharpflag && num != 0) {
835 if (!ladjust && padc == '0')
836 dwidth = width - tmp;
837 width -= tmp + imax(dwidth, n);
844 if (sharpflag && num != 0) {
847 } else if (base == 16) {
864 while (percent < fmt)
867 * Since we ignore an formatting argument it is no
868 * longer safe to obey the remaining formatting
869 * arguments as the arguments will no longer match
878 * Cleanup reentrancy issues.
880 if (func == kputchar)
881 atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
883 spin_unlock(&cons_spin);
892 * Called from the panic code to try to get the console working
893 * again in case we paniced inside a kprintf().
898 spin_init(&cons_spin);
899 atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
903 * Console support thread for constty intercepts. This is needed because
904 * console tty intercepts can block. Instead of having kputchar() attempt
905 * to directly write to the console intercept we just force it to log
906 * and wakeup this baby to track and dump the log to constty.
916 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
917 constty_td, SHUTDOWN_PRI_FIRST);
918 constty_td->td_flags |= TDF_SYSTHREAD;
921 kproc_suspend_loop();
925 if (mbp == NULL || msgbufmapped == 0 ||
926 windex == mbp->msg_bufx) {
927 tsleep(constty_td, 0, "waiting", hz*60);
931 windex = mbp->msg_bufx;
935 * Get message buf FIFO indices. rindex is tracking.
937 if ((tp = constty) == NULL) {
938 rindex = mbp->msg_bufx;
943 * Don't blow up if the message buffer is broken
945 if (windex < 0 || windex >= mbp->msg_size)
947 if (rindex < 0 || rindex >= mbp->msg_size)
951 * And dump it. If constty gets stuck will give up.
953 while (rindex != windex) {
954 if (tputchar((uint8_t)mbp->msg_ptr[rindex], tp) < 0) {
956 rindex = mbp->msg_bufx;
959 if (++rindex >= mbp->msg_size)
961 if (tp->t_outq.c_cc >= tp->t_ohiwat) {
962 tsleep(constty_daemon, 0, "blocked", hz / 10);
963 if (tp->t_outq.c_cc >= tp->t_ohiwat) {
972 static struct kproc_desc constty_kp = {
977 SYSINIT(bufdaemon, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY,
978 kproc_start, &constty_kp)
981 * Put character in log buffer with a particular priority.
986 msglogchar(int c, int pri)
988 static int lastpri = -1;
995 if (c == '\0' || c == '\r')
997 if (pri != -1 && pri != lastpri) {
999 msgaddchar('\n', NULL);
1002 msgaddchar('<', NULL);
1003 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
1004 msgaddchar(*p--, NULL);
1005 msgaddchar('>', NULL);
1008 msgaddchar(c, NULL);
1018 * Put char in log buffer. Make sure nothing blows up beyond repair if
1019 * we have an MP race.
1024 msgaddchar(int c, void *dummy)
1033 windex = mbp->msg_bufx;
1034 mbp->msg_ptr[windex] = c;
1035 if (++windex >= mbp->msg_size)
1037 rindex = mbp->msg_bufr;
1038 if (windex == rindex) {
1040 if (rindex >= mbp->msg_size)
1041 rindex -= mbp->msg_size;
1042 mbp->msg_bufr = rindex;
1044 mbp->msg_bufx = windex;
1048 msgbufcopy(struct msgbuf *oldp)
1052 pos = oldp->msg_bufr;
1053 while (pos != oldp->msg_bufx) {
1054 msglogchar(oldp->msg_ptr[pos], -1);
1055 if (++pos >= oldp->msg_size)
1061 msgbufinit(void *ptr, size_t size)
1064 static struct msgbuf *oldp = NULL;
1066 size -= sizeof(*msgbufp);
1068 msgbufp = (struct msgbuf *) (cp + size);
1069 if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
1070 msgbufp->msg_bufx >= size || msgbufp->msg_bufr >= size) {
1072 bzero(msgbufp, sizeof(*msgbufp));
1073 msgbufp->msg_magic = MSG_MAGIC;
1074 msgbufp->msg_size = (char *)msgbufp - cp;
1076 msgbufp->msg_ptr = cp;
1077 if (msgbufmapped && oldp != msgbufp)
1083 /* Sysctls for accessing/clearing the msgbuf */
1086 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1092 * Only wheel or root can access the message log.
1094 if (unprivileged_read_msgbuf == 0) {
1095 KKASSERT(req->td->td_proc);
1096 cred = req->td->td_proc->p_ucred;
1098 if ((cred->cr_prison || groupmember(0, cred) == 0) &&
1099 priv_check(req->td, PRIV_ROOT) != 0
1106 * Unwind the buffer, so that it's linear (possibly starting with
1107 * some initial nulls).
1109 error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
1110 msgbufp->msg_size - msgbufp->msg_bufx, req);
1113 if (msgbufp->msg_bufx > 0) {
1114 error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
1115 msgbufp->msg_bufx, req);
1120 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
1121 0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1123 static int msgbuf_clear;
1126 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1129 error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1130 if (!error && req->newptr) {
1131 /* Clear the buffer and reset write pointer */
1132 bzero(msgbufp->msg_ptr, msgbufp->msg_size);
1133 msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
1139 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1140 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
1141 sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
1145 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1149 if (!msgbufmapped) {
1150 db_printf("msgbuf not mapped yet\n");
1153 db_printf("msgbufp = %p\n", msgbufp);
1154 db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
1155 msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
1156 msgbufp->msg_bufx, msgbufp->msg_ptr);
1157 for (i = 0; i < msgbufp->msg_size; i++) {
1158 j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
1159 db_printf("%c", msgbufp->msg_ptr[j]);
1168 hexdump(const void *ptr, int length, const char *hdr, int flags)
1172 const unsigned char *cp;
1175 if ((flags & HD_DELIM_MASK) != 0)
1176 delim = (flags & HD_DELIM_MASK) >> 8;
1180 if ((flags & HD_COLUMN_MASK) != 0)
1181 cols = flags & HD_COLUMN_MASK;
1186 for (i = 0; i < length; i+= cols) {
1190 if ((flags & HD_OMIT_COUNT) == 0)
1191 kprintf("%04x ", i);
1193 if ((flags & HD_OMIT_HEX) == 0) {
1194 for (j = 0; j < cols; j++) {
1197 kprintf("%c%02x", delim, cp[k]);
1203 if ((flags & HD_OMIT_CHARS) == 0) {
1205 for (j = 0; j < cols; j++) {
1209 else if (cp[k] >= ' ' && cp[k] <= '~')
1210 kprintf("%c", cp[k]);