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 $
40 * $DragonFly: src/sys/kern/subr_prf.c,v 1.21 2008/07/17 23:56:23 dillon Exp $
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/msgbuf.h>
49 #include <sys/malloc.h>
53 #include <sys/tprintf.h>
54 #include <sys/stdint.h>
55 #include <sys/syslog.h>
58 #include <sys/sysctl.h>
60 #include <sys/ctype.h>
62 #include <sys/thread2.h>
63 #include <sys/spinlock2.h>
70 * Note that stdarg.h and the ANSI style va_start macro is used for both
71 * ANSI and traditional C compilers. We use the __ machine version to stay
72 * within the kernel header file set.
74 #include <machine/stdarg.h>
80 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
81 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
96 struct tty *constty; /* pointer to console "window" tty */
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,
103 static void snprintf_func (int ch, void *arg);
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);
111 static int log_console_output = 1;
112 TUNABLE_INT("kern.log_console_output", &log_console_output);
113 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
114 &log_console_output, 0, "");
116 static int unprivileged_read_msgbuf = 1;
117 SYSCTL_INT(_security, OID_AUTO, unprivileged_read_msgbuf, CTLFLAG_RW,
118 &unprivileged_read_msgbuf, 0,
119 "Unprivileged processes may read the kernel message buffer");
122 * Warn that a system table is full.
125 tablefull(const char *tab)
128 log(LOG_ERR, "%s: table is full\n", tab);
132 * Uprintf prints to the controlling terminal for the current process.
135 uprintf(const char *fmt, ...)
137 struct proc *p = curproc;
139 struct putchar_arg pca;
142 if (p && p->p_flag & P_CONTROLT &&
143 p->p_session->s_ttyvp) {
145 pca.tty = p->p_session->s_ttyp;
148 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
155 tprintf_open(struct proc *p)
158 if ((p->p_flag & P_CONTROLT) && p->p_session->s_ttyvp) {
159 sess_hold(p->p_session);
160 return ((tpr_t) p->p_session);
162 return ((tpr_t) NULL);
166 tprintf_close(tpr_t sess)
169 sess_rele((struct session *) sess);
173 * tprintf prints on the controlling terminal associated
174 * with the given session.
177 tprintf(tpr_t tpr, const char *fmt, ...)
179 struct session *sess = (struct session *)tpr;
180 struct tty *tp = NULL;
183 struct putchar_arg pca;
186 if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
194 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
201 * Ttyprintf displays a message on a tty; it should be used only by
202 * the tty driver, or anything that knows the underlying tty will not
203 * be revoke(2)'d away. Other callers should use tprintf.
206 ttyprintf(struct tty *tp, const char *fmt, ...)
209 struct putchar_arg pca;
215 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
221 * Log writes to the log buffer, and guarantees not to sleep (so can be
222 * called by interrupt routines). If there is no process reading the
223 * log yet, it writes to the console also.
226 log(int level, const char *fmt, ...)
230 struct putchar_arg pca;
234 pca.flags = log_open ? TOLOG : TOCONS;
237 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
244 #define CONSCHUNK 128
247 log_console(struct uio *uio)
249 int c, i, error, iovlen, nl;
251 struct iovec *miov = NULL;
255 if (!log_console_output)
258 pri = LOG_INFO | LOG_CONSOLE;
260 iovlen = uio->uio_iovcnt * sizeof (struct iovec);
261 MALLOC(miov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
262 MALLOC(consbuffer, char *, CONSCHUNK, M_TEMP, M_WAITOK);
263 bcopy((caddr_t)muio.uio_iov, (caddr_t)miov, iovlen);
268 while (uio->uio_resid > 0) {
269 c = (int)szmin(uio->uio_resid, CONSCHUNK);
270 error = uiomove(consbuffer, (size_t)c, uio);
273 for (i = 0; i < c; i++) {
274 msglogchar(consbuffer[i], pri);
275 if (consbuffer[i] == '\n')
282 msglogchar('\n', pri);
285 FREE(consbuffer, M_TEMP);
290 * Output to the console.
293 kprintf(const char *fmt, ...)
297 struct putchar_arg pca;
300 savintr = consintr; /* disable interrupts */
304 pca.flags = TOCONS | TOLOG;
306 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
310 consintr = savintr; /* reenable interrupts */
315 kvprintf(const char *fmt, __va_list ap)
318 struct putchar_arg pca;
321 savintr = consintr; /* disable interrupts */
324 pca.flags = TOCONS | TOLOG;
326 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
329 consintr = savintr; /* reenable interrupts */
334 * Limited rate kprintf. The passed rate structure must be initialized
335 * with the desired reporting frequency. A frequency of 0 will result in
338 * count may be initialized to a negative number to allow an initial
342 krateprintf(struct krate *rate, const char *fmt, ...)
346 if (rate->ticks != (int)time_second) {
347 rate->ticks = (int)time_second;
351 if (rate->count < rate->freq) {
360 * Print a character on console or users terminal. If destination is
361 * the console then the last bunch of characters are saved in msgbuf for
364 * NOT YET ENTIRELY MPSAFE, EVEN WHEN LOGGING JUST TO THE SYSCONSOLE.
367 kputchar(int c, void *arg)
369 struct putchar_arg *ap = (struct putchar_arg*) arg;
370 int flags = ap->flags;
371 struct tty *tp = ap->tty;
374 if ((flags & TOCONS) && tp == NULL && constty) {
378 if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
379 (flags & TOCONS) && tp == constty)
382 msglogchar(c, ap->pri);
383 if ((flags & TOCONS) && constty == NULL && c != '\0')
388 * Scaled down version of sprintf(3).
391 ksprintf(char *buf, const char *cfmt, ...)
396 __va_start(ap, cfmt);
397 retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
404 * Scaled down version of vsprintf(3).
407 kvsprintf(char *buf, const char *cfmt, __va_list ap)
411 retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
417 * Scaled down version of snprintf(3).
420 ksnprintf(char *str, size_t size, const char *format, ...)
425 __va_start(ap, format);
426 retval = kvsnprintf(str, size, format, ap);
432 * Scaled down version of vsnprintf(3).
435 kvsnprintf(char *str, size_t size, const char *format, __va_list ap)
437 struct snprintf_arg info;
442 retval = kvcprintf(format, snprintf_func, &info, 10, ap);
443 if (info.remain >= 1)
449 ksnrprintf(char *str, size_t size, int radix, const char *format, ...)
454 __va_start(ap, format);
455 retval = kvsnrprintf(str, size, radix, format, ap);
461 kvsnrprintf(char *str, size_t size, int radix, const char *format, __va_list ap)
463 struct snprintf_arg info;
468 retval = kvcprintf(format, snprintf_func, &info, radix, ap);
469 if (info.remain >= 1)
475 kvasnrprintf(char **strp, size_t size, int radix,
476 const char *format, __va_list ap)
478 struct snprintf_arg info;
481 *strp = kmalloc(size, M_TEMP, M_WAITOK);
484 retval = kvcprintf(format, snprintf_func, &info, radix, ap);
485 if (info.remain >= 1)
491 kvasfree(char **strp)
494 kfree(*strp, M_TEMP);
500 snprintf_func(int ch, void *arg)
502 struct snprintf_arg *const info = arg;
504 if (info->remain >= 2) {
511 * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
512 * order; return an optional length and a pointer to the last character
513 * written in the buffer (i.e., the first character of the string).
514 * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
517 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
524 c = hex2ascii(num % base);
525 *++p = upper ? toupper(c) : c;
526 } while (num /= base);
533 * Scaled down version of printf(3).
535 * Two additional formats:
537 * The format %b is supported to decode error registers.
540 * kprintf("reg=%b\n", regval, "<base><arg>*");
542 * where <base> is the output base expressed as a control character, e.g.
543 * \10 gives octal; \20 gives hex. Each arg is a sequence of characters,
544 * the first of which gives the bit number to be inspected (origin 1), and
545 * the next characters (up to a control character, i.e. a character <= 32),
546 * give the name of the register. Thus:
548 * kvcprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
550 * would produce output:
552 * reg=3<BITTWO,BITONE>
554 * XXX: %D -- Hexdump, takes pointer and separator string:
555 * ("%6D", ptr, ":") -> XX:XX:XX:XX:XX:XX
556 * ("%*D", len, ptr, " " -> XX XX XX XX ...
559 #define PCHAR(c) {int cc=(c); if(func) (*func)(cc,arg); else *d++=cc; retval++;}
562 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg,
563 int radix, __va_list ap)
567 const char *p, *percent, *q;
571 int base, tmp, width, ladjust, sharpflag, neg, sign, dot;
572 int cflag, hflag, jflag, lflag, qflag, tflag, zflag;
575 int retval = 0, stop = 0;
579 * Make a supreme effort to avoid reentrant panics or deadlocks.
581 if (func == kputchar) {
582 if (mycpu->gd_flags & GDF_KPRINTF)
584 atomic_set_long(&mycpu->gd_flags, GDF_KPRINTF);
594 fmt = "(fmt null)\n";
596 if (radix < 2 || radix > 36)
599 usespin = (panic_cpu_gd != mycpu &&
601 (((struct putchar_arg *)arg)->flags & TOTTY) == 0);
604 spin_lock(&cons_spin);
610 while ((ch = (u_char)*fmt++) != '%' || stop) {
616 dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
617 cflag = hflag = jflag = lflag = qflag = tflag = zflag = 0;
620 switch (ch = (u_char)*fmt++) {
638 width = __va_arg(ap, int);
644 dwidth = __va_arg(ap, int);
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';
657 if (ch < '0' || ch > '9')
666 num = (u_int)__va_arg(ap, int);
667 p = __va_arg(ap, char *);
668 for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
676 if (num & (1 << (n - 1))) {
677 PCHAR(tmp ? ',' : '<');
678 for (; (n = *p) > ' '; ++p)
682 for (; *p > ' '; ++p)
689 PCHAR(__va_arg(ap, int));
692 up = __va_arg(ap, u_char *);
693 p = __va_arg(ap, char *);
697 PCHAR(hex2ascii(*up >> 4));
698 PCHAR(hex2ascii(*up & 0x0f));
729 *(__va_arg(ap, char *)) = retval;
731 *(__va_arg(ap, short *)) = retval;
733 *(__va_arg(ap, intmax_t *)) = retval;
735 *(__va_arg(ap, long *)) = retval;
737 *(__va_arg(ap, quad_t *)) = retval;
739 *(__va_arg(ap, int *)) = retval;
746 sharpflag = (width == 0);
748 num = (uintptr_t)__va_arg(ap, void *);
759 p = __va_arg(ap, char *);
765 for (n = 0; n < dwidth && p[n]; n++)
770 if (!ladjust && width > 0)
775 if (ladjust && width > 0)
797 num = (u_char)__va_arg(ap, int);
799 num = (u_short)__va_arg(ap, int);
801 num = __va_arg(ap, uintmax_t);
803 num = __va_arg(ap, u_long);
805 num = __va_arg(ap, u_quad_t);
807 num = __va_arg(ap, ptrdiff_t);
809 num = __va_arg(ap, size_t);
811 num = __va_arg(ap, u_int);
815 num = (char)__va_arg(ap, int);
817 num = (short)__va_arg(ap, int);
819 num = __va_arg(ap, intmax_t);
821 num = __va_arg(ap, long);
823 num = __va_arg(ap, quad_t);
825 num = __va_arg(ap, ptrdiff_t);
827 num = __va_arg(ap, ssize_t);
829 num = __va_arg(ap, int);
831 if (sign && (intmax_t)num < 0) {
833 num = -(intmax_t)num;
835 p = ksprintn(nbuf, num, base, &tmp, upper);
836 if (sharpflag && num != 0) {
845 if (!ladjust && padc != '0' && width &&
846 (width -= tmp) > 0) {
852 if (sharpflag && num != 0) {
855 } else if (base == 16) {
860 if (!ladjust && width && (width -= tmp) > 0)
867 if (ladjust && width && (width -= tmp) > 0)
873 while (percent < fmt)
876 * Since we ignore an formatting argument it is no
877 * longer safe to obey the remaining formatting
878 * arguments as the arguments will no longer match
887 * Cleanup reentrancy issues.
889 if (func == kputchar)
890 atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
892 spin_unlock(&cons_spin);
901 * Called from the panic code to try to get the console working
902 * again in case we paniced inside a kprintf().
907 spin_init(&cons_spin);
908 atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
913 * Put character in log buffer with a particular priority.
918 msglogchar(int c, int pri)
920 static int lastpri = -1;
927 if (c == '\0' || c == '\r')
929 if (pri != -1 && pri != lastpri) {
931 msgaddchar('\n', NULL);
934 msgaddchar('<', NULL);
935 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
936 msgaddchar(*p--, NULL);
937 msgaddchar('>', NULL);
950 * Put char in log buffer. Make sure nothing blows up beyond repair if
951 * we have an MP race.
956 msgaddchar(int c, void *dummy)
965 windex = mbp->msg_bufx;
966 mbp->msg_ptr[windex] = c;
967 if (++windex >= mbp->msg_size)
969 rindex = mbp->msg_bufr;
970 if (windex == rindex) {
972 if (rindex >= mbp->msg_size)
973 rindex -= mbp->msg_size;
974 mbp->msg_bufr = rindex;
976 mbp->msg_bufx = windex;
980 msgbufcopy(struct msgbuf *oldp)
984 pos = oldp->msg_bufr;
985 while (pos != oldp->msg_bufx) {
986 msglogchar(oldp->msg_ptr[pos], -1);
987 if (++pos >= oldp->msg_size)
993 msgbufinit(void *ptr, size_t size)
996 static struct msgbuf *oldp = NULL;
998 size -= sizeof(*msgbufp);
1000 msgbufp = (struct msgbuf *) (cp + size);
1001 if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
1002 msgbufp->msg_bufx >= size || msgbufp->msg_bufr >= size) {
1004 bzero(msgbufp, sizeof(*msgbufp));
1005 msgbufp->msg_magic = MSG_MAGIC;
1006 msgbufp->msg_size = (char *)msgbufp - cp;
1008 msgbufp->msg_ptr = cp;
1009 if (msgbufmapped && oldp != msgbufp)
1015 /* Sysctls for accessing/clearing the msgbuf */
1018 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1024 * Only wheel or root can access the message log.
1026 if (unprivileged_read_msgbuf == 0) {
1027 KKASSERT(req->td->td_proc);
1028 cred = req->td->td_proc->p_ucred;
1030 if ((cred->cr_prison || groupmember(0, cred) == 0) &&
1031 priv_check(req->td, PRIV_ROOT) != 0
1038 * Unwind the buffer, so that it's linear (possibly starting with
1039 * some initial nulls).
1041 error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
1042 msgbufp->msg_size - msgbufp->msg_bufx, req);
1045 if (msgbufp->msg_bufx > 0) {
1046 error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
1047 msgbufp->msg_bufx, req);
1052 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
1053 0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1055 static int msgbuf_clear;
1058 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1061 error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1062 if (!error && req->newptr) {
1063 /* Clear the buffer and reset write pointer */
1064 bzero(msgbufp->msg_ptr, msgbufp->msg_size);
1065 msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
1071 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1072 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
1073 sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
1077 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1081 if (!msgbufmapped) {
1082 db_printf("msgbuf not mapped yet\n");
1085 db_printf("msgbufp = %p\n", msgbufp);
1086 db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
1087 msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
1088 msgbufp->msg_bufx, msgbufp->msg_ptr);
1089 for (i = 0; i < msgbufp->msg_size; i++) {
1090 j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
1091 db_printf("%c", msgbufp->msg_ptr[j]);