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.20.4.1 2008/07/17 23:56:43 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>
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>
66 * Note that stdarg.h and the ANSI style va_start macro is used for both
67 * ANSI and traditional C compilers. We use the __ machine version to stay
68 * within the kernel header file set.
70 #include <machine/stdarg.h>
76 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
77 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
92 struct tty *constty; /* pointer to console "window" tty */
94 static void (*v_putc)(int) = cnputc; /* routine to putc on virtual console */
95 static void msglogchar(int c, int pri);
96 static void msgaddchar(int c, void *dummy);
97 static void kputchar (int ch, void *arg);
98 static char *ksprintn (char *nbuf, uintmax_t num, int base, int *lenp,
100 static void snprintf_func (int ch, void *arg);
102 static int consintr = 1; /* Ok to handle console interrupts? */
103 static int msgbufmapped; /* Set when safe to use msgbuf */
106 static int log_console_output = 1;
107 TUNABLE_INT("kern.log_console_output", &log_console_output);
108 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
109 &log_console_output, 0, "");
111 static int unprivileged_read_msgbuf = 1;
112 SYSCTL_INT(_security, OID_AUTO, unprivileged_read_msgbuf, CTLFLAG_RW,
113 &unprivileged_read_msgbuf, 0,
114 "Unprivileged processes may read the kernel message buffer");
117 * Warn that a system table is full.
120 tablefull(const char *tab)
123 log(LOG_ERR, "%s: table is full\n", tab);
127 * Uprintf prints to the controlling terminal for the current process.
130 uprintf(const char *fmt, ...)
132 struct proc *p = curproc;
134 struct putchar_arg pca;
137 if (p && p->p_flag & P_CONTROLT &&
138 p->p_session->s_ttyvp) {
140 pca.tty = p->p_session->s_ttyp;
143 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
150 tprintf_open(struct proc *p)
153 if ((p->p_flag & P_CONTROLT) && p->p_session->s_ttyvp) {
154 sess_hold(p->p_session);
155 return ((tpr_t) p->p_session);
157 return ((tpr_t) NULL);
161 tprintf_close(tpr_t sess)
164 sess_rele((struct session *) sess);
168 * tprintf prints on the controlling terminal associated
169 * with the given session.
172 tprintf(tpr_t tpr, const char *fmt, ...)
174 struct session *sess = (struct session *)tpr;
175 struct tty *tp = NULL;
178 struct putchar_arg pca;
181 if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
189 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
196 * Ttyprintf displays a message on a tty; it should be used only by
197 * the tty driver, or anything that knows the underlying tty will not
198 * be revoke(2)'d away. Other callers should use tprintf.
201 ttyprintf(struct tty *tp, const char *fmt, ...)
204 struct putchar_arg pca;
210 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
216 * Log writes to the log buffer, and guarantees not to sleep (so can be
217 * called by interrupt routines). If there is no process reading the
218 * log yet, it writes to the console also.
221 log(int level, const char *fmt, ...)
225 struct putchar_arg pca;
229 pca.flags = log_open ? TOLOG : TOCONS;
232 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
239 #define CONSCHUNK 128
242 log_console(struct uio *uio)
244 int c, i, error, iovlen, nl;
246 struct iovec *miov = NULL;
250 if (!log_console_output)
253 pri = LOG_INFO | LOG_CONSOLE;
255 iovlen = uio->uio_iovcnt * sizeof (struct iovec);
256 MALLOC(miov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
257 MALLOC(consbuffer, char *, CONSCHUNK, M_TEMP, M_WAITOK);
258 bcopy((caddr_t)muio.uio_iov, (caddr_t)miov, iovlen);
263 while (uio->uio_resid > 0) {
264 c = imin(uio->uio_resid, CONSCHUNK);
265 error = uiomove(consbuffer, c, uio);
268 for (i = 0; i < c; i++) {
269 msglogchar(consbuffer[i], pri);
270 if (consbuffer[i] == '\n')
277 msglogchar('\n', pri);
280 FREE(consbuffer, M_TEMP);
285 * Output to the console.
287 * NOT YET ENTIRELY MPSAFE
290 kprintf(const char *fmt, ...)
294 struct putchar_arg pca;
297 savintr = consintr; /* disable interrupts */
301 pca.flags = TOCONS | TOLOG;
304 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
309 consintr = savintr; /* reenable interrupts */
314 kvprintf(const char *fmt, __va_list ap)
317 struct putchar_arg pca;
320 savintr = consintr; /* disable interrupts */
323 pca.flags = TOCONS | TOLOG;
326 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 on console or users terminal. If destination is
362 * the console then the last bunch of characters are saved in msgbuf for
365 * NOT YET ENTIRELY MPSAFE, EVEN WHEN LOGGING JUST TO THE SYSCONSOLE.
368 kputchar(int c, void *arg)
370 struct putchar_arg *ap = (struct putchar_arg*) arg;
371 int flags = ap->flags;
372 struct tty *tp = ap->tty;
375 if ((flags & TOCONS) && tp == NULL && constty) {
379 if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
380 (flags & TOCONS) && tp == constty)
383 msglogchar(c, ap->pri);
384 if ((flags & TOCONS) && constty == NULL && c != '\0')
389 * Scaled down version of sprintf(3).
392 ksprintf(char *buf, const char *cfmt, ...)
397 __va_start(ap, cfmt);
398 retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
405 * Scaled down version of vsprintf(3).
408 kvsprintf(char *buf, const char *cfmt, __va_list ap)
412 retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
418 * Scaled down version of snprintf(3).
421 ksnprintf(char *str, size_t size, const char *format, ...)
426 __va_start(ap, format);
427 retval = kvsnprintf(str, size, format, ap);
433 * Scaled down version of vsnprintf(3).
436 kvsnprintf(char *str, size_t size, const char *format, __va_list ap)
438 struct snprintf_arg info;
443 retval = kvcprintf(format, snprintf_func, &info, 10, ap);
444 if (info.remain >= 1)
450 snprintf_func(int ch, void *arg)
452 struct snprintf_arg *const info = arg;
454 if (info->remain >= 2) {
461 * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
462 * order; return an optional length and a pointer to the last character
463 * written in the buffer (i.e., the first character of the string).
464 * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
467 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
474 c = hex2ascii(num % base);
475 *++p = upper ? toupper(c) : c;
476 } while (num /= base);
483 * Scaled down version of printf(3).
485 * Two additional formats:
487 * The format %b is supported to decode error registers.
490 * kprintf("reg=%b\n", regval, "<base><arg>*");
492 * where <base> is the output base expressed as a control character, e.g.
493 * \10 gives octal; \20 gives hex. Each arg is a sequence of characters,
494 * the first of which gives the bit number to be inspected (origin 1), and
495 * the next characters (up to a control character, i.e. a character <= 32),
496 * give the name of the register. Thus:
498 * kvcprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
500 * would produce output:
502 * reg=3<BITTWO,BITONE>
504 * XXX: %D -- Hexdump, takes pointer and separator string:
505 * ("%6D", ptr, ":") -> XX:XX:XX:XX:XX:XX
506 * ("%*D", len, ptr, " " -> XX XX XX XX ...
509 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, __va_list ap)
511 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
514 const char *p, *percent, *q;
518 int base, tmp, width, ladjust, sharpflag, neg, sign, dot;
519 int jflag, lflag, qflag, tflag;
522 int retval = 0, stop = 0;
531 fmt = "(fmt null)\n";
533 if (radix < 2 || radix > 36)
539 while ((ch = (u_char)*fmt++) != '%' || stop) {
545 dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
546 jflag = lflag = qflag = tflag = 0;
549 switch (ch = (u_char)*fmt++) {
567 width = __va_arg(ap, int);
573 dwidth = __va_arg(ap, int);
581 case '1': case '2': case '3': case '4':
582 case '5': case '6': case '7': case '8': case '9':
583 for (n = 0;; ++fmt) {
584 n = n * 10 + ch - '0';
586 if (ch < '0' || ch > '9')
595 num = (u_int)__va_arg(ap, int);
596 p = __va_arg(ap, char *);
597 for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
605 if (num & (1 << (n - 1))) {
606 PCHAR(tmp ? ',' : '<');
607 for (; (n = *p) > ' '; ++p)
611 for (; *p > ' '; ++p)
618 PCHAR(__va_arg(ap, int));
621 up = __va_arg(ap, u_char *);
622 p = __va_arg(ap, char *);
626 PCHAR(hex2ascii(*up >> 4));
627 PCHAR(hex2ascii(*up & 0x0f));
651 *(__va_arg(ap, intmax_t *)) = retval;
653 *(__va_arg(ap, long *)) = retval;
655 *(__va_arg(ap, quad_t *)) = retval;
657 *(__va_arg(ap, int *)) = retval;
664 sharpflag = (width == 0);
666 num = (uintptr_t)__va_arg(ap, void *);
677 p = __va_arg(ap, char *);
683 for (n = 0; n < dwidth && p[n]; n++)
688 if (!ladjust && width > 0)
693 if (ladjust && width > 0)
716 num = __va_arg(ap, uintmax_t);
718 num = __va_arg(ap, u_long);
720 num = __va_arg(ap, u_quad_t);
722 num = __va_arg(ap, ptrdiff_t);
724 num = __va_arg(ap, u_int);
728 num = __va_arg(ap, intmax_t);
730 num = __va_arg(ap, long);
732 num = __va_arg(ap, quad_t);
734 num = __va_arg(ap, ptrdiff_t);
736 num = __va_arg(ap, int);
738 if (sign && (intmax_t)num < 0) {
740 num = -(intmax_t)num;
742 p = ksprintn(nbuf, num, base, &tmp, upper);
743 if (sharpflag && num != 0) {
752 if (!ladjust && padc != '0' && width &&
753 (width -= tmp) > 0) {
759 if (sharpflag && num != 0) {
762 } else if (base == 16) {
767 if (!ladjust && width && (width -= tmp) > 0)
774 if (ladjust && width && (width -= tmp) > 0)
780 while (percent < fmt)
783 * Since we ignore an formatting argument it is no
784 * longer safe to obey the remaining formatting
785 * arguments as the arguments will no longer match
796 * Put character in log buffer with a particular priority.
801 msglogchar(int c, int pri)
803 static int lastpri = -1;
810 if (c == '\0' || c == '\r')
812 if (pri != -1 && pri != lastpri) {
814 msgaddchar('\n', NULL);
817 msgaddchar('<', NULL);
818 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
819 msgaddchar(*p--, NULL);
820 msgaddchar('>', NULL);
833 * Put char in log buffer. Make sure nothing blows up beyond repair if
834 * we have an MP race.
839 msgaddchar(int c, void *dummy)
848 windex = mbp->msg_bufx;
849 mbp->msg_ptr[windex] = c;
850 if (++windex >= mbp->msg_size)
852 rindex = mbp->msg_bufr;
853 if (windex == rindex) {
855 if (rindex >= mbp->msg_size)
856 rindex -= mbp->msg_size;
857 mbp->msg_bufr = rindex;
859 mbp->msg_bufx = windex;
863 msgbufcopy(struct msgbuf *oldp)
867 pos = oldp->msg_bufr;
868 while (pos != oldp->msg_bufx) {
869 msglogchar(oldp->msg_ptr[pos], -1);
870 if (++pos >= oldp->msg_size)
876 msgbufinit(void *ptr, size_t size)
879 static struct msgbuf *oldp = NULL;
881 size -= sizeof(*msgbufp);
883 msgbufp = (struct msgbuf *) (cp + size);
884 if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
885 msgbufp->msg_bufx >= size || msgbufp->msg_bufr >= size) {
887 bzero(msgbufp, sizeof(*msgbufp));
888 msgbufp->msg_magic = MSG_MAGIC;
889 msgbufp->msg_size = (char *)msgbufp - cp;
891 msgbufp->msg_ptr = cp;
892 if (msgbufmapped && oldp != msgbufp)
898 /* Sysctls for accessing/clearing the msgbuf */
901 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
907 * Only wheel or root can access the message log.
909 if (unprivileged_read_msgbuf == 0) {
910 KKASSERT(req->td->td_proc);
911 cred = req->td->td_proc->p_ucred;
913 if ((cred->cr_prison || groupmember(0, cred) == 0) &&
921 * Unwind the buffer, so that it's linear (possibly starting with
922 * some initial nulls).
924 error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
925 msgbufp->msg_size - msgbufp->msg_bufx, req);
928 if (msgbufp->msg_bufx > 0) {
929 error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
930 msgbufp->msg_bufx, req);
935 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
936 0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
938 static int msgbuf_clear;
941 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
944 error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
945 if (!error && req->newptr) {
946 /* Clear the buffer and reset write pointer */
947 bzero(msgbufp->msg_ptr, msgbufp->msg_size);
948 msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
954 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
955 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
956 sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
960 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
965 db_printf("msgbuf not mapped yet\n");
968 db_printf("msgbufp = %p\n", msgbufp);
969 db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
970 msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
971 msgbufp->msg_bufx, msgbufp->msg_ptr);
972 for (i = 0; i < msgbufp->msg_size; i++) {
973 j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
974 db_printf("%c", msgbufp->msg_ptr[j]);