xref: /netbsd-src/sys/kern/subr_prf.c (revision b8c616269f5ebf18ab2e35cb8099d683130a177c)
1 /*	$NetBSD: subr_prf.c,v 1.89 2002/12/31 23:45:36 thorpej Exp $	*/
2 
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. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the University of
23  *	California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  *
40  *	@(#)subr_prf.c	8.4 (Berkeley) 5/4/95
41  */
42 
43 #include <sys/cdefs.h>
44 __KERNEL_RCSID(0, "$NetBSD: subr_prf.c,v 1.89 2002/12/31 23:45:36 thorpej Exp $");
45 
46 #include "opt_ddb.h"
47 #include "opt_ipkdb.h"
48 #include "opt_kgdb.h"
49 #include "opt_multiprocessor.h"
50 
51 #include <sys/param.h>
52 #include <sys/stdint.h>
53 #include <sys/systm.h>
54 #include <sys/buf.h>
55 #include <sys/reboot.h>
56 #include <sys/msgbuf.h>
57 #include <sys/proc.h>
58 #include <sys/ioctl.h>
59 #include <sys/vnode.h>
60 #include <sys/file.h>
61 #include <sys/tty.h>
62 #include <sys/tprintf.h>
63 #include <sys/syslog.h>
64 #include <sys/malloc.h>
65 #include <sys/lock.h>
66 #include <sys/kprintf.h>
67 
68 #include <dev/cons.h>
69 
70 #ifdef DDB
71 #include <ddb/ddbvar.h>
72 #include <machine/db_machdep.h>
73 #include <ddb/db_command.h>
74 #include <ddb/db_interface.h>
75 #endif
76 
77 #ifdef IPKDB
78 #include <ipkdb/ipkdb.h>
79 #endif
80 
81 #if defined(MULTIPROCESSOR)
82 struct simplelock kprintf_slock = SIMPLELOCK_INITIALIZER;
83 #endif /* MULTIPROCESSOR */
84 
85 /*
86  * note that stdarg.h and the ansi style va_start macro is used for both
87  * ansi and traditional c complers.
88  * XXX: this requires that stdarg.h define: va_alist and va_dcl
89  */
90 #include <machine/stdarg.h>
91 
92 
93 #ifdef KGDB
94 #include <sys/kgdb.h>
95 #include <machine/cpu.h>
96 #endif
97 #ifdef DDB
98 #include <ddb/db_output.h>	/* db_printf, db_putchar prototypes */
99 #endif
100 
101 
102 /*
103  * defines
104  */
105 
106 /* max size buffer kprintf needs to print quad_t [size in base 8 + \0] */
107 #define KPRINTF_BUFSIZE		(sizeof(quad_t) * NBBY / 3 + 2)
108 
109 
110 /*
111  * local prototypes
112  */
113 
114 static void	 putchar __P((int, int, struct tty *));
115 
116 
117 /*
118  * globals
119  */
120 
121 extern	struct tty *constty;	/* pointer to console "window" tty */
122 extern	int log_open;	/* subr_log: is /dev/klog open? */
123 const	char *panicstr; /* arg to first call to panic (used as a flag
124 			   to indicate that panic has already been called). */
125 long	panicstart, panicend;	/* position in the msgbuf of the start and
126 				   end of the formatted panicstr. */
127 int	doing_shutdown;	/* set to indicate shutdown in progress */
128 
129 /*
130  * v_putc: routine to putc on virtual console
131  *
132  * the v_putc pointer can be used to redirect the console cnputc elsewhere
133  * [e.g. to a "virtual console"].
134  */
135 
136 void (*v_putc) __P((int)) = cnputc;	/* start with cnputc (normal cons) */
137 
138 
139 /*
140  * functions
141  */
142 
143 /*
144  * tablefull: warn that a system table is full
145  */
146 
147 void
148 tablefull(tab, hint)
149 	const char *tab, *hint;
150 {
151 	if (hint)
152 		log(LOG_ERR, "%s: table is full - %s\n", tab, hint);
153 	else
154 		log(LOG_ERR, "%s: table is full\n", tab);
155 }
156 
157 /*
158  * twiddle: spin a little propellor on the console.
159  */
160 
161 void
162 twiddle(void)
163 {
164 	static const char twiddle_chars[] = "|/-\\";
165 	static int pos;
166 	int s;
167 
168 	KPRINTF_MUTEX_ENTER(s);
169 
170 	putchar(twiddle_chars[pos++ & 3], TOCONS, NULL);
171 	putchar('\b', TOCONS, NULL);
172 
173 	KPRINTF_MUTEX_EXIT(s);
174 }
175 
176 /*
177  * panic: handle an unresolvable fatal error
178  *
179  * prints "panic: <message>" and reboots.   if called twice (i.e. recursive
180  * call) we avoid trying to sync the disk and just reboot (to avoid
181  * recursive panics).
182  */
183 
184 void
185 #ifdef __STDC__
186 panic(const char *fmt, ...)
187 #else
188 panic(fmt, va_alist)
189 	char *fmt;
190 	va_dcl
191 #endif
192 {
193 	int bootopt;
194 	va_list ap;
195 
196 	bootopt = RB_AUTOBOOT | RB_DUMP;
197 	if (doing_shutdown)
198 		bootopt |= RB_NOSYNC;
199 	if (!panicstr)
200 		panicstr = fmt;
201 	doing_shutdown = 1;
202 
203 	if (msgbufenabled && msgbufp->msg_magic == MSG_MAGIC)
204 		panicstart = msgbufp->msg_bufx;
205 
206 	va_start(ap, fmt);
207 	printf("panic: ");
208 	vprintf(fmt, ap);
209 	printf("\n");
210 	va_end(ap);
211 
212 	if (msgbufenabled && msgbufp->msg_magic == MSG_MAGIC)
213 		panicend = msgbufp->msg_bufx;
214 
215 #ifdef IPKDB
216 	ipkdb_panic();
217 #endif
218 #ifdef KGDB
219 	kgdb_panic();
220 #endif
221 #ifdef KADB
222 	if (boothowto & RB_KDB)
223 		kdbpanic();
224 #endif
225 #ifdef DDB
226 	if (db_onpanic)
227 		Debugger();
228 	else {
229 		static int intrace = 0;
230 
231 		if (intrace==0) {
232 			intrace=1;
233 			printf("Begin traceback...\n");
234 			db_stack_trace_print(
235 			    (db_expr_t)(intptr_t)__builtin_frame_address(0),
236 			    TRUE, 65535, "", printf);
237 			printf("End traceback...\n");
238 			intrace=0;
239 		} else
240 			printf("Faulted in mid-traceback; aborting...");
241 	}
242 #endif
243 	cpu_reboot(bootopt, NULL);
244 }
245 
246 /*
247  * kernel logging functions: log, logpri, addlog
248  */
249 
250 /*
251  * log: write to the log buffer
252  *
253  * => will not sleep [so safe to call from interrupt]
254  * => will log to console if /dev/klog isn't open
255  */
256 
257 void
258 #ifdef __STDC__
259 log(int level, const char *fmt, ...)
260 #else
261 log(level, fmt, va_alist)
262 	int level;
263 	char *fmt;
264 	va_dcl
265 #endif
266 {
267 	int s;
268 	va_list ap;
269 
270 	KPRINTF_MUTEX_ENTER(s);
271 
272 	klogpri(level);		/* log the level first */
273 	va_start(ap, fmt);
274 	kprintf(fmt, TOLOG, NULL, NULL, ap);
275 	va_end(ap);
276 	if (!log_open) {
277 		va_start(ap, fmt);
278 		kprintf(fmt, TOCONS, NULL, NULL, ap);
279 		va_end(ap);
280 	}
281 
282 	KPRINTF_MUTEX_EXIT(s);
283 
284 	logwakeup();		/* wake up anyone waiting for log msgs */
285 }
286 
287 /*
288  * vlog: write to the log buffer [already have va_alist]
289  */
290 
291 void
292 vlog(level, fmt, ap)
293 	int level;
294 	const char *fmt;
295 	va_list ap;
296 {
297 	int s;
298 
299 	KPRINTF_MUTEX_ENTER(s);
300 
301 	klogpri(level);		/* log the level first */
302 	kprintf(fmt, TOLOG, NULL, NULL, ap);
303 	if (!log_open)
304 		kprintf(fmt, TOCONS, NULL, NULL, ap);
305 
306 	KPRINTF_MUTEX_EXIT(s);
307 
308 	logwakeup();		/* wake up anyone waiting for log msgs */
309 }
310 
311 /*
312  * logpri: log the priority level to the klog
313  */
314 
315 void
316 logpri(level)
317 	int level;
318 {
319 	int s;
320 
321 	KPRINTF_MUTEX_ENTER(s);
322 	klogpri(level);
323 	KPRINTF_MUTEX_EXIT(s);
324 }
325 
326 /*
327  * Note: we must be in the mutex here!
328  */
329 void
330 klogpri(level)
331 	int level;
332 {
333 	char *p;
334 	char snbuf[KPRINTF_BUFSIZE];
335 
336 	putchar('<', TOLOG, NULL);
337 	snprintf(snbuf, sizeof(snbuf), "%d", level);
338 	for (p = snbuf ; *p ; p++)
339 		putchar(*p, TOLOG, NULL);
340 	putchar('>', TOLOG, NULL);
341 }
342 
343 /*
344  * addlog: add info to previous log message
345  */
346 
347 void
348 #ifdef __STDC__
349 addlog(const char *fmt, ...)
350 #else
351 addlog(fmt, va_alist)
352 	char *fmt;
353 	va_dcl
354 #endif
355 {
356 	int s;
357 	va_list ap;
358 
359 	KPRINTF_MUTEX_ENTER(s);
360 
361 	va_start(ap, fmt);
362 	kprintf(fmt, TOLOG, NULL, NULL, ap);
363 	va_end(ap);
364 	if (!log_open) {
365 		va_start(ap, fmt);
366 		kprintf(fmt, TOCONS, NULL, NULL, ap);
367 		va_end(ap);
368 	}
369 
370 	KPRINTF_MUTEX_EXIT(s);
371 
372 	logwakeup();
373 }
374 
375 
376 /*
377  * putchar: print a single character on console or user terminal.
378  *
379  * => if console, then the last MSGBUFS chars are saved in msgbuf
380  *	for inspection later (e.g. dmesg/syslog)
381  * => we must already be in the mutex!
382  */
383 static void
384 putchar(c, flags, tp)
385 	int c;
386 	int flags;
387 	struct tty *tp;
388 {
389 	struct kern_msgbuf *mbp;
390 
391 	if (panicstr)
392 		constty = NULL;
393 	if ((flags & TOCONS) && tp == NULL && constty) {
394 		tp = constty;
395 		flags |= TOTTY;
396 	}
397 	if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
398 	    (flags & TOCONS) && tp == constty)
399 		constty = NULL;
400 	if ((flags & TOLOG) &&
401 	    c != '\0' && c != '\r' && c != 0177 && msgbufenabled) {
402 		mbp = msgbufp;
403 		if (mbp->msg_magic != MSG_MAGIC) {
404 			/*
405 			 * Arguably should panic or somehow notify the
406 			 * user...  but how?  Panic may be too drastic,
407 			 * and would obliterate the message being kicked
408 			 * out (maybe a panic itself), and printf
409 			 * would invoke us recursively.  Silently punt
410 			 * for now.  If syslog is running, it should
411 			 * notice.
412 			 */
413 			msgbufenabled = 0;
414 		} else {
415 			mbp->msg_bufc[mbp->msg_bufx++] = c;
416 			if (mbp->msg_bufx < 0 || mbp->msg_bufx >= mbp->msg_bufs)
417 				mbp->msg_bufx = 0;
418 			/* If the buffer is full, keep the most recent data. */
419 			if (mbp->msg_bufr == mbp->msg_bufx) {
420 				 if (++mbp->msg_bufr >= mbp->msg_bufs)
421 					mbp->msg_bufr = 0;
422 			}
423 		}
424 	}
425 	if ((flags & TOCONS) && constty == NULL && c != '\0')
426 		(*v_putc)(c);
427 #ifdef DDB
428 	if (flags & TODDB)
429 		db_putchar(c);
430 #endif
431 }
432 
433 
434 /*
435  * uprintf: print to the controlling tty of the current process
436  *
437  * => we may block if the tty queue is full
438  * => no message is printed if the queue doesn't clear in a reasonable
439  *	time
440  */
441 
442 void
443 #ifdef __STDC__
444 uprintf(const char *fmt, ...)
445 #else
446 uprintf(fmt, va_alist)
447 	char *fmt;
448 	va_dcl
449 #endif
450 {
451 	struct proc *p = curproc;
452 	va_list ap;
453 
454 	if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
455 		/* No mutex needed; going to process TTY. */
456 		va_start(ap, fmt);
457 		kprintf(fmt, TOTTY, p->p_session->s_ttyp, NULL, ap);
458 		va_end(ap);
459 	}
460 }
461 
462 /*
463  * tprintf functions: used to send messages to a specific process
464  *
465  * usage:
466  *   get a tpr_t handle on a process "p" by using "tprintf_open(p)"
467  *   use the handle when calling "tprintf"
468  *   when done, do a "tprintf_close" to drop the handle
469  */
470 
471 /*
472  * tprintf_open: get a tprintf handle on a process "p"
473  *
474  * => returns NULL if process can't be printed to
475  */
476 
477 tpr_t
478 tprintf_open(p)
479 	struct proc *p;
480 {
481 
482 	if (p->p_flag & P_CONTROLT && p->p_session->s_ttyvp) {
483 		SESSHOLD(p->p_session);
484 		return ((tpr_t) p->p_session);
485 	}
486 	return ((tpr_t) NULL);
487 }
488 
489 /*
490  * tprintf_close: dispose of a tprintf handle obtained with tprintf_open
491  */
492 
493 void
494 tprintf_close(sess)
495 	tpr_t sess;
496 {
497 
498 	if (sess)
499 		SESSRELE((struct session *) sess);
500 }
501 
502 /*
503  * tprintf: given tprintf handle to a process [obtained with tprintf_open],
504  * send a message to the controlling tty for that process.
505  *
506  * => also sends message to /dev/klog
507  */
508 void
509 #ifdef __STDC__
510 tprintf(tpr_t tpr, const char *fmt, ...)
511 #else
512 tprintf(tpr, fmt, va_alist)
513 	tpr_t tpr;
514 	char *fmt;
515 	va_dcl
516 #endif
517 {
518 	struct session *sess = (struct session *)tpr;
519 	struct tty *tp = NULL;
520 	int s, flags = TOLOG;
521 	va_list ap;
522 
523 	if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
524 		flags |= TOTTY;
525 		tp = sess->s_ttyp;
526 	}
527 
528 	KPRINTF_MUTEX_ENTER(s);
529 
530 	klogpri(LOG_INFO);
531 	va_start(ap, fmt);
532 	kprintf(fmt, flags, tp, NULL, ap);
533 	va_end(ap);
534 
535 	KPRINTF_MUTEX_EXIT(s);
536 
537 	logwakeup();
538 }
539 
540 
541 /*
542  * ttyprintf: send a message to a specific tty
543  *
544  * => should be used only by tty driver or anything that knows the
545  *    underlying tty will not be revoked(2)'d away.  [otherwise,
546  *    use tprintf]
547  */
548 void
549 #ifdef __STDC__
550 ttyprintf(struct tty *tp, const char *fmt, ...)
551 #else
552 ttyprintf(tp, fmt, va_alist)
553 	struct tty *tp;
554 	char *fmt;
555 	va_dcl
556 #endif
557 {
558 	va_list ap;
559 
560 	/* No mutex needed; going to process TTY. */
561 	va_start(ap, fmt);
562 	kprintf(fmt, TOTTY, tp, NULL, ap);
563 	va_end(ap);
564 }
565 
566 #ifdef DDB
567 
568 /*
569  * db_printf: printf for DDB (via db_putchar)
570  */
571 
572 void
573 #ifdef __STDC__
574 db_printf(const char *fmt, ...)
575 #else
576 db_printf(fmt, va_alist)
577 	char *fmt;
578 	va_dcl
579 #endif
580 {
581 	va_list ap;
582 
583 	/* No mutex needed; DDB pauses all processors. */
584 	va_start(ap, fmt);
585 	kprintf(fmt, TODDB, NULL, NULL, ap);
586 	va_end(ap);
587 }
588 
589 void
590 db_vprintf(fmt, ap)
591 	const char *fmt;
592 	va_list ap;
593 {
594 
595 	/* No mutex needed; DDB pauses all processors. */
596 	kprintf(fmt, TODDB, NULL, NULL, ap);
597 }
598 
599 #endif /* DDB */
600 
601 /*
602  * Device autoconfiguration printf routines.  These change their
603  * behavior based on the AB_* flags in boothowto.  If AB_SILENT
604  * is set, messages never go to the console (but they still always
605  * go to the log).  AB_VERBOSE overrides AB_SILENT.
606  */
607 
608 /*
609  * aprint_normal: Send to console unless AB_QUIET.  Always goes
610  * to the log.
611  */
612 void
613 #ifdef __STDC__
614 aprint_normal(const char *fmt, ...)
615 #else
616 aprint_normal(fmt, va_alist)
617 	char *fmt;
618 	va_dcl
619 #endif
620 {
621 	va_list ap;
622 	int s, flags = TOLOG;
623 
624 	if ((boothowto & (AB_SILENT|AB_QUIET)) == 0 ||
625 	    (boothowto & AB_VERBOSE) != 0)
626 		flags |= TOCONS;
627 
628 	KPRINTF_MUTEX_ENTER(s);
629 
630 	va_start(ap, fmt);
631 	kprintf(fmt, flags, NULL, NULL, ap);
632 	va_end(ap);
633 
634 	KPRINTF_MUTEX_EXIT(s);
635 
636 	if (!panicstr)
637 		logwakeup();
638 }
639 
640 /*
641  * aprint_error: Send to console unless AB_QUIET.  Always goes
642  * to the log.  Also counts the number of times called so other
643  * parts of the kernel can report the number of errors during a
644  * given phase of system startup.
645  */
646 static int aprint_error_count;
647 
648 int
649 aprint_get_error_count(void)
650 {
651 	int count, s;
652 
653 	KPRINTF_MUTEX_ENTER(s);
654 
655 	count = aprint_error_count;
656 	aprint_error_count = 0;
657 
658 	KPRINTF_MUTEX_EXIT(s);
659 
660 	return (count);
661 }
662 
663 void
664 #ifdef __STDC__
665 aprint_error(const char *fmt, ...)
666 #else
667 aprint_error(fmt, va_alist)
668 	char *fmt;
669 	va_dcl
670 #endif
671 {
672 	va_list ap;
673 	int s, flags = TOLOG;
674 
675 	if ((boothowto & (AB_SILENT|AB_QUIET)) == 0 ||
676 	    (boothowto & AB_VERBOSE) != 0)
677 		flags |= TOCONS;
678 
679 	KPRINTF_MUTEX_ENTER(s);
680 
681 	aprint_error_count++;
682 
683 	va_start(ap, fmt);
684 	kprintf(fmt, flags, NULL, NULL, ap);
685 	va_end(ap);
686 
687 	KPRINTF_MUTEX_EXIT(s);
688 
689 	if (!panicstr)
690 		logwakeup();
691 }
692 
693 /*
694  * aprint_naive: Send to console only if AB_QUIET.  Never goes
695  * to the log.
696  */
697 void
698 #ifdef __STDC__
699 aprint_naive(const char *fmt, ...)
700 #else
701 aprint_naive(fmt, va_alist)
702 	char *fmt;
703 	va_dcl
704 #endif
705 {
706 	va_list ap;
707 	int s;
708 
709 	if ((boothowto & (AB_QUIET|AB_SILENT|AB_VERBOSE)) == AB_QUIET) {
710 		KPRINTF_MUTEX_ENTER(s);
711 
712 		va_start(ap, fmt);
713 		kprintf(fmt, TOCONS, NULL, NULL, ap);
714 		va_end(ap);
715 
716 		KPRINTF_MUTEX_EXIT(s);
717 	}
718 }
719 
720 /*
721  * aprint_verbose: Send to console only if AB_VERBOSE.  Always
722  * goes to the log.
723  */
724 void
725 #ifdef __STDC__
726 aprint_verbose(const char *fmt, ...)
727 #else
728 aprint_verbose(fmt, va_alist)
729 	char *fmt;
730 	va_dcl
731 #endif
732 {
733 	va_list ap;
734 	int s, flags = TOLOG;
735 
736 	if (boothowto & AB_VERBOSE)
737 		flags |= TOCONS;
738 
739 	KPRINTF_MUTEX_ENTER(s);
740 
741 	va_start(ap, fmt);
742 	kprintf(fmt, flags, NULL, NULL, ap);
743 	va_end(ap);
744 
745 	KPRINTF_MUTEX_EXIT(s);
746 
747 	if (!panicstr)
748 		logwakeup();
749 }
750 
751 /*
752  * aprint_debug: Send to console and log only if AB_DEBUG.
753  */
754 void
755 #ifdef __STDC__
756 aprint_debug(const char *fmt, ...)
757 #else
758 aprint_debug(fmt, va_alist)
759 	char *fmt;
760 	va_dcl
761 #endif
762 {
763 	va_list ap;
764 	int s;
765 
766 	if (boothowto & AB_DEBUG) {
767 		KPRINTF_MUTEX_ENTER(s);
768 
769 		va_start(ap, fmt);
770 		kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
771 		va_end(ap);
772 
773 		KPRINTF_MUTEX_EXIT(s);
774 	}
775 }
776 
777 /*
778  * printf_nolog: Like printf(), but does not send message to the log.
779  */
780 
781 void
782 #ifdef __STDC__
783 printf_nolog(const char *fmt, ...)
784 #else
785 printf_nolog(fmt, va_alist)
786 	char *fmt;
787 	va_dcl;
788 #endif
789 {
790 	va_list ap;
791 	int s;
792 
793 	KPRINTF_MUTEX_ENTER(s);
794 
795 	va_start(ap, fmt);
796 	kprintf(fmt, TOCONS, NULL, NULL, ap);
797 	va_end(ap);
798 
799 	KPRINTF_MUTEX_EXIT(s);
800 }
801 
802 /*
803  * normal kernel printf functions: printf, vprintf, snprintf, vsnprintf
804  */
805 
806 /*
807  * printf: print a message to the console and the log
808  */
809 void
810 #ifdef __STDC__
811 printf(const char *fmt, ...)
812 #else
813 printf(fmt, va_alist)
814 	char *fmt;
815 	va_dcl
816 #endif
817 {
818 	va_list ap;
819 	int s;
820 
821 	KPRINTF_MUTEX_ENTER(s);
822 
823 	va_start(ap, fmt);
824 	kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
825 	va_end(ap);
826 
827 	KPRINTF_MUTEX_EXIT(s);
828 
829 	if (!panicstr)
830 		logwakeup();
831 }
832 
833 /*
834  * vprintf: print a message to the console and the log [already have
835  *	va_alist]
836  */
837 
838 void
839 vprintf(fmt, ap)
840 	const char *fmt;
841 	va_list ap;
842 {
843 	int s;
844 
845 	KPRINTF_MUTEX_ENTER(s);
846 
847 	kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
848 
849 	KPRINTF_MUTEX_EXIT(s);
850 
851 	if (!panicstr)
852 		logwakeup();
853 }
854 
855 /*
856  * sprintf: print a message to a buffer
857  */
858 int
859 #ifdef __STDC__
860 sprintf(char *buf, const char *fmt, ...)
861 #else
862 sprintf(buf, fmt, va_alist)
863         char *buf;
864         const char *cfmt;
865         va_dcl
866 #endif
867 {
868 	int retval;
869 	va_list ap;
870 
871 	va_start(ap, fmt);
872 	retval = kprintf(fmt, TOBUFONLY, NULL, buf, ap);
873 	va_end(ap);
874 	*(buf + retval) = 0;	/* null terminate */
875 	return(retval);
876 }
877 
878 /*
879  * vsprintf: print a message to a buffer [already have va_alist]
880  */
881 
882 int
883 vsprintf(buf, fmt, ap)
884 	char *buf;
885 	const char *fmt;
886 	va_list ap;
887 {
888 	int retval;
889 
890 	retval = kprintf(fmt, TOBUFONLY, NULL, buf, ap);
891 	*(buf + retval) = 0;	/* null terminate */
892 	return (retval);
893 }
894 
895 /*
896  * snprintf: print a message to a buffer
897  */
898 int
899 #ifdef __STDC__
900 snprintf(char *buf, size_t size, const char *fmt, ...)
901 #else
902 snprintf(buf, size, fmt, va_alist)
903         char *buf;
904         size_t size;
905         const char *cfmt;
906         va_dcl
907 #endif
908 {
909 	int retval;
910 	va_list ap;
911 	char *p;
912 
913 	if (size < 1)
914 		return (-1);
915 	p = buf + size - 1;
916 	va_start(ap, fmt);
917 	retval = kprintf(fmt, TOBUFONLY, &p, buf, ap);
918 	va_end(ap);
919 	*(p) = 0;	/* null terminate */
920 	return(retval);
921 }
922 
923 /*
924  * vsnprintf: print a message to a buffer [already have va_alist]
925  */
926 int
927 vsnprintf(buf, size, fmt, ap)
928         char *buf;
929         size_t size;
930         const char *fmt;
931         va_list ap;
932 {
933 	int retval;
934 	char *p;
935 
936 	if (size < 1)
937 		return (-1);
938 	p = buf + size - 1;
939 	retval = kprintf(fmt, TOBUFONLY, &p, buf, ap);
940 	*(p) = 0;	/* null terminate */
941 	return(retval);
942 }
943 
944 /*
945  * bitmask_snprintf: print an interpreted bitmask to a buffer
946  *
947  * => returns pointer to the buffer
948  */
949 char *
950 bitmask_snprintf(val, p, buf, buflen)
951 	u_quad_t val;
952 	const char *p;
953 	char *buf;
954 	size_t buflen;
955 {
956 	char *bp, *q;
957 	size_t left;
958 	char *sbase, snbuf[KPRINTF_BUFSIZE];
959 	int base, bit, ch, len, sep;
960 	u_quad_t field;
961 
962 	bp = buf;
963 	memset(buf, 0, buflen);
964 
965 	/*
966 	 * Always leave room for the trailing NULL.
967 	 */
968 	left = buflen - 1;
969 
970 	/*
971 	 * Print the value into the buffer.  Abort if there's not
972 	 * enough room.
973 	 */
974 	if (buflen < KPRINTF_BUFSIZE)
975 		return (buf);
976 
977 	ch = *p++;
978 	base = ch != '\177' ? ch : *p++;
979 	sbase = base == 8 ? "%qo" : base == 10 ? "%qd" : base == 16 ? "%qx" : 0;
980 	if (sbase == 0)
981 		return (buf);	/* punt if not oct, dec, or hex */
982 
983 	snprintf(snbuf, sizeof(snbuf), sbase, val);
984 	for (q = snbuf ; *q ; q++) {
985 		*bp++ = *q;
986 		left--;
987 	}
988 
989 	/*
990 	 * If the value we printed was 0 and we're using the old-style format,
991 	 * or if we don't have room for "<x>", we're done.
992 	 */
993 	if (((val == 0) && (ch != '\177')) || left < 3)
994 		return (buf);
995 
996 #define PUTBYTE(b, c, l) do {	\
997 	*(b)++ = (c);		\
998 	if (--(l) == 0)		\
999 		goto out;	\
1000 } while (/*CONSTCOND*/ 0)
1001 #define PUTSTR(b, p, l) do {		\
1002 	int c;				\
1003 	while ((c = *(p)++) != 0) {	\
1004 		*(b)++ = c;		\
1005 		if (--(l) == 0)		\
1006 			goto out;	\
1007 	}				\
1008 } while (/*CONSTCOND*/ 0)
1009 
1010 	/*
1011 	 * Chris Torek's new bitmask format is identified by a leading \177
1012 	 */
1013 	sep = '<';
1014 	if (ch != '\177') {
1015 		/* old (standard) format. */
1016 		for (;(bit = *p++) != 0;) {
1017 			if (val & (1 << (bit - 1))) {
1018 				PUTBYTE(bp, sep, left);
1019 				for (; (ch = *p) > ' '; ++p) {
1020 					PUTBYTE(bp, ch, left);
1021 				}
1022 				sep = ',';
1023 			} else
1024 				for (; *p > ' '; ++p)
1025 					continue;
1026 		}
1027 	} else {
1028 		/* new quad-capable format; also does fields. */
1029 		field = val;
1030 		while ((ch = *p++) != '\0') {
1031 			bit = *p++;	/* now 0-origin */
1032 			switch (ch) {
1033 			case 'b':
1034 				if (((u_int)(val >> bit) & 1) == 0)
1035 					goto skip;
1036 				PUTBYTE(bp, sep, left);
1037 				PUTSTR(bp, p, left);
1038 				sep = ',';
1039 				break;
1040 			case 'f':
1041 			case 'F':
1042 				len = *p++;	/* field length */
1043 				field = (val >> bit) & ((1ULL << len) - 1);
1044 				if (ch == 'F')	/* just extract */
1045 					break;
1046 				PUTBYTE(bp, sep, left);
1047 				sep = ',';
1048 				PUTSTR(bp, p, left);
1049 				PUTBYTE(bp, '=', left);
1050 				sprintf(snbuf, sbase, field);
1051 				q = snbuf; PUTSTR(bp, q, left);
1052 				break;
1053 			case '=':
1054 			case ':':
1055 				/*
1056 				 * Here "bit" is actually a value instead,
1057 				 * to be compared against the last field.
1058 				 * This only works for values in [0..255],
1059 				 * of course.
1060 				 */
1061 				if ((int)field != bit)
1062 					goto skip;
1063 				if (ch == '=')
1064 					PUTBYTE(bp, '=', left);
1065 				PUTSTR(bp, p, left);
1066 				break;
1067 			default:
1068 			skip:
1069 				while (*p++ != '\0')
1070 					continue;
1071 				break;
1072 			}
1073 		}
1074 	}
1075 	if (sep != '<')
1076 		PUTBYTE(bp, '>', left);
1077 
1078 out:
1079 	return (buf);
1080 
1081 #undef PUTBYTE
1082 #undef PUTSTR
1083 }
1084 
1085 /*
1086  * kprintf: scaled down version of printf(3).
1087  *
1088  * this version based on vfprintf() from libc which was derived from
1089  * software contributed to Berkeley by Chris Torek.
1090  *
1091  * NOTE: The kprintf mutex must be held if we're going TOBUF or TOCONS!
1092  */
1093 
1094 /*
1095  * macros for converting digits to letters and vice versa
1096  */
1097 #define	to_digit(c)	((c) - '0')
1098 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
1099 #define	to_char(n)	((n) + '0')
1100 
1101 /*
1102  * flags used during conversion.
1103  */
1104 #define	ALT		0x001		/* alternate form */
1105 #define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
1106 #define	LADJUST		0x004		/* left adjustment */
1107 #define	LONGDBL		0x008		/* long double; unimplemented */
1108 #define	LONGINT		0x010		/* long integer */
1109 #define	QUADINT		0x020		/* quad integer */
1110 #define	SHORTINT	0x040		/* short integer */
1111 #define	MAXINT		0x080		/* intmax_t */
1112 #define	PTRINT		0x100		/* intptr_t */
1113 #define	SIZEINT		0x200		/* size_t */
1114 #define	ZEROPAD		0x400		/* zero (as opposed to blank) pad */
1115 #define FPT		0x800		/* Floating point number */
1116 
1117 	/*
1118 	 * To extend shorts properly, we need both signed and unsigned
1119 	 * argument extraction methods.
1120 	 */
1121 #define	SARG() \
1122 	(flags&MAXINT ? va_arg(ap, intmax_t) : \
1123 	    flags&PTRINT ? va_arg(ap, intptr_t) : \
1124 	    flags&SIZEINT ? va_arg(ap, ssize_t) : /* XXX */ \
1125 	    flags&QUADINT ? va_arg(ap, quad_t) : \
1126 	    flags&LONGINT ? va_arg(ap, long) : \
1127 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
1128 	    (long)va_arg(ap, int))
1129 #define	UARG() \
1130 	(flags&MAXINT ? va_arg(ap, uintmax_t) : \
1131 	    flags&PTRINT ? va_arg(ap, uintptr_t) : \
1132 	    flags&SIZEINT ? va_arg(ap, size_t) : \
1133 	    flags&QUADINT ? va_arg(ap, u_quad_t) : \
1134 	    flags&LONGINT ? va_arg(ap, u_long) : \
1135 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
1136 	    (u_long)va_arg(ap, u_int))
1137 
1138 #define KPRINTF_PUTCHAR(C) {						\
1139 	if (oflags == TOBUFONLY) {					\
1140 		if ((vp != NULL) && (sbuf == tailp)) {			\
1141 			ret += 1;		/* indicate error */	\
1142 			goto overflow;					\
1143 		}							\
1144 		*sbuf++ = (C);						\
1145 	} else {							\
1146 		putchar((C), oflags, (struct tty *)vp);			\
1147 	}								\
1148 }
1149 
1150 /*
1151  * Guts of kernel printf.  Note, we already expect to be in a mutex!
1152  */
1153 int
1154 kprintf(fmt0, oflags, vp, sbuf, ap)
1155 	const char *fmt0;
1156 	int oflags;
1157 	void *vp;
1158 	char *sbuf;
1159 	va_list ap;
1160 {
1161 	char *fmt;		/* format string */
1162 	int ch;			/* character from fmt */
1163 	int n;			/* handy integer (short term usage) */
1164 	char *cp;		/* handy char pointer (short term usage) */
1165 	int flags;		/* flags as above */
1166 	int ret;		/* return value accumulator */
1167 	int width;		/* width from format (%8d), or 0 */
1168 	int prec;		/* precision from format (%.3d), or -1 */
1169 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
1170 
1171 	u_quad_t _uquad;	/* integer arguments %[diouxX] */
1172 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
1173 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
1174 	int realsz;		/* field size expanded by dprec */
1175 	int size;		/* size of converted field or string */
1176 	char *xdigs;		/* digits for [xX] conversion */
1177 	char buf[KPRINTF_BUFSIZE]; /* space for %c, %[diouxX] */
1178 	char *tailp;		/* tail pointer for snprintf */
1179 
1180 	tailp = NULL;	/* XXX: shutup gcc */
1181 	if (oflags == TOBUFONLY && (vp != NULL))
1182 		tailp = *(char **)vp;
1183 
1184 	cp = NULL;	/* XXX: shutup gcc */
1185 	size = 0;	/* XXX: shutup gcc */
1186 
1187 	fmt = (char *)fmt0;
1188 	ret = 0;
1189 
1190 	xdigs = NULL;		/* XXX: shut up gcc warning */
1191 
1192 	/*
1193 	 * Scan the format for conversions (`%' character).
1194 	 */
1195 	for (;;) {
1196 		while (*fmt != '%' && *fmt) {
1197 			ret++;
1198 			KPRINTF_PUTCHAR(*fmt++);
1199 		}
1200 		if (*fmt == 0)
1201 			goto done;
1202 
1203 		fmt++;		/* skip over '%' */
1204 
1205 		flags = 0;
1206 		dprec = 0;
1207 		width = 0;
1208 		prec = -1;
1209 		sign = '\0';
1210 
1211 rflag:		ch = *fmt++;
1212 reswitch:	switch (ch) {
1213 		case ' ':
1214 			/*
1215 			 * ``If the space and + flags both appear, the space
1216 			 * flag will be ignored.''
1217 			 *	-- ANSI X3J11
1218 			 */
1219 			if (!sign)
1220 				sign = ' ';
1221 			goto rflag;
1222 		case '#':
1223 			flags |= ALT;
1224 			goto rflag;
1225 		case '*':
1226 			/*
1227 			 * ``A negative field width argument is taken as a
1228 			 * - flag followed by a positive field width.''
1229 			 *	-- ANSI X3J11
1230 			 * They don't exclude field widths read from args.
1231 			 */
1232 			if ((width = va_arg(ap, int)) >= 0)
1233 				goto rflag;
1234 			width = -width;
1235 			/* FALLTHROUGH */
1236 		case '-':
1237 			flags |= LADJUST;
1238 			goto rflag;
1239 		case '+':
1240 			sign = '+';
1241 			goto rflag;
1242 		case '.':
1243 			if ((ch = *fmt++) == '*') {
1244 				n = va_arg(ap, int);
1245 				prec = n < 0 ? -1 : n;
1246 				goto rflag;
1247 			}
1248 			n = 0;
1249 			while (is_digit(ch)) {
1250 				n = 10 * n + to_digit(ch);
1251 				ch = *fmt++;
1252 			}
1253 			prec = n < 0 ? -1 : n;
1254 			goto reswitch;
1255 		case '0':
1256 			/*
1257 			 * ``Note that 0 is taken as a flag, not as the
1258 			 * beginning of a field width.''
1259 			 *	-- ANSI X3J11
1260 			 */
1261 			flags |= ZEROPAD;
1262 			goto rflag;
1263 		case '1': case '2': case '3': case '4':
1264 		case '5': case '6': case '7': case '8': case '9':
1265 			n = 0;
1266 			do {
1267 				n = 10 * n + to_digit(ch);
1268 				ch = *fmt++;
1269 			} while (is_digit(ch));
1270 			width = n;
1271 			goto reswitch;
1272 		case 'h':
1273 			flags |= SHORTINT;
1274 			goto rflag;
1275 		case 'j':
1276 			flags |= MAXINT;
1277 			goto rflag;
1278 		case 'l':
1279 			if (*fmt == 'l') {
1280 				fmt++;
1281 				flags |= QUADINT;
1282 			} else {
1283 				flags |= LONGINT;
1284 			}
1285 			goto rflag;
1286 		case 'q':
1287 			flags |= QUADINT;
1288 			goto rflag;
1289 		case 't':
1290 			flags |= PTRINT;
1291 			goto rflag;
1292 		case 'z':
1293 			flags |= SIZEINT;
1294 			goto rflag;
1295 		case 'c':
1296 			*(cp = buf) = va_arg(ap, int);
1297 			size = 1;
1298 			sign = '\0';
1299 			break;
1300 		case 'D':
1301 			flags |= LONGINT;
1302 			/*FALLTHROUGH*/
1303 		case 'd':
1304 		case 'i':
1305 			_uquad = SARG();
1306 			if ((quad_t)_uquad < 0) {
1307 				_uquad = -_uquad;
1308 				sign = '-';
1309 			}
1310 			base = DEC;
1311 			goto number;
1312 		case 'n':
1313 			if (flags & MAXINT)
1314 				*va_arg(ap, intmax_t *) = ret;
1315 			else if (flags & PTRINT)
1316 				*va_arg(ap, intptr_t *) = ret;
1317 			else if (flags & SIZEINT)
1318 				*va_arg(ap, ssize_t *) = ret;
1319 			else if (flags & QUADINT)
1320 				*va_arg(ap, quad_t *) = ret;
1321 			else if (flags & LONGINT)
1322 				*va_arg(ap, long *) = ret;
1323 			else if (flags & SHORTINT)
1324 				*va_arg(ap, short *) = ret;
1325 			else
1326 				*va_arg(ap, int *) = ret;
1327 			continue;	/* no output */
1328 		case 'O':
1329 			flags |= LONGINT;
1330 			/*FALLTHROUGH*/
1331 		case 'o':
1332 			_uquad = UARG();
1333 			base = OCT;
1334 			goto nosign;
1335 		case 'p':
1336 			/*
1337 			 * ``The argument shall be a pointer to void.  The
1338 			 * value of the pointer is converted to a sequence
1339 			 * of printable characters, in an implementation-
1340 			 * defined manner.''
1341 			 *	-- ANSI X3J11
1342 			 */
1343 			/* NOSTRICT */
1344 			_uquad = (u_long)va_arg(ap, void *);
1345 			base = HEX;
1346 			xdigs = "0123456789abcdef";
1347 			flags |= HEXPREFIX;
1348 			ch = 'x';
1349 			goto nosign;
1350 		case 's':
1351 			if ((cp = va_arg(ap, char *)) == NULL)
1352 				cp = "(null)";
1353 			if (prec >= 0) {
1354 				/*
1355 				 * can't use strlen; can only look for the
1356 				 * NUL in the first `prec' characters, and
1357 				 * strlen() will go further.
1358 				 */
1359 				char *p = memchr(cp, 0, prec);
1360 
1361 				if (p != NULL) {
1362 					size = p - cp;
1363 					if (size > prec)
1364 						size = prec;
1365 				} else
1366 					size = prec;
1367 			} else
1368 				size = strlen(cp);
1369 			sign = '\0';
1370 			break;
1371 		case 'U':
1372 			flags |= LONGINT;
1373 			/*FALLTHROUGH*/
1374 		case 'u':
1375 			_uquad = UARG();
1376 			base = DEC;
1377 			goto nosign;
1378 		case 'X':
1379 			xdigs = "0123456789ABCDEF";
1380 			goto hex;
1381 		case 'x':
1382 			xdigs = "0123456789abcdef";
1383 hex:			_uquad = UARG();
1384 			base = HEX;
1385 			/* leading 0x/X only if non-zero */
1386 			if (flags & ALT && _uquad != 0)
1387 				flags |= HEXPREFIX;
1388 
1389 			/* unsigned conversions */
1390 nosign:			sign = '\0';
1391 			/*
1392 			 * ``... diouXx conversions ... if a precision is
1393 			 * specified, the 0 flag will be ignored.''
1394 			 *	-- ANSI X3J11
1395 			 */
1396 number:			if ((dprec = prec) >= 0)
1397 				flags &= ~ZEROPAD;
1398 
1399 			/*
1400 			 * ``The result of converting a zero value with an
1401 			 * explicit precision of zero is no characters.''
1402 			 *	-- ANSI X3J11
1403 			 */
1404 			cp = buf + KPRINTF_BUFSIZE;
1405 			if (_uquad != 0 || prec != 0) {
1406 				/*
1407 				 * Unsigned mod is hard, and unsigned mod
1408 				 * by a constant is easier than that by
1409 				 * a variable; hence this switch.
1410 				 */
1411 				switch (base) {
1412 				case OCT:
1413 					do {
1414 						*--cp = to_char(_uquad & 7);
1415 						_uquad >>= 3;
1416 					} while (_uquad);
1417 					/* handle octal leading 0 */
1418 					if (flags & ALT && *cp != '0')
1419 						*--cp = '0';
1420 					break;
1421 
1422 				case DEC:
1423 					/* many numbers are 1 digit */
1424 					while (_uquad >= 10) {
1425 						*--cp = to_char(_uquad % 10);
1426 						_uquad /= 10;
1427 					}
1428 					*--cp = to_char(_uquad);
1429 					break;
1430 
1431 				case HEX:
1432 					do {
1433 						*--cp = xdigs[_uquad & 15];
1434 						_uquad >>= 4;
1435 					} while (_uquad);
1436 					break;
1437 
1438 				default:
1439 					cp = "bug in kprintf: bad base";
1440 					size = strlen(cp);
1441 					goto skipsize;
1442 				}
1443 			}
1444 			size = buf + KPRINTF_BUFSIZE - cp;
1445 		skipsize:
1446 			break;
1447 		default:	/* "%?" prints ?, unless ? is NUL */
1448 			if (ch == '\0')
1449 				goto done;
1450 			/* pretend it was %c with argument ch */
1451 			cp = buf;
1452 			*cp = ch;
1453 			size = 1;
1454 			sign = '\0';
1455 			break;
1456 		}
1457 
1458 		/*
1459 		 * All reasonable formats wind up here.  At this point, `cp'
1460 		 * points to a string which (if not flags&LADJUST) should be
1461 		 * padded out to `width' places.  If flags&ZEROPAD, it should
1462 		 * first be prefixed by any sign or other prefix; otherwise,
1463 		 * it should be blank padded before the prefix is emitted.
1464 		 * After any left-hand padding and prefixing, emit zeroes
1465 		 * required by a decimal [diouxX] precision, then print the
1466 		 * string proper, then emit zeroes required by any leftover
1467 		 * floating precision; finally, if LADJUST, pad with blanks.
1468 		 *
1469 		 * Compute actual size, so we know how much to pad.
1470 		 * size excludes decimal prec; realsz includes it.
1471 		 */
1472 		realsz = dprec > size ? dprec : size;
1473 		if (sign)
1474 			realsz++;
1475 		else if (flags & HEXPREFIX)
1476 			realsz+= 2;
1477 
1478 		/* adjust ret */
1479 		ret += width > realsz ? width : realsz;
1480 
1481 		/* right-adjusting blank padding */
1482 		if ((flags & (LADJUST|ZEROPAD)) == 0) {
1483 			n = width - realsz;
1484 			while (n-- > 0)
1485 				KPRINTF_PUTCHAR(' ');
1486 		}
1487 
1488 		/* prefix */
1489 		if (sign) {
1490 			KPRINTF_PUTCHAR(sign);
1491 		} else if (flags & HEXPREFIX) {
1492 			KPRINTF_PUTCHAR('0');
1493 			KPRINTF_PUTCHAR(ch);
1494 		}
1495 
1496 		/* right-adjusting zero padding */
1497 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) {
1498 			n = width - realsz;
1499 			while (n-- > 0)
1500 				KPRINTF_PUTCHAR('0');
1501 		}
1502 
1503 		/* leading zeroes from decimal precision */
1504 		n = dprec - size;
1505 		while (n-- > 0)
1506 			KPRINTF_PUTCHAR('0');
1507 
1508 		/* the string or number proper */
1509 		while (size--)
1510 			KPRINTF_PUTCHAR(*cp++);
1511 		/* left-adjusting padding (always blank) */
1512 		if (flags & LADJUST) {
1513 			n = width - realsz;
1514 			while (n-- > 0)
1515 				KPRINTF_PUTCHAR(' ');
1516 		}
1517 	}
1518 
1519 done:
1520 	if ((oflags == TOBUFONLY) && (vp != NULL))
1521 		*(char **)vp = sbuf;
1522 overflow:
1523 	return (ret);
1524 	/* NOTREACHED */
1525 }
1526