mbuf: Add helper functions to inc/dec mbuf limits
[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
79 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
80 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
81
82 struct putchar_arg {
83         int     flags;
84         int     pri;
85         struct  tty *tty;
86 };
87
88 struct snprintf_arg {
89         char    *str;
90         size_t  remain;
91 };
92
93 extern  int log_open;
94
95 struct  tty *constty;                   /* pointer to console "window" tty */
96
97 static void  msglogchar(int c, int pri);
98 static void  msgaddchar(int c, void *dummy);
99 static void  kputchar (int ch, void *arg);
100 static char *ksprintn (char *nbuf, uintmax_t num, int base, int *lenp,
101                        int upper);
102 static void  snprintf_func (int ch, void *arg);
103
104 static int consintr = 1;                /* Ok to handle console interrupts? */
105 static int msgbufmapped;                /* Set when safe to use msgbuf */
106 static struct spinlock cons_spin = SPINLOCK_INITIALIZER(cons_spin, "cons_spin");
107 static thread_t constty_td = NULL;
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_flags & P_CONTROLT) && p->p_session->s_ttyvp) {
143                 __va_start(ap, fmt);
144                 pca.tty = p->p_session->s_ttyp;
145                 pca.flags = TOTTY;
146
147                 retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
148                 __va_end(ap);
149         }
150         return (retval);
151 }
152
153 tpr_t
154 tprintf_open(struct proc *p)
155 {
156         if ((p->p_flags & P_CONTROLT) && p->p_session->s_ttyvp) {
157                 sess_hold(p->p_session);
158                 return ((tpr_t) p->p_session);
159         }
160         return (NULL);
161 }
162
163 void
164 tprintf_close(tpr_t sess)
165 {
166         if (sess)
167                 sess_rele((struct session *) sess);
168 }
169
170 /*
171  * tprintf prints on the controlling terminal associated
172  * with the given session.
173  */
174 int
175 tprintf(tpr_t tpr, const char *fmt, ...)
176 {
177         struct session *sess = (struct session *)tpr;
178         struct tty *tp = NULL;
179         int flags = TOLOG;
180         __va_list ap;
181         struct putchar_arg pca;
182         int retval;
183
184         if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
185                 flags |= TOTTY;
186                 tp = sess->s_ttyp;
187         }
188         __va_start(ap, fmt);
189         pca.tty = tp;
190         pca.flags = flags;
191         pca.pri = LOG_INFO;
192         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
193         __va_end(ap);
194         msgbuftrigger = 1;
195         return (retval);
196 }
197
198 /*
199  * Ttyprintf displays a message on a tty; it should be used only by
200  * the tty driver, or anything that knows the underlying tty will not
201  * be revoke(2)'d away.  Other callers should use tprintf.
202  */
203 int
204 ttyprintf(struct tty *tp, const char *fmt, ...)
205 {
206         __va_list ap;
207         struct putchar_arg pca;
208         int retval;
209
210         __va_start(ap, fmt);
211         pca.tty = tp;
212         pca.flags = TOTTY;
213         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
214         __va_end(ap);
215         return (retval);
216 }
217
218 /*
219  * Log writes to the log buffer, and guarantees not to sleep (so can be
220  * called by interrupt routines).  If there is no process reading the
221  * log yet, it writes to the console also.
222  */
223 int
224 log(int level, const char *fmt, ...)
225 {
226         __va_list ap;
227         int retval;
228         struct putchar_arg pca;
229
230         pca.tty = NULL;
231         pca.pri = level;
232         pca.flags = log_open ? TOLOG : TOCONS;
233
234         __va_start(ap, fmt);
235         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
236         __va_end(ap);
237
238         msgbuftrigger = 1;
239         return (retval);
240 }
241
242 #define CONSCHUNK 128
243
244 void
245 log_console(struct uio *uio)
246 {
247         int c, i, error, iovlen, nl;
248         struct uio muio;
249         struct iovec *miov = NULL;
250         char *consbuffer;
251         int pri;
252
253         if (!log_console_output)
254                 return;
255
256         pri = LOG_INFO | LOG_CONSOLE;
257         muio = *uio;
258         iovlen = uio->uio_iovcnt * sizeof (struct iovec);
259         miov = kmalloc(iovlen, M_TEMP, M_WAITOK);
260         consbuffer = kmalloc(CONSCHUNK, M_TEMP, M_WAITOK);
261         bcopy((caddr_t)muio.uio_iov, (caddr_t)miov, iovlen);
262         muio.uio_iov = miov;
263         uio = &muio;
264
265         nl = 0;
266         while (uio->uio_resid > 0) {
267                 c = (int)szmin(uio->uio_resid, CONSCHUNK);
268                 error = uiomove(consbuffer, (size_t)c, uio);
269                 if (error != 0)
270                         break;
271                 for (i = 0; i < c; i++) {
272                         msglogchar(consbuffer[i], pri);
273                         if (consbuffer[i] == '\n')
274                                 nl = 1;
275                         else
276                                 nl = 0;
277                 }
278         }
279         if (!nl)
280                 msglogchar('\n', pri);
281         msgbuftrigger = 1;
282         kfree(miov, M_TEMP);
283         kfree(consbuffer, M_TEMP);
284         return;
285 }
286
287 /*
288  * Output to the console.
289  */
290 int
291 kprintf(const char *fmt, ...)
292 {
293         __va_list ap;
294         int savintr;
295         struct putchar_arg pca;
296         int retval;
297
298         savintr = consintr;             /* disable interrupts */
299         consintr = 0;
300         __va_start(ap, fmt);
301         pca.tty = NULL;
302         pca.flags = TOCONS | TOLOG;
303         pca.pri = -1;
304         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
305         __va_end(ap);
306         if (!panicstr)
307                 msgbuftrigger = 1;
308         consintr = savintr;             /* reenable interrupts */
309         return (retval);
310 }
311
312 int
313 kvprintf(const char *fmt, __va_list ap)
314 {
315         int savintr;
316         struct putchar_arg pca;
317         int retval;
318
319         savintr = consintr;             /* disable interrupts */
320         consintr = 0;
321         pca.tty = NULL;
322         pca.flags = TOCONS | TOLOG;
323         pca.pri = -1;
324         retval = kvcprintf(fmt, kputchar, &pca, 10, ap);
325         if (!panicstr)
326                 msgbuftrigger = 1;
327         consintr = savintr;             /* reenable interrupts */
328         return (retval);
329 }
330
331 /*
332  * Limited rate kprintf.  The passed rate structure must be initialized
333  * with the desired reporting frequency.  A frequency of 0 will result in
334  * no output.
335  *
336  * count may be initialized to a negative number to allow an initial
337  * burst.
338  */
339 void
340 krateprintf(struct krate *rate, const char *fmt, ...)
341 {
342         __va_list ap;
343
344         if (rate->ticks != (int)time_uptime) {
345                 rate->ticks = (int)time_uptime;
346                 if (rate->count > 0)
347                         rate->count = 0;
348         }
349         if (rate->count < rate->freq) {
350                 ++rate->count;
351                 __va_start(ap, fmt);
352                 kvprintf(fmt, ap);
353                 __va_end(ap);
354         }
355 }
356
357 /*
358  * Print a character to the dmesg log, the console, and/or the user's
359  * terminal.
360  *
361  * NOTE: TOTTY does not require nonblocking operation, but TOCONS
362  *       and TOLOG do.  When we have a constty we still output to
363  *       the real console but we have a monitoring thread which
364  *       we wakeup which tracks the log.
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
373         if (panicstr)
374                 constty = NULL;
375         if ((flags & TOCONS) && tp == NULL && constty)
376                 flags |= TOLOG | TOWAKEUP;
377         if ((flags & TOTTY) && tputchar(c, tp) < 0)
378                 ap->flags &= ~TOTTY;
379         if ((flags & TOLOG))
380                 msglogchar(c, ap->pri);
381         if ((flags & TOCONS) && c)
382                 cnputc(c);
383         if (flags & TOWAKEUP)
384                 wakeup(constty_td);
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, 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, 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
555 #define PCHAR(c) {int cc=(c); if(func) (*func)(cc,arg); else *d++=cc; retval++;}
556
557 int
558 kvcprintf(char const *fmt, void (*func)(int, void*), void *arg,
559           int radix, __va_list ap)
560 {
561         char nbuf[MAXNBUF];
562         char *d;
563         const char *p, *percent, *q;
564         int ch, n;
565         uintmax_t num;
566         int base, tmp, width, ladjust, sharpflag, spaceflag, neg, sign, dot;
567         int cflag, hflag, jflag, lflag, qflag, tflag, zflag;
568         int dwidth, upper;
569         char padc;
570         int retval = 0, stop = 0;
571         int usespin;
572
573         /*
574          * Make a supreme effort to avoid reentrant panics or deadlocks.
575          *
576          * NOTE!  Do nothing that would access mycpu/gd/fs unless the
577          *        function is the normal kputchar(), which allows us to
578          *        use this function for very early debugging with a special
579          *        function.
580          */
581         if (func == kputchar) {
582                 if (mycpu->gd_flags & GDF_KPRINTF)
583                         return(0);
584                 atomic_set_long(&mycpu->gd_flags, GDF_KPRINTF);
585         }
586
587         num = 0;
588         if (!func)
589                 d = (char *) arg;
590         else
591                 d = NULL;
592
593         if (fmt == NULL)
594                 fmt = "(fmt null)\n";
595
596         if (radix < 2 || radix > 36)
597                 radix = 10;
598
599         usespin = (func == kputchar &&
600                    panic_cpu_gd != mycpu &&
601                    (((struct putchar_arg *)arg)->flags & TOTTY) == 0);
602         if (usespin) {
603                 crit_enter_hard();
604                 spin_lock(&cons_spin);
605         }
606
607         for (;;) {
608                 padc = ' ';
609                 width = 0;
610                 while ((ch = (u_char)*fmt++) != '%' || stop) {
611                         if (ch == '\0')
612                                 goto done;
613                         PCHAR(ch);
614                 }
615                 percent = fmt - 1;
616                 dot = dwidth = ladjust = neg = sharpflag = sign = upper = 0;
617                 spaceflag = 0;
618                 cflag = hflag = jflag = lflag = qflag = tflag = zflag = 0;
619
620 reswitch:
621                 switch (ch = (u_char)*fmt++) {
622                 case ' ':
623                         spaceflag = 1;
624                         goto reswitch;
625                 case '.':
626                         dot = 1;
627                         goto reswitch;
628                 case '#':
629                         sharpflag = 1;
630                         goto reswitch;
631                 case '+':
632                         sign = 1;
633                         goto reswitch;
634                 case '-':
635                         ladjust = 1;
636                         goto reswitch;
637                 case '%':
638                         PCHAR(ch);
639                         break;
640                 case '*':
641                         if (!dot) {
642                                 width = __va_arg(ap, int);
643                                 if (width < 0) {
644                                         ladjust = !ladjust;
645                                         width = -width;
646                                 }
647                         } else {
648                                 dwidth = __va_arg(ap, int);
649                         }
650                         goto reswitch;
651                 case '0':
652                         if (!dot) {
653                                 padc = '0';
654                                 goto reswitch;
655                         }
656                 case '1': case '2': case '3': case '4':
657                 case '5': case '6': case '7': case '8': case '9':
658                                 for (n = 0;; ++fmt) {
659                                         n = n * 10 + ch - '0';
660                                         ch = *fmt;
661                                         if (ch < '0' || ch > '9')
662                                                 break;
663                                 }
664                         if (dot)
665                                 dwidth = n;
666                         else
667                                 width = n;
668                         goto reswitch;
669                 case 'b':
670                         num = (u_int)__va_arg(ap, int);
671                         p = __va_arg(ap, char *);
672                         for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;)
673                                 PCHAR(*q--);
674
675                         if (num == 0)
676                                 break;
677
678                         for (tmp = 0; *p;) {
679                                 n = *p++;
680                                 if (num & (1 << (n - 1))) {
681                                         PCHAR(tmp ? ',' : '<');
682                                         for (; (n = *p) > ' '; ++p)
683                                                 PCHAR(n);
684                                         tmp = 1;
685                                 } else
686                                         for (; *p > ' '; ++p)
687                                                 continue;
688                         }
689                         if (tmp)
690                                 PCHAR('>');
691                         break;
692                 case 'c':
693                         PCHAR(__va_arg(ap, int));
694                         break;
695                 case 'd':
696                 case 'i':
697                         base = 10;
698                         sign = 1;
699                         goto handle_sign;
700                 case 'h':
701                         if (hflag) {
702                                 hflag = 0;
703                                 cflag = 1;
704                         } else
705                                 hflag = 1;
706                         goto reswitch;
707                 case 'j':
708                         jflag = 1;
709                         goto reswitch;
710                 case 'l':
711                         if (lflag) {
712                                 lflag = 0;
713                                 qflag = 1;
714                         } else
715                                 lflag = 1;
716                         goto reswitch;
717                 case 'n':
718                         if (cflag)
719                                 *(__va_arg(ap, char *)) = retval;
720                         else if (hflag)
721                                 *(__va_arg(ap, short *)) = retval;
722                         else if (jflag)
723                                 *(__va_arg(ap, intmax_t *)) = retval;
724                         else if (lflag)
725                                 *(__va_arg(ap, long *)) = retval;
726                         else if (qflag)
727                                 *(__va_arg(ap, quad_t *)) = retval;
728                         else
729                                 *(__va_arg(ap, int *)) = retval;
730                         break;
731                 case 'o':
732                         base = 8;
733                         goto handle_nosign;
734                 case 'p':
735                         base = 16;
736                         sharpflag = (width == 0);
737                         sign = 0;
738                         num = (uintptr_t)__va_arg(ap, void *);
739                         goto number;
740                 case 'q':
741                         qflag = 1;
742                         goto reswitch;
743                 case 'r':
744                         base = radix;
745                         if (sign)
746                                 goto handle_sign;
747                         goto handle_nosign;
748                 case 's':
749                         p = __va_arg(ap, char *);
750                         if (p == NULL)
751                                 p = "(null)";
752                         if (!dot)
753                                 n = strlen (p);
754                         else
755                                 for (n = 0; n < dwidth && p[n]; n++)
756                                         continue;
757
758                         width -= n;
759
760                         if (!ladjust && width > 0)
761                                 while (width--)
762                                         PCHAR(padc);
763                         while (n--)
764                                 PCHAR(*p++);
765                         if (ladjust && width > 0)
766                                 while (width--)
767                                         PCHAR(padc);
768                         break;
769                 case 't':
770                         tflag = 1;
771                         goto reswitch;
772                 case 'u':
773                         base = 10;
774                         goto handle_nosign;
775                 case 'X':
776                         upper = 1;
777                         /* FALLTHROUGH */
778                 case 'x':
779                         base = 16;
780                         goto handle_nosign;
781                 case 'z':
782                         zflag = 1;
783                         goto reswitch;
784 handle_nosign:
785                         sign = 0;
786                         if (cflag)
787                                 num = (u_char)__va_arg(ap, int);
788                         else if (hflag)
789                                 num = (u_short)__va_arg(ap, int);
790                         else if (jflag)
791                                 num = __va_arg(ap, uintmax_t);
792                         else if (lflag)
793                                 num = __va_arg(ap, u_long);
794                         else if (qflag)
795                                 num = __va_arg(ap, u_quad_t);
796                         else if (tflag)
797                                 num = __va_arg(ap, ptrdiff_t);
798                         else if (zflag)
799                                 num = __va_arg(ap, size_t);
800                         else
801                                 num = __va_arg(ap, u_int);
802                         goto number;
803 handle_sign:
804                         if (cflag)
805                                 num = (char)__va_arg(ap, int);
806                         else if (hflag)
807                                 num = (short)__va_arg(ap, int);
808                         else if (jflag)
809                                 num = __va_arg(ap, intmax_t);
810                         else if (lflag)
811                                 num = __va_arg(ap, long);
812                         else if (qflag)
813                                 num = __va_arg(ap, quad_t);
814                         else if (tflag)
815                                 num = __va_arg(ap, ptrdiff_t);
816                         else if (zflag)
817                                 num = __va_arg(ap, ssize_t);
818                         else
819                                 num = __va_arg(ap, int);
820 number:
821                         if (sign && (intmax_t)num < 0) {
822                                 neg = 1;
823                                 num = -(intmax_t)num;
824                         }
825                         p = ksprintn(nbuf, num, base, &n, upper);
826                         tmp = 0;
827                         if (sharpflag && num != 0) {
828                                 if (base == 8)
829                                         tmp++;
830                                 else if (base == 16)
831                                         tmp += 2;
832                         }
833                         if (neg || (sign && spaceflag))
834                                 tmp++;
835
836                         if (!ladjust && padc == '0')
837                                 dwidth = width - tmp;
838                         width -= tmp + imax(dwidth, n);
839                         dwidth -= n;
840                         if (!ladjust)
841                                 while (width-- > 0)
842                                         PCHAR(' ');
843                         if (neg) {
844                                 PCHAR('-');
845                         } else if (sign && spaceflag) {
846                                 PCHAR(' ');
847                         }
848                         if (sharpflag && num != 0) {
849                                 if (base == 8) {
850                                         PCHAR('0');
851                                 } else if (base == 16) {
852                                         PCHAR('0');
853                                         PCHAR('x');
854                                 }
855                         }
856                         while (dwidth-- > 0)
857                                 PCHAR('0');
858
859                         while (*p)
860                                 PCHAR(*p--);
861
862                         if (ladjust)
863                                 while (width-- > 0)
864                                         PCHAR(' ');
865
866                         break;
867                 default:
868                         while (percent < fmt)
869                                 PCHAR(*percent++);
870                         /*
871                          * Since we ignore an formatting argument it is no 
872                          * longer safe to obey the remaining formatting
873                          * arguments as the arguments will no longer match
874                          * the format specs.
875                          */
876                         stop = 1;
877                         break;
878                 }
879         }
880 done:
881         /*
882          * Cleanup reentrancy issues.
883          */
884         if (func == kputchar)
885                 atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
886         if (usespin) {
887                 spin_unlock(&cons_spin);
888                 crit_exit_hard();
889         }
890         return (retval);
891 }
892
893 #undef PCHAR
894
895 /*
896  * Called from the panic code to try to get the console working
897  * again in case we paniced inside a kprintf().
898  */
899 void
900 kvcreinitspin(void)
901 {
902         spin_init(&cons_spin, "kvcre");
903         atomic_clear_long(&mycpu->gd_flags, GDF_KPRINTF);
904 }
905
906 /*
907  * Console support thread for constty intercepts.  This is needed because
908  * console tty intercepts can block.  Instead of having kputchar() attempt
909  * to directly write to the console intercept we just force it to log
910  * and wakeup this baby to track and dump the log to constty.
911  */
912 static void
913 constty_daemon(void)
914 {
915         u_int rindex;
916         u_int xindex;
917         u_int n;
918         struct msgbuf *mbp;
919         struct tty *tp;
920
921         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
922                               constty_td, SHUTDOWN_PRI_FIRST);
923         constty_td->td_flags |= TDF_SYSTHREAD;
924
925         mbp = msgbufp;
926         rindex = mbp->msg_bufr;         /* persistent loop variable */
927         xindex = mbp->msg_bufx - 1;     /* anything different than bufx */
928         cpu_ccfence();
929
930         for (;;) {
931                 kproc_suspend_loop();
932
933                 crit_enter();
934                 if (mbp != msgbufp)
935                         mbp = msgbufp;
936                 if (xindex == mbp->msg_bufx ||
937                     mbp == NULL ||
938                     msgbufmapped == 0) {
939                         tsleep(constty_td, 0, "waiting", hz*60);
940                         crit_exit();
941                         continue;
942                 }
943                 crit_exit();
944
945                 /*
946                  * Get message buf FIFO indices.  rindex is tracking.
947                  */
948                 xindex = mbp->msg_bufx;
949                 cpu_ccfence();
950                 if ((tp = constty) == NULL) {
951                         rindex = xindex;
952                         continue;
953                 }
954
955                 /*
956                  * Check if the calculated bytes has rolled the whole
957                  * message buffer.
958                  */
959                 n = xindex - rindex;
960                 if (n > mbp->msg_size - 1024) {
961                         rindex = xindex - mbp->msg_size + 2048;
962                         n = xindex - rindex;
963                 }
964
965                 /*
966                  * And dump it.  If constty gets stuck will give up.
967                  */
968                 while (rindex != xindex) {
969                         u_int ri = rindex % mbp->msg_size;
970                         if (tputchar((uint8_t)mbp->msg_ptr[ri], tp) < 0) {
971                                 constty = NULL;
972                                 rindex = xindex;
973                                 break;
974                         }
975                         if (tp->t_outq.c_cc >= tp->t_ohiwat) {
976                                 tsleep(constty_daemon, 0, "blocked", hz / 10);
977                                 if (tp->t_outq.c_cc >= tp->t_ohiwat) {
978                                         rindex = xindex;
979                                         break;
980                                 }
981                         }
982                         ++rindex;
983                 }
984         }
985 }
986
987 static struct kproc_desc constty_kp = {
988         "consttyd",
989         constty_daemon,
990         &constty_td
991 };
992 SYSINIT(bufdaemon, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY,
993         kproc_start, &constty_kp);
994
995 /*
996  * Put character in log buffer with a particular priority.
997  *
998  * MPSAFE
999  */
1000 static void
1001 msglogchar(int c, int pri)
1002 {
1003         static int lastpri = -1;
1004         static int dangling;
1005         char nbuf[MAXNBUF];
1006         char *p;
1007
1008         if (!msgbufmapped)
1009                 return;
1010         if (c == '\0' || c == '\r')
1011                 return;
1012         if (pri != -1 && pri != lastpri) {
1013                 if (dangling) {
1014                         msgaddchar('\n', NULL);
1015                         dangling = 0;
1016                 }
1017                 msgaddchar('<', NULL);
1018                 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
1019                         msgaddchar(*p--, NULL);
1020                 msgaddchar('>', NULL);
1021                 lastpri = pri;
1022         }
1023         msgaddchar(c, NULL);
1024         if (c == '\n') {
1025                 dangling = 0;
1026                 lastpri = -1;
1027         } else {
1028                 dangling = 1;
1029         }
1030 }
1031
1032 /*
1033  * Put char in log buffer.   Make sure nothing blows up beyond repair if
1034  * we have an MP race.
1035  *
1036  * MPSAFE.
1037  */
1038 static void
1039 msgaddchar(int c, void *dummy)
1040 {
1041         struct msgbuf *mbp;
1042         u_int lindex;
1043         u_int rindex;
1044         u_int xindex;
1045         u_int n;
1046
1047         if (!msgbufmapped)
1048                 return;
1049         mbp = msgbufp;
1050         lindex = mbp->msg_bufl;
1051         rindex = mbp->msg_bufr;
1052         xindex = mbp->msg_bufx++;       /* Allow SMP race */
1053         cpu_ccfence();
1054
1055         mbp->msg_ptr[xindex % mbp->msg_size] = c;
1056         n = xindex - lindex;
1057         if (n > mbp->msg_size - 1024) {
1058                 lindex = xindex - mbp->msg_size + 2048;
1059                 cpu_ccfence();
1060                 mbp->msg_bufl = lindex;
1061         }
1062         n = xindex - rindex;
1063         if (n > mbp->msg_size - 1024) {
1064                 rindex = xindex - mbp->msg_size + 2048;
1065                 cpu_ccfence();
1066                 mbp->msg_bufr = rindex;
1067         }
1068 }
1069
1070 static void
1071 msgbufcopy(struct msgbuf *oldp)
1072 {
1073         u_int rindex;
1074         u_int xindex;
1075         u_int n;
1076
1077         rindex = oldp->msg_bufr;
1078         xindex = oldp->msg_bufx;
1079         cpu_ccfence();
1080
1081         n = xindex - rindex;
1082         if (n > oldp->msg_size - 1024)
1083                 rindex = xindex - oldp->msg_size + 2048;
1084         while (rindex != xindex) {
1085                 msglogchar(oldp->msg_ptr[rindex % oldp->msg_size], -1);
1086                 ++rindex;
1087         }
1088 }
1089
1090 void
1091 msgbufinit(void *ptr, size_t size)
1092 {
1093         char *cp;
1094         static struct msgbuf *oldp = NULL;
1095
1096         size -= sizeof(*msgbufp);
1097         cp = (char *)ptr;
1098         msgbufp = (struct msgbuf *) (cp + size);
1099         if (msgbufp->msg_magic != MSG_MAGIC || msgbufp->msg_size != size) {
1100                 bzero(cp, size);
1101                 bzero(msgbufp, sizeof(*msgbufp));
1102                 msgbufp->msg_magic = MSG_MAGIC;
1103                 msgbufp->msg_size = (char *)msgbufp - cp;
1104         }
1105         msgbufp->msg_ptr = cp;
1106         if (msgbufmapped && oldp != msgbufp)
1107                 msgbufcopy(oldp);
1108         cpu_mfence();
1109         msgbufmapped = 1;
1110         oldp = msgbufp;
1111 }
1112
1113 /* Sysctls for accessing/clearing the msgbuf */
1114
1115 static int
1116 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1117 {
1118         struct msgbuf *mbp;
1119         struct ucred *cred;
1120         int error;
1121         u_int rindex_modulo;
1122         u_int xindex_modulo;
1123         u_int rindex;
1124         u_int xindex;
1125         u_int n;
1126
1127         /*
1128          * Only wheel or root can access the message log.
1129          */
1130         if (unprivileged_read_msgbuf == 0) {
1131                 KKASSERT(req->td->td_proc);
1132                 cred = req->td->td_proc->p_ucred;
1133
1134                 if ((cred->cr_prison || groupmember(0, cred) == 0) &&
1135                     priv_check(req->td, PRIV_ROOT) != 0
1136                 ) {
1137                         return (EPERM);
1138                 }
1139         }
1140
1141         /*
1142          * Unwind the buffer, so that it's linear (possibly starting with
1143          * some initial nulls).
1144          *
1145          * We don't push the entire buffer like we did before because
1146          * bufr (and bufl) now advance in chunks when the fifo is full,
1147          * rather than one character.
1148          */
1149         mbp = msgbufp;
1150         rindex = mbp->msg_bufr;
1151         xindex = mbp->msg_bufx;
1152         n = xindex - rindex;
1153         if (n > mbp->msg_size - 1024) {
1154                 rindex = xindex - mbp->msg_size + 2048;
1155                 n = xindex - rindex;
1156         }
1157         rindex_modulo = rindex % mbp->msg_size;
1158         xindex_modulo = xindex % mbp->msg_size;
1159
1160         if (rindex_modulo < xindex_modulo) {
1161                 /*
1162                  * Can handle in one linear section.
1163                  */
1164                 error = sysctl_handle_opaque(oidp,
1165                                              mbp->msg_ptr + rindex_modulo,
1166                                              xindex_modulo - rindex_modulo,
1167                                              req);
1168         } else if (rindex_modulo == xindex_modulo) {
1169                 /*
1170                  * Empty buffer, just return a single newline
1171                  */
1172                 error = sysctl_handle_opaque(oidp, "\n", 1, req);
1173         } else if (n <= mbp->msg_size - rindex_modulo) {
1174                 /*
1175                  * Can handle in one linear section.
1176                  */
1177                 error = sysctl_handle_opaque(oidp,
1178                                              mbp->msg_ptr + rindex_modulo,
1179                                              n - rindex_modulo,
1180                                              req);
1181         } else {
1182                 /*
1183                  * Glue together two linear sections into one contiguous
1184                  * output.
1185                  */
1186                 error = sysctl_handle_opaque(oidp,
1187                                              mbp->msg_ptr + rindex_modulo,
1188                                              mbp->msg_size - rindex_modulo,
1189                                              req);
1190                 n -= mbp->msg_size - rindex_modulo;
1191                 if (error == 0)
1192                         error = sysctl_handle_opaque(oidp, mbp->msg_ptr,
1193                                                      n, req);
1194         }
1195         if (error)
1196                 return (error);
1197         return (error);
1198 }
1199
1200 SYSCTL_PROC(_kern, OID_AUTO, msgbuf, CTLTYPE_STRING | CTLFLAG_RD,
1201     0, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1202
1203 static int msgbuf_clear;
1204
1205 static int
1206 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1207 {
1208         int error;
1209         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1210         if (!error && req->newptr) {
1211                 /* Clear the buffer and reset write pointer */
1212                 msgbufp->msg_bufr = msgbufp->msg_bufx;
1213                 msgbufp->msg_bufl = msgbufp->msg_bufx;
1214                 bzero(msgbufp->msg_ptr, msgbufp->msg_size);
1215                 msgbuf_clear = 0;
1216         }
1217         return (error);
1218 }
1219
1220 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1221     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE, &msgbuf_clear, 0,
1222     sysctl_kern_msgbuf_clear, "I", "Clear kernel message buffer");
1223
1224 #ifdef DDB
1225
1226 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1227 {
1228         u_int rindex;
1229         u_int i;
1230         u_int j;
1231
1232         if (!msgbufmapped) {
1233                 db_printf("msgbuf not mapped yet\n");
1234                 return;
1235         }
1236         db_printf("msgbufp = %p\n", msgbufp);
1237         db_printf("magic = %x, size = %d, r= %d, w = %d, ptr = %p\n",
1238                   msgbufp->msg_magic, msgbufp->msg_size,
1239                   msgbufp->msg_bufr % msgbufp->msg_size,
1240                   msgbufp->msg_bufx % msgbufp->msg_size,
1241                   msgbufp->msg_ptr);
1242
1243         rindex = msgbufp->msg_bufr;
1244         for (i = 0; i < msgbufp->msg_size; i++) {
1245                 j = (i + rindex) % msgbufp->msg_size;
1246                 db_printf("%c", msgbufp->msg_ptr[j]);
1247         }
1248         db_printf("\n");
1249 }
1250
1251 #endif /* DDB */
1252
1253
1254 void
1255 hexdump(const void *ptr, int length, const char *hdr, int flags)
1256 {
1257         int i, j, k;
1258         int cols;
1259         const unsigned char *cp;
1260         char delim;
1261
1262         if ((flags & HD_DELIM_MASK) != 0)
1263                 delim = (flags & HD_DELIM_MASK) >> 8;
1264         else
1265                 delim = ' ';
1266
1267         if ((flags & HD_COLUMN_MASK) != 0)
1268                 cols = flags & HD_COLUMN_MASK;
1269         else
1270                 cols = 16;
1271
1272         cp = ptr;
1273         for (i = 0; i < length; i+= cols) {
1274                 if (hdr != NULL)
1275                         kprintf("%s", hdr);
1276
1277                 if ((flags & HD_OMIT_COUNT) == 0)
1278                         kprintf("%04x  ", i);
1279
1280                 if ((flags & HD_OMIT_HEX) == 0) {
1281                         for (j = 0; j < cols; j++) {
1282                                 k = i + j;
1283                                 if (k < length)
1284                                         kprintf("%c%02x", delim, cp[k]);
1285                                 else
1286                                         kprintf("   ");
1287                         }
1288                 }
1289
1290                 if ((flags & HD_OMIT_CHARS) == 0) {
1291                         kprintf("  |");
1292                         for (j = 0; j < cols; j++) {
1293                                 k = i + j;
1294                                 if (k >= length)
1295                                         kprintf(" ");
1296                                 else if (cp[k] >= ' ' && cp[k] <= '~')
1297                                         kprintf("%c", cp[k]);
1298                                 else
1299                                         kprintf(".");
1300                         }
1301                         kprintf("|");
1302                 }
1303                 kprintf("\n");
1304         }
1305 }
1306
1307 void
1308 kprint_cpuset(cpumask_t *mask)
1309 {
1310         int i;
1311         int b = -1;
1312         int e = -1;
1313         int more = 0;
1314
1315         kprintf("cpus(");
1316         CPUSET_FOREACH(i, *mask) {
1317                 if (b < 0) {
1318                         b = i;
1319                         e = b + 1;
1320                         continue;
1321                 }
1322                 if (e == i) {
1323                         ++e;
1324                         continue;
1325                 }
1326                 if (more)
1327                         kprintf(", ");
1328                 if (b == e - 1) {
1329                         kprintf("%d", b);
1330                 } else {
1331                         kprintf("%d-%d", b, e - 1);
1332                 }
1333                 more = 1;
1334                 b = i;
1335                 e = b + 1;
1336         }
1337         if (more)
1338                 kprintf(", ");
1339         if (b >= 0) {
1340                 if (b == e - 1) {
1341                         kprintf("%d", b);
1342                 } else {
1343                         kprintf("%d-%d", b, e - 1);
1344                 }
1345         }
1346         kprintf(") ");
1347 }