kernel - Fix panic when X11 intercepts console
[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 to the dmesg log, the console, and/or the user's
361  * terminal.
362  *
363  * When printing to the console if a tty console intercept is active
364  * (e.g. X11) we only generate output to it if we can acquire the
365  * tty_token non-blocking.  Otherwise kprintf()s from hard sections
366  * will panic us.
367  */
368 static void
369 kputchar(int c, void *arg)
370 {
371         struct putchar_arg *ap = (struct putchar_arg*) arg;
372         int flags = ap->flags;
373         struct tty *tp = ap->tty;
374         int have_tty_token = 0;
375
376         if (panicstr)
377                 constty = NULL;
378         if ((flags & TOCONS) && tp == NULL && constty) {
379                 if (lwkt_trytoken(&tty_token)) {
380                         tp = constty;
381                         flags |= TOTTY;
382                         have_tty_token = 1;
383                 }
384         }
385         if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
386             (flags & TOCONS) && tp == constty)
387                 constty = NULL;
388         if ((flags & TOLOG))
389                 msglogchar(c, ap->pri);
390         if ((flags & TOCONS) && constty == NULL && c != '\0')
391                 cnputc(c);
392         if (have_tty_token)
393                 lwkt_reltoken(&tty_token);
394 }
395
396 /*
397  * Scaled down version of sprintf(3).
398  */
399 int
400 ksprintf(char *buf, const char *cfmt, ...)
401 {
402         int retval;
403         __va_list ap;
404
405         __va_start(ap, cfmt);
406         retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
407         buf[retval] = '\0';
408         __va_end(ap);
409         return (retval);
410 }
411
412 /*
413  * Scaled down version of vsprintf(3).
414  */
415 int
416 kvsprintf(char *buf, const char *cfmt, __va_list ap)
417 {
418         int retval;
419
420         retval = kvcprintf(cfmt, NULL, (void *)buf, 10, ap);
421         buf[retval] = '\0';
422         return (retval);
423 }
424
425 /*
426  * Scaled down version of snprintf(3).
427  */
428 int
429 ksnprintf(char *str, size_t size, const char *format, ...)
430 {
431         int retval;
432         __va_list ap;
433
434         __va_start(ap, format);
435         retval = kvsnprintf(str, size, format, ap);
436         __va_end(ap);
437         return(retval);
438 }
439
440 /*
441  * Scaled down version of vsnprintf(3).
442  */
443 int
444 kvsnprintf(char *str, size_t size, const char *format, __va_list ap)
445 {
446         struct snprintf_arg info;
447         int retval;
448
449         info.str = str;
450         info.remain = size;
451         retval = kvcprintf(format, snprintf_func, &info, 10, ap);
452         if (info.remain >= 1)
453                 *info.str++ = '\0';
454         return (retval);
455 }
456
457 int
458 ksnrprintf(char *str, size_t size, int radix, const char *format, ...)
459 {
460         int retval;
461         __va_list ap;
462
463         __va_start(ap, format);
464         retval = kvsnrprintf(str, size, radix, format, ap);
465         __va_end(ap);
466         return(retval);
467 }
468
469 int
470 kvsnrprintf(char *str, size_t size, int radix, const char *format, __va_list ap)
471 {
472         struct snprintf_arg info;
473         int retval;
474
475         info.str = str;
476         info.remain = size;
477         retval = kvcprintf(format, snprintf_func, &info, radix, ap);
478         if (info.remain >= 1)
479                 *info.str++ = '\0';
480         return (retval);
481 }
482
483 int
484 kvasnrprintf(char **strp, size_t size, int radix,
485              const char *format, __va_list ap)
486 {
487         struct snprintf_arg info;
488         int retval;
489
490         *strp = kmalloc(size, M_TEMP, M_WAITOK);
491         info.str = *strp;
492         info.remain = size;
493         retval = kvcprintf(format, snprintf_func, &info, radix, ap);
494         if (info.remain >= 1)
495                 *info.str++ = '\0';
496         return (retval);
497 }
498
499 void
500 kvasfree(char **strp)
501 {
502         if (*strp) {
503                 kfree(*strp, M_TEMP);
504                 *strp = NULL;
505         }
506 }
507
508 static void
509 snprintf_func(int ch, void *arg)
510 {
511         struct snprintf_arg *const info = arg;
512
513         if (info->remain >= 2) {
514                 *info->str++ = ch;
515                 info->remain--;
516         }
517 }
518
519 /*
520  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
521  * order; return an optional length and a pointer to the last character
522  * written in the buffer (i.e., the first character of the string).
523  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
524  */
525 static char *
526 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
527 {
528         char *p, c;
529
530         p = nbuf;
531         *p = '\0';
532         do {
533                 c = hex2ascii(num % base);
534                 *++p = upper ? toupper(c) : c;
535         } while (num /= base);
536         if (lenp)
537                 *lenp = p - nbuf;
538         return (p);
539 }
540
541 /*
542  * Scaled down version of printf(3).
543  *
544  * Two additional formats:
545  *
546  * The format %b is supported to decode error registers.
547  * Its usage is:
548  *
549  *      kprintf("reg=%b\n", regval, "<base><arg>*");
550  *
551  * where <base> is the output base expressed as a control character, e.g.
552  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
553  * the first of which gives the bit number to be inspected (origin 1), and
554  * the next characters (up to a control character, i.e. a character <= 32),
555  * give the name of the register.  Thus:
556  *
557  *      kvcprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
558  *
559  * would produce output:
560  *
561  *      reg=3<BITTWO,BITONE>
562  *
563  * XXX:  %D  -- Hexdump, takes pointer and separator string:
564  *              ("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
565  *              ("%*D", len, ptr, " " -> XX XX XX XX ...
566  */
567
568 #define PCHAR(c) {int cc=(c); if(func) (*func)(cc,arg); else *d++=cc; retval++;}
569
570 int
571 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg,
572           int radix, __va_list ap)
573 {
574         char nbuf[MAXNBUF];
575         char *d;
576         const char *p, *percent, *q;
577         u_char *up;
578         int ch, n;
579         uintmax_t num;
580         int base, tmp, width, ladjust, sharpflag, neg, sign, dot;
581         int cflag, hflag, jflag, lflag, qflag, tflag, zflag;
582         int dwidth, upper;
583         char padc;
584         int retval = 0, stop = 0;
585         int usespin;
586
587         /*
588          * Make a supreme effort to avoid reentrant panics or deadlocks.
589          */
590         if (func == kputchar) {
591                 if (mycpu->gd_flags & GDF_KPRINTF)
592                         return(0);
593                 atomic_set_long(&mycpu->gd_flags, GDF_KPRINTF);
594         }
595
596         num = 0;
597         if (!func)
598                 d = (char *) arg;
599         else
600                 d = NULL;
601
602         if (fmt == NULL)
603                 fmt = "(fmt null)\n";
604
605         if (radix < 2 || radix > 36)
606                 radix = 10;
607
608         usespin = (panic_cpu_gd != mycpu &&
609                    func == kputchar &&
610                    (((struct putchar_arg *)arg)->flags & TOTTY) == 0);
611         if (usespin) {
612                 crit_enter_hard();
613                 spin_lock(&cons_spin);
614         }
615
616         for (;;) {
617                 padc = ' ';
618                 width = 0;
619                 while ((ch = (u_char)*fmt++) != '%' || stop) {
620                         if (ch == '\0')
621                                 goto done;
622                         PCHAR(ch);
623                 }
624                 percent = fmt - 1;
625                 dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
626                 cflag = hflag = jflag = lflag = qflag = tflag = zflag = 0;
627
628 reswitch:
629                 switch (ch = (u_char)*fmt++) {
630                 case '.':
631                         dot = 1;
632                         goto reswitch;
633                 case '#':
634                         sharpflag = 1;
635                         goto reswitch;
636                 case '+':
637                         sign = 1;
638                         goto reswitch;
639                 case '-':
640                         ladjust = 1;
641                         goto reswitch;
642                 case '%':
643                         PCHAR(ch);
644                         break;
645                 case '*':
646                         if (!dot) {
647                                 width = __va_arg(ap, int);
648                                 if (width < 0) {
649                                         ladjust = !ladjust;
650                                         width = -width;
651                                 }
652                         } else {
653                                 dwidth = __va_arg(ap, int);
654                         }
655                         goto reswitch;
656                 case '0':
657                         if (!dot) {
658                                 padc = '0';
659                                 goto reswitch;
660                         }
661                 case '1': case '2': case '3': case '4':
662                 case '5': case '6': case '7': case '8': case '9':
663                                 for (n = 0;; ++fmt) {
664                                         n = n * 10 + ch - '0';
665                                         ch = *fmt;
666                                         if (ch < '0' || ch > '9')
667                                                 break;
668                                 }
669                         if (dot)
670                                 dwidth = n;
671                         else
672                                 width = n;
673                         goto reswitch;
674                 case 'b':
675                         num = (u_int)__va_arg(ap, int);
676                         p = __va_arg(ap, char *);
677                         for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
678                                 PCHAR(*q--);
679
680                         if (num == 0)
681                                 break;
682
683                         for (tmp = 0; *p;) {
684                                 n = *p++;
685                                 if (num & (1 << (n - 1))) {
686                                         PCHAR(tmp ? ',' : '<');
687                                         for (; (n = *p) > ' '; ++p)
688                                                 PCHAR(n);
689                                         tmp = 1;
690                                 } else
691                                         for (; *p > ' '; ++p)
692                                                 continue;
693                         }
694                         if (tmp)
695                                 PCHAR('>');
696                         break;
697                 case 'c':
698                         PCHAR(__va_arg(ap, int));
699                         break;
700                 case 'D':
701                         up = __va_arg(ap, u_char *);
702                         p = __va_arg(ap, char *);
703                         if (!width)
704                                 width = 16;
705                         while(width--) {
706                                 PCHAR(hex2ascii(*up >> 4));
707                                 PCHAR(hex2ascii(*up & 0x0f));
708                                 up++;
709                                 if (width)
710                                         for (q=p;*q;q++)
711                                                 PCHAR(*q);
712                         }
713                         break;
714                 case 'd':
715                 case 'i':
716                         base = 10;
717                         sign = 1;
718                         goto handle_sign;
719                 case 'h':
720                         if (hflag) {
721                                 hflag = 0;
722                                 cflag = 1;
723                         } else
724                                 hflag = 1;
725                         goto reswitch;
726                 case 'j':
727                         jflag = 1;
728                         goto reswitch;
729                 case 'l':
730                         if (lflag) {
731                                 lflag = 0;
732                                 qflag = 1;
733                         } else
734                                 lflag = 1;
735                         goto reswitch;
736                 case 'n':
737                         if (cflag)
738                                 *(__va_arg(ap, char *)) = retval;
739                         else if (hflag)
740                                 *(__va_arg(ap, short *)) = retval;
741                         else if (jflag)
742                                 *(__va_arg(ap, intmax_t *)) = retval;
743                         else if (lflag)
744                                 *(__va_arg(ap, long *)) = retval;
745                         else if (qflag)
746                                 *(__va_arg(ap, quad_t *)) = retval;
747                         else
748                                 *(__va_arg(ap, int *)) = retval;
749                         break;
750                 case 'o':
751                         base = 8;
752                         goto handle_nosign;
753                 case 'p':
754                         base = 16;
755                         sharpflag = (width == 0);
756                         sign = 0;
757                         num = (uintptr_t)__va_arg(ap, void *);
758                         goto number;
759                 case 'q':
760                         qflag = 1;
761                         goto reswitch;
762                 case 'r':
763                         base = radix;
764                         if (sign)
765                                 goto handle_sign;
766                         goto handle_nosign;
767                 case 's':
768                         p = __va_arg(ap, char *);
769                         if (p == NULL)
770                                 p = "(null)";
771                         if (!dot)
772                                 n = strlen (p);
773                         else
774                                 for (n = 0; n < dwidth && p[n]; n++)
775                                         continue;
776
777                         width -= n;
778
779                         if (!ladjust && width > 0)
780                                 while (width--)
781                                         PCHAR(padc);
782                         while (n--)
783                                 PCHAR(*p++);
784                         if (ladjust && width > 0)
785                                 while (width--)
786                                         PCHAR(padc);
787                         break;
788                 case 't':
789                         tflag = 1;
790                         goto reswitch;
791                 case 'u':
792                         base = 10;
793                         goto handle_nosign;
794                 case 'X':
795                         upper = 1;
796                         /* FALLTHROUGH */
797                 case 'x':
798                         base = 16;
799                         goto handle_nosign;
800                 case 'z':
801                         zflag = 1;
802                         goto reswitch;
803 handle_nosign:
804                         sign = 0;
805                         if (cflag)
806                                 num = (u_char)__va_arg(ap, int);
807                         else if (hflag)
808                                 num = (u_short)__va_arg(ap, int);
809                         else if (jflag)
810                                 num = __va_arg(ap, uintmax_t);
811                         else if (lflag)
812                                 num = __va_arg(ap, u_long);
813                         else if (qflag)
814                                 num = __va_arg(ap, u_quad_t);
815                         else if (tflag)
816                                 num = __va_arg(ap, ptrdiff_t);
817                         else if (zflag)
818                                 num = __va_arg(ap, size_t);
819                         else
820                                 num = __va_arg(ap, u_int);
821                         goto number;
822 handle_sign:
823                         if (cflag)
824                                 num = (char)__va_arg(ap, int);
825                         else if (hflag)
826                                 num = (short)__va_arg(ap, int);
827                         else if (jflag)
828                                 num = __va_arg(ap, intmax_t);
829                         else if (lflag)
830                                 num = __va_arg(ap, long);
831                         else if (qflag)
832                                 num = __va_arg(ap, quad_t);
833                         else if (tflag)
834                                 num = __va_arg(ap, ptrdiff_t);
835                         else if (zflag)
836                                 num = __va_arg(ap, ssize_t);
837                         else
838                                 num = __va_arg(ap, int);
839 number:
840                         if (sign && (intmax_t)num < 0) {
841                                 neg = 1;
842                                 num = -(intmax_t)num;
843                         }
844                         p = ksprintn(nbuf, num, base, &tmp, upper);
845                         if (sharpflag && num != 0) {
846                                 if (base == 8)
847                                         tmp++;
848                                 else if (base == 16)
849                                         tmp += 2;
850                         }
851                         if (neg)
852                                 tmp++;
853
854                         if (!ladjust && padc != '0' && width &&
855                             (width -= tmp) > 0) {
856                                 while (width--)
857                                         PCHAR(padc);
858                         }
859                         if (neg)
860                                 PCHAR('-');
861                         if (sharpflag && num != 0) {
862                                 if (base == 8) {
863                                         PCHAR('0');
864                                 } else if (base == 16) {
865                                         PCHAR('0');
866                                         PCHAR('x');
867                                 }
868                         }
869                         if (!ladjust && width && (width -= tmp) > 0)
870                                 while (width--)
871                                         PCHAR(padc);
872
873                         while (*p)
874                                 PCHAR(*p--);
875
876                         if (ladjust && width && (width -= tmp) > 0)
877                                 while (width--)
878                                         PCHAR(padc);
879
880                         break;
881                 default:
882                         while (percent < fmt)
883                                 PCHAR(*percent++);
884                         /*
885                          * Since we ignore an formatting argument it is no 
886                          * longer safe to obey the remaining formatting
887                          * arguments as the arguments will no longer match
888                          * the format specs.
889                          */
890                         stop = 1;
891                         break;
892                 }
893         }
894 done:
895         /*
896          * Cleanup reentrancy issues.
897          */
898         if (func == kputchar)
899                 atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
900         if (usespin) {
901                 spin_unlock(&cons_spin);
902                 crit_exit_hard();
903         }
904         return (retval);
905 }
906
907 #undef PCHAR
908
909 /*
910  * Called from the panic code to try to get the console working
911  * again in case we paniced inside a kprintf().
912  */
913 void
914 kvcreinitspin(void)
915 {
916         spin_init(&cons_spin);
917         atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
918 }
919
920
921 /*
922  * Put character in log buffer with a particular priority.
923  *
924  * MPSAFE
925  */
926 static void
927 msglogchar(int c, int pri)
928 {
929         static int lastpri = -1;
930         static int dangling;
931         char nbuf[MAXNBUF];
932         char *p;
933
934         if (!msgbufmapped)
935                 return;
936         if (c == '\0' || c == '\r')
937                 return;
938         if (pri != -1 && pri != lastpri) {
939                 if (dangling) {
940                         msgaddchar('\n', NULL);
941                         dangling = 0;
942                 }
943                 msgaddchar('<', NULL);
944                 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
945                         msgaddchar(*p--, NULL);
946                 msgaddchar('>', NULL);
947                 lastpri = pri;
948         }
949         msgaddchar(c, NULL);
950         if (c == '\n') {
951                 dangling = 0;
952                 lastpri = -1;
953         } else {
954                 dangling = 1;
955         }
956 }
957
958 /*
959  * Put char in log buffer.   Make sure nothing blows up beyond repair if
960  * we have an MP race.
961  *
962  * MPSAFE.
963  */
964 static void
965 msgaddchar(int c, void *dummy)
966 {
967         struct msgbuf *mbp;
968         int rindex;
969         int windex;
970
971         if (!msgbufmapped)
972                 return;
973         mbp = msgbufp;
974         windex = mbp->msg_bufx;
975         mbp->msg_ptr[windex] = c;
976         if (++windex >= mbp->msg_size)
977                 windex = 0;
978         rindex = mbp->msg_bufr;
979         if (windex == rindex) {
980                 rindex += 32;
981                 if (rindex >= mbp->msg_size)
982                         rindex -= mbp->msg_size;
983                 mbp->msg_bufr = rindex;
984         }
985         mbp->msg_bufx = windex;
986 }
987
988 static void
989 msgbufcopy(struct msgbuf *oldp)
990 {
991         int pos;
992
993         pos = oldp->msg_bufr;
994         while (pos != oldp->msg_bufx) {
995                 msglogchar(oldp->msg_ptr[pos], -1);
996                 if (++pos >= oldp->msg_size)
997                         pos = 0;
998         }
999 }
1000
1001 void
1002 msgbufinit(void *ptr, size_t size)
1003 {
1004         char *cp;
1005         static struct msgbuf *oldp = NULL;
1006
1007         size -= sizeof(*msgbufp);
1008         cp = (char *)ptr;
1009         msgbufp = (struct msgbuf *) (cp + size);
1010         if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size ||
1011             msgbufp->msg_bufx >= size || msgbufp->msg_bufr >= size) {
1012                 bzero(cp, size);
1013                 bzero(msgbufp, sizeof(*msgbufp));
1014                 msgbufp->msg_magic = MSG_MAGIC;
1015                 msgbufp->msg_size = (char *)msgbufp - cp;
1016         }
1017         msgbufp->msg_ptr = cp;
1018         if (msgbufmapped && oldp != msgbufp)
1019                 msgbufcopy(oldp);
1020         msgbufmapped = 1;
1021         oldp = msgbufp;
1022 }
1023
1024 /* Sysctls for accessing/clearing the msgbuf */
1025
1026 static int
1027 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1028 {
1029         struct ucred *cred;
1030         int error;
1031
1032         /*
1033          * Only wheel or root can access the message log.
1034          */
1035         if (unprivileged_read_msgbuf == 0) {
1036                 KKASSERT(req->td->td_proc);
1037                 cred = req->td->td_proc->p_ucred;
1038
1039                 if ((cred->cr_prison || groupmember(0, cred) == 0) &&
1040                     priv_check(req->td, PRIV_ROOT) != 0
1041                 ) {
1042                         return (EPERM);
1043                 }
1044         }
1045
1046         /*
1047          * Unwind the buffer, so that it's linear (possibly starting with
1048          * some initial nulls).
1049          */
1050         error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr + msgbufp->msg_bufx,
1051             msgbufp->msg_size - msgbufp->msg_bufx, req);
1052         if (error)
1053                 return (error);
1054         if (msgbufp->msg_bufx > 0) {
1055                 error = sysctl_handle_opaque(oidp, msgbufp->msg_ptr,
1056                     msgbufp->msg_bufx, req);
1057         }
1058         return (error);
1059 }
1060
1061 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
1062     0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1063
1064 static int msgbuf_clear;
1065
1066 static int
1067 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1068 {
1069         int error;
1070         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1071         if (!error && req->newptr) {
1072                 /* Clear the buffer and reset write pointer */
1073                 bzero(msgbufp->msg_ptr, msgbufp->msg_size);
1074                 msgbufp->msg_bufr = msgbufp->msg_bufx = 0;
1075                 msgbuf_clear = 0;
1076         }
1077         return (error);
1078 }
1079
1080 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1081     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
1082     sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
1083
1084 #ifdef DDB
1085
1086 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1087 {
1088         int i, j;
1089
1090         if (!msgbufmapped) {
1091                 db_printf("msgbuf not mapped yet\n");
1092                 return;
1093         }
1094         db_printf("msgbufp = %p\n", msgbufp);
1095         db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
1096             msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_bufr,
1097             msgbufp->msg_bufx, msgbufp->msg_ptr);
1098         for (i = 0; i < msgbufp->msg_size; i++) {
1099                 j = (i + msgbufp->msg_bufr) % msgbufp->msg_size;
1100                 db_printf("%c", msgbufp->msg_ptr[j]);
1101         }
1102         db_printf("\n");
1103 }
1104
1105 #endif /* DDB */