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