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