2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1986, 1988, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)subr_prf.c 8.3 (Berkeley) 1/21/94
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
44 #include "opt_printf.h"
47 #include <sys/param.h>
49 #include <sys/systm.h>
52 #include <sys/mutex.h>
54 #include <sys/kernel.h>
55 #include <sys/msgbuf.h>
56 #include <sys/malloc.h>
59 #include <sys/stddef.h>
60 #include <sys/sysctl.h>
62 #include <sys/syslog.h>
66 #include <sys/ctype.h>
74 * Note that stdarg.h and the ANSI style va_start macro is used for both
75 * ANSI and traditional C compilers.
78 #include <machine/stdarg.h>
84 * This is needed for sbuf_putbuf() when compiled into userland. Due to the
85 * shared nature of this file, it's the only place to put it.
97 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
98 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
110 struct snprintf_arg {
117 static void msglogchar(int c, int pri);
118 static void msglogstr(char *str, int pri, int filter_cr);
119 static void putchar(int ch, void *arg);
120 static char *ksprintn(char *nbuf, uintmax_t num, int base, int *len, int upper);
121 static void snprintf_func(int ch, void *arg);
123 static bool msgbufmapped; /* Set when safe to use msgbuf */
125 struct msgbuf *msgbufp;
128 #define BOOT_TAG_SZ 32
131 /* Tag used to mark the start of a boot in dmesg */
132 #define BOOT_TAG "---<<BOOT>>---"
135 static char current_boot_tag[BOOT_TAG_SZ + 1] = BOOT_TAG;
136 SYSCTL_STRING(_kern, OID_AUTO, boot_tag, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
137 current_boot_tag, 0, "Tag added to dmesg at start of boot");
139 static int log_console_output = 1;
140 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RWTUN,
141 &log_console_output, 0, "Duplicate console output to the syslog");
144 * See the comment in log_console() below for more explanation of this.
146 static int log_console_add_linefeed;
147 SYSCTL_INT(_kern, OID_AUTO, log_console_add_linefeed, CTLFLAG_RWTUN,
148 &log_console_add_linefeed, 0, "log_console() adds extra newlines");
150 static int always_console_output;
151 SYSCTL_INT(_kern, OID_AUTO, always_console_output, CTLFLAG_RWTUN,
152 &always_console_output, 0, "Always output to console despite TIOCCONS");
155 * Warn that a system table is full.
158 tablefull(const char *tab)
161 log(LOG_ERR, "%s: table is full\n", tab);
165 * Uprintf prints to the controlling terminal for the current process.
168 uprintf(const char *fmt, ...)
171 struct putchar_arg pca;
177 if (TD_IS_IDLETHREAD(td))
180 sx_slock(&proctree_lock);
183 if ((p->p_flag & P_CONTROLT) == 0) {
185 sx_sunlock(&proctree_lock);
188 SESS_LOCK(p->p_session);
189 pca.tty = p->p_session->s_ttyp;
190 SESS_UNLOCK(p->p_session);
192 if (pca.tty == NULL) {
193 sx_sunlock(&proctree_lock);
200 sx_sunlock(&proctree_lock);
201 retval = kvprintf(fmt, putchar, &pca, 10, ap);
208 * tprintf and vtprintf print on the controlling terminal associated with the
209 * given session, possibly to the log as well.
212 tprintf(struct proc *p, int pri, const char *fmt, ...)
217 vtprintf(p, pri, fmt, ap);
222 vtprintf(struct proc *p, int pri, const char *fmt, va_list ap)
224 struct tty *tp = NULL;
226 struct putchar_arg pca;
227 struct session *sess = NULL;
229 sx_slock(&proctree_lock);
234 if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
239 if (tp != NULL && tty_checkoutq(tp))
252 sx_sunlock(&proctree_lock);
253 kvprintf(fmt, putchar, &pca, 10, ap);
262 _vprintf(int level, int flags, const char *fmt, va_list ap)
264 struct putchar_arg pca;
266 #ifdef PRINTF_BUFR_SIZE
267 char bufr[PRINTF_BUFR_SIZE];
274 #ifdef PRINTF_BUFR_SIZE
276 pca.p_next = pca.p_bufr;
277 pca.n_bufr = sizeof(bufr);
278 pca.remain = sizeof(bufr);
281 /* Don't buffer console output. */
285 retval = kvprintf(fmt, putchar, &pca, 10, ap);
287 #ifdef PRINTF_BUFR_SIZE
288 /* Write any buffered console/log output: */
289 if (*pca.p_bufr != '\0') {
290 if (pca.flags & TOLOG)
291 msglogstr(pca.p_bufr, level, /*filter_cr*/1);
293 if (pca.flags & TOCONS)
303 * Log writes to the log buffer, and guarantees not to sleep (so can be
304 * called by interrupt routines). If there is no process reading the
305 * log yet, it writes to the console also.
308 log(int level, const char *fmt, ...)
313 vlog(level, fmt, ap);
318 vlog(int level, const char *fmt, va_list ap)
321 (void)_vprintf(level, log_open ? TOLOG : TOCONS | TOLOG, fmt, ap);
325 #define CONSCHUNK 128
328 log_console(struct uio *uio)
334 if (!log_console_output)
337 pri = LOG_INFO | LOG_CONSOLE;
339 consbuffer = malloc(CONSCHUNK, M_TEMP, M_WAITOK);
342 while (uio->uio_resid > 0) {
343 c = imin(uio->uio_resid, CONSCHUNK - 1);
344 error = uiomove(consbuffer, c, uio);
347 /* Make sure we're NUL-terminated */
348 consbuffer[c] = '\0';
349 if (consbuffer[c - 1] == '\n')
353 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
356 * The previous behavior in log_console() is preserved when
357 * log_console_add_linefeed is non-zero. For that behavior, if an
358 * individual console write came in that was not terminated with a
359 * line feed, it would add a line feed.
361 * This results in different data in the message buffer than
362 * appears on the system console (which doesn't add extra line feed
365 * A number of programs and rc scripts write a line feed, or a period
366 * and a line feed when they have completed their operation. On
367 * the console, this looks seamless, but when displayed with
368 * 'dmesg -a', you wind up with output that looks like this:
373 * On the console, it looks like this:
376 * We could add logic to detect that situation, or just not insert
377 * the extra newlines. Set the kern.log_console_add_linefeed
378 * sysctl/tunable variable to get the old behavior.
380 if (!nl && log_console_add_linefeed) {
381 consbuffer[0] = '\n';
382 consbuffer[1] = '\0';
383 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
387 free(consbuffer, M_TEMP);
391 printf(const char *fmt, ...)
397 retval = vprintf(fmt, ap);
404 vprintf(const char *fmt, va_list ap)
408 retval = _vprintf(-1, TOCONS | TOLOG, fmt, ap);
417 prf_putbuf(char *bufr, int flags, int pri)
421 msglogstr(bufr, pri, /*filter_cr*/1);
423 if (flags & TOCONS) {
424 if ((panicstr == NULL) && (constty != NULL))
425 msgbuf_addstr(&consmsgbuf, -1,
426 bufr, /*filter_cr*/ 0);
428 if ((constty == NULL) ||(always_console_output))
434 putbuf(int c, struct putchar_arg *ap)
436 /* Check if no console output buffer was provided. */
437 if (ap->p_bufr == NULL) {
438 /* Output direct to the console. */
439 if (ap->flags & TOCONS)
442 if (ap->flags & TOLOG)
443 msglogchar(c, ap->pri);
445 /* Buffer the character: */
449 /* Always leave the buffer zero terminated. */
452 /* Check if the buffer needs to be flushed. */
453 if (ap->remain == 2 || c == '\n') {
454 prf_putbuf(ap->p_bufr, ap->flags, ap->pri);
456 ap->p_next = ap->p_bufr;
457 ap->remain = ap->n_bufr;
462 * Since we fill the buffer up one character at a time,
463 * this should not happen. We should always catch it when
464 * ap->remain == 2 (if not sooner due to a newline), flush
465 * the buffer and move on. One way this could happen is
466 * if someone sets PRINTF_BUFR_SIZE to 1 or something
469 KASSERT(ap->remain > 2, ("Bad buffer logic, remain = %zd",
475 * Print a character on console or users terminal. If destination is
476 * the console then the last bunch of characters are saved in msgbuf for
480 putchar(int c, void *arg)
482 struct putchar_arg *ap = (struct putchar_arg*) arg;
483 struct tty *tp = ap->tty;
484 int flags = ap->flags;
486 /* Don't use the tty code after a panic or while in ddb. */
493 if ((flags & TOTTY) && tp != NULL && panicstr == NULL)
496 if ((flags & (TOCONS | TOLOG)) && c != '\0')
501 * Scaled down version of sprintf(3).
504 sprintf(char *buf, const char *cfmt, ...)
510 retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
517 * Scaled down version of vsprintf(3).
520 vsprintf(char *buf, const char *cfmt, va_list ap)
524 retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
530 * Scaled down version of snprintf(3).
533 snprintf(char *str, size_t size, const char *format, ...)
538 va_start(ap, format);
539 retval = vsnprintf(str, size, format, ap);
545 * Scaled down version of vsnprintf(3).
548 vsnprintf(char *str, size_t size, const char *format, va_list ap)
550 struct snprintf_arg info;
555 retval = kvprintf(format, snprintf_func, &info, 10, ap);
556 if (info.remain >= 1)
562 * Kernel version which takes radix argument vsnprintf(3).
565 vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
567 struct snprintf_arg info;
572 retval = kvprintf(format, snprintf_func, &info, radix, ap);
573 if (info.remain >= 1)
579 snprintf_func(int ch, void *arg)
581 struct snprintf_arg *const info = arg;
583 if (info->remain >= 2) {
590 * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
591 * order; return an optional length and a pointer to the last character
592 * written in the buffer (i.e., the first character of the string).
593 * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
596 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
603 c = hex2ascii(num % base);
604 *++p = upper ? toupper(c) : c;
605 } while (num /= base);
612 * Scaled down version of printf(3).
614 * Two additional formats:
616 * The format %b is supported to decode error registers.
619 * printf("reg=%b\n", regval, "<base><arg>*");
621 * where <base> is the output base expressed as a control character, e.g.
622 * \10 gives octal; \20 gives hex. Each arg is a sequence of characters,
623 * the first of which gives the bit number to be inspected (origin 1), and
624 * the next characters (up to a control character, i.e. a character <= 32),
625 * give the name of the register. Thus:
627 * kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE");
629 * would produce output:
631 * reg=3<BITTWO,BITONE>
633 * XXX: %D -- Hexdump, takes pointer and separator string:
634 * ("%6D", ptr, ":") -> XX:XX:XX:XX:XX:XX
635 * ("%*D", len, ptr, " " -> XX XX XX XX ...
638 kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
640 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
643 const char *p, *percent, *q;
647 int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
648 int cflag, hflag, jflag, tflag, zflag;
649 int bconv, dwidth, upper;
651 int stop = 0, retval = 0;
661 fmt = "(fmt null)\n";
663 if (radix < 2 || radix > 36)
669 while ((ch = (u_char)*fmt++) != '%' || stop) {
675 qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
676 sign = 0; dot = 0; bconv = 0; dwidth = 0; upper = 0;
677 cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
678 reswitch: switch (ch = (u_char)*fmt++) {
696 width = va_arg(ap, int);
702 dwidth = va_arg(ap, int);
711 case '1': case '2': case '3': case '4':
712 case '5': case '6': case '7': case '8': case '9':
713 for (n = 0;; ++fmt) {
714 n = n * 10 + ch - '0';
716 if (ch < '0' || ch > '9')
731 if (!ladjust && width > 0)
734 PCHAR(va_arg(ap, int));
735 if (ladjust && width > 0)
740 up = va_arg(ap, u_char *);
741 p = va_arg(ap, char *);
745 PCHAR(hex2ascii(*up >> 4));
746 PCHAR(hex2ascii(*up & 0x0f));
777 *(va_arg(ap, intmax_t *)) = retval;
779 *(va_arg(ap, quad_t *)) = retval;
781 *(va_arg(ap, long *)) = retval;
783 *(va_arg(ap, size_t *)) = retval;
785 *(va_arg(ap, short *)) = retval;
787 *(va_arg(ap, char *)) = retval;
789 *(va_arg(ap, int *)) = retval;
796 sharpflag = (width == 0);
798 num = (uintptr_t)va_arg(ap, void *);
809 p = va_arg(ap, char *);
815 for (n = 0; n < dwidth && p[n]; n++)
820 if (!ladjust && width > 0)
825 if (ladjust && width > 0)
850 num = va_arg(ap, uintmax_t);
852 num = va_arg(ap, u_quad_t);
854 num = va_arg(ap, ptrdiff_t);
856 num = va_arg(ap, u_long);
858 num = va_arg(ap, size_t);
860 num = (u_short)va_arg(ap, int);
862 num = (u_char)va_arg(ap, int);
864 num = va_arg(ap, u_int);
866 q = va_arg(ap, char *);
872 num = va_arg(ap, intmax_t);
874 num = va_arg(ap, quad_t);
876 num = va_arg(ap, ptrdiff_t);
878 num = va_arg(ap, long);
880 num = va_arg(ap, ssize_t);
882 num = (short)va_arg(ap, int);
884 num = (char)va_arg(ap, int);
886 num = va_arg(ap, int);
888 if (sign && (intmax_t)num < 0) {
890 num = -(intmax_t)num;
892 p = ksprintn(nbuf, num, base, &n, upper);
894 if (sharpflag && num != 0) {
903 if (!ladjust && padc == '0')
904 dwidth = width - tmp;
905 width -= tmp + imax(dwidth, n);
912 if (sharpflag && num != 0) {
915 } else if (base == 16) {
926 if (bconv && num != 0) {
927 /* %b conversion flag format. */
931 if (num & (1 << (n - 1))) {
932 PCHAR(retval != tmp ?
934 for (; (n = *q) > ' '; ++q)
937 for (; *q > ' '; ++q)
942 width -= retval - tmp;
952 while (percent < fmt)
955 * Since we ignore a formatting argument it is no
956 * longer safe to obey the remaining formatting
957 * arguments as the arguments will no longer match
968 * Put character in log buffer with a particular priority.
971 msglogchar(int c, int pri)
973 static int lastpri = -1;
980 if (c == '\0' || c == '\r')
982 if (pri != -1 && pri != lastpri) {
984 msgbuf_addchar(msgbufp, '\n');
987 msgbuf_addchar(msgbufp, '<');
988 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
989 msgbuf_addchar(msgbufp, *p--);
990 msgbuf_addchar(msgbufp, '>');
993 msgbuf_addchar(msgbufp, c);
1003 msglogstr(char *str, int pri, int filter_cr)
1008 msgbuf_addstr(msgbufp, pri, str, filter_cr);
1012 msgbufinit(void *ptr, int size)
1015 static struct msgbuf *oldp = NULL;
1016 bool print_boot_tag;
1018 size -= sizeof(*msgbufp);
1020 print_boot_tag = !msgbufmapped;
1021 /* Attempt to fetch kern.boot_tag tunable on first mapping */
1023 TUNABLE_STR_FETCH("kern.boot_tag", current_boot_tag,
1024 sizeof(current_boot_tag));
1025 msgbufp = (struct msgbuf *)(cp + size);
1026 msgbuf_reinit(msgbufp, cp, size);
1027 if (msgbufmapped && oldp != msgbufp)
1028 msgbuf_copy(oldp, msgbufp);
1029 msgbufmapped = true;
1030 if (print_boot_tag && *current_boot_tag != '\0')
1031 printf("%s\n", current_boot_tag);
1035 /* Sysctls for accessing/clearing the msgbuf */
1037 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1043 error = priv_check(req->td, PRIV_MSGBUF);
1047 /* Read the whole buffer, one chunk at a time. */
1048 mtx_lock(&msgbuf_lock);
1049 msgbuf_peekbytes(msgbufp, NULL, 0, &seq);
1051 len = msgbuf_peekbytes(msgbufp, buf, sizeof(buf), &seq);
1052 mtx_unlock(&msgbuf_lock);
1054 return (SYSCTL_OUT(req, "", 1)); /* add nulterm */
1056 error = sysctl_handle_opaque(oidp, buf, len, req);
1060 mtx_lock(&msgbuf_lock);
1064 SYSCTL_PROC(_kern, OID_AUTO, msgbuf,
1065 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1066 NULL, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1068 static int msgbuf_clearflag;
1071 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1074 error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1075 if (!error && req->newptr) {
1076 mtx_lock(&msgbuf_lock);
1077 msgbuf_clear(msgbufp);
1078 mtx_unlock(&msgbuf_lock);
1079 msgbuf_clearflag = 0;
1084 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1085 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE | CTLFLAG_MPSAFE,
1086 &msgbuf_clearflag, 0, sysctl_kern_msgbuf_clear, "I",
1087 "Clear kernel message buffer");
1091 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1095 if (!msgbufmapped) {
1096 db_printf("msgbuf not mapped yet\n");
1099 db_printf("msgbufp = %p\n", msgbufp);
1100 db_printf("magic = %x, size = %d, r= %u, w = %u, ptr = %p, cksum= %u\n",
1101 msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_rseq,
1102 msgbufp->msg_wseq, msgbufp->msg_ptr, msgbufp->msg_cksum);
1103 for (i = 0; i < msgbufp->msg_size && !db_pager_quit; i++) {
1104 j = MSGBUF_SEQ_TO_POS(msgbufp, i + msgbufp->msg_rseq);
1105 db_printf("%c", msgbufp->msg_ptr[j]);
1113 hexdump(const void *ptr, int length, const char *hdr, int flags)
1117 const unsigned char *cp;
1120 if ((flags & HD_DELIM_MASK) != 0)
1121 delim = (flags & HD_DELIM_MASK) >> 8;
1125 if ((flags & HD_COLUMN_MASK) != 0)
1126 cols = flags & HD_COLUMN_MASK;
1131 for (i = 0; i < length; i+= cols) {
1135 if ((flags & HD_OMIT_COUNT) == 0)
1138 if ((flags & HD_OMIT_HEX) == 0) {
1139 for (j = 0; j < cols; j++) {
1142 printf("%c%02x", delim, cp[k]);
1148 if ((flags & HD_OMIT_CHARS) == 0) {
1150 for (j = 0; j < cols; j++) {
1154 else if (cp[k] >= ' ' && cp[k] <= '~')
1155 printf("%c", cp[k]);
1164 #endif /* _KERNEL */
1167 sbuf_hexdump(struct sbuf *sb, const void *ptr, int length, const char *hdr,
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) {
1188 sbuf_printf(sb, "%s", hdr);
1190 if ((flags & HD_OMIT_COUNT) == 0)
1191 sbuf_printf(sb, "%04x ", i);
1193 if ((flags & HD_OMIT_HEX) == 0) {
1194 for (j = 0; j < cols; j++) {
1197 sbuf_printf(sb, "%c%02x", delim, cp[k]);
1199 sbuf_printf(sb, " ");
1203 if ((flags & HD_OMIT_CHARS) == 0) {
1204 sbuf_printf(sb, " |");
1205 for (j = 0; j < cols; j++) {
1208 sbuf_printf(sb, " ");
1209 else if (cp[k] >= ' ' && cp[k] <= '~')
1210 sbuf_printf(sb, "%c", cp[k]);
1212 sbuf_printf(sb, ".");
1214 sbuf_printf(sb, "|");
1216 sbuf_printf(sb, "\n");
1222 counted_warning(unsigned *counter, const char *msg)
1231 if (atomic_cmpset_int(counter, c, c - 1)) {
1233 log(LOG_INFO, "pid %d (%s) %s%s\n",
1234 td->td_proc->p_pid, td->td_name, msg,
1235 c > 1 ? "" : " - not logging anymore");
1244 sbuf_putbuf(struct sbuf *sb)
1247 prf_putbuf(sbuf_data(sb), TOLOG | TOCONS, -1);
1251 sbuf_putbuf(struct sbuf *sb)
1254 printf("%s", sbuf_data(sb));