world: Remove references to %r and %b.
[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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)subr_prf.c  8.3 (Berkeley) 1/21/94
35  * $FreeBSD: src/sys/kern/subr_prf.c,v 1.61.2.5 2002/08/31 18:22:08 dwmalone Exp $
36  */
37
38 #include "opt_ddb.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/msgbuf.h>
44 #include <sys/malloc.h>
45 #include <sys/proc.h>
46 #include <sys/priv.h>
47 #include <sys/tty.h>
48 #include <sys/tprintf.h>
49 #include <sys/stdint.h>
50 #include <sys/syslog.h>
51 #include <sys/cons.h>
52 #include <sys/uio.h>
53 #include <sys/sysctl.h>
54 #include <sys/lock.h>
55 #include <sys/ctype.h>
56 #include <sys/eventhandler.h>
57 #include <sys/kthread.h>
58 #include <sys/cpu_topology.h>
59
60 #include <sys/thread2.h>
61 #include <sys/spinlock2.h>
62
63 #ifdef DDB
64 #include <ddb/ddb.h>
65 #endif
66
67 /*
68  * Note that stdarg.h and the ANSI style va_start macro is used for both
69  * ANSI and traditional C compilers.  We use the __ machine version to stay
70  * within the kernel header file set.
71  */
72 #include <machine/stdarg.h>
73
74 #define TOCONS          0x01
75 #define TOTTY           0x02
76 #define TOLOG           0x04
77 #define TOWAKEUP        0x08
78 #define TONOSPIN        0x10    /* avoid serialization */
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, "cons_spin");
108 static thread_t constty_td = NULL;
109
110 int msgbuftrigger;
111
112 static int      log_console_output = 1;
113 TUNABLE_INT("kern.log_console_output", &log_console_output);
114 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RW,
115     &log_console_output, 0, "");
116 static int      kprintf_logging = TOLOG | TOCONS;
117 SYSCTL_INT(_kern, OID_AUTO, kprintf_logging, CTLFLAG_RW,
118     &kprintf_logging, 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_flags & P_CONTROLT) && p->p_session->s_ttyvp) {
147                 __va_start(ap, fmt);
148                 pca.tty = p->p_session->s_ttyp;
149                 pca.flags = TOTTY;
150
151                 retval = kvcprintf(fmt, kputchar, &pca, ap);
152                 __va_end(ap);
153         }
154         return (retval);
155 }
156
157 tpr_t
158 tprintf_open(struct proc *p)
159 {
160         if ((p->p_flags & P_CONTROLT) && p->p_session->s_ttyvp) {
161                 sess_hold(p->p_session);
162                 return ((tpr_t) p->p_session);
163         }
164         return (NULL);
165 }
166
167 void
168 tprintf_close(tpr_t sess)
169 {
170         if (sess)
171                 sess_rele((struct session *) sess);
172 }
173
174 /*
175  * tprintf prints on the controlling terminal associated
176  * with the given session.
177  */
178 int
179 tprintf(tpr_t tpr, const char *fmt, ...)
180 {
181         struct session *sess = (struct session *)tpr;
182         struct tty *tp = NULL;
183         int flags = TOLOG;
184         __va_list ap;
185         struct putchar_arg pca;
186         int retval;
187
188         if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
189                 flags |= TOTTY;
190                 tp = sess->s_ttyp;
191         }
192         __va_start(ap, fmt);
193         pca.tty = tp;
194         pca.flags = flags;
195         pca.pri = LOG_INFO;
196         retval = kvcprintf(fmt, kputchar, &pca, ap);
197         __va_end(ap);
198         msgbuftrigger = 1;
199         return (retval);
200 }
201
202 /*
203  * Ttyprintf displays a message on a tty; it should be used only by
204  * the tty driver, or anything that knows the underlying tty will not
205  * be revoke(2)'d away.  Other callers should use tprintf.
206  */
207 int
208 ttyprintf(struct tty *tp, const char *fmt, ...)
209 {
210         __va_list ap;
211         struct putchar_arg pca;
212         int retval;
213
214         __va_start(ap, fmt);
215         pca.tty = tp;
216         pca.flags = TOTTY;
217         retval = kvcprintf(fmt, kputchar, &pca, ap);
218         __va_end(ap);
219         return (retval);
220 }
221
222 /*
223  * Log writes to the log buffer, and guarantees not to sleep (so can be
224  * called by interrupt routines).  If there is no process reading the
225  * log yet, it writes to the console also.
226  */
227 int
228 log(int level, const char *fmt, ...)
229 {
230         __va_list ap;
231         int retval;
232         struct putchar_arg pca;
233
234         pca.tty = NULL;
235         pca.pri = level;
236         if ((kprintf_logging & TOCONS) == 0 || log_open)
237                 pca.flags = TOLOG;
238         else
239                 pca.flags = TOCONS;
240
241         __va_start(ap, fmt);
242         retval = kvcprintf(fmt, kputchar, &pca, ap);
243         __va_end(ap);
244
245         msgbuftrigger = 1;
246         return (retval);
247 }
248
249 #define CONSCHUNK 128
250
251 void
252 log_console(struct uio *uio)
253 {
254         int c, i, error, iovlen, nl;
255         struct uio muio;
256         struct iovec *miov = NULL;
257         char *consbuffer;
258         int pri;
259
260         if (!log_console_output)
261                 return;
262
263         pri = LOG_INFO | LOG_CONSOLE;
264         muio = *uio;
265         iovlen = uio->uio_iovcnt * sizeof (struct iovec);
266         miov = kmalloc(iovlen, M_TEMP, M_WAITOK);
267         consbuffer = kmalloc(CONSCHUNK, M_TEMP, M_WAITOK);
268         bcopy((caddr_t)muio.uio_iov, (caddr_t)miov, iovlen);
269         muio.uio_iov = miov;
270         uio = &muio;
271
272         nl = 0;
273         while (uio->uio_resid > 0) {
274                 c = (int)szmin(uio->uio_resid, CONSCHUNK);
275                 error = uiomove(consbuffer, (size_t)c, uio);
276                 if (error != 0)
277                         break;
278                 for (i = 0; i < c; i++) {
279                         msglogchar(consbuffer[i], pri);
280                         if (consbuffer[i] == '\n')
281                                 nl = 1;
282                         else
283                                 nl = 0;
284                 }
285         }
286         if (!nl)
287                 msglogchar('\n', pri);
288         msgbuftrigger = 1;
289         kfree(miov, M_TEMP);
290         kfree(consbuffer, M_TEMP);
291         return;
292 }
293
294 /*
295  * Output to the console.
296  */
297 int
298 kprintf(const char *fmt, ...)
299 {
300         __va_list ap;
301         int savintr;
302         struct putchar_arg pca;
303         int retval;
304
305         savintr = consintr;             /* disable interrupts */
306         consintr = 0;
307         __va_start(ap, fmt);
308         pca.tty = NULL;
309         pca.flags = kprintf_logging & ~TOTTY;
310         pca.pri = -1;
311         retval = kvcprintf(fmt, kputchar, &pca, ap);
312         __va_end(ap);
313         if (!panicstr)
314                 msgbuftrigger = 1;
315         consintr = savintr;             /* reenable interrupts */
316         return (retval);
317 }
318
319 int
320 kvprintf(const char *fmt, __va_list ap)
321 {
322         int savintr;
323         struct putchar_arg pca;
324         int retval;
325
326         savintr = consintr;             /* disable interrupts */
327         consintr = 0;
328         pca.tty = NULL;
329         pca.flags = kprintf_logging & ~TOTTY;
330         pca.pri = -1;
331         retval = kvcprintf(fmt, kputchar, &pca, ap);
332         if (!panicstr)
333                 msgbuftrigger = 1;
334         consintr = savintr;             /* reenable interrupts */
335         return (retval);
336 }
337
338 /*
339  * Limited rate kprintf.  The passed rate structure must be initialized
340  * with the desired reporting frequency.  A frequency of 0 will result in
341  * no output.
342  *
343  * count may be initialized to a negative number to allow an initial
344  * burst.
345  */
346 void
347 krateprintf(struct krate *rate, const char *fmt, ...)
348 {
349         __va_list ap;
350
351         if (rate->ticks != (int)time_uptime) {
352                 rate->ticks = (int)time_uptime;
353                 if (rate->count > 0)
354                         rate->count = 0;
355         }
356         if (rate->count < rate->freq) {
357                 ++rate->count;
358                 __va_start(ap, fmt);
359                 kvprintf(fmt, ap);
360                 __va_end(ap);
361         }
362 }
363
364 /*
365  * Print a character to the dmesg log, the console, and/or the user's
366  * terminal.
367  *
368  * NOTE: TOTTY does not require nonblocking operation, but TOCONS
369  *       and TOLOG do.  When we have a constty we still output to
370  *       the real console but we have a monitoring thread which
371  *       we wakeup which tracks the log.
372  */
373 static void
374 kputchar(int c, void *arg)
375 {
376         struct putchar_arg *ap = (struct putchar_arg*) arg;
377         int flags = ap->flags;
378         struct tty *tp = ap->tty;
379
380         if (panicstr)
381                 constty = NULL;
382         if ((flags & TOCONS) && tp == NULL && constty)
383                 flags |= TOLOG | TOWAKEUP;
384         if ((flags & TOTTY) && tputchar(c, tp) < 0)
385                 ap->flags &= ~TOTTY;
386         if ((flags & TOLOG))
387                 msglogchar(c, ap->pri);
388         if ((flags & TOCONS) && c)
389                 cnputc(c);
390         if (flags & TOWAKEUP)
391                 wakeup(constty_td);
392 }
393
394 /*
395  * Scaled down version of sprintf(3).
396  */
397 int
398 ksprintf(char *buf, const char *cfmt, ...)
399 {
400         int retval;
401         __va_list ap;
402
403         __va_start(ap, cfmt);
404         retval = kvcprintf(cfmt, NULL, buf, ap);
405         buf[retval] = '\0';
406         __va_end(ap);
407         return (retval);
408 }
409
410 /*
411  * Scaled down version of vsprintf(3).
412  */
413 int
414 kvsprintf(char *buf, const char *cfmt, __va_list ap)
415 {
416         int retval;
417
418         retval = kvcprintf(cfmt, NULL, buf, ap);
419         buf[retval] = '\0';
420         return (retval);
421 }
422
423 /*
424  * Scaled down version of snprintf(3).
425  */
426 int
427 ksnprintf(char *str, size_t size, const char *format, ...)
428 {
429         int retval;
430         __va_list ap;
431
432         __va_start(ap, format);
433         retval = kvsnprintf(str, size, format, ap);
434         __va_end(ap);
435         return(retval);
436 }
437
438 /*
439  * Scaled down version of vsnprintf(3).
440  */
441 int
442 kvsnprintf(char *str, size_t size, const char *format, __va_list ap)
443 {
444         struct snprintf_arg info;
445         int retval;
446
447         info.str = str;
448         info.remain = size;
449         retval = kvcprintf(format, snprintf_func, &info, ap);
450         if (info.remain >= 1)
451                 *info.str++ = '\0';
452         return (retval);
453 }
454
455 int
456 kvasnprintf(char **strp, size_t size, const char *format, __va_list ap)
457 {
458         struct snprintf_arg info;
459         int retval;
460
461         *strp = kmalloc(size, M_TEMP, M_WAITOK);
462         info.str = *strp;
463         info.remain = size;
464         retval = kvcprintf(format, snprintf_func, &info, ap);
465         if (info.remain >= 1)
466                 *info.str++ = '\0';
467         return (retval);
468 }
469
470 void
471 kvasfree(char **strp)
472 {
473         if (*strp) {
474                 kfree(*strp, M_TEMP);
475                 *strp = NULL;
476         }
477 }
478
479 static void
480 snprintf_func(int ch, void *arg)
481 {
482         struct snprintf_arg *const info = arg;
483
484         if (info->remain >= 2) {
485                 *info->str++ = ch;
486                 info->remain--;
487         }
488 }
489
490 /*
491  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
492  * order; return an optional length and a pointer to the last character
493  * written in the buffer (i.e., the first character of the string).
494  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
495  */
496 static char *
497 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
498 {
499         char *p, c;
500
501         p = nbuf;
502         *p = '\0';
503         do {
504                 c = hex2ascii(num % base);
505                 *++p = upper ? toupper(c) : c;
506         } while (num /= base);
507         if (lenp)
508                 *lenp = p - nbuf;
509         return (p);
510 }
511
512 /*
513  * Scaled down version of printf(3).
514  *
515  * Two additional formats:
516  *
517  * The format %pb%i is supported to decode error registers.
518  * Its usage is:
519  *
520  *      kprintf("reg=%pb%i\n", "<base><arg>*", regval);
521  *
522  * where <base> is the output base expressed as a control character, e.g.
523  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
524  * the first of which gives the bit number to be inspected (origin 1), and
525  * the next characters (up to a control character, i.e. a character <= 32),
526  * give the name of the register.  Thus:
527  *
528  *      kvcprintf("reg=%pb%i\n", "\10\2BITTWO\1BITONE\n", 3);
529  *
530  * would produce output:
531  *
532  *      reg=3<BITTWO,BITONE>
533  */
534
535 #define PCHAR(c) {int cc=(c); if(func) (*func)(cc,arg); else *d++=cc; retval++;}
536
537 int
538 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg, __va_list ap)
539 {
540         char nbuf[MAXNBUF];
541         char *d;
542         const char *p, *percent, *q;
543         int ch, n;
544         uintmax_t num;
545         int base, tmp, width, ladjust, sharpflag, spaceflag, neg, sign, dot;
546         int cflag, hflag, jflag, lflag, qflag, tflag, zflag;
547         int dwidth, upper;
548         char padc;
549         int retval = 0, stop = 0;
550         int usespin;
551
552         /*
553          * Make a supreme effort to avoid reentrant panics or deadlocks.
554          *
555          * NOTE!  Do nothing that would access mycpu/gd/fs unless the
556          *        function is the normal kputchar(), which allows us to
557          *        use this function for very early debugging with a special
558          *        function.
559          */
560         if (func == kputchar) {
561                 if (mycpu->gd_flags & GDF_KPRINTF)
562                         return(0);
563                 atomic_set_long(&mycpu->gd_flags, GDF_KPRINTF);
564         }
565
566         num = 0;
567         if (!func)
568                 d = (char *) arg;
569         else
570                 d = NULL;
571
572         if (fmt == NULL)
573                 fmt = "(fmt null)\n";
574
575         usespin = (func == kputchar &&
576                    (kprintf_logging & TONOSPIN) == 0 &&
577                    panic_cpu_gd != mycpu &&
578                    (((struct putchar_arg *)arg)->flags & TOTTY) == 0);
579         if (usespin) {
580                 crit_enter_hard();
581                 spin_lock(&cons_spin);
582         }
583
584         for (;;) {
585                 padc = ' ';
586                 width = 0;
587                 while ((ch = (u_char)*fmt++) != '%' || stop) {
588                         if (ch == '\0')
589                                 goto done;
590                         PCHAR(ch);
591                 }
592                 percent = fmt - 1;
593                 dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
594                 spaceflag = 0;
595                 cflag = hflag = jflag = lflag = qflag = tflag = zflag = 0;
596
597 reswitch:
598                 switch (ch = (u_char)*fmt++) {
599                 case ' ':
600                         spaceflag = 1;
601                         goto reswitch;
602                 case '.':
603                         dot = 1;
604                         goto reswitch;
605                 case '#':
606                         sharpflag = 1;
607                         goto reswitch;
608                 case '+':
609                         sign = 1;
610                         goto reswitch;
611                 case '-':
612                         ladjust = 1;
613                         goto reswitch;
614                 case '%':
615                         PCHAR(ch);
616                         break;
617                 case '*':
618                         if (!dot) {
619                                 width = __va_arg(ap, int);
620                                 if (width < 0) {
621                                         ladjust = !ladjust;
622                                         width = -width;
623                                 }
624                         } else {
625                                 dwidth = __va_arg(ap, int);
626                         }
627                         goto reswitch;
628                 case '0':
629                         if (!dot) {
630                                 padc = '0';
631                                 goto reswitch;
632                         }
633                 case '1': case '2': case '3': case '4':
634                 case '5': case '6': case '7': case '8': case '9':
635                                 for (n = 0;; ++fmt) {
636                                         n = n * 10 + ch - '0';
637                                         ch = *fmt;
638                                         if (ch < '0' || ch > '9')
639                                                 break;
640                                 }
641                         if (dot)
642                                 dwidth = n;
643                         else
644                                 width = n;
645                         goto reswitch;
646                 case 'c':
647                         PCHAR(__va_arg(ap, int));
648                         break;
649                 case 'd':
650                 case 'i':
651                         base = 10;
652                         sign = 1;
653                         goto handle_sign;
654                 case 'h':
655                         if (hflag) {
656                                 hflag = 0;
657                                 cflag = 1;
658                         } else
659                                 hflag = 1;
660                         goto reswitch;
661                 case 'j':
662                         jflag = 1;
663                         goto reswitch;
664                 case 'l':
665                         if (lflag) {
666                                 lflag = 0;
667                                 qflag = 1;
668                         } else
669                                 lflag = 1;
670                         goto reswitch;
671                 case 'n':
672                         if (cflag)
673                                 *(__va_arg(ap, char *)) = retval;
674                         else if (hflag)
675                                 *(__va_arg(ap, short *)) = retval;
676                         else if (jflag)
677                                 *(__va_arg(ap, intmax_t *)) = retval;
678                         else if (lflag)
679                                 *(__va_arg(ap, long *)) = retval;
680                         else if (qflag)
681                                 *(__va_arg(ap, quad_t *)) = retval;
682                         else
683                                 *(__va_arg(ap, int *)) = retval;
684                         break;
685                 case 'o':
686                         base = 8;
687                         goto handle_nosign;
688                 case 'p':
689                         /* peek if this is a /b/ hiding as /p/ or not */
690                         if (fmt[0] == 'b' && fmt[1] == '%' && fmt[2] == 'i') {
691                                 fmt += 3; /* consume "b%i" */
692                                 p = __va_arg(ap, char *);
693                                 num = (u_int)__va_arg(ap, int);
694                                 for (q = ksprintn(nbuf, num, *p++, NULL, 0);*q;)
695                                         PCHAR(*q--);
696
697                                 if (num == 0)
698                                         break;
699
700                                 for (tmp = 0; *p;) {
701                                         n = *p++;
702                                         if (num & (1 << (n - 1))) {
703                                                 PCHAR(tmp ? ',' : '<');
704                                                 for (; (n = *p) > ' '; ++p)
705                                                         PCHAR(n);
706                                                 tmp = 1;
707                                         } else {
708                                                 for (; *p > ' '; ++p)
709                                                         continue;
710                                         }
711                                 }
712                                 if (tmp)
713                                         PCHAR('>');
714                                 break;
715                         }
716                         base = 16;
717                         sharpflag = (width == 0);
718                         sign = 0;
719                         num = (uintptr_t)__va_arg(ap, void *);
720                         goto number;
721                 case 'q':
722                         qflag = 1;
723                         goto reswitch;
724                 case 's':
725                         p = __va_arg(ap, char *);
726                         if (p == NULL)
727                                 p = "(null)";
728                         if (!dot)
729                                 n = strlen (p);
730                         else
731                                 for (n = 0; n < dwidth && p[n]; n++)
732                                         continue;
733
734                         width -= n;
735
736                         if (!ladjust && width > 0)
737                                 while (width--)
738                                         PCHAR(padc);
739                         while (n--)
740                                 PCHAR(*p++);
741                         if (ladjust && width > 0)
742                                 while (width--)
743                                         PCHAR(padc);
744                         break;
745                 case 't':
746                         tflag = 1;
747                         goto reswitch;
748                 case 'u':
749                         base = 10;
750                         goto handle_nosign;
751                 case 'X':
752                         upper = 1;
753                         /* FALLTHROUGH */
754                 case 'x':
755                         base = 16;
756                         goto handle_nosign;
757                 case 'z':
758                         zflag = 1;
759                         goto reswitch;
760 handle_nosign:
761                         sign = 0;
762                         if (cflag)
763                                 num = (u_char)__va_arg(ap, int);
764                         else if (hflag)
765                                 num = (u_short)__va_arg(ap, int);
766                         else if (jflag)
767                                 num = __va_arg(ap, uintmax_t);
768                         else if (lflag)
769                                 num = __va_arg(ap, u_long);
770                         else if (qflag)
771                                 num = __va_arg(ap, u_quad_t);
772                         else if (tflag)
773                                 num = __va_arg(ap, ptrdiff_t);
774                         else if (zflag)
775                                 num = __va_arg(ap, size_t);
776                         else
777                                 num = __va_arg(ap, u_int);
778                         goto number;
779 handle_sign:
780                         if (cflag)
781                                 num = (char)__va_arg(ap, int);
782                         else if (hflag)
783                                 num = (short)__va_arg(ap, int);
784                         else if (jflag)
785                                 num = __va_arg(ap, intmax_t);
786                         else if (lflag)
787                                 num = __va_arg(ap, long);
788                         else if (qflag)
789                                 num = __va_arg(ap, quad_t);
790                         else if (tflag)
791                                 num = __va_arg(ap, ptrdiff_t);
792                         else if (zflag)
793                                 num = __va_arg(ap, ssize_t);
794                         else
795                                 num = __va_arg(ap, int);
796 number:
797                         if (sign && (intmax_t)num < 0) {
798                                 neg = 1;
799                                 num = -(intmax_t)num;
800                         }
801                         p = ksprintn(nbuf, num, base, &n, upper);
802                         tmp = 0;
803                         if (sharpflag && num != 0) {
804                                 if (base == 8)
805                                         tmp++;
806                                 else if (base == 16)
807                                         tmp += 2;
808                         }
809                         if (neg || (sign && spaceflag))
810                                 tmp++;
811
812                         if (!ladjust && padc == '0')
813                                 dwidth = width - tmp;
814                         width -= tmp + imax(dwidth, n);
815                         dwidth -= n;
816                         if (!ladjust)
817                                 while (width-- > 0)
818                                         PCHAR(' ');
819                         if (neg) {
820                                 PCHAR('-');
821                         } else if (sign && spaceflag) {
822                                 PCHAR(' ');
823                         }
824                         if (sharpflag && num != 0) {
825                                 if (base == 8) {
826                                         PCHAR('0');
827                                 } else if (base == 16) {
828                                         PCHAR('0');
829                                         PCHAR('x');
830                                 }
831                         }
832                         while (dwidth-- > 0)
833                                 PCHAR('0');
834
835                         while (*p)
836                                 PCHAR(*p--);
837
838                         if (ladjust)
839                                 while (width-- > 0)
840                                         PCHAR(' ');
841
842                         break;
843                 default:
844                         while (percent < fmt)
845                                 PCHAR(*percent++);
846                         /*
847                          * Since we ignore an formatting argument it is no 
848                          * longer safe to obey the remaining formatting
849                          * arguments as the arguments will no longer match
850                          * the format specs.
851                          */
852                         stop = 1;
853                         break;
854                 }
855         }
856 done:
857         /*
858          * Cleanup reentrancy issues.
859          */
860         if (func == kputchar)
861                 atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
862         if (usespin) {
863                 spin_unlock(&cons_spin);
864                 crit_exit_hard();
865         }
866         return (retval);
867 }
868
869 #undef PCHAR
870
871 /*
872  * Called from the panic code to try to get the console working
873  * again in case we paniced inside a kprintf().
874  */
875 void
876 kvcreinitspin(void)
877 {
878         spin_init(&cons_spin, "kvcre");
879         atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
880 }
881
882 /*
883  * Console support thread for constty intercepts.  This is needed because
884  * console tty intercepts can block.  Instead of having kputchar() attempt
885  * to directly write to the console intercept we just force it to log
886  * and wakeup this baby to track and dump the log to constty.
887  */
888 static void
889 constty_daemon(void)
890 {
891         u_int rindex;
892         u_int xindex;
893         u_int n;
894         struct msgbuf *mbp;
895         struct tty *tp;
896
897         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
898                               constty_td, SHUTDOWN_PRI_FIRST);
899         constty_td->td_flags |= TDF_SYSTHREAD;
900
901         mbp = msgbufp;
902         rindex = mbp->msg_bufr;         /* persistent loop variable */
903         xindex = mbp->msg_bufx - 1;     /* anything different than bufx */
904         cpu_ccfence();
905
906         for (;;) {
907                 kproc_suspend_loop();
908
909                 crit_enter();
910                 if (mbp != msgbufp)
911                         mbp = msgbufp;
912                 if (xindex == mbp->msg_bufx ||
913                     mbp == NULL ||
914                     msgbufmapped == 0) {
915                         tsleep(constty_td, 0, "waiting", hz*60);
916                         crit_exit();
917                         continue;
918                 }
919                 crit_exit();
920
921                 /*
922                  * Get message buf FIFO indices.  rindex is tracking.
923                  */
924                 xindex = mbp->msg_bufx;
925                 cpu_ccfence();
926                 if ((tp = constty) == NULL) {
927                         rindex = xindex;
928                         continue;
929                 }
930
931                 /*
932                  * Check if the calculated bytes has rolled the whole
933                  * message buffer.
934                  */
935                 n = xindex - rindex;
936                 if (n > mbp->msg_size - 1024) {
937                         rindex = xindex - mbp->msg_size + 2048;
938                         n = xindex - rindex;
939                 }
940
941                 /*
942                  * And dump it.  If constty gets stuck will give up.
943                  */
944                 while (rindex != xindex) {
945                         u_int ri = rindex % mbp->msg_size;
946                         if (tputchar((uint8_t)mbp->msg_ptr[ri], tp) < 0) {
947                                 constty = NULL;
948                                 rindex = xindex;
949                                 break;
950                         }
951                         if (tp->t_outq.c_cc >= tp->t_ohiwat) {
952                                 tsleep(constty_daemon, 0, "blocked", hz / 10);
953                                 if (tp->t_outq.c_cc >= tp->t_ohiwat) {
954                                         rindex = xindex;
955                                         break;
956                                 }
957                         }
958                         ++rindex;
959                 }
960         }
961 }
962
963 static struct kproc_desc constty_kp = {
964         "consttyd",
965         constty_daemon,
966         &constty_td
967 };
968 SYSINIT(bufdaemon, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY,
969         kproc_start, &constty_kp);
970
971 /*
972  * Put character in log buffer with a particular priority.
973  *
974  * MPSAFE
975  */
976 static void
977 msglogchar(int c, int pri)
978 {
979         static int lastpri = -1;
980         static int dangling;
981         char nbuf[MAXNBUF];
982         char *p;
983
984         if (!msgbufmapped)
985                 return;
986         if (c == '\0' || c == '\r')
987                 return;
988         if (pri != -1 && pri != lastpri) {
989                 if (dangling) {
990                         msgaddchar('\n', NULL);
991                         dangling = 0;
992                 }
993                 msgaddchar('<', NULL);
994                 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
995                         msgaddchar(*p--, NULL);
996                 msgaddchar('>', NULL);
997                 lastpri = pri;
998         }
999         msgaddchar(c, NULL);
1000         if (c == '\n') {
1001                 dangling = 0;
1002                 lastpri = -1;
1003         } else {
1004                 dangling = 1;
1005         }
1006 }
1007
1008 /*
1009  * Put char in log buffer.   Make sure nothing blows up beyond repair if
1010  * we have an MP race.
1011  *
1012  * MPSAFE.
1013  */
1014 static void
1015 msgaddchar(int c, void *dummy)
1016 {
1017         struct msgbuf *mbp;
1018         u_int lindex;
1019         u_int rindex;
1020         u_int xindex;
1021         u_int n;
1022
1023         if (!msgbufmapped)
1024                 return;
1025         mbp = msgbufp;
1026         lindex = mbp->msg_bufl;
1027         rindex = mbp->msg_bufr;
1028         xindex = mbp->msg_bufx++;       /* Allow SMP race */
1029         cpu_ccfence();
1030
1031         mbp->msg_ptr[xindex % mbp->msg_size] = c;
1032         n = xindex - lindex;
1033         if (n > mbp->msg_size - 1024) {
1034                 lindex = xindex - mbp->msg_size + 2048;
1035                 cpu_ccfence();
1036                 mbp->msg_bufl = lindex;
1037         }
1038         n = xindex - rindex;
1039         if (n > mbp->msg_size - 1024) {
1040                 rindex = xindex - mbp->msg_size + 2048;
1041                 cpu_ccfence();
1042                 mbp->msg_bufr = rindex;
1043         }
1044 }
1045
1046 static void
1047 msgbufcopy(struct msgbuf *oldp)
1048 {
1049         u_int rindex;
1050         u_int xindex;
1051         u_int n;
1052
1053         rindex = oldp->msg_bufr;
1054         xindex = oldp->msg_bufx;
1055         cpu_ccfence();
1056
1057         n = xindex - rindex;
1058         if (n > oldp->msg_size - 1024)
1059                 rindex = xindex - oldp->msg_size + 2048;
1060         while (rindex != xindex) {
1061                 msglogchar(oldp->msg_ptr[rindex % oldp->msg_size], -1);
1062                 ++rindex;
1063         }
1064 }
1065
1066 void
1067 msgbufinit(void *ptr, size_t size)
1068 {
1069         char *cp;
1070         static struct msgbuf *oldp = NULL;
1071
1072         size -= sizeof(*msgbufp);
1073         cp = (char *)ptr;
1074         msgbufp = (struct msgbuf *) (cp + size);
1075         if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size) {
1076                 bzero(cp, size);
1077                 bzero(msgbufp, sizeof(*msgbufp));
1078                 msgbufp->msg_magic = MSG_MAGIC;
1079                 msgbufp->msg_size = (char *)msgbufp - cp;
1080         }
1081         msgbufp->msg_ptr = cp;
1082         if (msgbufmapped && oldp != msgbufp)
1083                 msgbufcopy(oldp);
1084         cpu_mfence();
1085         msgbufmapped = 1;
1086         oldp = msgbufp;
1087 }
1088
1089 /* Sysctls for accessing/clearing the msgbuf */
1090
1091 static int
1092 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1093 {
1094         struct msgbuf *mbp;
1095         struct ucred *cred;
1096         int error;
1097         u_int rindex_modulo;
1098         u_int xindex_modulo;
1099         u_int rindex;
1100         u_int xindex;
1101         u_int n;
1102
1103         /*
1104          * Only wheel or root can access the message log.
1105          */
1106         if (unprivileged_read_msgbuf == 0) {
1107                 KKASSERT(req->td->td_proc);
1108                 cred = req->td->td_proc->p_ucred;
1109
1110                 if ((cred->cr_prison || groupmember(0, cred) == 0) &&
1111                     priv_check(req->td, PRIV_ROOT) != 0
1112                 ) {
1113                         return (EPERM);
1114                 }
1115         }
1116
1117         /*
1118          * Unwind the buffer, so that it's linear (possibly starting with
1119          * some initial nulls).
1120          *
1121          * We don't push the entire buffer like we did before because
1122          * bufr (and bufl) now advance in chunks when the fifo is full,
1123          * rather than one character.
1124          */
1125         mbp = msgbufp;
1126         rindex = mbp->msg_bufr;
1127         xindex = mbp->msg_bufx;
1128         n = xindex - rindex;
1129         if (n > mbp->msg_size - 1024) {
1130                 rindex = xindex - mbp->msg_size + 2048;
1131                 n = xindex - rindex;
1132         }
1133         rindex_modulo = rindex % mbp->msg_size;
1134         xindex_modulo = xindex % mbp->msg_size;
1135
1136         if (rindex_modulo < xindex_modulo) {
1137                 /*
1138                  * Can handle in one linear section.
1139                  */
1140                 error = sysctl_handle_opaque(oidp,
1141                                              mbp->msg_ptr + rindex_modulo,
1142                                              xindex_modulo - rindex_modulo,
1143                                              req);
1144         } else if (rindex_modulo == xindex_modulo) {
1145                 /*
1146                  * Empty buffer, just return a single newline
1147                  */
1148                 error = sysctl_handle_opaque(oidp, "\n", 1, req);
1149         } else if (n <= mbp->msg_size - rindex_modulo) {
1150                 /*
1151                  * Can handle in one linear section.
1152                  */
1153                 error = sysctl_handle_opaque(oidp,
1154                                              mbp->msg_ptr + rindex_modulo,
1155                                              n - rindex_modulo,
1156                                              req);
1157         } else {
1158                 /*
1159                  * Glue together two linear sections into one contiguous
1160                  * output.
1161                  */
1162                 error = sysctl_handle_opaque(oidp,
1163                                              mbp->msg_ptr + rindex_modulo,
1164                                              mbp->msg_size - rindex_modulo,
1165                                              req);
1166                 n -= mbp->msg_size - rindex_modulo;
1167                 if (error == 0)
1168                         error = sysctl_handle_opaque(oidp, mbp->msg_ptr,
1169                                                      n, req);
1170         }
1171         return (error);
1172 }
1173
1174 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
1175     0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1176
1177 static int msgbuf_clear;
1178
1179 static int
1180 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1181 {
1182         int error;
1183         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1184         if (!error && req->newptr) {
1185                 /* Clear the buffer and reset write pointer */
1186                 msgbufp->msg_bufr = msgbufp->msg_bufx;
1187                 msgbufp->msg_bufl = msgbufp->msg_bufx;
1188                 bzero(msgbufp->msg_ptr, msgbufp->msg_size);
1189                 msgbuf_clear = 0;
1190         }
1191         return (error);
1192 }
1193
1194 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1195     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
1196     sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
1197
1198 #ifdef DDB
1199
1200 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1201 {
1202         u_int rindex;
1203         u_int i;
1204         u_int j;
1205
1206         if (!msgbufmapped) {
1207                 db_printf("msgbuf not mapped yet\n");
1208                 return;
1209         }
1210         db_printf("msgbufp = %p\n", msgbufp);
1211         db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
1212                   msgbufp->msg_magic, msgbufp->msg_size,
1213                   msgbufp->msg_bufr % msgbufp->msg_size,
1214                   msgbufp->msg_bufx % msgbufp->msg_size,
1215                   msgbufp->msg_ptr);
1216
1217         rindex = msgbufp->msg_bufr;
1218         for (i = 0; i < msgbufp->msg_size; i++) {
1219                 j = (i + rindex) % msgbufp->msg_size;
1220                 db_printf("%c", msgbufp->msg_ptr[j]);
1221         }
1222         db_printf("\n");
1223 }
1224
1225 #endif /* DDB */
1226
1227
1228 void
1229 hexdump(const void *ptr, int length, const char *hdr, int flags)
1230 {
1231         int i, j, k;
1232         int cols;
1233         const unsigned char *cp;
1234         char delim;
1235
1236         if ((flags & HD_DELIM_MASK) != 0)
1237                 delim = (flags & HD_DELIM_MASK) >> 8;
1238         else
1239                 delim = ' ';
1240
1241         if ((flags & HD_COLUMN_MASK) != 0)
1242                 cols = flags & HD_COLUMN_MASK;
1243         else
1244                 cols = 16;
1245
1246         cp = ptr;
1247         for (i = 0; i < length; i+= cols) {
1248                 if (hdr != NULL)
1249                         kprintf("%s", hdr);
1250
1251                 if ((flags & HD_OMIT_COUNT) == 0)
1252                         kprintf("%04x  ", i);
1253
1254                 if ((flags & HD_OMIT_HEX) == 0) {
1255                         for (j = 0; j < cols; j++) {
1256                                 k = i + j;
1257                                 if (k < length)
1258                                         kprintf("%c%02x", delim, cp[k]);
1259                                 else
1260                                         kprintf("   ");
1261                         }
1262                 }
1263
1264                 if ((flags & HD_OMIT_CHARS) == 0) {
1265                         kprintf("  |");
1266                         for (j = 0; j < cols; j++) {
1267                                 k = i + j;
1268                                 if (k >= length)
1269                                         kprintf(" ");
1270                                 else if (cp[k] >= ' ' && cp[k] <= '~')
1271                                         kprintf("%c", cp[k]);
1272                                 else
1273                                         kprintf(".");
1274                         }
1275                         kprintf("|");
1276                 }
1277                 kprintf("\n");
1278         }
1279 }
1280
1281 void
1282 kprint_cpuset(cpumask_t *mask)
1283 {
1284         int i;
1285         int b = -1;
1286         int e = -1;
1287         int more = 0;
1288
1289         kprintf("cpus(");
1290         CPUSET_FOREACH(i, *mask) {
1291                 if (b < 0) {
1292                         b = i;
1293                         e = b + 1;
1294                         continue;
1295                 }
1296                 if (e == i) {
1297                         ++e;
1298                         continue;
1299                 }
1300                 if (more)
1301                         kprintf(", ");
1302                 if (b == e - 1) {
1303                         kprintf("%d", b);
1304                 } else {
1305                         kprintf("%d-%d", b, e - 1);
1306                 }
1307                 more = 1;
1308                 b = i;
1309                 e = b + 1;
1310         }
1311         if (more)
1312                 kprintf(", ");
1313         if (b >= 0) {
1314                 if (b == e - 1) {
1315                         kprintf("%d", b);
1316                 } else {
1317                         kprintf("%d-%d", b, e - 1);
1318                 }
1319         }
1320         kprintf(") ");
1321 }