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