fb532a31776a91f112db886cd8c95e8b2e777721
[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.21 2008/07/17 23:56:23 dillon 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/priv.h>
52 #include <sys/tty.h>
53 #include <sys/tprintf.h>
54 #include <sys/stdint.h>
55 #include <sys/syslog.h>
56 #include <sys/cons.h>
57 #include <sys/uio.h>
58 #include <sys/sysctl.h>
59 #include <sys/lock.h>
60 #include <sys/ctype.h>
61 #include <sys/eventhandler.h>
62 #include <sys/kthread.h>
63
64 #include <sys/thread2.h>
65 #include <sys/spinlock2.h>
66
67 #ifdef DDB
68 #include <ddb/ddb.h>
69 #endif
70
71 /*
72  * Note that stdarg.h and the ANSI style va_start macro is used for both
73  * ANSI and traditional C compilers.  We use the __ machine version to stay
74  * within the kernel header file set.
75  */
76 #include <machine/stdarg.h>
77
78 #define TOCONS          0x01
79 #define TOTTY           0x02
80 #define TOLOG           0x04
81 #define TOWAKEUP        0x08
82
83 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
84 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
85
86 struct putchar_arg {
87         int     flags;
88         int     pri;
89         struct  tty *tty;
90 };
91
92 struct snprintf_arg {
93         char    *str;
94         size_t  remain;
95 };
96
97 extern  int log_open;
98
99 struct  tty *constty;                   /* pointer to console "window" tty */
100
101 static void  msglogchar(int c, int pri);
102 static void  msgaddchar(int c, void *dummy);
103 static void  kputchar (int ch, void *arg);
104 static char *ksprintn (char *nbuf, uintmax_t num, int base, int *lenp,
105                        int upper);
106 static void  snprintf_func (int ch, void *arg);
107
108 static int consintr = 1;                /* Ok to handle console interrupts? */
109 static int msgbufmapped;                /* Set when safe to use msgbuf */
110 static struct spinlock cons_spin = SPINLOCK_INITIALIZER(cons_spin);
111 static thread_t constty_td = NULL;
112
113 int msgbuftrigger;
114
115 static int      log_console_output = 1;
116 TUNABLE_INT("kern.log_console_output", &log_console_output);
117 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
118     &log_console_output, 0, "");
119
120 static int unprivileged_read_msgbuf = 1;
121 SYSCTL_INT(_security, OID_AUTO, unprivileged_read_msgbuf, CTLFLAG_RW,
122     &unprivileged_read_msgbuf, 0,
123     "Unprivileged processes may read the kernel message buffer");
124
125 /*
126  * Warn that a system table is full.
127  */
128 void
129 tablefull(const char *tab)
130 {
131
132         log(LOG_ERR, "%s: table is full\n", tab);
133 }
134
135 /*
136  * Uprintf prints to the controlling terminal for the current process.
137  */
138 int
139 uprintf(const char *fmt, ...)
140 {
141         struct proc *p = curproc;
142         __va_list ap;
143         struct putchar_arg pca;
144         int retval = 0;
145
146         if (p && p->p_flag & P_CONTROLT &&
147             p->p_session->s_ttyvp) {
148                 __va_start(ap, fmt);
149                 pca.tty = p->p_session->s_ttyp;
150                 pca.flags = TOTTY;
151
152                 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
153                 __va_end(ap);
154         }
155         return (retval);
156 }
157
158 tpr_t
159 tprintf_open(struct proc *p)
160 {
161
162         if ((p->p_flag & P_CONTROLT) && p->p_session->s_ttyvp) {
163                 sess_hold(p->p_session);
164                 return ((tpr_t) p->p_session);
165         }
166         return ((tpr_t) NULL);
167 }
168
169 void
170 tprintf_close(tpr_t sess)
171 {
172         if (sess)
173                 sess_rele((struct session *) sess);
174 }
175
176 /*
177  * tprintf prints on the controlling terminal associated
178  * with the given session.
179  */
180 int
181 tprintf(tpr_t tpr, const char *fmt, ...)
182 {
183         struct session *sess = (struct session *)tpr;
184         struct tty *tp = NULL;
185         int flags = TOLOG;
186         __va_list ap;
187         struct putchar_arg pca;
188         int retval;
189
190         if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
191                 flags |= TOTTY;
192                 tp = sess->s_ttyp;
193         }
194         __va_start(ap, fmt);
195         pca.tty = tp;
196         pca.flags = flags;
197         pca.pri = LOG_INFO;
198         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
199         __va_end(ap);
200         msgbuftrigger = 1;
201         return (retval);
202 }
203
204 /*
205  * Ttyprintf displays a message on a tty; it should be used only by
206  * the tty driver, or anything that knows the underlying tty will not
207  * be revoke(2)'d away.  Other callers should use tprintf.
208  */
209 int
210 ttyprintf(struct tty *tp, const char *fmt, ...)
211 {
212         __va_list ap;
213         struct putchar_arg pca;
214         int retval;
215
216         __va_start(ap, fmt);
217         pca.tty = tp;
218         pca.flags = TOTTY;
219         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
220         __va_end(ap);
221         return (retval);
222 }
223
224 /*
225  * Log writes to the log buffer, and guarantees not to sleep (so can be
226  * called by interrupt routines).  If there is no process reading the
227  * log yet, it writes to the console also.
228  */
229 int
230 log(int level, const char *fmt, ...)
231 {
232         __va_list ap;
233         int retval;
234         struct putchar_arg pca;
235
236         pca.tty = NULL;
237         pca.pri = level;
238         pca.flags = log_open ? TOLOG : TOCONS;
239
240         __va_start(ap, fmt);
241         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
242         __va_end(ap);
243
244         msgbuftrigger = 1;
245         return (retval);
246 }
247
248 #define CONSCHUNK 128
249
250 void
251 log_console(struct uio *uio)
252 {
253         int c, i, error, iovlen, nl;
254         struct uio muio;
255         struct iovec *miov = NULL;
256         char *consbuffer;
257         int pri;
258
259         if (!log_console_output)
260                 return;
261
262         pri = LOG_INFO | LOG_CONSOLE;
263         muio = *uio;
264         iovlen = uio->uio_iovcnt * sizeof (struct iovec);
265         MALLOC(miov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
266         MALLOC(consbuffer, char *, CONSCHUNK, M_TEMP, M_WAITOK);
267         bcopy((caddr_t)muio.uio_iov, (caddr_t)miov, iovlen);
268         muio.uio_iov = miov;
269         uio = &muio;
270
271         nl = 0;
272         while (uio->uio_resid > 0) {
273                 c = (int)szmin(uio->uio_resid, CONSCHUNK);
274                 error = uiomove(consbuffer, (size_t)c, uio);
275                 if (error != 0)
276                         break;
277                 for (i = 0; i < c; i++) {
278                         msglogchar(consbuffer[i], pri);
279                         if (consbuffer[i] == '\n')
280                                 nl = 1;
281                         else
282                                 nl = 0;
283                 }
284         }
285         if (!nl)
286                 msglogchar('\n', pri);
287         msgbuftrigger = 1;
288         FREE(miov, M_TEMP);
289         FREE(consbuffer, M_TEMP);
290         return;
291 }
292
293 /*
294  * Output to the console.
295  */
296 int
297 kprintf(const char *fmt, ...)
298 {
299         __va_list ap;
300         int savintr;
301         struct putchar_arg pca;
302         int retval;
303
304         savintr = consintr;             /* disable interrupts */
305         consintr = 0;
306         __va_start(ap, fmt);
307         pca.tty = NULL;
308         pca.flags = TOCONS | TOLOG;
309         pca.pri = -1;
310         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
311         __va_end(ap);
312         if (!panicstr)
313                 msgbuftrigger = 1;
314         consintr = savintr;             /* reenable interrupts */
315         return (retval);
316 }
317
318 int
319 kvprintf(const char *fmt, __va_list ap)
320 {
321         int savintr;
322         struct putchar_arg pca;
323         int retval;
324
325         savintr = consintr;             /* disable interrupts */
326         consintr = 0;
327         pca.tty = NULL;
328         pca.flags = TOCONS | TOLOG;
329         pca.pri = -1;
330         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
331         if (!panicstr)
332                 msgbuftrigger = 1;
333         consintr = savintr;             /* reenable interrupts */
334         return (retval);
335 }
336
337 /*
338  * Limited rate kprintf.  The passed rate structure must be initialized
339  * with the desired reporting frequency.  A frequency of 0 will result in
340  * no output.
341  *
342  * count may be initialized to a negative number to allow an initial
343  * burst.
344  */
345 void
346 krateprintf(struct krate *rate, const char *fmt, ...)
347 {
348         __va_list ap;
349
350         if (rate->ticks != (int)time_second) {
351                 rate->ticks = (int)time_second;
352                 if (rate->count > 0)
353                         rate->count = 0;
354         }
355         if (rate->count < rate->freq) {
356                 ++rate->count;
357                 __va_start(ap, fmt);
358                 kvprintf(fmt, ap);
359                 __va_end(ap);
360         }
361 }
362
363 /*
364  * Print a character to the dmesg log, the console, and/or the user's
365  * terminal.
366  *
367  * NOTE: TOTTY does not require nonblocking operation, but TOCONS
368  *       and TOLOG do.  When we have a constty we still output to
369  *       the real console but we have a monitoring thread which
370  *       we wakeup which tracks the log.
371  */
372 static void
373 kputchar(int c, void *arg)
374 {
375         struct putchar_arg *ap = (struct putchar_arg*) arg;
376         int flags = ap->flags;
377         struct tty *tp = ap->tty;
378
379         if (panicstr)
380                 constty = NULL;
381         if ((flags & TOCONS) && tp == NULL && constty)
382                 flags |= TOLOG | TOWAKEUP;
383         if ((flags & TOLOG))
384                 msglogchar(c, ap->pri);
385         if ((flags & TOCONS) && c)
386                 cnputc(c);
387         if (flags & TOWAKEUP)
388                 wakeup(constty_td);
389 }
390
391 /*
392  * Scaled down version of sprintf(3).
393  */
394 int
395 ksprintf(char *buf, const char *cfmt, ...)
396 {
397         int retval;
398         __va_list ap;
399
400         __va_start(ap, cfmt);
401         retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
402         buf[retval] = '\0';
403         __va_end(ap);
404         return (retval);
405 }
406
407 /*
408  * Scaled down version of vsprintf(3).
409  */
410 int
411 kvsprintf(char *buf, const char *cfmt, __va_list ap)
412 {
413         int retval;
414
415         retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
416         buf[retval] = '\0';
417         return (retval);
418 }
419
420 /*
421  * Scaled down version of snprintf(3).
422  */
423 int
424 ksnprintf(char *str, size_t size, const char *format, ...)
425 {
426         int retval;
427         __va_list ap;
428
429         __va_start(ap, format);
430         retval = kvsnprintf(str, size, format, ap);
431         __va_end(ap);
432         return(retval);
433 }
434
435 /*
436  * Scaled down version of vsnprintf(3).
437  */
438 int
439 kvsnprintf(char *str, size_t size, const char *format, __va_list ap)
440 {
441         struct snprintf_arg info;
442         int retval;
443
444         info.str = str;
445         info.remain = size;
446         retval = kvcprintf(format, snprintf_func, &info, 10, ap);
447         if (info.remain >= 1)
448                 *info.str++ = '\0';
449         return (retval);
450 }
451
452 int
453 ksnrprintf(char *str, size_t size, int radix, const char *format, ...)
454 {
455         int retval;
456         __va_list ap;
457
458         __va_start(ap, format);
459         retval = kvsnrprintf(str, size, radix, format, ap);
460         __va_end(ap);
461         return(retval);
462 }
463
464 int
465 kvsnrprintf(char *str, size_t size, int radix, const char *format, __va_list ap)
466 {
467         struct snprintf_arg info;
468         int retval;
469
470         info.str = str;
471         info.remain = size;
472         retval = kvcprintf(format, snprintf_func, &info, radix, ap);
473         if (info.remain >= 1)
474                 *info.str++ = '\0';
475         return (retval);
476 }
477
478 int
479 kvasnrprintf(char **strp, size_t size, int radix,
480              const char *format, __va_list ap)
481 {
482         struct snprintf_arg info;
483         int retval;
484
485         *strp = kmalloc(size, M_TEMP, M_WAITOK);
486         info.str = *strp;
487         info.remain = size;
488         retval = kvcprintf(format, snprintf_func, &info, radix, ap);
489         if (info.remain >= 1)
490                 *info.str++ = '\0';
491         return (retval);
492 }
493
494 void
495 kvasfree(char **strp)
496 {
497         if (*strp) {
498                 kfree(*strp, M_TEMP);
499                 *strp = NULL;
500         }
501 }
502
503 static void
504 snprintf_func(int ch, void *arg)
505 {
506         struct snprintf_arg *const info = arg;
507
508         if (info->remain >= 2) {
509                 *info->str++ = ch;
510                 info->remain--;
511         }
512 }
513
514 /*
515  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
516  * order; return an optional length and a pointer to the last character
517  * written in the buffer (i.e., the first character of the string).
518  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
519  */
520 static char *
521 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
522 {
523         char *p, c;
524
525         p = nbuf;
526         *p = '\0';
527         do {
528                 c = hex2ascii(num % base);
529                 *++p = upper ? toupper(c) : c;
530         } while (num /= base);
531         if (lenp)
532                 *lenp = p - nbuf;
533         return (p);
534 }
535
536 /*
537  * Scaled down version of printf(3).
538  *
539  * Two additional formats:
540  *
541  * The format %b is supported to decode error registers.
542  * Its usage is:
543  *
544  *      kprintf("reg=%b\n", regval, "<base><arg>*");
545  *
546  * where <base> is the output base expressed as a control character, e.g.
547  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
548  * the first of which gives the bit number to be inspected (origin 1), and
549  * the next characters (up to a control character, i.e. a character <= 32),
550  * give the name of the register.  Thus:
551  *
552  *      kvcprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
553  *
554  * would produce output:
555  *
556  *      reg=3<BITTWO,BITONE>
557  *
558  * XXX:  %D  -- Hexdump, takes pointer and separator string:
559  *              ("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
560  *              ("%*D", len, ptr, " " -> XX XX XX XX ...
561  */
562
563 #define PCHAR(c) {int cc=(c); if(func) (*func)(cc,arg); else *d++=cc; retval++;}
564
565 int
566 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg,
567           int radix, __va_list ap)
568 {
569         char nbuf[MAXNBUF];
570         char *d;
571         const char *p, *percent, *q;
572         u_char *up;
573         int ch, n;
574         uintmax_t num;
575         int base, tmp, width, ladjust, sharpflag, neg, sign, dot;
576         int cflag, hflag, jflag, lflag, qflag, tflag, zflag;
577         int dwidth, upper;
578         char padc;
579         int retval = 0, stop = 0;
580         int usespin;
581
582         /*
583          * Make a supreme effort to avoid reentrant panics or deadlocks.
584          */
585         if (func == kputchar) {
586                 if (mycpu->gd_flags & GDF_KPRINTF)
587                         return(0);
588                 atomic_set_long(&mycpu->gd_flags, GDF_KPRINTF);
589         }
590
591         num = 0;
592         if (!func)
593                 d = (char *) arg;
594         else
595                 d = NULL;
596
597         if (fmt == NULL)
598                 fmt = "(fmt null)\n";
599
600         if (radix < 2 || radix > 36)
601                 radix = 10;
602
603         usespin = (panic_cpu_gd != mycpu &&
604                    func == kputchar &&
605                    (((struct putchar_arg *)arg)->flags & TOTTY) == 0);
606         if (usespin) {
607                 crit_enter_hard();
608                 spin_lock(&cons_spin);
609         }
610
611         for (;;) {
612                 padc = ' ';
613                 width = 0;
614                 while ((ch = (u_char)*fmt++) != '%' || stop) {
615                         if (ch == '\0')
616                                 goto done;
617                         PCHAR(ch);
618                 }
619                 percent = fmt - 1;
620                 dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
621                 cflag = hflag = jflag = lflag = qflag = tflag = zflag = 0;
622
623 reswitch:
624                 switch (ch = (u_char)*fmt++) {
625                 case '.':
626                         dot = 1;
627                         goto reswitch;
628                 case '#':
629                         sharpflag = 1;
630                         goto reswitch;
631                 case '+':
632                         sign = 1;
633                         goto reswitch;
634                 case '-':
635                         ladjust = 1;
636                         goto reswitch;
637                 case '%':
638                         PCHAR(ch);
639                         break;
640                 case '*':
641                         if (!dot) {
642                                 width = __va_arg(ap, int);
643                                 if (width < 0) {
644                                         ladjust = !ladjust;
645                                         width = -width;
646                                 }
647                         } else {
648                                 dwidth = __va_arg(ap, int);
649                         }
650                         goto reswitch;
651                 case '0':
652                         if (!dot) {
653                                 padc = '0';
654                                 goto reswitch;
655                         }
656                 case '1': case '2': case '3': case '4':
657                 case '5': case '6': case '7': case '8': case '9':
658                                 for (n = 0;; ++fmt) {
659                                         n = n * 10 + ch - '0';
660                                         ch = *fmt;
661                                         if (ch < '0' || ch > '9')
662                                                 break;
663                                 }
664                         if (dot)
665                                 dwidth = n;
666                         else
667                                 width = n;
668                         goto reswitch;
669                 case 'b':
670                         num = (u_int)__va_arg(ap, int);
671                         p = __va_arg(ap, char *);
672                         for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
673                                 PCHAR(*q--);
674
675                         if (num == 0)
676                                 break;
677
678                         for (tmp = 0; *p;) {
679                                 n = *p++;
680                                 if (num & (1 << (n - 1))) {
681                                         PCHAR(tmp ? ',' : '<');
682                                         for (; (n = *p) > ' '; ++p)
683                                                 PCHAR(n);
684                                         tmp = 1;
685                                 } else
686                                         for (; *p > ' '; ++p)
687                                                 continue;
688                         }
689                         if (tmp)
690                                 PCHAR('>');
691                         break;
692                 case 'c':
693                         PCHAR(__va_arg(ap, int));
694                         break;
695                 case 'D':
696                         up = __va_arg(ap, u_char *);
697                         p = __va_arg(ap, char *);
698                         if (!width)
699                                 width = 16;
700                         while(width--) {
701                                 PCHAR(hex2ascii(*up >> 4));
702                                 PCHAR(hex2ascii(*up & 0x0f));
703                                 up++;
704                                 if (width)
705                                         for (q=p;*q;q++)
706                                                 PCHAR(*q);
707                         }
708                         break;
709                 case 'd':
710                 case 'i':
711                         base = 10;
712                         sign = 1;
713                         goto handle_sign;
714                 case 'h':
715                         if (hflag) {
716                                 hflag = 0;
717                                 cflag = 1;
718                         } else
719                                 hflag = 1;
720                         goto reswitch;
721                 case 'j':
722                         jflag = 1;
723                         goto reswitch;
724                 case 'l':
725                         if (lflag) {
726                                 lflag = 0;
727                                 qflag = 1;
728                         } else
729                                 lflag = 1;
730                         goto reswitch;
731                 case 'n':
732                         if (cflag)
733                                 *(__va_arg(ap, char *)) = retval;
734                         else if (hflag)
735                                 *(__va_arg(ap, short *)) = retval;
736                         else if (jflag)
737                                 *(__va_arg(ap, intmax_t *)) = retval;
738                         else if (lflag)
739                                 *(__va_arg(ap, long *)) = retval;
740                         else if (qflag)
741                                 *(__va_arg(ap, quad_t *)) = retval;
742                         else
743                                 *(__va_arg(ap, int *)) = retval;
744                         break;
745                 case 'o':
746                         base = 8;
747                         goto handle_nosign;
748                 case 'p':
749                         base = 16;
750                         sharpflag = (width == 0);
751                         sign = 0;
752                         num = (uintptr_t)__va_arg(ap, void *);
753                         goto number;
754                 case 'q':
755                         qflag = 1;
756                         goto reswitch;
757                 case 'r':
758                         base = radix;
759                         if (sign)
760                                 goto handle_sign;
761                         goto handle_nosign;
762                 case 's':
763                         p = __va_arg(ap, char *);
764                         if (p == NULL)
765                                 p = "(null)";
766                         if (!dot)
767                                 n = strlen (p);
768                         else
769                                 for (n = 0; n < dwidth && p[n]; n++)
770                                         continue;
771
772                         width -= n;
773
774                         if (!ladjust && width > 0)
775                                 while (width--)
776                                         PCHAR(padc);
777                         while (n--)
778                                 PCHAR(*p++);
779                         if (ladjust && width > 0)
780                                 while (width--)
781                                         PCHAR(padc);
782                         break;
783                 case 't':
784                         tflag = 1;
785                         goto reswitch;
786                 case 'u':
787                         base = 10;
788                         goto handle_nosign;
789                 case 'X':
790                         upper = 1;
791                         /* FALLTHROUGH */
792                 case 'x':
793                         base = 16;
794                         goto handle_nosign;
795                 case 'z':
796                         zflag = 1;
797                         goto reswitch;
798 handle_nosign:
799                         sign = 0;
800                         if (cflag)
801                                 num = (u_char)__va_arg(ap, int);
802                         else if (hflag)
803                                 num = (u_short)__va_arg(ap, int);
804                         else if (jflag)
805                                 num = __va_arg(ap, uintmax_t);
806                         else if (lflag)
807                                 num = __va_arg(ap, u_long);
808                         else if (qflag)
809                                 num = __va_arg(ap, u_quad_t);
810                         else if (tflag)
811                                 num = __va_arg(ap, ptrdiff_t);
812                         else if (zflag)
813                                 num = __va_arg(ap, size_t);
814                         else
815                                 num = __va_arg(ap, u_int);
816                         goto number;
817 handle_sign:
818                         if (cflag)
819                                 num = (char)__va_arg(ap, int);
820                         else if (hflag)
821                                 num = (short)__va_arg(ap, int);
822                         else if (jflag)
823                                 num = __va_arg(ap, intmax_t);
824                         else if (lflag)
825                                 num = __va_arg(ap, long);
826                         else if (qflag)
827                                 num = __va_arg(ap, quad_t);
828                         else if (tflag)
829                                 num = __va_arg(ap, ptrdiff_t);
830                         else if (zflag)
831                                 num = __va_arg(ap, ssize_t);
832                         else
833                                 num = __va_arg(ap, int);
834 number:
835                         if (sign && (intmax_t)num < 0) {
836                                 neg = 1;
837                                 num = -(intmax_t)num;
838                         }
839                         p = ksprintn(nbuf, num, base, &tmp, upper);
840                         if (sharpflag && num != 0) {
841                                 if (base == 8)
842                                         tmp++;
843                                 else if (base == 16)
844                                         tmp += 2;
845                         }
846                         if (neg)
847                                 tmp++;
848
849                         if (!ladjust && padc != '0' && width &&
850                             (width -= tmp) > 0) {
851                                 while (width--)
852                                         PCHAR(padc);
853                         }
854                         if (neg)
855                                 PCHAR('-');
856                         if (sharpflag && num != 0) {
857                                 if (base == 8) {
858                                         PCHAR('0');
859                                 } else if (base == 16) {
860                                         PCHAR('0');
861                                         PCHAR('x');
862                                 }
863                         }
864                         if (!ladjust && width && (width -= tmp) > 0)
865                                 while (width--)
866                                         PCHAR(padc);
867
868                         while (*p)
869                                 PCHAR(*p--);
870
871                         if (ladjust && width && (width -= tmp) > 0)
872                                 while (width--)
873                                         PCHAR(padc);
874
875                         break;
876                 default:
877                         while (percent < fmt)
878                                 PCHAR(*percent++);
879                         /*
880                          * Since we ignore an formatting argument it is no 
881                          * longer safe to obey the remaining formatting
882                          * arguments as the arguments will no longer match
883                          * the format specs.
884                          */
885                         stop = 1;
886                         break;
887                 }
888         }
889 done:
890         /*
891          * Cleanup reentrancy issues.
892          */
893         if (func == kputchar)
894                 atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
895         if (usespin) {
896                 spin_unlock(&cons_spin);
897                 crit_exit_hard();
898         }
899         return (retval);
900 }
901
902 #undef PCHAR
903
904 /*
905  * Called from the panic code to try to get the console working
906  * again in case we paniced inside a kprintf().
907  */
908 void
909 kvcreinitspin(void)
910 {
911         spin_init(&cons_spin);
912         atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
913 }
914
915 /*
916  * Console support thread for constty intercepts.  This is needed because
917  * console tty intercepts can block.  Instead of having kputchar() attempt
918  * to directly write to the console intercept we just force it to log
919  * and wakeup this baby to track and dump the log to constty.
920  */
921 static void
922 constty_daemon(void)
923 {
924         int rindex = -1;
925         int windex = -1;
926         struct msgbuf *mbp;
927         struct tty *tp;
928
929         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
930                               constty_td, SHUTDOWN_PRI_FIRST);
931         constty_td->td_flags |= TDF_SYSTHREAD;
932
933         for (;;) {
934                 kproc_suspend_loop();
935
936                 crit_enter();
937                 mbp = msgbufp;
938                 if (mbp == NULL || msgbufmapped == 0 ||
939                     windex == mbp->msg_bufx) {
940                         tsleep(constty_td, 0, "waiting", hz*60);
941                         crit_exit();
942                         continue;
943                 }
944                 windex = mbp->msg_bufx;
945                 crit_exit();
946
947                 /*
948                  * Get message buf FIFO indices.  rindex is tracking.
949                  */
950                 if ((tp = constty) == NULL) {
951                         rindex = mbp->msg_bufx;
952                         continue;
953                 }
954
955                 /*
956                  * Don't blow up if the message buffer is broken
957                  */
958                 if (windex < 0 || windex >= mbp->msg_size)
959                         continue;
960                 if (rindex < 0 || rindex >= mbp->msg_size)
961                         rindex = windex;
962
963                 /*
964                  * And dump it.  If constty gets stuck will give up.
965                  */
966                 while (rindex != windex) {
967                         if (tputchar((uint8_t)mbp->msg_ptr[rindex], tp) < 0) {
968                                 constty = NULL;
969                                 rindex = mbp->msg_bufx;
970                                 break;
971                         }
972                         if (++rindex >= mbp->msg_size)
973                                 rindex = 0;
974                         if (tp->t_outq.c_cc >= tp->t_ohiwat) {
975                                 tsleep(constty_daemon, 0, "blocked", hz / 10);
976                                 if (tp->t_outq.c_cc >= tp->t_ohiwat) {
977                                         rindex = windex;
978                                         break;
979                                 }
980                         }
981                 }
982         }
983 }
984
985 static struct kproc_desc constty_kp = {
986         "consttyd",
987         constty_daemon,
988         &constty_td
989 };
990 SYSINIT(bufdaemon, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY,
991         kproc_start, &constty_kp)
992
993 /*
994  * Put character in log buffer with a particular priority.
995  *
996  * MPSAFE
997  */
998 static void
999 msglogchar(int c, int pri)
1000 {
1001         static int lastpri = -1;
1002         static int dangling;
1003         char nbuf[MAXNBUF];
1004         char *p;
1005
1006         if (!msgbufmapped)
1007                 return;
1008         if (c == '\0' || c == '\r')
1009                 return;
1010         if (pri != -1 && pri != lastpri) {
1011                 if (dangling) {
1012                         msgaddchar('\n', NULL);
1013                         dangling = 0;
1014                 }
1015                 msgaddchar('<', NULL);
1016                 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
1017                         msgaddchar(*p--, NULL);
1018                 msgaddchar('>', NULL);
1019                 lastpri = pri;
1020         }
1021         msgaddchar(c, NULL);
1022         if (c == '\n') {
1023                 dangling = 0;
1024                 lastpri = -1;
1025         } else {
1026                 dangling = 1;
1027         }
1028 }
1029
1030 /*
1031  * Put char in log buffer.   Make sure nothing blows up beyond repair if
1032  * we have an MP race.
1033  *
1034  * MPSAFE.
1035  */
1036 static void
1037 msgaddchar(int c, void *dummy)
1038 {
1039         struct msgbuf *mbp;
1040         int rindex;
1041         int windex;
1042
1043         if (!msgbufmapped)
1044                 return;
1045         mbp = msgbufp;
1046         windex = mbp->msg_bufx;
1047         mbp->msg_ptr[windex] = c;
1048         if (++windex >= mbp->msg_size)
1049                 windex = 0;
1050         rindex = mbp->msg_bufr;
1051         if (windex == rindex) {
1052                 rindex += 32;
1053                 if (rindex >= mbp->msg_size)
1054                         rindex -= mbp->msg_size;
1055                 mbp->msg_bufr = rindex;
1056         }
1057         mbp->msg_bufx = windex;
1058 }
1059
1060 static void
1061 msgbufcopy(struct msgbuf *oldp)
1062 {
1063         int pos;
1064
1065         pos = oldp->msg_bufr;
1066         while (pos != oldp->msg_bufx) {
1067                 msglogchar(oldp->msg_ptr[pos], -1);
1068                 if (++pos >= oldp->msg_size)
1069                         pos = 0;
1070         }
1071 }
1072
1073 void
1074 msgbufinit(void *ptr, size_t size)
1075 {
1076         char *cp;
1077         static struct msgbuf *oldp = NULL;
1078
1079         size -= sizeof(*msgbufp);
1080         cp = (char *)ptr;
1081         msgbufp = (struct msgbuf *) (cp + size);
1082         if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
1083             msgbufp->msg_bufx >= size || msgbufp->msg_bufr >= size) {
1084                 bzero(cp, size);
1085                 bzero(msgbufp, sizeof(*msgbufp));
1086                 msgbufp->msg_magic = MSG_MAGIC;
1087                 msgbufp->msg_size = (char *)msgbufp - cp;
1088         }
1089         msgbufp->msg_ptr = cp;
1090         if (msgbufmapped && oldp != msgbufp)
1091                 msgbufcopy(oldp);
1092         msgbufmapped = 1;
1093         oldp = msgbufp;
1094 }
1095
1096 /* Sysctls for accessing/clearing the msgbuf */
1097
1098 static int
1099 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1100 {
1101         struct ucred *cred;
1102         int error;
1103
1104         /*
1105          * Only wheel or root can access the message log.
1106          */
1107         if (unprivileged_read_msgbuf == 0) {
1108                 KKASSERT(req->td->td_proc);
1109                 cred = req->td->td_proc->p_ucred;
1110
1111                 if ((cred->cr_prison || groupmember(0, cred) == 0) &&
1112                     priv_check(req->td, PRIV_ROOT) != 0
1113                 ) {
1114                         return (EPERM);
1115                 }
1116         }
1117
1118         /*
1119          * Unwind the buffer, so that it's linear (possibly starting with
1120          * some initial nulls).
1121          */
1122         error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
1123             msgbufp->msg_size - msgbufp->msg_bufx, req);
1124         if (error)
1125                 return (error);
1126         if (msgbufp->msg_bufx > 0) {
1127                 error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
1128                     msgbufp->msg_bufx, req);
1129         }
1130         return (error);
1131 }
1132
1133 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
1134     0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1135
1136 static int msgbuf_clear;
1137
1138 static int
1139 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1140 {
1141         int error;
1142         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1143         if (!error && req->newptr) {
1144                 /* Clear the buffer and reset write pointer */
1145                 bzero(msgbufp->msg_ptr, msgbufp->msg_size);
1146                 msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
1147                 msgbuf_clear = 0;
1148         }
1149         return (error);
1150 }
1151
1152 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1153     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
1154     sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
1155
1156 #ifdef DDB
1157
1158 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1159 {
1160         int i, j;
1161
1162         if (!msgbufmapped) {
1163                 db_printf("msgbuf not mapped yet\n");
1164                 return;
1165         }
1166         db_printf("msgbufp = %p\n", msgbufp);
1167         db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
1168             msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
1169             msgbufp->msg_bufx, msgbufp->msg_ptr);
1170         for (i = 0; i < msgbufp->msg_size; i++) {
1171                 j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
1172                 db_printf("%c", msgbufp->msg_ptr[j]);
1173         }
1174         db_printf("\n");
1175 }
1176
1177 #endif /* DDB */