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