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>
67 * Note that stdarg.h and the ANSI style va_start macro is used for both
68 * ANSI and traditional C compilers. We use the __ machine version to stay
69 * within the kernel header file set.
71 #include <machine/stdarg.h>
77 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
78 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
93 struct tty *constty; /* pointer to console "window" tty */
95 static void (*v_putc)(int) = cnputc; /* routine to putc on virtual console */
96 static void msglogchar(int c, int pri);
97 static void msgaddchar(int c, void *dummy);
98 static void kputchar (int ch, void *arg);
99 static char *ksprintn (char *nbuf, uintmax_t num, int base, int *lenp,
101 static void snprintf_func (int ch, void *arg);
103 static int consintr = 1; /* Ok to handle console interrupts? */
104 static int msgbufmapped; /* Set when safe to use msgbuf */
107 static int log_console_output = 1;
108 TUNABLE_INT("kern.log_console_output", &log_console_output);
109 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
110 &log_console_output, 0, "");
112 static int unprivileged_read_msgbuf = 1;
113 SYSCTL_INT(_security, OID_AUTO, unprivileged_read_msgbuf, CTLFLAG_RW,
114 &unprivileged_read_msgbuf, 0,
115 "Unprivileged processes may read the kernel message buffer");
118 * Warn that a system table is full.
121 tablefull(const char *tab)
124 log(LOG_ERR, "%s: table is full\n", tab);
128 * Uprintf prints to the controlling terminal for the current process.
131 uprintf(const char *fmt, ...)
133 struct proc *p = curproc;
135 struct putchar_arg pca;
138 if (p && p->p_flag & P_CONTROLT &&
139 p->p_session->s_ttyvp) {
141 pca.tty = p->p_session->s_ttyp;
144 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
151 tprintf_open(struct proc *p)
154 if ((p->p_flag & P_CONTROLT) && p->p_session->s_ttyvp) {
155 sess_hold(p->p_session);
156 return ((tpr_t) p->p_session);
158 return ((tpr_t) NULL);
162 tprintf_close(tpr_t sess)
165 sess_rele((struct session *) sess);
169 * tprintf prints on the controlling terminal associated
170 * with the given session.
173 tprintf(tpr_t tpr, const char *fmt, ...)
175 struct session *sess = (struct session *)tpr;
176 struct tty *tp = NULL;
179 struct putchar_arg pca;
182 if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
190 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
197 * Ttyprintf displays a message on a tty; it should be used only by
198 * the tty driver, or anything that knows the underlying tty will not
199 * be revoke(2)'d away. Other callers should use tprintf.
202 ttyprintf(struct tty *tp, const char *fmt, ...)
205 struct putchar_arg pca;
211 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
217 * Log writes to the log buffer, and guarantees not to sleep (so can be
218 * called by interrupt routines). If there is no process reading the
219 * log yet, it writes to the console also.
222 log(int level, const char *fmt, ...)
226 struct putchar_arg pca;
230 pca.flags = log_open ? TOLOG : TOCONS;
233 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
240 #define CONSCHUNK 128
243 log_console(struct uio *uio)
245 int c, i, error, iovlen, nl;
247 struct iovec *miov = NULL;
251 if (!log_console_output)
254 pri = LOG_INFO | LOG_CONSOLE;
256 iovlen = uio->uio_iovcnt * sizeof (struct iovec);
257 MALLOC(miov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
258 MALLOC(consbuffer, char *, CONSCHUNK, M_TEMP, M_WAITOK);
259 bcopy((caddr_t)muio.uio_iov, (caddr_t)miov, iovlen);
264 while (uio->uio_resid > 0) {
265 c = imin(uio->uio_resid, CONSCHUNK);
266 error = uiomove(consbuffer, c, uio);
269 for (i = 0; i < c; i++) {
270 msglogchar(consbuffer[i], pri);
271 if (consbuffer[i] == '\n')
278 msglogchar('\n', pri);
281 FREE(consbuffer, M_TEMP);
286 * Output to the console.
288 * NOT YET ENTIRELY MPSAFE
291 kprintf(const char *fmt, ...)
295 struct putchar_arg pca;
298 savintr = consintr; /* disable interrupts */
302 pca.flags = TOCONS | TOLOG;
305 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;
327 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
331 consintr = savintr; /* reenable interrupts */
336 * Limited rate kprintf. The passed rate structure must be initialized
337 * with the desired reporting frequency. A frequency of 0 will result in
340 * count may be initialized to a negative number to allow an initial
344 krateprintf(struct krate *rate, const char *fmt, ...)
348 if (rate->ticks != (int)time_second) {
349 rate->ticks = (int)time_second;
353 if (rate->count < rate->freq) {
362 * Print a character on console or users terminal. If destination is
363 * the console then the last bunch of characters are saved in msgbuf for
366 * NOT YET ENTIRELY MPSAFE, EVEN WHEN LOGGING JUST TO THE SYSCONSOLE.
369 kputchar(int c, void *arg)
371 struct putchar_arg *ap = (struct putchar_arg*) arg;
372 int flags = ap->flags;
373 struct tty *tp = ap->tty;
376 if ((flags & TOCONS) && tp == NULL && constty) {
380 if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
381 (flags & TOCONS) && tp == constty)
384 msglogchar(c, ap->pri);
385 if ((flags & TOCONS) && constty == NULL && c != '\0')
390 * Scaled down version of sprintf(3).
393 ksprintf(char *buf, const char *cfmt, ...)
398 __va_start(ap, cfmt);
399 retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
406 * Scaled down version of vsprintf(3).
409 kvsprintf(char *buf, const char *cfmt, __va_list ap)
413 retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
419 * Scaled down version of snprintf(3).
422 ksnprintf(char *str, size_t size, const char *format, ...)
427 __va_start(ap, format);
428 retval = kvsnprintf(str, size, format, ap);
434 * Scaled down version of vsnprintf(3).
437 kvsnprintf(char *str, size_t size, const char *format, __va_list ap)
439 struct snprintf_arg info;
444 retval = kvcprintf(format, snprintf_func, &info, 10, ap);
445 if (info.remain >= 1)
451 snprintf_func(int ch, void *arg)
453 struct snprintf_arg *const info = arg;
455 if (info->remain >= 2) {
462 * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
463 * order; return an optional length and a pointer to the last character
464 * written in the buffer (i.e., the first character of the string).
465 * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
468 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
475 c = hex2ascii(num % base);
476 *++p = upper ? toupper(c) : c;
477 } while (num /= base);
484 * Scaled down version of printf(3).
486 * Two additional formats:
488 * The format %b is supported to decode error registers.
491 * kprintf("reg=%b\n", regval, "<base><arg>*");
493 * where <base> is the output base expressed as a control character, e.g.
494 * \10 gives octal; \20 gives hex. Each arg is a sequence of characters,
495 * the first of which gives the bit number to be inspected (origin 1), and
496 * the next characters (up to a control character, i.e. a character <= 32),
497 * give the name of the register. Thus:
499 * kvcprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
501 * would produce output:
503 * reg=3<BITTWO,BITONE>
505 * XXX: %D -- Hexdump, takes pointer and separator string:
506 * ("%6D", ptr, ":") -> XX:XX:XX:XX:XX:XX
507 * ("%*D", len, ptr, " " -> XX XX XX XX ...
510 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, __va_list ap)
512 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
515 const char *p, *percent, *q;
519 int base, tmp, width, ladjust, sharpflag, neg, sign, dot;
520 int jflag, lflag, qflag, tflag;
523 int retval = 0, stop = 0;
532 fmt = "(fmt null)\n";
534 if (radix < 2 || radix > 36)
540 while ((ch = (u_char)*fmt++) != '%' || stop) {
546 dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
547 jflag = lflag = qflag = tflag = 0;
550 switch (ch = (u_char)*fmt++) {
568 width = __va_arg(ap, int);
574 dwidth = __va_arg(ap, int);
582 case '1': case '2': case '3': case '4':
583 case '5': case '6': case '7': case '8': case '9':
584 for (n = 0;; ++fmt) {
585 n = n * 10 + ch - '0';
587 if (ch < '0' || ch > '9')
596 num = (u_int)__va_arg(ap, int);
597 p = __va_arg(ap, char *);
598 for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
606 if (num & (1 << (n - 1))) {
607 PCHAR(tmp ? ',' : '<');
608 for (; (n = *p) > ' '; ++p)
612 for (; *p > ' '; ++p)
619 PCHAR(__va_arg(ap, int));
622 up = __va_arg(ap, u_char *);
623 p = __va_arg(ap, char *);
627 PCHAR(hex2ascii(*up >> 4));
628 PCHAR(hex2ascii(*up & 0x0f));
652 *(__va_arg(ap, intmax_t *)) = retval;
654 *(__va_arg(ap, long *)) = retval;
656 *(__va_arg(ap, quad_t *)) = retval;
658 *(__va_arg(ap, int *)) = retval;
665 sharpflag = (width == 0);
667 num = (uintptr_t)__va_arg(ap, void *);
678 p = __va_arg(ap, char *);
684 for (n = 0; n < dwidth && p[n]; n++)
689 if (!ladjust && width > 0)
694 if (ladjust && width > 0)
717 num = __va_arg(ap, uintmax_t);
719 num = __va_arg(ap, u_long);
721 num = __va_arg(ap, u_quad_t);
723 num = __va_arg(ap, ptrdiff_t);
725 num = __va_arg(ap, u_int);
729 num = __va_arg(ap, intmax_t);
731 num = __va_arg(ap, long);
733 num = __va_arg(ap, quad_t);
735 num = __va_arg(ap, ptrdiff_t);
737 num = __va_arg(ap, int);
739 if (sign && (intmax_t)num < 0) {
741 num = -(intmax_t)num;
743 p = ksprintn(nbuf, num, base, &tmp, upper);
744 if (sharpflag && num != 0) {
753 if (!ladjust && padc != '0' && width &&
754 (width -= tmp) > 0) {
760 if (sharpflag && num != 0) {
763 } else if (base == 16) {
768 if (!ladjust && width && (width -= tmp) > 0)
775 if (ladjust && width && (width -= tmp) > 0)
781 while (percent < fmt)
784 * Since we ignore an formatting argument it is no
785 * longer safe to obey the remaining formatting
786 * arguments as the arguments will no longer match
797 * Put character in log buffer with a particular priority.
802 msglogchar(int c, int pri)
804 static int lastpri = -1;
811 if (c == '\0' || c == '\r')
813 if (pri != -1 && pri != lastpri) {
815 msgaddchar('\n', NULL);
818 msgaddchar('<', NULL);
819 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
820 msgaddchar(*p--, NULL);
821 msgaddchar('>', NULL);
834 * Put char in log buffer. Make sure nothing blows up beyond repair if
835 * we have an MP race.
840 msgaddchar(int c, void *dummy)
849 windex = mbp->msg_bufx;
850 mbp->msg_ptr[windex] = c;
851 if (++windex >= mbp->msg_size)
853 rindex = mbp->msg_bufr;
854 if (windex == rindex) {
856 if (rindex >= mbp->msg_size)
857 rindex -= mbp->msg_size;
858 mbp->msg_bufr = rindex;
860 mbp->msg_bufx = windex;
864 msgbufcopy(struct msgbuf *oldp)
868 pos = oldp->msg_bufr;
869 while (pos != oldp->msg_bufx) {
870 msglogchar(oldp->msg_ptr[pos], -1);
871 if (++pos >= oldp->msg_size)
877 msgbufinit(void *ptr, size_t size)
880 static struct msgbuf *oldp = NULL;
882 size -= sizeof(*msgbufp);
884 msgbufp = (struct msgbuf *) (cp + size);
885 if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
886 msgbufp->msg_bufx >= size || msgbufp->msg_bufr >= size) {
888 bzero(msgbufp, sizeof(*msgbufp));
889 msgbufp->msg_magic = MSG_MAGIC;
890 msgbufp->msg_size = (char *)msgbufp - cp;
892 msgbufp->msg_ptr = cp;
893 if (msgbufmapped && oldp != msgbufp)
899 /* Sysctls for accessing/clearing the msgbuf */
902 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
908 * Only wheel or root can access the message log.
910 if (unprivileged_read_msgbuf == 0) {
911 KKASSERT(req->td->td_proc);
912 cred = req->td->td_proc->p_ucred;
914 if ((cred->cr_prison || groupmember(0, cred) == 0) &&
915 priv_check(req->td, PRIV_ROOT) != 0
922 * Unwind the buffer, so that it's linear (possibly starting with
923 * some initial nulls).
925 error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
926 msgbufp->msg_size - msgbufp->msg_bufx, req);
929 if (msgbufp->msg_bufx > 0) {
930 error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
931 msgbufp->msg_bufx, req);
936 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
937 0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
939 static int msgbuf_clear;
942 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
945 error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
946 if (!error && req->newptr) {
947 /* Clear the buffer and reset write pointer */
948 bzero(msgbufp->msg_ptr, msgbufp->msg_size);
949 msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
955 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
956 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
957 sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
961 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
966 db_printf("msgbuf not mapped yet\n");
969 db_printf("msgbufp = %p\n", msgbufp);
970 db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
971 msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
972 msgbufp->msg_bufx, msgbufp->msg_ptr);
973 for (i = 0; i < msgbufp->msg_size; i++) {
974 j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
975 db_printf("%c", msgbufp->msg_ptr[j]);