1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
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.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
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.
23 *
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
34 * SUCH DAMAGE.
35 */
36
37 #include <sys/cdefs.h>
38 #ifdef _KERNEL
39 #include "opt_ddb.h"
40 #include "opt_printf.h"
41 #endif /* _KERNEL */
42
43 #include <sys/param.h>
44 #ifdef _KERNEL
45 #include <sys/systm.h>
46 #include <sys/lock.h>
47 #include <sys/kdb.h>
48 #include <sys/mutex.h>
49 #include <sys/sx.h>
50 #include <sys/kernel.h>
51 #include <sys/msgbuf.h>
52 #include <sys/malloc.h>
53 #include <sys/priv.h>
54 #include <sys/proc.h>
55 #include <sys/stddef.h>
56 #include <sys/sysctl.h>
57 #include <sys/tslog.h>
58 #include <sys/tty.h>
59 #include <sys/syslog.h>
60 #include <sys/cons.h>
61 #include <sys/uio.h>
62 #else /* !_KERNEL */
63 #include <errno.h>
64 #endif
65 #include <sys/ctype.h>
66 #include <sys/sbuf.h>
67
68 #ifdef DDB
69 #include <ddb/ddb.h>
70 #endif
71
72 #ifdef _KERNEL
73 #include <sys/stdarg.h>
74 #else
75 #include <stdarg.h>
76 #endif
77
78 /*
79 * This is needed for sbuf_putbuf() when compiled into userland. Due to the
80 * shared nature of this file, it's the only place to put it.
81 */
82 #ifndef _KERNEL
83 #include <stdio.h>
84 #endif
85
86 #ifdef _KERNEL
87
88 #define TOCONS 0x01
89 #define TOTTY 0x02
90 #define TOLOG 0x04
91
92 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
93 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
94
95 struct putchar_arg {
96 int flags;
97 int pri;
98 struct tty *tty;
99 char *p_bufr;
100 size_t n_bufr;
101 char *p_next;
102 size_t remain;
103 };
104
105 struct snprintf_arg {
106 char *str;
107 size_t remain;
108 };
109
110 extern int log_open;
111 extern int cn_mute;
112
113 static void msglogchar(int c, int pri);
114 static void msglogstr(char *str, int pri, int filter_cr);
115 static void prf_putbuf(char *bufr, int flags, int pri);
116 static void putchar(int ch, void *arg);
117 static char *ksprintn(char *nbuf, uintmax_t num, int base, int *len, int upper);
118 static void snprintf_func(int ch, void *arg);
119
120 static bool msgbufmapped; /* Set when safe to use msgbuf */
121 int msgbuftrigger;
122 struct msgbuf *msgbufp;
123
124 #ifndef BOOT_TAG_SZ
125 #define BOOT_TAG_SZ 32
126 #endif
127 #ifndef BOOT_TAG
128 /* Tag used to mark the start of a boot in dmesg */
129 #define BOOT_TAG "---<<BOOT>>---"
130 #endif
131
132 static char current_boot_tag[BOOT_TAG_SZ + 1] = BOOT_TAG;
133 SYSCTL_STRING(_kern, OID_AUTO, boot_tag, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
134 current_boot_tag, 0, "Tag added to dmesg at start of boot");
135
136 static int log_console_output = 1;
137 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RWTUN,
138 &log_console_output, 0, "Duplicate console output to the syslog");
139
140 /*
141 * See the comment in log_console() below for more explanation of this.
142 */
143 static int log_console_add_linefeed;
144 SYSCTL_INT(_kern, OID_AUTO, log_console_add_linefeed, CTLFLAG_RWTUN,
145 &log_console_add_linefeed, 0, "log_console() adds extra newlines");
146
147 static int always_console_output;
148 SYSCTL_INT(_kern, OID_AUTO, always_console_output, CTLFLAG_RWTUN,
149 &always_console_output, 0, "Always output to console despite TIOCCONS");
150
151 /*
152 * Warn that a system table is full.
153 */
154 void
tablefull(const char * tab)155 tablefull(const char *tab)
156 {
157
158 log(LOG_ERR, "%s: table is full\n", tab);
159 }
160
161 /*
162 * Uprintf prints to the controlling terminal for the current process.
163 */
164 int
uprintf(const char * fmt,...)165 uprintf(const char *fmt, ...)
166 {
167 va_list ap;
168 struct putchar_arg pca;
169 struct proc *p;
170 struct thread *td;
171 int retval;
172
173 td = curthread;
174 if (TD_IS_IDLETHREAD(td))
175 return (0);
176
177 if (td->td_proc == initproc) {
178 /* Produce output when we fail to load /sbin/init: */
179 va_start(ap, fmt);
180 retval = vprintf(fmt, ap);
181 va_end(ap);
182 return (retval);
183 }
184
185 sx_slock(&proctree_lock);
186 p = td->td_proc;
187 PROC_LOCK(p);
188 if ((p->p_flag & P_CONTROLT) == 0) {
189 PROC_UNLOCK(p);
190 sx_sunlock(&proctree_lock);
191 return (0);
192 }
193 SESS_LOCK(p->p_session);
194 pca.tty = p->p_session->s_ttyp;
195 SESS_UNLOCK(p->p_session);
196 PROC_UNLOCK(p);
197 if (pca.tty == NULL) {
198 sx_sunlock(&proctree_lock);
199 return (0);
200 }
201 pca.flags = TOTTY;
202 pca.p_bufr = NULL;
203 va_start(ap, fmt);
204 tty_lock(pca.tty);
205 sx_sunlock(&proctree_lock);
206 retval = kvprintf(fmt, putchar, &pca, 10, ap);
207 tty_unlock(pca.tty);
208 va_end(ap);
209 return (retval);
210 }
211
212 /*
213 * tprintf and vtprintf print on the controlling terminal associated with the
214 * given session, possibly to the log as well.
215 */
216 void
tprintf(struct proc * p,int pri,const char * fmt,...)217 tprintf(struct proc *p, int pri, const char *fmt, ...)
218 {
219 va_list ap;
220
221 va_start(ap, fmt);
222 vtprintf(p, pri, fmt, ap);
223 va_end(ap);
224 }
225
226 void
vtprintf(struct proc * p,int pri,const char * fmt,va_list ap)227 vtprintf(struct proc *p, int pri, const char *fmt, va_list ap)
228 {
229 struct tty *tp = NULL;
230 int flags = 0;
231 struct putchar_arg pca;
232 struct session *sess = NULL;
233
234 sx_slock(&proctree_lock);
235 if (pri != -1)
236 flags |= TOLOG;
237 if (p != NULL) {
238 PROC_LOCK(p);
239 if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
240 sess = p->p_session;
241 sess_hold(sess);
242 PROC_UNLOCK(p);
243 tp = sess->s_ttyp;
244 if (tp != NULL && tty_checkoutq(tp))
245 flags |= TOTTY;
246 else
247 tp = NULL;
248 } else
249 PROC_UNLOCK(p);
250 }
251 pca.pri = pri;
252 pca.tty = tp;
253 pca.flags = flags;
254 pca.p_bufr = NULL;
255 if (pca.tty != NULL)
256 tty_lock(pca.tty);
257 sx_sunlock(&proctree_lock);
258 kvprintf(fmt, putchar, &pca, 10, ap);
259 if (pca.tty != NULL)
260 tty_unlock(pca.tty);
261 if (sess != NULL)
262 sess_release(sess);
263 msgbuftrigger = 1;
264 }
265
266 static int
_vprintf(int level,int flags,const char * fmt,va_list ap)267 _vprintf(int level, int flags, const char *fmt, va_list ap)
268 {
269 struct putchar_arg pca;
270 int retval;
271 #ifdef PRINTF_BUFR_SIZE
272 char bufr[PRINTF_BUFR_SIZE];
273 #endif
274
275 TSENTER();
276 pca.tty = NULL;
277 pca.pri = level;
278 pca.flags = flags;
279 #ifdef PRINTF_BUFR_SIZE
280 pca.p_bufr = bufr;
281 pca.p_next = pca.p_bufr;
282 pca.n_bufr = sizeof(bufr);
283 pca.remain = sizeof(bufr);
284 *pca.p_next = '\0';
285 #else
286 /* Don't buffer console output. */
287 pca.p_bufr = NULL;
288 #endif
289
290 retval = kvprintf(fmt, putchar, &pca, 10, ap);
291
292 #ifdef PRINTF_BUFR_SIZE
293 /* Write any buffered console/log output: */
294 if (*pca.p_bufr != '\0')
295 prf_putbuf(pca.p_bufr, flags, level);
296 #endif
297
298 TSEXIT();
299 return (retval);
300 }
301
302 /*
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.
306 */
307 void
log(int level,const char * fmt,...)308 log(int level, const char *fmt, ...)
309 {
310 va_list ap;
311
312 va_start(ap, fmt);
313 vlog(level, fmt, ap);
314 va_end(ap);
315 }
316
317 void
vlog(int level,const char * fmt,va_list ap)318 vlog(int level, const char *fmt, va_list ap)
319 {
320
321 (void)_vprintf(level, log_open ? TOLOG : TOCONS | TOLOG, fmt, ap);
322 msgbuftrigger = 1;
323 }
324
325 #define CONSCHUNK 128
326
327 void
log_console(struct uio * uio)328 log_console(struct uio *uio)
329 {
330 int c, error, nl;
331 char *consbuffer;
332 int pri;
333
334 if (!log_console_output)
335 return;
336
337 pri = LOG_INFO | LOG_CONSOLE;
338 uio = cloneuio(uio);
339 consbuffer = malloc(CONSCHUNK, M_TEMP, M_WAITOK);
340
341 nl = 0;
342 while (uio->uio_resid > 0) {
343 c = imin(uio->uio_resid, CONSCHUNK - 1);
344 error = uiomove(consbuffer, c, uio);
345 if (error != 0)
346 break;
347 /* Make sure we're NUL-terminated */
348 consbuffer[c] = '\0';
349 if (consbuffer[c - 1] == '\n')
350 nl = 1;
351 else
352 nl = 0;
353 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
354 }
355 /*
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.
360 *
361 * This results in different data in the message buffer than
362 * appears on the system console (which doesn't add extra line feed
363 * characters).
364 *
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:
369 *
370 * Updating motd:
371 * .
372 *
373 * On the console, it looks like this:
374 * Updating motd:.
375 *
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.
379 */
380 if (!nl && log_console_add_linefeed) {
381 consbuffer[0] = '\n';
382 consbuffer[1] = '\0';
383 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
384 }
385 msgbuftrigger = 1;
386 freeuio(uio);
387 free(consbuffer, M_TEMP);
388 }
389
390 int
printf(const char * fmt,...)391 printf(const char *fmt, ...)
392 {
393 va_list ap;
394 int retval;
395
396 va_start(ap, fmt);
397 retval = vprintf(fmt, ap);
398 va_end(ap);
399
400 return (retval);
401 }
402
403 int
vprintf(const char * fmt,va_list ap)404 vprintf(const char *fmt, va_list ap)
405 {
406 int retval;
407
408 retval = _vprintf(-1, TOCONS | TOLOG, fmt, ap);
409
410 if (!KERNEL_PANICKED())
411 msgbuftrigger = 1;
412
413 return (retval);
414 }
415
416 static void
prf_putchar(int c,int flags,int pri)417 prf_putchar(int c, int flags, int pri)
418 {
419
420 if (flags & TOLOG) {
421 msglogchar(c, pri);
422 msgbuftrigger = 1;
423 }
424
425 if ((flags & TOCONS) && !cn_mute) {
426 if ((!KERNEL_PANICKED()) && (constty != NULL))
427 msgbuf_addchar(&consmsgbuf, c);
428
429 if ((constty == NULL) || always_console_output)
430 cnputc(c);
431 }
432 }
433
434 static void
prf_putbuf(char * bufr,int flags,int pri)435 prf_putbuf(char *bufr, int flags, int pri)
436 {
437
438 if (flags & TOLOG) {
439 msglogstr(bufr, pri, /*filter_cr*/1);
440 msgbuftrigger = 1;
441 }
442
443 if ((flags & TOCONS) && !cn_mute) {
444 if ((!KERNEL_PANICKED()) && (constty != NULL))
445 msgbuf_addstr(&consmsgbuf, -1,
446 bufr, /*filter_cr*/ 0);
447
448 if ((constty == NULL) || always_console_output)
449 cnputs(bufr);
450 }
451 }
452
453 static void
putbuf(int c,struct putchar_arg * ap)454 putbuf(int c, struct putchar_arg *ap)
455 {
456 /* Check if no console output buffer was provided. */
457 if (ap->p_bufr == NULL) {
458 prf_putchar(c, ap->flags, ap->pri);
459 } else {
460 /* Buffer the character: */
461 *ap->p_next++ = c;
462 ap->remain--;
463
464 /* Always leave the buffer zero terminated. */
465 *ap->p_next = '\0';
466
467 /* Check if the buffer needs to be flushed. */
468 if (ap->remain == 2 || c == '\n') {
469 prf_putbuf(ap->p_bufr, ap->flags, ap->pri);
470
471 ap->p_next = ap->p_bufr;
472 ap->remain = ap->n_bufr;
473 *ap->p_next = '\0';
474 }
475
476 /*
477 * Since we fill the buffer up one character at a time,
478 * this should not happen. We should always catch it when
479 * ap->remain == 2 (if not sooner due to a newline), flush
480 * the buffer and move on. One way this could happen is
481 * if someone sets PRINTF_BUFR_SIZE to 1 or something
482 * similarly silly.
483 */
484 KASSERT(ap->remain > 2, ("Bad buffer logic, remain = %zd",
485 ap->remain));
486 }
487 }
488
489 /*
490 * Print a character on console or users terminal. If destination is
491 * the console then the last bunch of characters are saved in msgbuf for
492 * inspection later.
493 */
494 static void
putchar(int c,void * arg)495 putchar(int c, void *arg)
496 {
497 struct putchar_arg *ap = (struct putchar_arg*) arg;
498 struct tty *tp = ap->tty;
499 int flags = ap->flags;
500
501 /* Don't use the tty code after a panic or while in ddb. */
502 if (kdb_active) {
503 if (c != '\0')
504 cnputc(c);
505 return;
506 }
507
508 if ((flags & TOTTY) && tp != NULL && !KERNEL_PANICKED())
509 tty_putchar(tp, c);
510
511 if ((flags & TOCONS) && cn_mute) {
512 flags &= ~TOCONS;
513 ap->flags = flags;
514 }
515
516 if ((flags & (TOCONS | TOLOG)) && c != '\0')
517 putbuf(c, ap);
518 }
519
520 /*
521 * Scaled down version of sprintf(3).
522 */
523 int
sprintf(char * buf,const char * cfmt,...)524 sprintf(char *buf, const char *cfmt, ...)
525 {
526 int retval;
527 va_list ap;
528
529 va_start(ap, cfmt);
530 retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
531 buf[retval] = '\0';
532 va_end(ap);
533 return (retval);
534 }
535
536 /*
537 * Scaled down version of vsprintf(3).
538 */
539 int
vsprintf(char * buf,const char * cfmt,va_list ap)540 vsprintf(char *buf, const char *cfmt, va_list ap)
541 {
542 int retval;
543
544 retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
545 buf[retval] = '\0';
546 return (retval);
547 }
548
549 /*
550 * Scaled down version of snprintf(3).
551 */
552 int
snprintf(char * str,size_t size,const char * format,...)553 snprintf(char *str, size_t size, const char *format, ...)
554 {
555 int retval;
556 va_list ap;
557
558 va_start(ap, format);
559 retval = vsnprintf(str, size, format, ap);
560 va_end(ap);
561 return(retval);
562 }
563
564 /*
565 * Scaled down version of vsnprintf(3).
566 */
567 int
vsnprintf(char * str,size_t size,const char * format,va_list ap)568 vsnprintf(char *str, size_t size, const char *format, va_list ap)
569 {
570 struct snprintf_arg info;
571 int retval;
572
573 info.str = str;
574 info.remain = size;
575 retval = kvprintf(format, snprintf_func, &info, 10, ap);
576 if (info.remain >= 1)
577 *info.str++ = '\0';
578 return (retval);
579 }
580
581 /*
582 * Kernel version which takes radix argument vsnprintf(3).
583 */
584 int
vsnrprintf(char * str,size_t size,int radix,const char * format,va_list ap)585 vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
586 {
587 struct snprintf_arg info;
588 int retval;
589
590 info.str = str;
591 info.remain = size;
592 retval = kvprintf(format, snprintf_func, &info, radix, ap);
593 if (info.remain >= 1)
594 *info.str++ = '\0';
595 return (retval);
596 }
597
598 static void
snprintf_func(int ch,void * arg)599 snprintf_func(int ch, void *arg)
600 {
601 struct snprintf_arg *const info = arg;
602
603 if (info->remain >= 2) {
604 *info->str++ = ch;
605 info->remain--;
606 }
607 }
608
609 /*
610 * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
611 * order; return an optional length and a pointer to the last character
612 * written in the buffer (i.e., the first character of the string).
613 * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
614 */
615 static char *
ksprintn(char * nbuf,uintmax_t num,int base,int * lenp,int upper)616 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
617 {
618 char *p, c;
619
620 p = nbuf;
621 *p = '\0';
622 do {
623 c = hex2ascii(num % base);
624 *++p = upper ? toupper(c) : c;
625 } while (num /= base);
626 if (lenp)
627 *lenp = p - nbuf;
628 return (p);
629 }
630
631 /*
632 * Scaled down version of printf(3).
633 *
634 * Two additional formats:
635 *
636 * The format %b is supported to decode error registers.
637 * Its usage is:
638 *
639 * printf("reg=%b\n", regval, "<base><arg>*");
640 *
641 * where <base> is the output base expressed as a control character, e.g.
642 * \10 gives octal; \20 gives hex. Each arg is a sequence of characters,
643 * the first of which gives the bit number to be inspected (origin 1), and
644 * the next characters (up to a control character, i.e. a character <= 32),
645 * give the name of the register. Thus:
646 *
647 * kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE");
648 *
649 * would produce output:
650 *
651 * reg=3<BITTWO,BITONE>
652 *
653 * XXX: %D -- Hexdump, takes pointer and separator string:
654 * ("%6D", ptr, ":") -> XX:XX:XX:XX:XX:XX
655 * ("%*D", len, ptr, " " -> XX XX XX XX ...
656 */
657 int
kvprintf(char const * fmt,void (* func)(int,void *),void * arg,int radix,va_list ap)658 kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
659 {
660 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
661 char nbuf[MAXNBUF];
662 char *d;
663 const char *p, *percent, *q;
664 u_char *up;
665 int ch, n, sign;
666 uintmax_t num;
667 int base, lflag, qflag, tmp, width, ladjust, sharpflag, dot;
668 int cflag, hflag, jflag, tflag, zflag;
669 int bconv, dwidth, upper;
670 char padc;
671 int stop = 0, retval = 0;
672
673 num = 0;
674 q = NULL;
675 if (!func)
676 d = (char *) arg;
677 else
678 d = NULL;
679
680 if (fmt == NULL)
681 fmt = "(fmt null)\n";
682
683 if (radix < 2 || radix > 36)
684 radix = 10;
685
686 for (;;) {
687 padc = ' ';
688 width = 0;
689 while ((ch = (u_char)*fmt++) != '%' || stop) {
690 if (ch == '\0')
691 return (retval);
692 PCHAR(ch);
693 }
694 percent = fmt - 1;
695 qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0;
696 sign = 0; dot = 0; bconv = 0; dwidth = 0; upper = 0;
697 cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
698 reswitch: switch (ch = (u_char)*fmt++) {
699 case '.':
700 dot = 1;
701 goto reswitch;
702 case '#':
703 sharpflag = 1;
704 goto reswitch;
705 case '+':
706 sign = '+';
707 goto reswitch;
708 case '-':
709 ladjust = 1;
710 goto reswitch;
711 case '%':
712 PCHAR(ch);
713 break;
714 case '*':
715 if (!dot) {
716 width = va_arg(ap, int);
717 if (width < 0) {
718 ladjust = !ladjust;
719 width = -width;
720 }
721 } else {
722 dwidth = va_arg(ap, int);
723 }
724 goto reswitch;
725 case '0':
726 if (!dot) {
727 padc = '0';
728 goto reswitch;
729 }
730 /* FALLTHROUGH */
731 case '1': case '2': case '3': case '4':
732 case '5': case '6': case '7': case '8': case '9':
733 for (n = 0;; ++fmt) {
734 n = n * 10 + ch - '0';
735 ch = *fmt;
736 if (ch < '0' || ch > '9')
737 break;
738 }
739 if (dot)
740 dwidth = n;
741 else
742 width = n;
743 goto reswitch;
744 case 'b':
745 ladjust = 1;
746 bconv = 1;
747 goto handle_nosign;
748 case 'c':
749 width -= 1;
750
751 if (!ladjust && width > 0)
752 while (width--)
753 PCHAR(padc);
754 PCHAR(va_arg(ap, int));
755 if (ladjust && width > 0)
756 while (width--)
757 PCHAR(padc);
758 break;
759 case 'D':
760 up = va_arg(ap, u_char *);
761 p = va_arg(ap, char *);
762 if (!width)
763 width = 16;
764 while(width--) {
765 PCHAR(hex2ascii(*up >> 4));
766 PCHAR(hex2ascii(*up & 0x0f));
767 up++;
768 if (width)
769 for (q=p;*q;q++)
770 PCHAR(*q);
771 }
772 break;
773 case 'd':
774 case 'i':
775 base = 10;
776 goto handle_sign;
777 case 'h':
778 if (hflag) {
779 hflag = 0;
780 cflag = 1;
781 } else
782 hflag = 1;
783 goto reswitch;
784 case 'j':
785 jflag = 1;
786 goto reswitch;
787 case 'l':
788 if (lflag) {
789 lflag = 0;
790 qflag = 1;
791 } else
792 lflag = 1;
793 goto reswitch;
794 case 'n':
795 /*
796 * We do not support %n in kernel, but consume the
797 * argument.
798 */
799 if (jflag)
800 (void)va_arg(ap, intmax_t *);
801 else if (qflag)
802 (void)va_arg(ap, quad_t *);
803 else if (lflag)
804 (void)va_arg(ap, long *);
805 else if (zflag)
806 (void)va_arg(ap, size_t *);
807 else if (hflag)
808 (void)va_arg(ap, short *);
809 else if (cflag)
810 (void)va_arg(ap, char *);
811 else
812 (void)va_arg(ap, int *);
813 break;
814 case 'o':
815 base = 8;
816 goto handle_nosign;
817 case 'p':
818 base = 16;
819 sharpflag = (width == 0);
820 sign = 0;
821 num = (uintptr_t)va_arg(ap, void *);
822 goto number;
823 case 'q':
824 qflag = 1;
825 goto reswitch;
826 case 'r':
827 base = radix;
828 if (sign) {
829 sign = 0;
830 goto handle_sign;
831 }
832 goto handle_nosign;
833 case 's':
834 p = va_arg(ap, char *);
835 if (p == NULL)
836 p = "(null)";
837 if (!dot)
838 n = strlen (p);
839 else
840 for (n = 0; n < dwidth && p[n]; n++)
841 continue;
842
843 width -= n;
844
845 if (!ladjust && width > 0)
846 while (width--)
847 PCHAR(padc);
848 while (n--)
849 PCHAR(*p++);
850 if (ladjust && width > 0)
851 while (width--)
852 PCHAR(padc);
853 break;
854 case 't':
855 tflag = 1;
856 goto reswitch;
857 case 'u':
858 base = 10;
859 goto handle_nosign;
860 case 'X':
861 upper = 1;
862 /* FALLTHROUGH */
863 case 'x':
864 base = 16;
865 goto handle_nosign;
866 case 'y':
867 base = 16;
868 goto handle_sign;
869 case 'z':
870 zflag = 1;
871 goto reswitch;
872 handle_nosign:
873 if (jflag)
874 num = va_arg(ap, uintmax_t);
875 else if (qflag)
876 num = va_arg(ap, u_quad_t);
877 else if (tflag)
878 num = va_arg(ap, ptrdiff_t);
879 else if (lflag)
880 num = va_arg(ap, u_long);
881 else if (zflag)
882 num = va_arg(ap, size_t);
883 else if (hflag)
884 num = (u_short)va_arg(ap, int);
885 else if (cflag)
886 num = (u_char)va_arg(ap, int);
887 else
888 num = va_arg(ap, u_int);
889 if (bconv) {
890 q = va_arg(ap, char *);
891 base = *q++;
892 }
893 goto number;
894 handle_sign:
895 if (jflag)
896 num = va_arg(ap, intmax_t);
897 else if (qflag)
898 num = va_arg(ap, quad_t);
899 else if (tflag)
900 num = va_arg(ap, ptrdiff_t);
901 else if (lflag)
902 num = va_arg(ap, long);
903 else if (zflag)
904 num = va_arg(ap, ssize_t);
905 else if (hflag)
906 num = (short)va_arg(ap, int);
907 else if (cflag)
908 num = (signed char)va_arg(ap, int);
909 else
910 num = va_arg(ap, int);
911 if ((intmax_t)num < 0) {
912 sign = '-';
913 num = -(intmax_t)num;
914 }
915 number:
916 p = ksprintn(nbuf, num, base, &n, upper);
917 tmp = 0;
918 if (sharpflag && num != 0) {
919 if (base == 8)
920 tmp++;
921 else if (base == 16)
922 tmp += 2;
923 }
924 if (sign)
925 tmp++;
926
927 if (!ladjust && padc == '0')
928 dwidth = width - tmp;
929 width -= tmp + imax(dwidth, n);
930 dwidth -= n;
931 if (!ladjust)
932 while (width-- > 0)
933 PCHAR(' ');
934 if (sign)
935 PCHAR(sign);
936 if (sharpflag && num != 0) {
937 if (base == 8) {
938 PCHAR('0');
939 } else if (base == 16) {
940 PCHAR('0');
941 PCHAR('x');
942 }
943 }
944 while (dwidth-- > 0)
945 PCHAR('0');
946
947 while (*p)
948 PCHAR(*p--);
949
950 if (bconv && num != 0) {
951 /* %b conversion flag format. */
952 tmp = retval;
953 while (*q) {
954 n = *q++;
955 if (num & (1 << (n - 1))) {
956 PCHAR(retval != tmp ?
957 ',' : '<');
958 for (; (n = *q) > ' '; ++q)
959 PCHAR(n);
960 } else
961 for (; *q > ' '; ++q)
962 continue;
963 }
964 if (retval != tmp) {
965 PCHAR('>');
966 width -= retval - tmp;
967 }
968 }
969
970 if (ladjust)
971 while (width-- > 0)
972 PCHAR(' ');
973
974 break;
975 default:
976 while (percent < fmt)
977 PCHAR(*percent++);
978 /*
979 * Since we ignore a formatting argument it is no
980 * longer safe to obey the remaining formatting
981 * arguments as the arguments will no longer match
982 * the format specs.
983 */
984 stop = 1;
985 break;
986 }
987 }
988 #undef PCHAR
989 }
990
991 /*
992 * Put character in log buffer with a particular priority.
993 */
994 static void
msglogchar(int c,int pri)995 msglogchar(int c, int pri)
996 {
997 static int lastpri = -1;
998 static int dangling;
999 char nbuf[MAXNBUF];
1000 char *p;
1001
1002 if (!msgbufmapped)
1003 return;
1004 if (c == '\0' || c == '\r')
1005 return;
1006 if (pri != -1 && pri != lastpri) {
1007 if (dangling) {
1008 msgbuf_addchar(msgbufp, '\n');
1009 dangling = 0;
1010 }
1011 msgbuf_addchar(msgbufp, '<');
1012 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
1013 msgbuf_addchar(msgbufp, *p--);
1014 msgbuf_addchar(msgbufp, '>');
1015 lastpri = pri;
1016 }
1017 msgbuf_addchar(msgbufp, c);
1018 if (c == '\n') {
1019 dangling = 0;
1020 lastpri = -1;
1021 } else {
1022 dangling = 1;
1023 }
1024 }
1025
1026 static void
msglogstr(char * str,int pri,int filter_cr)1027 msglogstr(char *str, int pri, int filter_cr)
1028 {
1029 if (!msgbufmapped)
1030 return;
1031
1032 msgbuf_addstr(msgbufp, pri, str, filter_cr);
1033 }
1034
1035 void
msgbufinit(void * ptr,int size)1036 msgbufinit(void *ptr, int size)
1037 {
1038 char *cp;
1039 static struct msgbuf *oldp = NULL;
1040 bool print_boot_tag;
1041
1042 TSENTER();
1043 size -= sizeof(*msgbufp);
1044 cp = (char *)ptr;
1045 print_boot_tag = !msgbufmapped;
1046 /* Attempt to fetch kern.boot_tag tunable on first mapping */
1047 if (!msgbufmapped)
1048 TUNABLE_STR_FETCH("kern.boot_tag", current_boot_tag,
1049 sizeof(current_boot_tag));
1050 msgbufp = (struct msgbuf *)(cp + size);
1051 msgbuf_reinit(msgbufp, cp, size);
1052 if (msgbufmapped && oldp != msgbufp)
1053 msgbuf_copy(oldp, msgbufp);
1054 msgbufmapped = true;
1055 if (print_boot_tag && *current_boot_tag != '\0')
1056 printf("%s\n", current_boot_tag);
1057 oldp = msgbufp;
1058 TSEXIT();
1059 }
1060
1061 /* Sysctls for accessing/clearing the msgbuf */
1062 static int
sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)1063 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1064 {
1065 char buf[128], *bp;
1066 u_int seq;
1067 int error, len;
1068 bool wrap;
1069
1070 error = priv_check(req->td, PRIV_MSGBUF);
1071 if (error)
1072 return (error);
1073
1074 /* Read the whole buffer, one chunk at a time. */
1075 mtx_lock(&msgbuf_lock);
1076 msgbuf_peekbytes(msgbufp, NULL, 0, &seq);
1077 wrap = (seq != 0);
1078 for (;;) {
1079 len = msgbuf_peekbytes(msgbufp, buf, sizeof(buf), &seq);
1080 mtx_unlock(&msgbuf_lock);
1081 if (len == 0)
1082 return (SYSCTL_OUT(req, "", 1)); /* add nulterm */
1083 if (wrap) {
1084 /* Skip the first line, as it is probably incomplete. */
1085 bp = memchr(buf, '\n', len);
1086 if (bp == NULL) {
1087 mtx_lock(&msgbuf_lock);
1088 continue;
1089 }
1090 wrap = false;
1091 bp++;
1092 len -= bp - buf;
1093 if (len == 0) {
1094 mtx_lock(&msgbuf_lock);
1095 continue;
1096 }
1097 } else
1098 bp = buf;
1099 error = sysctl_handle_opaque(oidp, bp, len, req);
1100 if (error)
1101 return (error);
1102
1103 mtx_lock(&msgbuf_lock);
1104 }
1105 }
1106
1107 SYSCTL_PROC(_kern, OID_AUTO, msgbuf,
1108 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1109 NULL, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1110
1111 static int msgbuf_clearflag;
1112
1113 static int
sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)1114 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1115 {
1116 int error;
1117 error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1118 if (!error && req->newptr) {
1119 mtx_lock(&msgbuf_lock);
1120 msgbuf_clear(msgbufp);
1121 mtx_unlock(&msgbuf_lock);
1122 msgbuf_clearflag = 0;
1123 }
1124 return (error);
1125 }
1126
1127 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1128 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE | CTLFLAG_MPSAFE,
1129 &msgbuf_clearflag, 0, sysctl_kern_msgbuf_clear, "I",
1130 "Clear kernel message buffer");
1131
1132 #ifdef DDB
1133
DB_SHOW_COMMAND_FLAGS(msgbuf,db_show_msgbuf,DB_CMD_MEMSAFE)1134 DB_SHOW_COMMAND_FLAGS(msgbuf, db_show_msgbuf, DB_CMD_MEMSAFE)
1135 {
1136 int i, j;
1137
1138 if (!msgbufmapped) {
1139 db_printf("msgbuf not mapped yet\n");
1140 return;
1141 }
1142 db_printf("msgbufp = %p\n", msgbufp);
1143 db_printf("magic = %x, size = %d, r= %u, w = %u, ptr = %p, cksum= %u\n",
1144 msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_rseq,
1145 msgbufp->msg_wseq, msgbufp->msg_ptr, msgbufp->msg_cksum);
1146 for (i = 0; i < msgbufp->msg_size && !db_pager_quit; i++) {
1147 j = MSGBUF_SEQ_TO_POS(msgbufp, i + msgbufp->msg_rseq);
1148 db_printf("%c", msgbufp->msg_ptr[j]);
1149 }
1150 db_printf("\n");
1151 }
1152
1153 #endif /* DDB */
1154
1155 void
hexdump(const void * ptr,int length,const char * hdr,int flags)1156 hexdump(const void *ptr, int length, const char *hdr, int flags)
1157 {
1158 int i, j, k;
1159 int cols;
1160 const unsigned char *cp;
1161 char delim;
1162
1163 if ((flags & HD_DELIM_MASK) != 0)
1164 delim = (flags & HD_DELIM_MASK) >> 8;
1165 else
1166 delim = ' ';
1167
1168 if ((flags & HD_COLUMN_MASK) != 0)
1169 cols = flags & HD_COLUMN_MASK;
1170 else
1171 cols = 16;
1172
1173 cp = ptr;
1174 for (i = 0; i < length; i+= cols) {
1175 if (hdr != NULL)
1176 printf("%s", hdr);
1177
1178 if ((flags & HD_OMIT_COUNT) == 0)
1179 printf("%04x ", i);
1180
1181 if ((flags & HD_OMIT_HEX) == 0) {
1182 for (j = 0; j < cols; j++) {
1183 k = i + j;
1184 if (k < length)
1185 printf("%c%02x", delim, cp[k]);
1186 else
1187 printf(" ");
1188 }
1189 }
1190
1191 if ((flags & HD_OMIT_CHARS) == 0) {
1192 printf(" |");
1193 for (j = 0; j < cols; j++) {
1194 k = i + j;
1195 if (k >= length)
1196 printf(" ");
1197 else if (cp[k] >= ' ' && cp[k] <= '~')
1198 printf("%c", cp[k]);
1199 else
1200 printf(".");
1201 }
1202 printf("|");
1203 }
1204 printf("\n");
1205 }
1206 }
1207 #endif /* _KERNEL */
1208
1209 void
sbuf_hexdump(struct sbuf * sb,const void * ptr,int length,const char * hdr,int flags)1210 sbuf_hexdump(struct sbuf *sb, const void *ptr, int length, const char *hdr,
1211 int flags)
1212 {
1213 int i, j, k;
1214 int cols;
1215 const unsigned char *cp;
1216 char delim;
1217
1218 if ((flags & HD_DELIM_MASK) != 0)
1219 delim = (flags & HD_DELIM_MASK) >> 8;
1220 else
1221 delim = ' ';
1222
1223 if ((flags & HD_COLUMN_MASK) != 0)
1224 cols = flags & HD_COLUMN_MASK;
1225 else
1226 cols = 16;
1227
1228 cp = ptr;
1229 for (i = 0; i < length; i+= cols) {
1230 if (hdr != NULL)
1231 sbuf_printf(sb, "%s", hdr);
1232
1233 if ((flags & HD_OMIT_COUNT) == 0)
1234 sbuf_printf(sb, "%04x ", i);
1235
1236 if ((flags & HD_OMIT_HEX) == 0) {
1237 for (j = 0; j < cols; j++) {
1238 k = i + j;
1239 if (k < length)
1240 sbuf_printf(sb, "%c%02x", delim, cp[k]);
1241 else
1242 sbuf_cat(sb, " ");
1243 }
1244 }
1245
1246 if ((flags & HD_OMIT_CHARS) == 0) {
1247 sbuf_cat(sb, " |");
1248 for (j = 0; j < cols; j++) {
1249 k = i + j;
1250 if (k >= length)
1251 sbuf_putc(sb, ' ');
1252 else if (cp[k] >= ' ' && cp[k] <= '~')
1253 sbuf_putc(sb, cp[k]);
1254 else
1255 sbuf_putc(sb, '.');
1256 }
1257 sbuf_putc(sb, '|');
1258 }
1259 sbuf_putc(sb, '\n');
1260 }
1261 }
1262
1263 #ifdef _KERNEL
1264 void
counted_warning(unsigned * counter,const char * msg)1265 counted_warning(unsigned *counter, const char *msg)
1266 {
1267 struct thread *td;
1268 unsigned c;
1269
1270 for (;;) {
1271 c = *counter;
1272 if (c == 0)
1273 break;
1274 if (atomic_cmpset_int(counter, c, c - 1)) {
1275 td = curthread;
1276 log(LOG_INFO, "pid %d (%s) %s%s\n",
1277 td->td_proc->p_pid, td->td_name, msg,
1278 c > 1 ? "" : " - not logging anymore");
1279 break;
1280 }
1281 }
1282 }
1283 #endif
1284
1285 #ifdef _KERNEL
1286 void
sbuf_putbuf(struct sbuf * sb)1287 sbuf_putbuf(struct sbuf *sb)
1288 {
1289
1290 prf_putbuf(sbuf_data(sb), TOLOG | TOCONS, -1);
1291 }
1292 #else
1293 void
sbuf_putbuf(struct sbuf * sb)1294 sbuf_putbuf(struct sbuf *sb)
1295 {
1296
1297 printf("%s", sbuf_data(sb));
1298 }
1299 #endif
1300
1301 int
sbuf_printf_drain(void * arg,const char * data,int len)1302 sbuf_printf_drain(void *arg, const char *data, int len)
1303 {
1304 size_t *retvalptr;
1305 int r;
1306 #ifdef _KERNEL
1307 char *dataptr;
1308 char oldchr;
1309
1310 /*
1311 * This is allowed as an extra byte is always resvered for
1312 * terminating NUL byte. Save and restore the byte because
1313 * we might be flushing a record, and there may be valid
1314 * data after the buffer.
1315 */
1316 oldchr = data[len];
1317 dataptr = __DECONST(char *, data);
1318 dataptr[len] = '\0';
1319
1320 prf_putbuf(dataptr, TOLOG | TOCONS, -1);
1321 r = len;
1322
1323 dataptr[len] = oldchr;
1324
1325 #else /* !_KERNEL */
1326
1327 r = printf("%.*s", len, data);
1328 if (r < 0)
1329 return (-errno);
1330
1331 #endif
1332
1333 retvalptr = arg;
1334 if (retvalptr != NULL)
1335 *retvalptr += r;
1336
1337 return (r);
1338 }
1339