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