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