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