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