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