Revert part of r300109.
[freebsd.git] / sys / kern / subr_prf.c
1 /*-
2  * Copyright (c) 1986, 1988, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)subr_prf.c  8.3 (Berkeley) 1/21/94
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
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 #endif
64 #include <sys/ctype.h>
65 #include <sys/sbuf.h>
66
67 #ifdef DDB
68 #include <ddb/ddb.h>
69 #endif
70
71 /*
72  * Note that stdarg.h and the ANSI style va_start macro is used for both
73  * ANSI and traditional C compilers.
74  */
75 #ifdef _KERNEL
76 #include <machine/stdarg.h>
77 #else
78 #include <stdarg.h>
79 #endif
80
81 #ifdef _KERNEL
82
83 #define TOCONS  0x01
84 #define TOTTY   0x02
85 #define TOLOG   0x04
86
87 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
88 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
89
90 struct putchar_arg {
91         int     flags;
92         int     pri;
93         struct  tty *tty;
94         char    *p_bufr;
95         size_t  n_bufr;
96         char    *p_next;
97         size_t  remain;
98 };
99
100 struct snprintf_arg {
101         char    *str;
102         size_t  remain;
103 };
104
105 extern  int log_open;
106
107 static void  msglogchar(int c, int pri);
108 static void  msglogstr(char *str, int pri, int filter_cr);
109 static void  putchar(int ch, void *arg);
110 static char *ksprintn(char *nbuf, uintmax_t num, int base, int *len, int upper);
111 static void  snprintf_func(int ch, void *arg);
112
113 static int msgbufmapped;                /* Set when safe to use msgbuf */
114 int msgbuftrigger;
115
116 static int log_console_output = 1;
117 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RWTUN,
118     &log_console_output, 0, "Duplicate console output to the syslog");
119
120 /*
121  * See the comment in log_console() below for more explanation of this.
122  */
123 static int log_console_add_linefeed;
124 SYSCTL_INT(_kern, OID_AUTO, log_console_add_linefeed, CTLFLAG_RWTUN,
125     &log_console_add_linefeed, 0, "log_console() adds extra newlines");
126
127 static int always_console_output;
128 SYSCTL_INT(_kern, OID_AUTO, always_console_output, CTLFLAG_RWTUN,
129     &always_console_output, 0, "Always output to console despite TIOCCONS");
130
131 /*
132  * Warn that a system table is full.
133  */
134 void
135 tablefull(const char *tab)
136 {
137
138         log(LOG_ERR, "%s: table is full\n", tab);
139 }
140
141 /*
142  * Uprintf prints to the controlling terminal for the current process.
143  */
144 int
145 uprintf(const char *fmt, ...)
146 {
147         va_list ap;
148         struct putchar_arg pca;
149         struct proc *p;
150         struct thread *td;
151         int retval;
152
153         td = curthread;
154         if (TD_IS_IDLETHREAD(td))
155                 return (0);
156
157         sx_slock(&proctree_lock);
158         p = td->td_proc;
159         PROC_LOCK(p);
160         if ((p->p_flag & P_CONTROLT) == 0) {
161                 PROC_UNLOCK(p);
162                 sx_sunlock(&proctree_lock);
163                 return (0);
164         }
165         SESS_LOCK(p->p_session);
166         pca.tty = p->p_session->s_ttyp;
167         SESS_UNLOCK(p->p_session);
168         PROC_UNLOCK(p);
169         if (pca.tty == NULL) {
170                 sx_sunlock(&proctree_lock);
171                 return (0);
172         }
173         pca.flags = TOTTY;
174         pca.p_bufr = NULL;
175         va_start(ap, fmt);
176         tty_lock(pca.tty);
177         sx_sunlock(&proctree_lock);
178         retval = kvprintf(fmt, putchar, &pca, 10, ap);
179         tty_unlock(pca.tty);
180         va_end(ap);
181         return (retval);
182 }
183
184 /*
185  * tprintf and vtprintf print on the controlling terminal associated with the
186  * given session, possibly to the log as well.
187  */
188 void
189 tprintf(struct proc *p, int pri, const char *fmt, ...)
190 {
191         va_list ap;
192
193         va_start(ap, fmt);
194         vtprintf(p, pri, fmt, ap);
195         va_end(ap);
196 }
197
198 void
199 vtprintf(struct proc *p, int pri, const char *fmt, va_list ap)
200 {
201         struct tty *tp = NULL;
202         int flags = 0;
203         struct putchar_arg pca;
204         struct session *sess = NULL;
205
206         sx_slock(&proctree_lock);
207         if (pri != -1)
208                 flags |= TOLOG;
209         if (p != NULL) {
210                 PROC_LOCK(p);
211                 if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
212                         sess = p->p_session;
213                         sess_hold(sess);
214                         PROC_UNLOCK(p);
215                         tp = sess->s_ttyp;
216                         if (tp != NULL && tty_checkoutq(tp))
217                                 flags |= TOTTY;
218                         else
219                                 tp = NULL;
220                 } else
221                         PROC_UNLOCK(p);
222         }
223         pca.pri = pri;
224         pca.tty = tp;
225         pca.flags = flags;
226         pca.p_bufr = NULL;
227         if (pca.tty != NULL)
228                 tty_lock(pca.tty);
229         sx_sunlock(&proctree_lock);
230         kvprintf(fmt, putchar, &pca, 10, ap);
231         if (pca.tty != NULL)
232                 tty_unlock(pca.tty);
233         if (sess != NULL)
234                 sess_release(sess);
235         msgbuftrigger = 1;
236 }
237
238 /*
239  * Ttyprintf displays a message on a tty; it should be used only by
240  * the tty driver, or anything that knows the underlying tty will not
241  * be revoke(2)'d away.  Other callers should use tprintf.
242  */
243 int
244 ttyprintf(struct tty *tp, const char *fmt, ...)
245 {
246         va_list ap;
247         struct putchar_arg pca;
248         int retval;
249
250         va_start(ap, fmt);
251         pca.tty = tp;
252         pca.flags = TOTTY;
253         pca.p_bufr = NULL;
254         retval = kvprintf(fmt, putchar, &pca, 10, ap);
255         va_end(ap);
256         return (retval);
257 }
258
259 static int
260 _vprintf(int level, int flags, const char *fmt, va_list ap)
261 {
262         struct putchar_arg pca;
263         int retval;
264 #ifdef PRINTF_BUFR_SIZE
265         char bufr[PRINTF_BUFR_SIZE];
266 #endif
267
268         pca.tty = NULL;
269         pca.pri = level;
270         pca.flags = flags;
271 #ifdef PRINTF_BUFR_SIZE
272         pca.p_bufr = bufr;
273         pca.p_next = pca.p_bufr;
274         pca.n_bufr = sizeof(bufr);
275         pca.remain = sizeof(bufr);
276         *pca.p_next = '\0';
277 #else
278         /* Don't buffer console output. */
279         pca.p_bufr = NULL;
280 #endif
281
282         retval = kvprintf(fmt, putchar, &pca, 10, ap);
283
284 #ifdef PRINTF_BUFR_SIZE
285         /* Write any buffered console/log output: */
286         if (*pca.p_bufr != '\0') {
287                 if (pca.flags & TOLOG)
288                         msglogstr(pca.p_bufr, level, /*filter_cr*/1);
289
290                 if (pca.flags & TOCONS)
291                         cnputs(pca.p_bufr);
292         }
293 #endif
294
295         return (retval);
296 }
297
298 /*
299  * Log writes to the log buffer, and guarantees not to sleep (so can be
300  * called by interrupt routines).  If there is no process reading the
301  * log yet, it writes to the console also.
302  */
303 void
304 log(int level, const char *fmt, ...)
305 {
306         va_list ap;
307
308         va_start(ap, fmt);
309         vlog(level, fmt, ap);
310         va_end(ap);
311 }
312
313 void
314 vlog(int level, const char *fmt, va_list ap)
315 {
316
317         (void)_vprintf(level, log_open ? TOLOG : TOCONS | TOLOG, fmt, ap);
318         msgbuftrigger = 1;
319 }
320
321 #define CONSCHUNK 128
322
323 void
324 log_console(struct uio *uio)
325 {
326         int c, error, nl;
327         char *consbuffer;
328         int pri;
329
330         if (!log_console_output)
331                 return;
332
333         pri = LOG_INFO | LOG_CONSOLE;
334         uio = cloneuio(uio);
335         consbuffer = malloc(CONSCHUNK, M_TEMP, M_WAITOK);
336
337         nl = 0;
338         while (uio->uio_resid > 0) {
339                 c = imin(uio->uio_resid, CONSCHUNK - 1);
340                 error = uiomove(consbuffer, c, uio);
341                 if (error != 0)
342                         break;
343                 /* Make sure we're NUL-terminated */
344                 consbuffer[c] = '\0';
345                 if (consbuffer[c - 1] == '\n')
346                         nl = 1;
347                 else
348                         nl = 0;
349                 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
350         }
351         /*
352          * The previous behavior in log_console() is preserved when
353          * log_console_add_linefeed is non-zero.  For that behavior, if an
354          * individual console write came in that was not terminated with a
355          * line feed, it would add a line feed.
356          *
357          * This results in different data in the message buffer than
358          * appears on the system console (which doesn't add extra line feed
359          * characters).
360          *
361          * A number of programs and rc scripts write a line feed, or a period
362          * and a line feed when they have completed their operation.  On
363          * the console, this looks seamless, but when displayed with
364          * 'dmesg -a', you wind up with output that looks like this:
365          *
366          * Updating motd:
367          * .
368          *
369          * On the console, it looks like this:
370          * Updating motd:.
371          *
372          * We could add logic to detect that situation, or just not insert
373          * the extra newlines.  Set the kern.log_console_add_linefeed
374          * sysctl/tunable variable to get the old behavior.
375          */
376         if (!nl && log_console_add_linefeed) {
377                 consbuffer[0] = '\n';
378                 consbuffer[1] = '\0';
379                 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
380         }
381         msgbuftrigger = 1;
382         free(uio, M_IOV);
383         free(consbuffer, M_TEMP);
384         return;
385 }
386
387 int
388 printf(const char *fmt, ...)
389 {
390         va_list ap;
391         int retval;
392
393         va_start(ap, fmt);
394         retval = vprintf(fmt, ap);
395         va_end(ap);
396
397         return (retval);
398 }
399
400 int
401 vprintf(const char *fmt, va_list ap)
402 {
403         int retval;
404
405         retval = _vprintf(-1, TOCONS | TOLOG, fmt, ap);
406
407         if (!panicstr)
408                 msgbuftrigger = 1;
409
410         return (retval);
411 }
412
413 static void
414 putbuf(int c, struct putchar_arg *ap)
415 {
416         /* Check if no console output buffer was provided. */
417         if (ap->p_bufr == NULL) {
418                 /* Output direct to the console. */
419                 if (ap->flags & TOCONS)
420                         cnputc(c);
421
422                 if (ap->flags & TOLOG)
423                         msglogchar(c, ap->pri);
424         } else {
425                 /* Buffer the character: */
426                 *ap->p_next++ = c;
427                 ap->remain--;
428
429                 /* Always leave the buffer zero terminated. */
430                 *ap->p_next = '\0';
431
432                 /* Check if the buffer needs to be flushed. */
433                 if (ap->remain == 2 || c == '\n') {
434
435                         if (ap->flags & TOLOG)
436                                 msglogstr(ap->p_bufr, ap->pri, /*filter_cr*/1);
437
438                         if (ap->flags & TOCONS) {
439                                 if ((panicstr == NULL) && (constty != NULL))
440                                         msgbuf_addstr(&consmsgbuf, -1,
441                                             ap->p_bufr, /*filter_cr*/ 0);
442
443                                 if ((constty == NULL) ||(always_console_output))
444                                         cnputs(ap->p_bufr);
445                         }
446
447                         ap->p_next = ap->p_bufr;
448                         ap->remain = ap->n_bufr;
449                         *ap->p_next = '\0';
450                 }
451
452                 /*
453                  * Since we fill the buffer up one character at a time,
454                  * this should not happen.  We should always catch it when
455                  * ap->remain == 2 (if not sooner due to a newline), flush
456                  * the buffer and move on.  One way this could happen is
457                  * if someone sets PRINTF_BUFR_SIZE to 1 or something
458                  * similarly silly.
459                  */
460                 KASSERT(ap->remain > 2, ("Bad buffer logic, remain = %zd",
461                     ap->remain));
462         }
463 }
464
465 /*
466  * Print a character on console or users terminal.  If destination is
467  * the console then the last bunch of characters are saved in msgbuf for
468  * inspection later.
469  */
470 static void
471 putchar(int c, void *arg)
472 {
473         struct putchar_arg *ap = (struct putchar_arg*) arg;
474         struct tty *tp = ap->tty;
475         int flags = ap->flags;
476
477         /* Don't use the tty code after a panic or while in ddb. */
478         if (kdb_active) {
479                 if (c != '\0')
480                         cnputc(c);
481                 return;
482         }
483
484         if ((flags & TOTTY) && tp != NULL && panicstr == NULL)
485                 tty_putchar(tp, c);
486
487         if ((flags & (TOCONS | TOLOG)) && c != '\0')
488                 putbuf(c, ap);
489 }
490
491 /*
492  * Scaled down version of sprintf(3).
493  */
494 int
495 sprintf(char *buf, const char *cfmt, ...)
496 {
497         int retval;
498         va_list ap;
499
500         va_start(ap, cfmt);
501         retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
502         buf[retval] = '\0';
503         va_end(ap);
504         return (retval);
505 }
506
507 /*
508  * Scaled down version of vsprintf(3).
509  */
510 int
511 vsprintf(char *buf, const char *cfmt, va_list ap)
512 {
513         int retval;
514
515         retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
516         buf[retval] = '\0';
517         return (retval);
518 }
519
520 /*
521  * Scaled down version of snprintf(3).
522  */
523 int
524 snprintf(char *str, size_t size, const char *format, ...)
525 {
526         int retval;
527         va_list ap;
528
529         va_start(ap, format);
530         retval = vsnprintf(str, size, format, ap);
531         va_end(ap);
532         return(retval);
533 }
534
535 /*
536  * Scaled down version of vsnprintf(3).
537  */
538 int
539 vsnprintf(char *str, size_t size, const char *format, va_list ap)
540 {
541         struct snprintf_arg info;
542         int retval;
543
544         info.str = str;
545         info.remain = size;
546         retval = kvprintf(format, snprintf_func, &info, 10, ap);
547         if (info.remain >= 1)
548                 *info.str++ = '\0';
549         return (retval);
550 }
551
552 /*
553  * Kernel version which takes radix argument vsnprintf(3).
554  */
555 int
556 vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
557 {
558         struct snprintf_arg info;
559         int retval;
560
561         info.str = str;
562         info.remain = size;
563         retval = kvprintf(format, snprintf_func, &info, radix, ap);
564         if (info.remain >= 1)
565                 *info.str++ = '\0';
566         return (retval);
567 }
568
569 static void
570 snprintf_func(int ch, void *arg)
571 {
572         struct snprintf_arg *const info = arg;
573
574         if (info->remain >= 2) {
575                 *info->str++ = ch;
576                 info->remain--;
577         }
578 }
579
580 /*
581  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
582  * order; return an optional length and a pointer to the last character
583  * written in the buffer (i.e., the first character of the string).
584  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
585  */
586 static char *
587 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
588 {
589         char *p, c;
590
591         p = nbuf;
592         *p = '\0';
593         do {
594                 c = hex2ascii(num % base);
595                 *++p = upper ? toupper(c) : c;
596         } while (num /= base);
597         if (lenp)
598                 *lenp = p - nbuf;
599         return (p);
600 }
601
602 /*
603  * Scaled down version of printf(3).
604  *
605  * Two additional formats:
606  *
607  * The format %b is supported to decode error registers.
608  * Its usage is:
609  *
610  *      printf("reg=%b\n", regval, "<base><arg>*");
611  *
612  * where <base> is the output base expressed as a control character, e.g.
613  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
614  * the first of which gives the bit number to be inspected (origin 1), and
615  * the next characters (up to a control character, i.e. a character <= 32),
616  * give the name of the register.  Thus:
617  *
618  *      kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE");
619  *
620  * would produce output:
621  *
622  *      reg=3<BITTWO,BITONE>
623  *
624  * XXX:  %D  -- Hexdump, takes pointer and separator string:
625  *              ("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
626  *              ("%*D", len, ptr, " " -> XX XX XX XX ...
627  */
628 int
629 kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
630 {
631 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
632         char nbuf[MAXNBUF];
633         char *d;
634         const char *p, *percent, *q;
635         u_char *up;
636         int ch, n;
637         uintmax_t num;
638         int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
639         int cflag, hflag, jflag, tflag, zflag;
640         int dwidth, upper;
641         char padc;
642         int stop = 0, retval = 0;
643
644         num = 0;
645         if (!func)
646                 d = (char *) arg;
647         else
648                 d = NULL;
649
650         if (fmt == NULL)
651                 fmt = "(fmt null)\n";
652
653         if (radix < 2 || radix > 36)
654                 radix = 10;
655
656         for (;;) {
657                 padc = ' ';
658                 width = 0;
659                 while ((ch = (u_char)*fmt++) != '%' || stop) {
660                         if (ch == '\0')
661                                 return (retval);
662                         PCHAR(ch);
663                 }
664                 percent = fmt - 1;
665                 qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
666                 sign = 0; dot = 0; dwidth = 0; upper = 0;
667                 cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
668 reswitch:       switch (ch = (u_char)*fmt++) {
669                 case '.':
670                         dot = 1;
671                         goto reswitch;
672                 case '#':
673                         sharpflag = 1;
674                         goto reswitch;
675                 case '+':
676                         sign = 1;
677                         goto reswitch;
678                 case '-':
679                         ladjust = 1;
680                         goto reswitch;
681                 case '%':
682                         PCHAR(ch);
683                         break;
684                 case '*':
685                         if (!dot) {
686                                 width = va_arg(ap, int);
687                                 if (width < 0) {
688                                         ladjust = !ladjust;
689                                         width = -width;
690                                 }
691                         } else {
692                                 dwidth = va_arg(ap, int);
693                         }
694                         goto reswitch;
695                 case '0':
696                         if (!dot) {
697                                 padc = '0';
698                                 goto reswitch;
699                         }
700                 case '1': case '2': case '3': case '4':
701                 case '5': case '6': case '7': case '8': case '9':
702                                 for (n = 0;; ++fmt) {
703                                         n = n * 10 + ch - '0';
704                                         ch = *fmt;
705                                         if (ch < '0' || ch > '9')
706                                                 break;
707                                 }
708                         if (dot)
709                                 dwidth = n;
710                         else
711                                 width = n;
712                         goto reswitch;
713                 case 'b':
714                         num = (u_int)va_arg(ap, int);
715                         p = va_arg(ap, char *);
716                         for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
717                                 PCHAR(*q--);
718
719                         if (num == 0)
720                                 break;
721
722                         for (tmp = 0; *p;) {
723                                 n = *p++;
724                                 if (num & (1 << (n - 1))) {
725                                         PCHAR(tmp ? ',' : '<');
726                                         for (; (n = *p) > ' '; ++p)
727                                                 PCHAR(n);
728                                         tmp = 1;
729                                 } else
730                                         for (; *p > ' '; ++p)
731                                                 continue;
732                         }
733                         if (tmp)
734                                 PCHAR('>');
735                         break;
736                 case 'c':
737                         width -= 1;
738
739                         if (!ladjust && width > 0)
740                                 while (width--)
741                                         PCHAR(padc);
742                         PCHAR(va_arg(ap, int));
743                         if (ladjust && width > 0)
744                                 while (width--)
745                                         PCHAR(padc);
746                         break;
747                 case 'D':
748                         up = va_arg(ap, u_char *);
749                         p = va_arg(ap, char *);
750                         if (!width)
751                                 width = 16;
752                         while(width--) {
753                                 PCHAR(hex2ascii(*up >> 4));
754                                 PCHAR(hex2ascii(*up & 0x0f));
755                                 up++;
756                                 if (width)
757                                         for (q=p;*q;q++)
758                                                 PCHAR(*q);
759                         }
760                         break;
761                 case 'd':
762                 case 'i':
763                         base = 10;
764                         sign = 1;
765                         goto handle_sign;
766                 case 'h':
767                         if (hflag) {
768                                 hflag = 0;
769                                 cflag = 1;
770                         } else
771                                 hflag = 1;
772                         goto reswitch;
773                 case 'j':
774                         jflag = 1;
775                         goto reswitch;
776                 case 'l':
777                         if (lflag) {
778                                 lflag = 0;
779                                 qflag = 1;
780                         } else
781                                 lflag = 1;
782                         goto reswitch;
783                 case 'n':
784                         if (jflag)
785                                 *(va_arg(ap, intmax_t *)) = retval;
786                         else if (qflag)
787                                 *(va_arg(ap, quad_t *)) = retval;
788                         else if (lflag)
789                                 *(va_arg(ap, long *)) = retval;
790                         else if (zflag)
791                                 *(va_arg(ap, size_t *)) = retval;
792                         else if (hflag)
793                                 *(va_arg(ap, short *)) = retval;
794                         else if (cflag)
795                                 *(va_arg(ap, char *)) = retval;
796                         else
797                                 *(va_arg(ap, int *)) = retval;
798                         break;
799                 case 'o':
800                         base = 8;
801                         goto handle_nosign;
802                 case 'p':
803                         base = 16;
804                         sharpflag = (width == 0);
805                         sign = 0;
806                         num = (uintptr_t)va_arg(ap, void *);
807                         goto number;
808                 case 'q':
809                         qflag = 1;
810                         goto reswitch;
811                 case 'r':
812                         base = radix;
813                         if (sign)
814                                 goto handle_sign;
815                         goto handle_nosign;
816                 case 's':
817                         p = va_arg(ap, char *);
818                         if (p == NULL)
819                                 p = "(null)";
820                         if (!dot)
821                                 n = strlen (p);
822                         else
823                                 for (n = 0; n < dwidth && p[n]; n++)
824                                         continue;
825
826                         width -= n;
827
828                         if (!ladjust && width > 0)
829                                 while (width--)
830                                         PCHAR(padc);
831                         while (n--)
832                                 PCHAR(*p++);
833                         if (ladjust && width > 0)
834                                 while (width--)
835                                         PCHAR(padc);
836                         break;
837                 case 't':
838                         tflag = 1;
839                         goto reswitch;
840                 case 'u':
841                         base = 10;
842                         goto handle_nosign;
843                 case 'X':
844                         upper = 1;
845                 case 'x':
846                         base = 16;
847                         goto handle_nosign;
848                 case 'y':
849                         base = 16;
850                         sign = 1;
851                         goto handle_sign;
852                 case 'z':
853                         zflag = 1;
854                         goto reswitch;
855 handle_nosign:
856                         sign = 0;
857                         if (jflag)
858                                 num = va_arg(ap, uintmax_t);
859                         else if (qflag)
860                                 num = va_arg(ap, u_quad_t);
861                         else if (tflag)
862                                 num = va_arg(ap, ptrdiff_t);
863                         else if (lflag)
864                                 num = va_arg(ap, u_long);
865                         else if (zflag)
866                                 num = va_arg(ap, size_t);
867                         else if (hflag)
868                                 num = (u_short)va_arg(ap, int);
869                         else if (cflag)
870                                 num = (u_char)va_arg(ap, int);
871                         else
872                                 num = va_arg(ap, u_int);
873                         goto number;
874 handle_sign:
875                         if (jflag)
876                                 num = va_arg(ap, intmax_t);
877                         else if (qflag)
878                                 num = va_arg(ap, quad_t);
879                         else if (tflag)
880                                 num = va_arg(ap, ptrdiff_t);
881                         else if (lflag)
882                                 num = va_arg(ap, long);
883                         else if (zflag)
884                                 num = va_arg(ap, ssize_t);
885                         else if (hflag)
886                                 num = (short)va_arg(ap, int);
887                         else if (cflag)
888                                 num = (char)va_arg(ap, int);
889                         else
890                                 num = va_arg(ap, int);
891 number:
892                         if (sign && (intmax_t)num < 0) {
893                                 neg = 1;
894                                 num = -(intmax_t)num;
895                         }
896                         p = ksprintn(nbuf, num, base, &n, upper);
897                         tmp = 0;
898                         if (sharpflag && num != 0) {
899                                 if (base == 8)
900                                         tmp++;
901                                 else if (base == 16)
902                                         tmp += 2;
903                         }
904                         if (neg)
905                                 tmp++;
906
907                         if (!ladjust && padc == '0')
908                                 dwidth = width - tmp;
909                         width -= tmp + imax(dwidth, n);
910                         dwidth -= n;
911                         if (!ladjust)
912                                 while (width-- > 0)
913                                         PCHAR(' ');
914                         if (neg)
915                                 PCHAR('-');
916                         if (sharpflag && num != 0) {
917                                 if (base == 8) {
918                                         PCHAR('0');
919                                 } else if (base == 16) {
920                                         PCHAR('0');
921                                         PCHAR('x');
922                                 }
923                         }
924                         while (dwidth-- > 0)
925                                 PCHAR('0');
926
927                         while (*p)
928                                 PCHAR(*p--);
929
930                         if (ladjust)
931                                 while (width-- > 0)
932                                         PCHAR(' ');
933
934                         break;
935                 default:
936                         while (percent < fmt)
937                                 PCHAR(*percent++);
938                         /*
939                          * Since we ignore a formatting argument it is no
940                          * longer safe to obey the remaining formatting
941                          * arguments as the arguments will no longer match
942                          * the format specs.
943                          */
944                         stop = 1;
945                         break;
946                 }
947         }
948 #undef PCHAR
949 }
950
951 /*
952  * Put character in log buffer with a particular priority.
953  */
954 static void
955 msglogchar(int c, int pri)
956 {
957         static int lastpri = -1;
958         static int dangling;
959         char nbuf[MAXNBUF];
960         char *p;
961
962         if (!msgbufmapped)
963                 return;
964         if (c == '\0' || c == '\r')
965                 return;
966         if (pri != -1 && pri != lastpri) {
967                 if (dangling) {
968                         msgbuf_addchar(msgbufp, '\n');
969                         dangling = 0;
970                 }
971                 msgbuf_addchar(msgbufp, '<');
972                 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
973                         msgbuf_addchar(msgbufp, *p--);
974                 msgbuf_addchar(msgbufp, '>');
975                 lastpri = pri;
976         }
977         msgbuf_addchar(msgbufp, c);
978         if (c == '\n') {
979                 dangling = 0;
980                 lastpri = -1;
981         } else {
982                 dangling = 1;
983         }
984 }
985
986 static void
987 msglogstr(char *str, int pri, int filter_cr)
988 {
989         if (!msgbufmapped)
990                 return;
991
992         msgbuf_addstr(msgbufp, pri, str, filter_cr);
993 }
994
995 void
996 msgbufinit(void *ptr, int size)
997 {
998         char *cp;
999         static struct msgbuf *oldp = NULL;
1000
1001         size -= sizeof(*msgbufp);
1002         cp = (char *)ptr;
1003         msgbufp = (struct msgbuf *)(cp + size);
1004         msgbuf_reinit(msgbufp, cp, size);
1005         if (msgbufmapped && oldp != msgbufp)
1006                 msgbuf_copy(oldp, msgbufp);
1007         msgbufmapped = 1;
1008         oldp = msgbufp;
1009 }
1010
1011 static int unprivileged_read_msgbuf = 1;
1012 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_read_msgbuf,
1013     CTLFLAG_RW, &unprivileged_read_msgbuf, 0,
1014     "Unprivileged processes may read the kernel message buffer");
1015
1016 /* Sysctls for accessing/clearing the msgbuf */
1017 static int
1018 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1019 {
1020         char buf[128];
1021         u_int seq;
1022         int error, len;
1023
1024         if (!unprivileged_read_msgbuf) {
1025                 error = priv_check(req->td, PRIV_MSGBUF);
1026                 if (error)
1027                         return (error);
1028         }
1029
1030         /* Read the whole buffer, one chunk at a time. */
1031         mtx_lock(&msgbuf_lock);
1032         msgbuf_peekbytes(msgbufp, NULL, 0, &seq);
1033         for (;;) {
1034                 len = msgbuf_peekbytes(msgbufp, buf, sizeof(buf), &seq);
1035                 mtx_unlock(&msgbuf_lock);
1036                 if (len == 0)
1037                         return (SYSCTL_OUT(req, "", 1)); /* add nulterm */
1038
1039                 error = sysctl_handle_opaque(oidp, buf, len, req);
1040                 if (error)
1041                         return (error);
1042
1043                 mtx_lock(&msgbuf_lock);
1044         }
1045 }
1046
1047 SYSCTL_PROC(_kern, OID_AUTO, msgbuf,
1048     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1049     NULL, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1050
1051 static int msgbuf_clearflag;
1052
1053 static int
1054 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1055 {
1056         int error;
1057         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1058         if (!error && req->newptr) {
1059                 mtx_lock(&msgbuf_lock);
1060                 msgbuf_clear(msgbufp);
1061                 mtx_unlock(&msgbuf_lock);
1062                 msgbuf_clearflag = 0;
1063         }
1064         return (error);
1065 }
1066
1067 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1068     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE | CTLFLAG_MPSAFE,
1069     &msgbuf_clearflag, 0, sysctl_kern_msgbuf_clear, "I",
1070     "Clear kernel message buffer");
1071
1072 #ifdef DDB
1073
1074 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1075 {
1076         int i, j;
1077
1078         if (!msgbufmapped) {
1079                 db_printf("msgbuf not mapped yet\n");
1080                 return;
1081         }
1082         db_printf("msgbufp = %p\n", msgbufp);
1083         db_printf("magic = %x, size = %d, r= %u, w = %u, ptr = %p, cksum= %u\n",
1084             msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_rseq,
1085             msgbufp->msg_wseq, msgbufp->msg_ptr, msgbufp->msg_cksum);
1086         for (i = 0; i < msgbufp->msg_size && !db_pager_quit; i++) {
1087                 j = MSGBUF_SEQ_TO_POS(msgbufp, i + msgbufp->msg_rseq);
1088                 db_printf("%c", msgbufp->msg_ptr[j]);
1089         }
1090         db_printf("\n");
1091 }
1092
1093 #endif /* DDB */
1094
1095 void
1096 hexdump(const void *ptr, int length, const char *hdr, int flags)
1097 {
1098         int i, j, k;
1099         int cols;
1100         const unsigned char *cp;
1101         char delim;
1102
1103         if ((flags & HD_DELIM_MASK) != 0)
1104                 delim = (flags & HD_DELIM_MASK) >> 8;
1105         else
1106                 delim = ' ';
1107
1108         if ((flags & HD_COLUMN_MASK) != 0)
1109                 cols = flags & HD_COLUMN_MASK;
1110         else
1111                 cols = 16;
1112
1113         cp = ptr;
1114         for (i = 0; i < length; i+= cols) {
1115                 if (hdr != NULL)
1116                         printf("%s", hdr);
1117
1118                 if ((flags & HD_OMIT_COUNT) == 0)
1119                         printf("%04x  ", i);
1120
1121                 if ((flags & HD_OMIT_HEX) == 0) {
1122                         for (j = 0; j < cols; j++) {
1123                                 k = i + j;
1124                                 if (k < length)
1125                                         printf("%c%02x", delim, cp[k]);
1126                                 else
1127                                         printf("   ");
1128                         }
1129                 }
1130
1131                 if ((flags & HD_OMIT_CHARS) == 0) {
1132                         printf("  |");
1133                         for (j = 0; j < cols; j++) {
1134                                 k = i + j;
1135                                 if (k >= length)
1136                                         printf(" ");
1137                                 else if (cp[k] >= ' ' && cp[k] <= '~')
1138                                         printf("%c", cp[k]);
1139                                 else
1140                                         printf(".");
1141                         }
1142                         printf("|");
1143                 }
1144                 printf("\n");
1145         }
1146 }
1147 #endif /* _KERNEL */
1148
1149 void
1150 sbuf_hexdump(struct sbuf *sb, const void *ptr, int length, const char *hdr,
1151              int flags)
1152 {
1153         int i, j, k;
1154         int cols;
1155         const unsigned char *cp;
1156         char delim;
1157
1158         if ((flags & HD_DELIM_MASK) != 0)
1159                 delim = (flags & HD_DELIM_MASK) >> 8;
1160         else
1161                 delim = ' ';
1162
1163         if ((flags & HD_COLUMN_MASK) != 0)
1164                 cols = flags & HD_COLUMN_MASK;
1165         else
1166                 cols = 16;
1167
1168         cp = ptr;
1169         for (i = 0; i < length; i+= cols) {
1170                 if (hdr != NULL)
1171                         sbuf_printf(sb, "%s", hdr);
1172
1173                 if ((flags & HD_OMIT_COUNT) == 0)
1174                         sbuf_printf(sb, "%04x  ", i);
1175
1176                 if ((flags & HD_OMIT_HEX) == 0) {
1177                         for (j = 0; j < cols; j++) {
1178                                 k = i + j;
1179                                 if (k < length)
1180                                         sbuf_printf(sb, "%c%02x", delim, cp[k]);
1181                                 else
1182                                         sbuf_printf(sb, "   ");
1183                         }
1184                 }
1185
1186                 if ((flags & HD_OMIT_CHARS) == 0) {
1187                         sbuf_printf(sb, "  |");
1188                         for (j = 0; j < cols; j++) {
1189                                 k = i + j;
1190                                 if (k >= length)
1191                                         sbuf_printf(sb, " ");
1192                                 else if (cp[k] >= ' ' && cp[k] <= '~')
1193                                         sbuf_printf(sb, "%c", cp[k]);
1194                                 else
1195                                         sbuf_printf(sb, ".");
1196                         }
1197                         sbuf_printf(sb, "|");
1198                 }
1199                 sbuf_printf(sb, "\n");
1200         }
1201 }
1202
1203 #ifdef _KERNEL
1204 void
1205 counted_warning(unsigned *counter, const char *msg)
1206 {
1207         struct thread *td;
1208         unsigned c;
1209
1210         for (;;) {
1211                 c = *counter;
1212                 if (c == 0)
1213                         break;
1214                 if (atomic_cmpset_int(counter, c, c - 1)) {
1215                         td = curthread;
1216                         log(LOG_INFO, "pid %d (%s) %s%s\n",
1217                             td->td_proc->p_pid, td->td_name, msg,
1218                             c > 1 ? "" : " - not logging anymore");
1219                         break;
1220                 }
1221         }
1222 }
1223 #endif