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