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