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