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