Merge from vendor branch LIBARCHIVE:
[dragonfly.git] / sys / kern / subr_prf.c
1 /*-
2  * Copyright (c) 1986, 1988, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)subr_prf.c  8.3 (Berkeley) 1/21/94
39  * $FreeBSD: src/sys/kern/subr_prf.c,v 1.61.2.5 2002/08/31 18:22:08 dwmalone Exp $
40  * $DragonFly: src/sys/kern/subr_prf.c,v 1.17 2006/12/26 11:01:07 swildner Exp $
41  */
42
43 #include "opt_ddb.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/msgbuf.h>
49 #include <sys/malloc.h>
50 #include <sys/proc.h>
51 #include <sys/tty.h>
52 #include <sys/tprintf.h>
53 #include <sys/stdint.h>
54 #include <sys/syslog.h>
55 #include <sys/cons.h>
56 #include <sys/uio.h>
57 #include <sys/sysctl.h>
58 #include <sys/lock.h>
59 #include <sys/ctype.h>
60
61 #ifdef DDB
62 #include <ddb/ddb.h>
63 #endif
64
65 /*
66  * Note that stdarg.h and the ANSI style va_start macro is used for both
67  * ANSI and traditional C compilers.  We use the __ machine version to stay
68  * within the kernel header file set.
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 };
84
85 struct snprintf_arg {
86         char    *str;
87         size_t  remain;
88 };
89
90 extern  int log_open;
91
92 struct  tty *constty;                   /* pointer to console "window" tty */
93
94 static void (*v_putc)(int) = cnputc;    /* routine to putc on virtual console */
95 static void  msglogchar(int c, int pri);
96 static void  msgaddchar(int c, void *dummy);
97 static void  kputchar (int ch, void *arg);
98 static char *ksprintn (char *nbuf, uintmax_t num, int base, int *lenp,
99                        int upper);
100 static void  snprintf_func (int ch, void *arg);
101
102 static int consintr = 1;                /* Ok to handle console interrupts? */
103 static int msgbufmapped;                /* Set when safe to use msgbuf */
104 int msgbuftrigger;
105
106 static int      log_console_output = 1;
107 TUNABLE_INT("kern.log_console_output", &log_console_output);
108 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
109     &log_console_output, 0, "");
110
111 static int unprivileged_read_msgbuf = 1;
112 SYSCTL_INT(_kern, OID_AUTO, unprivileged_read_msgbuf, CTLFLAG_RW,
113     &unprivileged_read_msgbuf, 0,
114     "Unprivileged processes may read the kernel message buffer");
115
116 /*
117  * Warn that a system table is full.
118  */
119 void
120 tablefull(const char *tab)
121 {
122
123         log(LOG_ERR, "%s: table is full\n", tab);
124 }
125
126 /*
127  * Uprintf prints to the controlling terminal for the current process.
128  */
129 int
130 uprintf(const char *fmt, ...)
131 {
132         struct proc *p = curproc;
133         __va_list ap;
134         struct putchar_arg pca;
135         int retval = 0;
136
137         if (p && p->p_flag & P_CONTROLT &&
138             p->p_session->s_ttyvp) {
139                 __va_start(ap, fmt);
140                 pca.tty = p->p_session->s_ttyp;
141                 pca.flags = TOTTY;
142
143                 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
144                 __va_end(ap);
145         }
146         return (retval);
147 }
148
149 tpr_t
150 tprintf_open(struct proc *p)
151 {
152
153         if ((p->p_flag & P_CONTROLT) && p->p_session->s_ttyvp) {
154                 sess_hold(p->p_session);
155                 return ((tpr_t) p->p_session);
156         }
157         return ((tpr_t) NULL);
158 }
159
160 void
161 tprintf_close(tpr_t sess)
162 {
163         if (sess)
164                 sess_rele((struct session *) sess);
165 }
166
167 /*
168  * tprintf prints on the controlling terminal associated
169  * with the given session.
170  */
171 int
172 tprintf(tpr_t tpr, const char *fmt, ...)
173 {
174         struct session *sess = (struct session *)tpr;
175         struct tty *tp = NULL;
176         int flags = TOLOG;
177         __va_list ap;
178         struct putchar_arg pca;
179         int retval;
180
181         if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
182                 flags |= TOTTY;
183                 tp = sess->s_ttyp;
184         }
185         __va_start(ap, fmt);
186         pca.tty = tp;
187         pca.flags = flags;
188         pca.pri = LOG_INFO;
189         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
190         __va_end(ap);
191         msgbuftrigger = 1;
192         return (retval);
193 }
194
195 /*
196  * Ttyprintf displays a message on a tty; it should be used only by
197  * the tty driver, or anything that knows the underlying tty will not
198  * be revoke(2)'d away.  Other callers should use tprintf.
199  */
200 int
201 ttyprintf(struct tty *tp, const char *fmt, ...)
202 {
203         __va_list ap;
204         struct putchar_arg pca;
205         int retval;
206
207         __va_start(ap, fmt);
208         pca.tty = tp;
209         pca.flags = TOTTY;
210         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
211         __va_end(ap);
212         return (retval);
213 }
214
215 /*
216  * Log writes to the log buffer, and guarantees not to sleep (so can be
217  * called by interrupt routines).  If there is no process reading the
218  * log yet, it writes to the console also.
219  */
220 int
221 log(int level, const char *fmt, ...)
222 {
223         __va_list ap;
224         int retval;
225         struct putchar_arg pca;
226
227         pca.tty = NULL;
228         pca.pri = level;
229         pca.flags = log_open ? TOLOG : TOCONS;
230
231         __va_start(ap, fmt);
232         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
233         __va_end(ap);
234
235         msgbuftrigger = 1;
236         return (retval);
237 }
238
239 #define CONSCHUNK 128
240
241 void
242 log_console(struct uio *uio)
243 {
244         int c, i, error, iovlen, nl;
245         struct uio muio;
246         struct iovec *miov = NULL;
247         char *consbuffer;
248         int pri;
249
250         if (!log_console_output)
251                 return;
252
253         pri = LOG_INFO | LOG_CONSOLE;
254         muio = *uio;
255         iovlen = uio->uio_iovcnt * sizeof (struct iovec);
256         MALLOC(miov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
257         MALLOC(consbuffer, char *, CONSCHUNK, M_TEMP, M_WAITOK);
258         bcopy((caddr_t)muio.uio_iov, (caddr_t)miov, iovlen);
259         muio.uio_iov = miov;
260         uio = &muio;
261
262         nl = 0;
263         while (uio->uio_resid > 0) {
264                 c = imin(uio->uio_resid, CONSCHUNK);
265                 error = uiomove(consbuffer, c, uio);
266                 if (error != 0)
267                         break;
268                 for (i = 0; i < c; i++) {
269                         msglogchar(consbuffer[i], pri);
270                         if (consbuffer[i] == '\n')
271                                 nl = 1;
272                         else
273                                 nl = 0;
274                 }
275         }
276         if (!nl)
277                 msglogchar('\n', pri);
278         msgbuftrigger = 1;
279         FREE(miov, M_TEMP);
280         FREE(consbuffer, M_TEMP);
281         return;
282 }
283
284 /*
285  * Output to the console.
286  *
287  * NOT YET ENTIRELY MPSAFE
288  */
289 int
290 kprintf(const char *fmt, ...)
291 {
292         __va_list ap;
293         int savintr;
294         struct putchar_arg pca;
295         int retval;
296
297         savintr = consintr;             /* disable interrupts */
298         consintr = 0;
299         __va_start(ap, fmt);
300         pca.tty = NULL;
301         pca.flags = TOCONS | TOLOG;
302         pca.pri = -1;
303         cons_lock();
304         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
305         cons_unlock();
306         __va_end(ap);
307         if (!panicstr)
308                 msgbuftrigger = 1;
309         consintr = savintr;             /* reenable interrupts */
310         return (retval);
311 }
312
313 int
314 kvprintf(const char *fmt, __va_list ap)
315 {
316         int savintr;
317         struct putchar_arg pca;
318         int retval;
319
320         savintr = consintr;             /* disable interrupts */
321         consintr = 0;
322         pca.tty = NULL;
323         pca.flags = TOCONS | TOLOG;
324         pca.pri = -1;
325         cons_lock();
326         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
327         cons_unlock();
328         if (!panicstr)
329                 msgbuftrigger = 1;
330         consintr = savintr;             /* reenable interrupts */
331         return (retval);
332 }
333
334 /*
335  * Print a character on console or users terminal.  If destination is
336  * the console then the last bunch of characters are saved in msgbuf for
337  * inspection later.
338  *
339  * NOT YET ENTIRELY MPSAFE, EVEN WHEN LOGGING JUST TO THE SYSCONSOLE.
340  */
341 static void
342 kputchar(int c, void *arg)
343 {
344         struct putchar_arg *ap = (struct putchar_arg*) arg;
345         int flags = ap->flags;
346         struct tty *tp = ap->tty;
347         if (panicstr)
348                 constty = NULL;
349         if ((flags & TOCONS) && tp == NULL && constty) {
350                 tp = constty;
351                 flags |= TOTTY;
352         }
353         if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
354             (flags & TOCONS) && tp == constty)
355                 constty = NULL;
356         if ((flags & TOLOG))
357                 msglogchar(c, ap->pri);
358         if ((flags & TOCONS) && constty == NULL && c != '\0')
359                 (*v_putc)(c);
360 }
361
362 /*
363  * Scaled down version of sprintf(3).
364  */
365 int
366 ksprintf(char *buf, const char *cfmt, ...)
367 {
368         int retval;
369         __va_list ap;
370
371         __va_start(ap, cfmt);
372         retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
373         buf[retval] = '\0';
374         __va_end(ap);
375         return (retval);
376 }
377
378 /*
379  * Scaled down version of vsprintf(3).
380  */
381 int
382 kvsprintf(char *buf, const char *cfmt, __va_list ap)
383 {
384         int retval;
385
386         retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
387         buf[retval] = '\0';
388         return (retval);
389 }
390
391 /*
392  * Scaled down version of snprintf(3).
393  */
394 int
395 ksnprintf(char *str, size_t size, const char *format, ...)
396 {
397         int retval;
398         __va_list ap;
399
400         __va_start(ap, format);
401         retval = kvsnprintf(str, size, format, ap);
402         __va_end(ap);
403         return(retval);
404 }
405
406 /*
407  * Scaled down version of vsnprintf(3).
408  */
409 int
410 kvsnprintf(char *str, size_t size, const char *format, __va_list ap)
411 {
412         struct snprintf_arg info;
413         int retval;
414
415         info.str = str;
416         info.remain = size;
417         retval = kvcprintf(format, snprintf_func, &info, 10, ap);
418         if (info.remain >= 1)
419                 *info.str++ = '\0';
420         return (retval);
421 }
422
423 static void
424 snprintf_func(int ch, void *arg)
425 {
426         struct snprintf_arg *const info = arg;
427
428         if (info->remain >= 2) {
429                 *info->str++ = ch;
430                 info->remain--;
431         }
432 }
433
434 /*
435  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
436  * order; return an optional length and a pointer to the last character
437  * written in the buffer (i.e., the first character of the string).
438  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
439  */
440 static char *
441 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
442 {
443         char *p, c;
444
445         p = nbuf;
446         *p = '\0';
447         do {
448                 c = hex2ascii(num % base);
449                 *++p = upper ? toupper(c) : c;
450         } while (num /= base);
451         if (lenp)
452                 *lenp = p - nbuf;
453         return (p);
454 }
455
456 /*
457  * Scaled down version of printf(3).
458  *
459  * Two additional formats:
460  *
461  * The format %b is supported to decode error registers.
462  * Its usage is:
463  *
464  *      kprintf("reg=%b\n", regval, "<base><arg>*");
465  *
466  * where <base> is the output base expressed as a control character, e.g.
467  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
468  * the first of which gives the bit number to be inspected (origin 1), and
469  * the next characters (up to a control character, i.e. a character <= 32),
470  * give the name of the register.  Thus:
471  *
472  *      kvcprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
473  *
474  * would produce output:
475  *
476  *      reg=3<BITTWO,BITONE>
477  *
478  * XXX:  %D  -- Hexdump, takes pointer and separator string:
479  *              ("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
480  *              ("%*D", len, ptr, " " -> XX XX XX XX ...
481  */
482 int
483 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, __va_list ap)
484 {
485 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
486         char nbuf[MAXNBUF];
487         char *d;
488         const char *p, *percent, *q;
489         u_char *up;
490         int ch, n;
491         uintmax_t num;
492         int base, tmp, width, ladjust, sharpflag, neg, sign, dot;
493         int jflag, lflag, qflag, tflag;
494         int dwidth, upper;
495         char padc;
496         int retval = 0, stop = 0;
497
498         num = 0;
499         if (!func)
500                 d = (char *) arg;
501         else
502                 d = NULL;
503
504         if (fmt == NULL)
505                 fmt = "(fmt null)\n";
506
507         if (radix < 2 || radix > 36)
508                 radix = 10;
509
510         for (;;) {
511                 padc = ' ';
512                 width = 0;
513                 while ((ch = (u_char)*fmt++) != '%' || stop) {
514                         if (ch == '\0')
515                                 return (retval);
516                         PCHAR(ch);
517                 }
518                 percent = fmt - 1;
519                 dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
520                 jflag = lflag = qflag = tflag = 0;
521
522 reswitch:
523                 switch (ch = (u_char)*fmt++) {
524                 case '.':
525                         dot = 1;
526                         goto reswitch;
527                 case '#':
528                         sharpflag = 1;
529                         goto reswitch;
530                 case '+':
531                         sign = 1;
532                         goto reswitch;
533                 case '-':
534                         ladjust = 1;
535                         goto reswitch;
536                 case '%':
537                         PCHAR(ch);
538                         break;
539                 case '*':
540                         if (!dot) {
541                                 width = __va_arg(ap, int);
542                                 if (width < 0) {
543                                         ladjust = !ladjust;
544                                         width = -width;
545                                 }
546                         } else {
547                                 dwidth = __va_arg(ap, int);
548                         }
549                         goto reswitch;
550                 case '0':
551                         if (!dot) {
552                                 padc = '0';
553                                 goto reswitch;
554                         }
555                 case '1': case '2': case '3': case '4':
556                 case '5': case '6': case '7': case '8': case '9':
557                                 for (n = 0;; ++fmt) {
558                                         n = n * 10 + ch - '0';
559                                         ch = *fmt;
560                                         if (ch < '0' || ch > '9')
561                                                 break;
562                                 }
563                         if (dot)
564                                 dwidth = n;
565                         else
566                                 width = n;
567                         goto reswitch;
568                 case 'b':
569                         num = (u_int)__va_arg(ap, int);
570                         p = __va_arg(ap, char *);
571                         for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
572                                 PCHAR(*q--);
573
574                         if (num == 0)
575                                 break;
576
577                         for (tmp = 0; *p;) {
578                                 n = *p++;
579                                 if (num & (1 << (n - 1))) {
580                                         PCHAR(tmp ? ',' : '<');
581                                         for (; (n = *p) > ' '; ++p)
582                                                 PCHAR(n);
583                                         tmp = 1;
584                                 } else
585                                         for (; *p > ' '; ++p)
586                                                 continue;
587                         }
588                         if (tmp)
589                                 PCHAR('>');
590                         break;
591                 case 'c':
592                         PCHAR(__va_arg(ap, int));
593                         break;
594                 case 'D':
595                         up = __va_arg(ap, u_char *);
596                         p = __va_arg(ap, char *);
597                         if (!width)
598                                 width = 16;
599                         while(width--) {
600                                 PCHAR(hex2ascii(*up >> 4));
601                                 PCHAR(hex2ascii(*up & 0x0f));
602                                 up++;
603                                 if (width)
604                                         for (q=p;*q;q++)
605                                                 PCHAR(*q);
606                         }
607                         break;
608                 case 'd':
609                 case 'i':
610                         base = 10;
611                         sign = 1;
612                         goto handle_sign;
613                 case 'j':
614                         jflag = 1;
615                         goto reswitch;
616                 case 'l':
617                         if (lflag) {
618                                 lflag = 0;
619                                 qflag = 1;
620                         } else
621                                 lflag = 1;
622                         goto reswitch;
623                 case 'n':
624                         if (jflag)
625                                 *(__va_arg(ap, intmax_t *)) = retval;
626                         else if (lflag)
627                                 *(__va_arg(ap, long *)) = retval;
628                         else if (qflag)
629                                 *(__va_arg(ap, quad_t *)) = retval;
630                         else
631                                 *(__va_arg(ap, int *)) = retval;
632                         break;
633                 case 'o':
634                         base = 8;
635                         goto handle_nosign;
636                 case 'p':
637                         base = 16;
638                         sharpflag = (width == 0);
639                         sign = 0;
640                         num = (uintptr_t)__va_arg(ap, void *);
641                         goto number;
642                 case 'q':
643                         qflag = 1;
644                         goto reswitch;
645                 case 'r':
646                         base = radix;
647                         if (sign)
648                                 goto handle_sign;
649                         goto handle_nosign;
650                 case 's':
651                         p = __va_arg(ap, char *);
652                         if (p == NULL)
653                                 p = "(null)";
654                         if (!dot)
655                                 n = strlen (p);
656                         else
657                                 for (n = 0; n < dwidth && p[n]; n++)
658                                         continue;
659
660                         width -= n;
661
662                         if (!ladjust && width > 0)
663                                 while (width--)
664                                         PCHAR(padc);
665                         while (n--)
666                                 PCHAR(*p++);
667                         if (ladjust && width > 0)
668                                 while (width--)
669                                         PCHAR(padc);
670                         break;
671                 case 't':
672                         tflag = 1;
673                         goto reswitch;
674                 case 'u':
675                         base = 10;
676                         goto handle_nosign;
677                 case 'X':
678                         upper = 1;
679                         /* FALLTHROUGH */
680                 case 'x':
681                         base = 16;
682                         goto handle_nosign;
683                 case 'z':
684                         base = 16;
685                         sign = 1;
686                         goto handle_sign;
687 handle_nosign:
688                         sign = 0;
689                         if (jflag)
690                                 num = __va_arg(ap, uintmax_t);
691                         else if (lflag)
692                                 num = __va_arg(ap, u_long);
693                         else if (qflag)
694                                 num = __va_arg(ap, u_quad_t);
695                         else if (tflag)
696                                 num = __va_arg(ap, ptrdiff_t);
697                         else
698                                 num = __va_arg(ap, u_int);
699                         goto number;
700 handle_sign:
701                         if (jflag)
702                                 num = __va_arg(ap, intmax_t);
703                         else if (lflag)
704                                 num = __va_arg(ap, long);
705                         else if (qflag)
706                                 num = __va_arg(ap, quad_t);
707                         else if (tflag)
708                                 num = __va_arg(ap, ptrdiff_t);
709                         else
710                                 num = __va_arg(ap, int);
711 number:
712                         if (sign && (intmax_t)num < 0) {
713                                 neg = 1;
714                                 num = -(intmax_t)num;
715                         }
716                         p = ksprintn(nbuf, num, base, &tmp, upper);
717                         if (sharpflag && num != 0) {
718                                 if (base == 8)
719                                         tmp++;
720                                 else if (base == 16)
721                                         tmp += 2;
722                         }
723                         if (neg)
724                                 tmp++;
725
726                         if (!ladjust && padc != '0' && width &&
727                             (width -= tmp) > 0) {
728                                 while (width--)
729                                         PCHAR(padc);
730                         }
731                         if (neg)
732                                 PCHAR('-');
733                         if (sharpflag && num != 0) {
734                                 if (base == 8) {
735                                         PCHAR('0');
736                                 } else if (base == 16) {
737                                         PCHAR('0');
738                                         PCHAR('x');
739                                 }
740                         }
741                         if (!ladjust && width && (width -= tmp) > 0)
742                                 while (width--)
743                                         PCHAR(padc);
744
745                         while (*p)
746                                 PCHAR(*p--);
747
748                         if (ladjust && width && (width -= tmp) > 0)
749                                 while (width--)
750                                         PCHAR(padc);
751
752                         break;
753                 default:
754                         while (percent < fmt)
755                                 PCHAR(*percent++);
756                         /*
757                          * Since we ignore an formatting argument it is no 
758                          * longer safe to obey the remaining formatting
759                          * arguments as the arguments will no longer match
760                          * the format specs.
761                          */
762                         stop = 1;
763                         break;
764                 }
765         }
766 #undef PCHAR
767 }
768
769 /*
770  * Put character in log buffer with a particular priority.
771  *
772  * MPSAFE
773  */
774 static void
775 msglogchar(int c, int pri)
776 {
777         static int lastpri = -1;
778         static int dangling;
779         char nbuf[MAXNBUF];
780         char *p;
781
782         if (!msgbufmapped)
783                 return;
784         if (c == '\0' || c == '\r')
785                 return;
786         if (pri != -1 && pri != lastpri) {
787                 if (dangling) {
788                         msgaddchar('\n', NULL);
789                         dangling = 0;
790                 }
791                 msgaddchar('<', NULL);
792                 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
793                         msgaddchar(*p--, NULL);
794                 msgaddchar('>', NULL);
795                 lastpri = pri;
796         }
797         msgaddchar(c, NULL);
798         if (c == '\n') {
799                 dangling = 0;
800                 lastpri = -1;
801         } else {
802                 dangling = 1;
803         }
804 }
805
806 /*
807  * Put char in log buffer.   Make sure nothing blows up beyond repair if
808  * we have an MP race.
809  *
810  * MPSAFE.
811  */
812 static void
813 msgaddchar(int c, void *dummy)
814 {
815         struct msgbuf *mbp;
816         int rindex;
817         int windex;
818
819         if (!msgbufmapped)
820                 return;
821         mbp = msgbufp;
822         windex = mbp->msg_bufx;
823         mbp->msg_ptr[windex] = c;
824         if (++windex >= mbp->msg_size)
825                 windex = 0;
826         rindex = mbp->msg_bufr;
827         if (windex == rindex) {
828                 rindex += 32;
829                 if (rindex >= mbp->msg_size)
830                         rindex -= mbp->msg_size;
831                 mbp->msg_bufr = rindex;
832         }
833         mbp->msg_bufx = windex;
834 }
835
836 static void
837 msgbufcopy(struct msgbuf *oldp)
838 {
839         int pos;
840
841         pos = oldp->msg_bufr;
842         while (pos != oldp->msg_bufx) {
843                 msglogchar(oldp->msg_ptr[pos], -1);
844                 if (++pos >= oldp->msg_size)
845                         pos = 0;
846         }
847 }
848
849 void
850 msgbufinit(void *ptr, size_t size)
851 {
852         char *cp;
853         static struct msgbuf *oldp = NULL;
854
855         size -= sizeof(*msgbufp);
856         cp = (char *)ptr;
857         msgbufp = (struct msgbuf *) (cp + size);
858         if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
859             msgbufp->msg_bufx >= size || msgbufp->msg_bufr >= size) {
860                 bzero(cp, size);
861                 bzero(msgbufp, sizeof(*msgbufp));
862                 msgbufp->msg_magic = MSG_MAGIC;
863                 msgbufp->msg_size = (char *)msgbufp - cp;
864         }
865         msgbufp->msg_ptr = cp;
866         if (msgbufmapped && oldp != msgbufp)
867                 msgbufcopy(oldp);
868         msgbufmapped = 1;
869         oldp = msgbufp;
870 }
871
872 /* Sysctls for accessing/clearing the msgbuf */
873
874 static int
875 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
876 {
877         struct ucred *cred;
878         int error;
879
880         /*
881          * Only wheel or root can access the message log.
882          */
883         if (unprivileged_read_msgbuf == 0) {
884                 KKASSERT(req->td->td_proc);
885                 cred = req->td->td_proc->p_ucred;
886
887                 if ((cred->cr_prison || groupmember(0, cred) == 0) &&
888                     suser(req->td) != 0
889                 ) {
890                         return (EPERM);
891                 }
892         }
893
894         /*
895          * Unwind the buffer, so that it's linear (possibly starting with
896          * some initial nulls).
897          */
898         error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
899             msgbufp->msg_size - msgbufp->msg_bufx, req);
900         if (error)
901                 return (error);
902         if (msgbufp->msg_bufx > 0) {
903                 error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
904                     msgbufp->msg_bufx, req);
905         }
906         return (error);
907 }
908
909 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
910     0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
911
912 static int msgbuf_clear;
913
914 static int
915 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
916 {
917         int error;
918         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
919         if (!error && req->newptr) {
920                 /* Clear the buffer and reset write pointer */
921                 bzero(msgbufp->msg_ptr, msgbufp->msg_size);
922                 msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
923                 msgbuf_clear = 0;
924         }
925         return (error);
926 }
927
928 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
929     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
930     sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
931
932 #ifdef DDB
933
934 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
935 {
936         int i, j;
937
938         if (!msgbufmapped) {
939                 db_printf("msgbuf not mapped yet\n");
940                 return;
941         }
942         db_printf("msgbufp = %p\n", msgbufp);
943         db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
944             msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
945             msgbufp->msg_bufx, msgbufp->msg_ptr);
946         for (i = 0; i < msgbufp->msg_size; i++) {
947                 j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
948                 db_printf("%c", msgbufp->msg_ptr[j]);
949         }
950         db_printf("\n");
951 }
952
953 #endif /* DDB */