]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/subr_prf.c
Merge compiler-rt trunk r321017 to contrib/compiler-rt.
[FreeBSD/FreeBSD.git] / sys / kern / subr_prf.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1986, 1988, 1991, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      @(#)subr_prf.c  8.3 (Berkeley) 1/21/94
37  */
38
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41
42 #ifdef _KERNEL
43 #include "opt_ddb.h"
44 #include "opt_printf.h"
45 #endif  /* _KERNEL */
46
47 #include <sys/param.h>
48 #ifdef _KERNEL
49 #include <sys/systm.h>
50 #include <sys/lock.h>
51 #include <sys/kdb.h>
52 #include <sys/mutex.h>
53 #include <sys/sx.h>
54 #include <sys/kernel.h>
55 #include <sys/msgbuf.h>
56 #include <sys/malloc.h>
57 #include <sys/priv.h>
58 #include <sys/proc.h>
59 #include <sys/stddef.h>
60 #include <sys/sysctl.h>
61 #include <sys/tty.h>
62 #include <sys/syslog.h>
63 #include <sys/cons.h>
64 #include <sys/uio.h>
65 #endif
66 #include <sys/ctype.h>
67 #include <sys/sbuf.h>
68
69 #ifdef DDB
70 #include <ddb/ddb.h>
71 #endif
72
73 /*
74  * Note that stdarg.h and the ANSI style va_start macro is used for both
75  * ANSI and traditional C compilers.
76  */
77 #ifdef _KERNEL
78 #include <machine/stdarg.h>
79 #else
80 #include <stdarg.h>
81 #endif
82
83 /*
84  * This is needed for sbuf_putbuf() when compiled into userland.  Due to the
85  * shared nature of this file, it's the only place to put it.
86  */
87 #ifndef _KERNEL
88 #include <stdio.h>
89 #endif
90
91 #ifdef _KERNEL
92
93 #define TOCONS  0x01
94 #define TOTTY   0x02
95 #define TOLOG   0x04
96
97 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */
98 #define MAXNBUF (sizeof(intmax_t) * NBBY + 1)
99
100 struct putchar_arg {
101         int     flags;
102         int     pri;
103         struct  tty *tty;
104         char    *p_bufr;
105         size_t  n_bufr;
106         char    *p_next;
107         size_t  remain;
108 };
109
110 struct snprintf_arg {
111         char    *str;
112         size_t  remain;
113 };
114
115 extern  int log_open;
116
117 static void  msglogchar(int c, int pri);
118 static void  msglogstr(char *str, int pri, int filter_cr);
119 static void  putchar(int ch, void *arg);
120 static char *ksprintn(char *nbuf, uintmax_t num, int base, int *len, int upper);
121 static void  snprintf_func(int ch, void *arg);
122
123 static int msgbufmapped;                /* Set when safe to use msgbuf */
124 int msgbuftrigger;
125 struct msgbuf *msgbufp;
126
127 static int log_console_output = 1;
128 SYSCTL_INT(_kern, OID_AUTO, log_console_output, CTLFLAG_RWTUN,
129     &log_console_output, 0, "Duplicate console output to the syslog");
130
131 /*
132  * See the comment in log_console() below for more explanation of this.
133  */
134 static int log_console_add_linefeed;
135 SYSCTL_INT(_kern, OID_AUTO, log_console_add_linefeed, CTLFLAG_RWTUN,
136     &log_console_add_linefeed, 0, "log_console() adds extra newlines");
137
138 static int always_console_output;
139 SYSCTL_INT(_kern, OID_AUTO, always_console_output, CTLFLAG_RWTUN,
140     &always_console_output, 0, "Always output to console despite TIOCCONS");
141
142 /*
143  * Warn that a system table is full.
144  */
145 void
146 tablefull(const char *tab)
147 {
148
149         log(LOG_ERR, "%s: table is full\n", tab);
150 }
151
152 /*
153  * Uprintf prints to the controlling terminal for the current process.
154  */
155 int
156 uprintf(const char *fmt, ...)
157 {
158         va_list ap;
159         struct putchar_arg pca;
160         struct proc *p;
161         struct thread *td;
162         int retval;
163
164         td = curthread;
165         if (TD_IS_IDLETHREAD(td))
166                 return (0);
167
168         sx_slock(&proctree_lock);
169         p = td->td_proc;
170         PROC_LOCK(p);
171         if ((p->p_flag & P_CONTROLT) == 0) {
172                 PROC_UNLOCK(p);
173                 sx_sunlock(&proctree_lock);
174                 return (0);
175         }
176         SESS_LOCK(p->p_session);
177         pca.tty = p->p_session->s_ttyp;
178         SESS_UNLOCK(p->p_session);
179         PROC_UNLOCK(p);
180         if (pca.tty == NULL) {
181                 sx_sunlock(&proctree_lock);
182                 return (0);
183         }
184         pca.flags = TOTTY;
185         pca.p_bufr = NULL;
186         va_start(ap, fmt);
187         tty_lock(pca.tty);
188         sx_sunlock(&proctree_lock);
189         retval = kvprintf(fmt, putchar, &pca, 10, ap);
190         tty_unlock(pca.tty);
191         va_end(ap);
192         return (retval);
193 }
194
195 /*
196  * tprintf and vtprintf print on the controlling terminal associated with the
197  * given session, possibly to the log as well.
198  */
199 void
200 tprintf(struct proc *p, int pri, const char *fmt, ...)
201 {
202         va_list ap;
203
204         va_start(ap, fmt);
205         vtprintf(p, pri, fmt, ap);
206         va_end(ap);
207 }
208
209 void
210 vtprintf(struct proc *p, int pri, const char *fmt, va_list ap)
211 {
212         struct tty *tp = NULL;
213         int flags = 0;
214         struct putchar_arg pca;
215         struct session *sess = NULL;
216
217         sx_slock(&proctree_lock);
218         if (pri != -1)
219                 flags |= TOLOG;
220         if (p != NULL) {
221                 PROC_LOCK(p);
222                 if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
223                         sess = p->p_session;
224                         sess_hold(sess);
225                         PROC_UNLOCK(p);
226                         tp = sess->s_ttyp;
227                         if (tp != NULL && tty_checkoutq(tp))
228                                 flags |= TOTTY;
229                         else
230                                 tp = NULL;
231                 } else
232                         PROC_UNLOCK(p);
233         }
234         pca.pri = pri;
235         pca.tty = tp;
236         pca.flags = flags;
237         pca.p_bufr = NULL;
238         if (pca.tty != NULL)
239                 tty_lock(pca.tty);
240         sx_sunlock(&proctree_lock);
241         kvprintf(fmt, putchar, &pca, 10, ap);
242         if (pca.tty != NULL)
243                 tty_unlock(pca.tty);
244         if (sess != NULL)
245                 sess_release(sess);
246         msgbuftrigger = 1;
247 }
248
249 /*
250  * Ttyprintf displays a message on a tty; it should be used only by
251  * the tty driver, or anything that knows the underlying tty will not
252  * be revoke(2)'d away.  Other callers should use tprintf.
253  */
254 int
255 ttyprintf(struct tty *tp, const char *fmt, ...)
256 {
257         va_list ap;
258         struct putchar_arg pca;
259         int retval;
260
261         va_start(ap, fmt);
262         pca.tty = tp;
263         pca.flags = TOTTY;
264         pca.p_bufr = NULL;
265         retval = kvprintf(fmt, putchar, &pca, 10, ap);
266         va_end(ap);
267         return (retval);
268 }
269
270 static int
271 _vprintf(int level, int flags, const char *fmt, va_list ap)
272 {
273         struct putchar_arg pca;
274         int retval;
275 #ifdef PRINTF_BUFR_SIZE
276         char bufr[PRINTF_BUFR_SIZE];
277 #endif
278
279         pca.tty = NULL;
280         pca.pri = level;
281         pca.flags = flags;
282 #ifdef PRINTF_BUFR_SIZE
283         pca.p_bufr = bufr;
284         pca.p_next = pca.p_bufr;
285         pca.n_bufr = sizeof(bufr);
286         pca.remain = sizeof(bufr);
287         *pca.p_next = '\0';
288 #else
289         /* Don't buffer console output. */
290         pca.p_bufr = NULL;
291 #endif
292
293         retval = kvprintf(fmt, putchar, &pca, 10, ap);
294
295 #ifdef PRINTF_BUFR_SIZE
296         /* Write any buffered console/log output: */
297         if (*pca.p_bufr != '\0') {
298                 if (pca.flags & TOLOG)
299                         msglogstr(pca.p_bufr, level, /*filter_cr*/1);
300
301                 if (pca.flags & TOCONS)
302                         cnputs(pca.p_bufr);
303         }
304 #endif
305
306         return (retval);
307 }
308
309 /*
310  * Log writes to the log buffer, and guarantees not to sleep (so can be
311  * called by interrupt routines).  If there is no process reading the
312  * log yet, it writes to the console also.
313  */
314 void
315 log(int level, const char *fmt, ...)
316 {
317         va_list ap;
318
319         va_start(ap, fmt);
320         vlog(level, fmt, ap);
321         va_end(ap);
322 }
323
324 void
325 vlog(int level, const char *fmt, va_list ap)
326 {
327
328         (void)_vprintf(level, log_open ? TOLOG : TOCONS | TOLOG, fmt, ap);
329         msgbuftrigger = 1;
330 }
331
332 #define CONSCHUNK 128
333
334 void
335 log_console(struct uio *uio)
336 {
337         int c, error, nl;
338         char *consbuffer;
339         int pri;
340
341         if (!log_console_output)
342                 return;
343
344         pri = LOG_INFO | LOG_CONSOLE;
345         uio = cloneuio(uio);
346         consbuffer = malloc(CONSCHUNK, M_TEMP, M_WAITOK);
347
348         nl = 0;
349         while (uio->uio_resid > 0) {
350                 c = imin(uio->uio_resid, CONSCHUNK - 1);
351                 error = uiomove(consbuffer, c, uio);
352                 if (error != 0)
353                         break;
354                 /* Make sure we're NUL-terminated */
355                 consbuffer[c] = '\0';
356                 if (consbuffer[c - 1] == '\n')
357                         nl = 1;
358                 else
359                         nl = 0;
360                 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
361         }
362         /*
363          * The previous behavior in log_console() is preserved when
364          * log_console_add_linefeed is non-zero.  For that behavior, if an
365          * individual console write came in that was not terminated with a
366          * line feed, it would add a line feed.
367          *
368          * This results in different data in the message buffer than
369          * appears on the system console (which doesn't add extra line feed
370          * characters).
371          *
372          * A number of programs and rc scripts write a line feed, or a period
373          * and a line feed when they have completed their operation.  On
374          * the console, this looks seamless, but when displayed with
375          * 'dmesg -a', you wind up with output that looks like this:
376          *
377          * Updating motd:
378          * .
379          *
380          * On the console, it looks like this:
381          * Updating motd:.
382          *
383          * We could add logic to detect that situation, or just not insert
384          * the extra newlines.  Set the kern.log_console_add_linefeed
385          * sysctl/tunable variable to get the old behavior.
386          */
387         if (!nl && log_console_add_linefeed) {
388                 consbuffer[0] = '\n';
389                 consbuffer[1] = '\0';
390                 msglogstr(consbuffer, pri, /*filter_cr*/ 1);
391         }
392         msgbuftrigger = 1;
393         free(uio, M_IOV);
394         free(consbuffer, M_TEMP);
395 }
396
397 int
398 printf(const char *fmt, ...)
399 {
400         va_list ap;
401         int retval;
402
403         va_start(ap, fmt);
404         retval = vprintf(fmt, ap);
405         va_end(ap);
406
407         return (retval);
408 }
409
410 int
411 vprintf(const char *fmt, va_list ap)
412 {
413         int retval;
414
415         retval = _vprintf(-1, TOCONS | TOLOG, fmt, ap);
416
417         if (!panicstr)
418                 msgbuftrigger = 1;
419
420         return (retval);
421 }
422
423 static void
424 prf_putbuf(char *bufr, int flags, int pri)
425 {
426
427         if (flags & TOLOG)
428                 msglogstr(bufr, pri, /*filter_cr*/1);
429
430         if (flags & TOCONS) {
431                 if ((panicstr == NULL) && (constty != NULL))
432                         msgbuf_addstr(&consmsgbuf, -1,
433                             bufr, /*filter_cr*/ 0);
434
435                 if ((constty == NULL) ||(always_console_output))
436                         cnputs(bufr);
437         }
438 }
439
440 static void
441 putbuf(int c, struct putchar_arg *ap)
442 {
443         /* Check if no console output buffer was provided. */
444         if (ap->p_bufr == NULL) {
445                 /* Output direct to the console. */
446                 if (ap->flags & TOCONS)
447                         cnputc(c);
448
449                 if (ap->flags & TOLOG)
450                         msglogchar(c, ap->pri);
451         } else {
452                 /* Buffer the character: */
453                 *ap->p_next++ = c;
454                 ap->remain--;
455
456                 /* Always leave the buffer zero terminated. */
457                 *ap->p_next = '\0';
458
459                 /* Check if the buffer needs to be flushed. */
460                 if (ap->remain == 2 || c == '\n') {
461                         prf_putbuf(ap->p_bufr, ap->flags, ap->pri);
462
463                         ap->p_next = ap->p_bufr;
464                         ap->remain = ap->n_bufr;
465                         *ap->p_next = '\0';
466                 }
467
468                 /*
469                  * Since we fill the buffer up one character at a time,
470                  * this should not happen.  We should always catch it when
471                  * ap->remain == 2 (if not sooner due to a newline), flush
472                  * the buffer and move on.  One way this could happen is
473                  * if someone sets PRINTF_BUFR_SIZE to 1 or something
474                  * similarly silly.
475                  */
476                 KASSERT(ap->remain > 2, ("Bad buffer logic, remain = %zd",
477                     ap->remain));
478         }
479 }
480
481 /*
482  * Print a character on console or users terminal.  If destination is
483  * the console then the last bunch of characters are saved in msgbuf for
484  * inspection later.
485  */
486 static void
487 putchar(int c, void *arg)
488 {
489         struct putchar_arg *ap = (struct putchar_arg*) arg;
490         struct tty *tp = ap->tty;
491         int flags = ap->flags;
492
493         /* Don't use the tty code after a panic or while in ddb. */
494         if (kdb_active) {
495                 if (c != '\0')
496                         cnputc(c);
497                 return;
498         }
499
500         if ((flags & TOTTY) && tp != NULL && panicstr == NULL)
501                 tty_putchar(tp, c);
502
503         if ((flags & (TOCONS | TOLOG)) && c != '\0')
504                 putbuf(c, ap);
505 }
506
507 /*
508  * Scaled down version of sprintf(3).
509  */
510 int
511 sprintf(char *buf, const char *cfmt, ...)
512 {
513         int retval;
514         va_list ap;
515
516         va_start(ap, cfmt);
517         retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
518         buf[retval] = '\0';
519         va_end(ap);
520         return (retval);
521 }
522
523 /*
524  * Scaled down version of vsprintf(3).
525  */
526 int
527 vsprintf(char *buf, const char *cfmt, va_list ap)
528 {
529         int retval;
530
531         retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap);
532         buf[retval] = '\0';
533         return (retval);
534 }
535
536 /*
537  * Scaled down version of snprintf(3).
538  */
539 int
540 snprintf(char *str, size_t size, const char *format, ...)
541 {
542         int retval;
543         va_list ap;
544
545         va_start(ap, format);
546         retval = vsnprintf(str, size, format, ap);
547         va_end(ap);
548         return(retval);
549 }
550
551 /*
552  * Scaled down version of vsnprintf(3).
553  */
554 int
555 vsnprintf(char *str, size_t size, const char *format, va_list ap)
556 {
557         struct snprintf_arg info;
558         int retval;
559
560         info.str = str;
561         info.remain = size;
562         retval = kvprintf(format, snprintf_func, &info, 10, ap);
563         if (info.remain >= 1)
564                 *info.str++ = '\0';
565         return (retval);
566 }
567
568 /*
569  * Kernel version which takes radix argument vsnprintf(3).
570  */
571 int
572 vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap)
573 {
574         struct snprintf_arg info;
575         int retval;
576
577         info.str = str;
578         info.remain = size;
579         retval = kvprintf(format, snprintf_func, &info, radix, ap);
580         if (info.remain >= 1)
581                 *info.str++ = '\0';
582         return (retval);
583 }
584
585 static void
586 snprintf_func(int ch, void *arg)
587 {
588         struct snprintf_arg *const info = arg;
589
590         if (info->remain >= 2) {
591                 *info->str++ = ch;
592                 info->remain--;
593         }
594 }
595
596 /*
597  * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse
598  * order; return an optional length and a pointer to the last character
599  * written in the buffer (i.e., the first character of the string).
600  * The buffer pointed to by `nbuf' must have length >= MAXNBUF.
601  */
602 static char *
603 ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper)
604 {
605         char *p, c;
606
607         p = nbuf;
608         *p = '\0';
609         do {
610                 c = hex2ascii(num % base);
611                 *++p = upper ? toupper(c) : c;
612         } while (num /= base);
613         if (lenp)
614                 *lenp = p - nbuf;
615         return (p);
616 }
617
618 /*
619  * Scaled down version of printf(3).
620  *
621  * Two additional formats:
622  *
623  * The format %b is supported to decode error registers.
624  * Its usage is:
625  *
626  *      printf("reg=%b\n", regval, "<base><arg>*");
627  *
628  * where <base> is the output base expressed as a control character, e.g.
629  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
630  * the first of which gives the bit number to be inspected (origin 1), and
631  * the next characters (up to a control character, i.e. a character <= 32),
632  * give the name of the register.  Thus:
633  *
634  *      kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE");
635  *
636  * would produce output:
637  *
638  *      reg=3<BITTWO,BITONE>
639  *
640  * XXX:  %D  -- Hexdump, takes pointer and separator string:
641  *              ("%6D", ptr, ":")   -> XX:XX:XX:XX:XX:XX
642  *              ("%*D", len, ptr, " " -> XX XX XX XX ...
643  */
644 int
645 kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap)
646 {
647 #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; }
648         char nbuf[MAXNBUF];
649         char *d;
650         const char *p, *percent, *q;
651         u_char *up;
652         int ch, n;
653         uintmax_t num;
654         int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot;
655         int cflag, hflag, jflag, tflag, zflag;
656         int bconv, dwidth, upper;
657         char padc;
658         int stop = 0, retval = 0;
659
660         num = 0;
661         if (!func)
662                 d = (char *) arg;
663         else
664                 d = NULL;
665
666         if (fmt == NULL)
667                 fmt = "(fmt null)\n";
668
669         if (radix < 2 || radix > 36)
670                 radix = 10;
671
672         for (;;) {
673                 padc = ' ';
674                 width = 0;
675                 while ((ch = (u_char)*fmt++) != '%' || stop) {
676                         if (ch == '\0')
677                                 return (retval);
678                         PCHAR(ch);
679                 }
680                 percent = fmt - 1;
681                 qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0;
682                 sign = 0; dot = 0; bconv = 0; dwidth = 0; upper = 0;
683                 cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0;
684 reswitch:       switch (ch = (u_char)*fmt++) {
685                 case '.':
686                         dot = 1;
687                         goto reswitch;
688                 case '#':
689                         sharpflag = 1;
690                         goto reswitch;
691                 case '+':
692                         sign = 1;
693                         goto reswitch;
694                 case '-':
695                         ladjust = 1;
696                         goto reswitch;
697                 case '%':
698                         PCHAR(ch);
699                         break;
700                 case '*':
701                         if (!dot) {
702                                 width = va_arg(ap, int);
703                                 if (width < 0) {
704                                         ladjust = !ladjust;
705                                         width = -width;
706                                 }
707                         } else {
708                                 dwidth = va_arg(ap, int);
709                         }
710                         goto reswitch;
711                 case '0':
712                         if (!dot) {
713                                 padc = '0';
714                                 goto reswitch;
715                         }
716                 case '1': case '2': case '3': case '4':
717                 case '5': case '6': case '7': case '8': case '9':
718                                 for (n = 0;; ++fmt) {
719                                         n = n * 10 + ch - '0';
720                                         ch = *fmt;
721                                         if (ch < '0' || ch > '9')
722                                                 break;
723                                 }
724                         if (dot)
725                                 dwidth = n;
726                         else
727                                 width = n;
728                         goto reswitch;
729                 case 'b':
730                         ladjust = 1;
731                         bconv = 1;
732                         goto handle_nosign;
733                 case 'c':
734                         width -= 1;
735
736                         if (!ladjust && width > 0)
737                                 while (width--)
738                                         PCHAR(padc);
739                         PCHAR(va_arg(ap, int));
740                         if (ladjust && width > 0)
741                                 while (width--)
742                                         PCHAR(padc);
743                         break;
744                 case 'D':
745                         up = va_arg(ap, u_char *);
746                         p = va_arg(ap, char *);
747                         if (!width)
748                                 width = 16;
749                         while(width--) {
750                                 PCHAR(hex2ascii(*up >> 4));
751                                 PCHAR(hex2ascii(*up & 0x0f));
752                                 up++;
753                                 if (width)
754                                         for (q=p;*q;q++)
755                                                 PCHAR(*q);
756                         }
757                         break;
758                 case 'd':
759                 case 'i':
760                         base = 10;
761                         sign = 1;
762                         goto handle_sign;
763                 case 'h':
764                         if (hflag) {
765                                 hflag = 0;
766                                 cflag = 1;
767                         } else
768                                 hflag = 1;
769                         goto reswitch;
770                 case 'j':
771                         jflag = 1;
772                         goto reswitch;
773                 case 'l':
774                         if (lflag) {
775                                 lflag = 0;
776                                 qflag = 1;
777                         } else
778                                 lflag = 1;
779                         goto reswitch;
780                 case 'n':
781                         if (jflag)
782                                 *(va_arg(ap, intmax_t *)) = retval;
783                         else if (qflag)
784                                 *(va_arg(ap, quad_t *)) = retval;
785                         else if (lflag)
786                                 *(va_arg(ap, long *)) = retval;
787                         else if (zflag)
788                                 *(va_arg(ap, size_t *)) = retval;
789                         else if (hflag)
790                                 *(va_arg(ap, short *)) = retval;
791                         else if (cflag)
792                                 *(va_arg(ap, char *)) = retval;
793                         else
794                                 *(va_arg(ap, int *)) = retval;
795                         break;
796                 case 'o':
797                         base = 8;
798                         goto handle_nosign;
799                 case 'p':
800                         base = 16;
801                         sharpflag = (width == 0);
802                         sign = 0;
803                         num = (uintptr_t)va_arg(ap, void *);
804                         goto number;
805                 case 'q':
806                         qflag = 1;
807                         goto reswitch;
808                 case 'r':
809                         base = radix;
810                         if (sign)
811                                 goto handle_sign;
812                         goto handle_nosign;
813                 case 's':
814                         p = va_arg(ap, char *);
815                         if (p == NULL)
816                                 p = "(null)";
817                         if (!dot)
818                                 n = strlen (p);
819                         else
820                                 for (n = 0; n < dwidth && p[n]; n++)
821                                         continue;
822
823                         width -= n;
824
825                         if (!ladjust && width > 0)
826                                 while (width--)
827                                         PCHAR(padc);
828                         while (n--)
829                                 PCHAR(*p++);
830                         if (ladjust && width > 0)
831                                 while (width--)
832                                         PCHAR(padc);
833                         break;
834                 case 't':
835                         tflag = 1;
836                         goto reswitch;
837                 case 'u':
838                         base = 10;
839                         goto handle_nosign;
840                 case 'X':
841                         upper = 1;
842                 case 'x':
843                         base = 16;
844                         goto handle_nosign;
845                 case 'y':
846                         base = 16;
847                         sign = 1;
848                         goto handle_sign;
849                 case 'z':
850                         zflag = 1;
851                         goto reswitch;
852 handle_nosign:
853                         sign = 0;
854                         if (jflag)
855                                 num = va_arg(ap, uintmax_t);
856                         else if (qflag)
857                                 num = va_arg(ap, u_quad_t);
858                         else if (tflag)
859                                 num = va_arg(ap, ptrdiff_t);
860                         else if (lflag)
861                                 num = va_arg(ap, u_long);
862                         else if (zflag)
863                                 num = va_arg(ap, size_t);
864                         else if (hflag)
865                                 num = (u_short)va_arg(ap, int);
866                         else if (cflag)
867                                 num = (u_char)va_arg(ap, int);
868                         else
869                                 num = va_arg(ap, u_int);
870                         if (bconv) {
871                                 q = va_arg(ap, char *);
872                                 base = *q++;
873                         }
874                         goto number;
875 handle_sign:
876                         if (jflag)
877                                 num = va_arg(ap, intmax_t);
878                         else if (qflag)
879                                 num = va_arg(ap, quad_t);
880                         else if (tflag)
881                                 num = va_arg(ap, ptrdiff_t);
882                         else if (lflag)
883                                 num = va_arg(ap, long);
884                         else if (zflag)
885                                 num = va_arg(ap, ssize_t);
886                         else if (hflag)
887                                 num = (short)va_arg(ap, int);
888                         else if (cflag)
889                                 num = (char)va_arg(ap, int);
890                         else
891                                 num = va_arg(ap, int);
892 number:
893                         if (sign && (intmax_t)num < 0) {
894                                 neg = 1;
895                                 num = -(intmax_t)num;
896                         }
897                         p = ksprintn(nbuf, num, base, &n, upper);
898                         tmp = 0;
899                         if (sharpflag && num != 0) {
900                                 if (base == 8)
901                                         tmp++;
902                                 else if (base == 16)
903                                         tmp += 2;
904                         }
905                         if (neg)
906                                 tmp++;
907
908                         if (!ladjust && padc == '0')
909                                 dwidth = width - tmp;
910                         width -= tmp + imax(dwidth, n);
911                         dwidth -= n;
912                         if (!ladjust)
913                                 while (width-- > 0)
914                                         PCHAR(' ');
915                         if (neg)
916                                 PCHAR('-');
917                         if (sharpflag && num != 0) {
918                                 if (base == 8) {
919                                         PCHAR('0');
920                                 } else if (base == 16) {
921                                         PCHAR('0');
922                                         PCHAR('x');
923                                 }
924                         }
925                         while (dwidth-- > 0)
926                                 PCHAR('0');
927
928                         while (*p)
929                                 PCHAR(*p--);
930
931                         if (bconv && num != 0) {
932                                 /* %b conversion flag format. */
933                                 tmp = retval;
934                                 while (*q) {
935                                         n = *q++;
936                                         if (num & (1 << (n - 1))) {
937                                                 PCHAR(retval != tmp ?
938                                                     ',' : '<');
939                                                 for (; (n = *q) > ' '; ++q)
940                                                         PCHAR(n);
941                                         } else
942                                                 for (; *q > ' '; ++q)
943                                                         continue;
944                                 }
945                                 if (retval != tmp) {
946                                         PCHAR('>');
947                                         width -= retval - tmp;
948                                 }
949                         }
950
951                         if (ladjust)
952                                 while (width-- > 0)
953                                         PCHAR(' ');
954
955                         break;
956                 default:
957                         while (percent < fmt)
958                                 PCHAR(*percent++);
959                         /*
960                          * Since we ignore a formatting argument it is no
961                          * longer safe to obey the remaining formatting
962                          * arguments as the arguments will no longer match
963                          * the format specs.
964                          */
965                         stop = 1;
966                         break;
967                 }
968         }
969 #undef PCHAR
970 }
971
972 /*
973  * Put character in log buffer with a particular priority.
974  */
975 static void
976 msglogchar(int c, int pri)
977 {
978         static int lastpri = -1;
979         static int dangling;
980         char nbuf[MAXNBUF];
981         char *p;
982
983         if (!msgbufmapped)
984                 return;
985         if (c == '\0' || c == '\r')
986                 return;
987         if (pri != -1 && pri != lastpri) {
988                 if (dangling) {
989                         msgbuf_addchar(msgbufp, '\n');
990                         dangling = 0;
991                 }
992                 msgbuf_addchar(msgbufp, '<');
993                 for (p = ksprintn(nbuf, (uintmax_t)pri, 10, NULL, 0); *p;)
994                         msgbuf_addchar(msgbufp, *p--);
995                 msgbuf_addchar(msgbufp, '>');
996                 lastpri = pri;
997         }
998         msgbuf_addchar(msgbufp, c);
999         if (c == '\n') {
1000                 dangling = 0;
1001                 lastpri = -1;
1002         } else {
1003                 dangling = 1;
1004         }
1005 }
1006
1007 static void
1008 msglogstr(char *str, int pri, int filter_cr)
1009 {
1010         if (!msgbufmapped)
1011                 return;
1012
1013         msgbuf_addstr(msgbufp, pri, str, filter_cr);
1014 }
1015
1016 void
1017 msgbufinit(void *ptr, int size)
1018 {
1019         char *cp;
1020         static struct msgbuf *oldp = NULL;
1021
1022         size -= sizeof(*msgbufp);
1023         cp = (char *)ptr;
1024         msgbufp = (struct msgbuf *)(cp + size);
1025         msgbuf_reinit(msgbufp, cp, size);
1026         if (msgbufmapped && oldp != msgbufp)
1027                 msgbuf_copy(oldp, msgbufp);
1028         msgbufmapped = 1;
1029         oldp = msgbufp;
1030 }
1031
1032 static int unprivileged_read_msgbuf = 1;
1033 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_read_msgbuf,
1034     CTLFLAG_RW, &unprivileged_read_msgbuf, 0,
1035     "Unprivileged processes may read the kernel message buffer");
1036
1037 /* Sysctls for accessing/clearing the msgbuf */
1038 static int
1039 sysctl_kern_msgbuf(SYSCTL_HANDLER_ARGS)
1040 {
1041         char buf[128];
1042         u_int seq;
1043         int error, len;
1044
1045         if (!unprivileged_read_msgbuf) {
1046                 error = priv_check(req->td, PRIV_MSGBUF);
1047                 if (error)
1048                         return (error);
1049         }
1050
1051         /* Read the whole buffer, one chunk at a time. */
1052         mtx_lock(&msgbuf_lock);
1053         msgbuf_peekbytes(msgbufp, NULL, 0, &seq);
1054         for (;;) {
1055                 len = msgbuf_peekbytes(msgbufp, buf, sizeof(buf), &seq);
1056                 mtx_unlock(&msgbuf_lock);
1057                 if (len == 0)
1058                         return (SYSCTL_OUT(req, "", 1)); /* add nulterm */
1059
1060                 error = sysctl_handle_opaque(oidp, buf, len, req);
1061                 if (error)
1062                         return (error);
1063
1064                 mtx_lock(&msgbuf_lock);
1065         }
1066 }
1067
1068 SYSCTL_PROC(_kern, OID_AUTO, msgbuf,
1069     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
1070     NULL, 0, sysctl_kern_msgbuf, "A", "Contents of kernel message buffer");
1071
1072 static int msgbuf_clearflag;
1073
1074 static int
1075 sysctl_kern_msgbuf_clear(SYSCTL_HANDLER_ARGS)
1076 {
1077         int error;
1078         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
1079         if (!error && req->newptr) {
1080                 mtx_lock(&msgbuf_lock);
1081                 msgbuf_clear(msgbufp);
1082                 mtx_unlock(&msgbuf_lock);
1083                 msgbuf_clearflag = 0;
1084         }
1085         return (error);
1086 }
1087
1088 SYSCTL_PROC(_kern, OID_AUTO, msgbuf_clear,
1089     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE | CTLFLAG_MPSAFE,
1090     &msgbuf_clearflag, 0, sysctl_kern_msgbuf_clear, "I",
1091     "Clear kernel message buffer");
1092
1093 #ifdef DDB
1094
1095 DB_SHOW_COMMAND(msgbuf, db_show_msgbuf)
1096 {
1097         int i, j;
1098
1099         if (!msgbufmapped) {
1100                 db_printf("msgbuf not mapped yet\n");
1101                 return;
1102         }
1103         db_printf("msgbufp = %p\n", msgbufp);
1104         db_printf("magic = %x, size = %d, r= %u, w = %u, ptr = %p, cksum= %u\n",
1105             msgbufp->msg_magic, msgbufp->msg_size, msgbufp->msg_rseq,
1106             msgbufp->msg_wseq, msgbufp->msg_ptr, msgbufp->msg_cksum);
1107         for (i = 0; i < msgbufp->msg_size && !db_pager_quit; i++) {
1108                 j = MSGBUF_SEQ_TO_POS(msgbufp, i + msgbufp->msg_rseq);
1109                 db_printf("%c", msgbufp->msg_ptr[j]);
1110         }
1111         db_printf("\n");
1112 }
1113
1114 #endif /* DDB */
1115
1116 void
1117 hexdump(const void *ptr, int length, const char *hdr, int flags)
1118 {
1119         int i, j, k;
1120         int cols;
1121         const unsigned char *cp;
1122         char delim;
1123
1124         if ((flags & HD_DELIM_MASK) != 0)
1125                 delim = (flags & HD_DELIM_MASK) >> 8;
1126         else
1127                 delim = ' ';
1128
1129         if ((flags & HD_COLUMN_MASK) != 0)
1130                 cols = flags & HD_COLUMN_MASK;
1131         else
1132                 cols = 16;
1133
1134         cp = ptr;
1135         for (i = 0; i < length; i+= cols) {
1136                 if (hdr != NULL)
1137                         printf("%s", hdr);
1138
1139                 if ((flags & HD_OMIT_COUNT) == 0)
1140                         printf("%04x  ", i);
1141
1142                 if ((flags & HD_OMIT_HEX) == 0) {
1143                         for (j = 0; j < cols; j++) {
1144                                 k = i + j;
1145                                 if (k < length)
1146                                         printf("%c%02x", delim, cp[k]);
1147                                 else
1148                                         printf("   ");
1149                         }
1150                 }
1151
1152                 if ((flags & HD_OMIT_CHARS) == 0) {
1153                         printf("  |");
1154                         for (j = 0; j < cols; j++) {
1155                                 k = i + j;
1156                                 if (k >= length)
1157                                         printf(" ");
1158                                 else if (cp[k] >= ' ' && cp[k] <= '~')
1159                                         printf("%c", cp[k]);
1160                                 else
1161                                         printf(".");
1162                         }
1163                         printf("|");
1164                 }
1165                 printf("\n");
1166         }
1167 }
1168 #endif /* _KERNEL */
1169
1170 void
1171 sbuf_hexdump(struct sbuf *sb, const void *ptr, int length, const char *hdr,
1172              int flags)
1173 {
1174         int i, j, k;
1175         int cols;
1176         const unsigned char *cp;
1177         char delim;
1178
1179         if ((flags & HD_DELIM_MASK) != 0)
1180                 delim = (flags & HD_DELIM_MASK) >> 8;
1181         else
1182                 delim = ' ';
1183
1184         if ((flags & HD_COLUMN_MASK) != 0)
1185                 cols = flags & HD_COLUMN_MASK;
1186         else
1187                 cols = 16;
1188
1189         cp = ptr;
1190         for (i = 0; i < length; i+= cols) {
1191                 if (hdr != NULL)
1192                         sbuf_printf(sb, "%s", hdr);
1193
1194                 if ((flags & HD_OMIT_COUNT) == 0)
1195                         sbuf_printf(sb, "%04x  ", i);
1196
1197                 if ((flags & HD_OMIT_HEX) == 0) {
1198                         for (j = 0; j < cols; j++) {
1199                                 k = i + j;
1200                                 if (k < length)
1201                                         sbuf_printf(sb, "%c%02x", delim, cp[k]);
1202                                 else
1203                                         sbuf_printf(sb, "   ");
1204                         }
1205                 }
1206
1207                 if ((flags & HD_OMIT_CHARS) == 0) {
1208                         sbuf_printf(sb, "  |");
1209                         for (j = 0; j < cols; j++) {
1210                                 k = i + j;
1211                                 if (k >= length)
1212                                         sbuf_printf(sb, " ");
1213                                 else if (cp[k] >= ' ' && cp[k] <= '~')
1214                                         sbuf_printf(sb, "%c", cp[k]);
1215                                 else
1216                                         sbuf_printf(sb, ".");
1217                         }
1218                         sbuf_printf(sb, "|");
1219                 }
1220                 sbuf_printf(sb, "\n");
1221         }
1222 }
1223
1224 #ifdef _KERNEL
1225 void
1226 counted_warning(unsigned *counter, const char *msg)
1227 {
1228         struct thread *td;
1229         unsigned c;
1230
1231         for (;;) {
1232                 c = *counter;
1233                 if (c == 0)
1234                         break;
1235                 if (atomic_cmpset_int(counter, c, c - 1)) {
1236                         td = curthread;
1237                         log(LOG_INFO, "pid %d (%s) %s%s\n",
1238                             td->td_proc->p_pid, td->td_name, msg,
1239                             c > 1 ? "" : " - not logging anymore");
1240                         break;
1241                 }
1242         }
1243 }
1244 #endif
1245
1246 #ifdef _KERNEL
1247 void
1248 sbuf_putbuf(struct sbuf *sb)
1249 {
1250
1251         prf_putbuf(sbuf_data(sb), TOLOG | TOCONS, -1);
1252 }
1253 #else
1254 void
1255 sbuf_putbuf(struct sbuf *sb)
1256 {
1257
1258         printf("%s", sbuf_data(sb));
1259 }
1260 #endif