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