subr_prf.c revision 1.98 1 /* $NetBSD: subr_prf.c,v 1.98 2005/05/29 22:24:15 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.98 2005/05/29 22:24:15 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 *bf, const char *fmt, ...)
790 {
791 int retval;
792 va_list ap;
793
794 va_start(ap, fmt);
795 retval = kprintf(fmt, TOBUFONLY, NULL, bf, ap);
796 va_end(ap);
797 *(bf + 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(bf, fmt, ap)
807 char *bf;
808 const char *fmt;
809 va_list ap;
810 {
811 int retval;
812
813 retval = kprintf(fmt, TOBUFONLY, NULL, bf, ap);
814 *(bf + retval) = 0; /* null terminate */
815 return (retval);
816 }
817
818 /*
819 * snprintf: print a message to a buffer
820 */
821 int
822 snprintf(char *bf, 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 = bf + size - 1;
831 va_start(ap, fmt);
832 retval = kprintf(fmt, TOBUFONLY, &p, bf, 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(bf, size, fmt, ap)
843 char *bf;
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 = bf + size - 1;
854 retval = kprintf(fmt, TOBUFONLY, &p, bf, 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, bf, buflen)
866 u_quad_t val;
867 const char *p;
868 char *bf;
869 size_t buflen;
870 {
871 char *bp, *q;
872 size_t left;
873 const char *sbase;
874 char snbuf[KPRINTF_BUFSIZE];
875 int base, bit, ch, len, sep;
876 u_quad_t field;
877
878 bp = bf;
879 memset(bf, 0, buflen);
880
881 /*
882 * Always leave room for the trailing NULL.
883 */
884 left = buflen - 1;
885
886 /*
887 * Print the value into the buffer. Abort if there's not
888 * enough room.
889 */
890 if (buflen < KPRINTF_BUFSIZE)
891 return (bf);
892
893 ch = *p++;
894 base = ch != '\177' ? ch : *p++;
895 sbase = base == 8 ? "%qo" : base == 10 ? "%qd" : base == 16 ? "%qx" : 0;
896 if (sbase == 0)
897 return (bf); /* punt if not oct, dec, or hex */
898
899 snprintf(snbuf, sizeof(snbuf), sbase, val);
900 for (q = snbuf ; *q ; q++) {
901 *bp++ = *q;
902 left--;
903 }
904
905 /*
906 * If the value we printed was 0 and we're using the old-style format,
907 * or if we don't have room for "<x>", we're done.
908 */
909 if (((val == 0) && (ch != '\177')) || left < 3)
910 return (bf);
911
912 #define PUTBYTE(b, c, l) do { \
913 *(b)++ = (c); \
914 if (--(l) == 0) \
915 goto out; \
916 } while (/*CONSTCOND*/ 0)
917 #define PUTSTR(b, p, l) do { \
918 int c; \
919 while ((c = *(p)++) != 0) { \
920 *(b)++ = c; \
921 if (--(l) == 0) \
922 goto out; \
923 } \
924 } while (/*CONSTCOND*/ 0)
925
926 /*
927 * Chris Torek's new bitmask format is identified by a leading \177
928 */
929 sep = '<';
930 if (ch != '\177') {
931 /* old (standard) format. */
932 for (;(bit = *p++) != 0;) {
933 if (val & (1 << (bit - 1))) {
934 PUTBYTE(bp, sep, left);
935 for (; (ch = *p) > ' '; ++p) {
936 PUTBYTE(bp, ch, left);
937 }
938 sep = ',';
939 } else
940 for (; *p > ' '; ++p)
941 continue;
942 }
943 } else {
944 /* new quad-capable format; also does fields. */
945 field = val;
946 while ((ch = *p++) != '\0') {
947 bit = *p++; /* now 0-origin */
948 switch (ch) {
949 case 'b':
950 if (((u_int)(val >> bit) & 1) == 0)
951 goto skip;
952 PUTBYTE(bp, sep, left);
953 PUTSTR(bp, p, left);
954 sep = ',';
955 break;
956 case 'f':
957 case 'F':
958 len = *p++; /* field length */
959 field = (val >> bit) & ((1ULL << len) - 1);
960 if (ch == 'F') /* just extract */
961 break;
962 PUTBYTE(bp, sep, left);
963 sep = ',';
964 PUTSTR(bp, p, left);
965 PUTBYTE(bp, '=', left);
966 sprintf(snbuf, sbase, field);
967 q = snbuf; PUTSTR(bp, q, left);
968 break;
969 case '=':
970 case ':':
971 /*
972 * Here "bit" is actually a value instead,
973 * to be compared against the last field.
974 * This only works for values in [0..255],
975 * of course.
976 */
977 if ((int)field != bit)
978 goto skip;
979 if (ch == '=')
980 PUTBYTE(bp, '=', left);
981 PUTSTR(bp, p, left);
982 break;
983 default:
984 skip:
985 while (*p++ != '\0')
986 continue;
987 break;
988 }
989 }
990 }
991 if (sep != '<')
992 PUTBYTE(bp, '>', left);
993
994 out:
995 return (bf);
996
997 #undef PUTBYTE
998 #undef PUTSTR
999 }
1000
1001 /*
1002 * kprintf: scaled down version of printf(3).
1003 *
1004 * this version based on vfprintf() from libc which was derived from
1005 * software contributed to Berkeley by Chris Torek.
1006 *
1007 * NOTE: The kprintf mutex must be held if we're going TOBUF or TOCONS!
1008 */
1009
1010 /*
1011 * macros for converting digits to letters and vice versa
1012 */
1013 #define to_digit(c) ((c) - '0')
1014 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
1015 #define to_char(n) ((n) + '0')
1016
1017 /*
1018 * flags used during conversion.
1019 */
1020 #define ALT 0x001 /* alternate form */
1021 #define HEXPREFIX 0x002 /* add 0x or 0X prefix */
1022 #define LADJUST 0x004 /* left adjustment */
1023 #define LONGDBL 0x008 /* long double; unimplemented */
1024 #define LONGINT 0x010 /* long integer */
1025 #define QUADINT 0x020 /* quad integer */
1026 #define SHORTINT 0x040 /* short integer */
1027 #define MAXINT 0x080 /* intmax_t */
1028 #define PTRINT 0x100 /* intptr_t */
1029 #define SIZEINT 0x200 /* size_t */
1030 #define ZEROPAD 0x400 /* zero (as opposed to blank) pad */
1031 #define FPT 0x800 /* Floating point number */
1032
1033 /*
1034 * To extend shorts properly, we need both signed and unsigned
1035 * argument extraction methods.
1036 */
1037 #define SARG() \
1038 (flags&MAXINT ? va_arg(ap, intmax_t) : \
1039 flags&PTRINT ? va_arg(ap, intptr_t) : \
1040 flags&SIZEINT ? va_arg(ap, ssize_t) : /* XXX */ \
1041 flags&QUADINT ? va_arg(ap, quad_t) : \
1042 flags&LONGINT ? va_arg(ap, long) : \
1043 flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
1044 (long)va_arg(ap, int))
1045 #define UARG() \
1046 (flags&MAXINT ? va_arg(ap, uintmax_t) : \
1047 flags&PTRINT ? va_arg(ap, uintptr_t) : \
1048 flags&SIZEINT ? va_arg(ap, size_t) : \
1049 flags&QUADINT ? va_arg(ap, u_quad_t) : \
1050 flags&LONGINT ? va_arg(ap, u_long) : \
1051 flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
1052 (u_long)va_arg(ap, u_int))
1053
1054 #define KPRINTF_PUTCHAR(C) { \
1055 if (oflags == TOBUFONLY) { \
1056 if ((vp != NULL) && (sbuf == tailp)) { \
1057 ret += 1; /* indicate error */ \
1058 goto overflow; \
1059 } \
1060 *sbuf++ = (C); \
1061 } else { \
1062 putchar((C), oflags, (struct tty *)vp); \
1063 } \
1064 }
1065
1066 /*
1067 * Guts of kernel printf. Note, we already expect to be in a mutex!
1068 */
1069 int
1070 kprintf(fmt0, oflags, vp, sbuf, ap)
1071 const char *fmt0;
1072 int oflags;
1073 void *vp;
1074 char *sbuf;
1075 va_list ap;
1076 {
1077 const char *fmt; /* format string */
1078 int ch; /* character from fmt */
1079 int n; /* handy integer (short term usage) */
1080 char *cp; /* handy char pointer (short term usage) */
1081 int flags; /* flags as above */
1082 int ret; /* return value accumulator */
1083 int width; /* width from format (%8d), or 0 */
1084 int prec; /* precision from format (%.3d), or -1 */
1085 char sign; /* sign prefix (' ', '+', '-', or \0) */
1086
1087 u_quad_t _uquad; /* integer arguments %[diouxX] */
1088 enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
1089 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
1090 int realsz; /* field size expanded by dprec */
1091 int size; /* size of converted field or string */
1092 const char *xdigs; /* digits for [xX] conversion */
1093 char bf[KPRINTF_BUFSIZE]; /* space for %c, %[diouxX] */
1094 char *tailp; /* tail pointer for snprintf */
1095
1096 tailp = NULL; /* XXX: shutup gcc */
1097 if (oflags == TOBUFONLY && (vp != NULL))
1098 tailp = *(char **)vp;
1099
1100 cp = NULL; /* XXX: shutup gcc */
1101 size = 0; /* XXX: shutup gcc */
1102
1103 fmt = fmt0;
1104 ret = 0;
1105
1106 xdigs = NULL; /* XXX: shut up gcc warning */
1107
1108 /*
1109 * Scan the format for conversions (`%' character).
1110 */
1111 for (;;) {
1112 while (*fmt != '%' && *fmt) {
1113 ret++;
1114 KPRINTF_PUTCHAR(*fmt++);
1115 }
1116 if (*fmt == 0)
1117 goto done;
1118
1119 fmt++; /* skip over '%' */
1120
1121 flags = 0;
1122 dprec = 0;
1123 width = 0;
1124 prec = -1;
1125 sign = '\0';
1126
1127 rflag: ch = *fmt++;
1128 reswitch: switch (ch) {
1129 case ' ':
1130 /*
1131 * ``If the space and + flags both appear, the space
1132 * flag will be ignored.''
1133 * -- ANSI X3J11
1134 */
1135 if (!sign)
1136 sign = ' ';
1137 goto rflag;
1138 case '#':
1139 flags |= ALT;
1140 goto rflag;
1141 case '*':
1142 /*
1143 * ``A negative field width argument is taken as a
1144 * - flag followed by a positive field width.''
1145 * -- ANSI X3J11
1146 * They don't exclude field widths read from args.
1147 */
1148 if ((width = va_arg(ap, int)) >= 0)
1149 goto rflag;
1150 width = -width;
1151 /* FALLTHROUGH */
1152 case '-':
1153 flags |= LADJUST;
1154 goto rflag;
1155 case '+':
1156 sign = '+';
1157 goto rflag;
1158 case '.':
1159 if ((ch = *fmt++) == '*') {
1160 n = va_arg(ap, int);
1161 prec = n < 0 ? -1 : n;
1162 goto rflag;
1163 }
1164 n = 0;
1165 while (is_digit(ch)) {
1166 n = 10 * n + to_digit(ch);
1167 ch = *fmt++;
1168 }
1169 prec = n < 0 ? -1 : n;
1170 goto reswitch;
1171 case '0':
1172 /*
1173 * ``Note that 0 is taken as a flag, not as the
1174 * beginning of a field width.''
1175 * -- ANSI X3J11
1176 */
1177 flags |= ZEROPAD;
1178 goto rflag;
1179 case '1': case '2': case '3': case '4':
1180 case '5': case '6': case '7': case '8': case '9':
1181 n = 0;
1182 do {
1183 n = 10 * n + to_digit(ch);
1184 ch = *fmt++;
1185 } while (is_digit(ch));
1186 width = n;
1187 goto reswitch;
1188 case 'h':
1189 flags |= SHORTINT;
1190 goto rflag;
1191 case 'j':
1192 flags |= MAXINT;
1193 goto rflag;
1194 case 'l':
1195 if (*fmt == 'l') {
1196 fmt++;
1197 flags |= QUADINT;
1198 } else {
1199 flags |= LONGINT;
1200 }
1201 goto rflag;
1202 case 'q':
1203 flags |= QUADINT;
1204 goto rflag;
1205 case 't':
1206 flags |= PTRINT;
1207 goto rflag;
1208 case 'z':
1209 flags |= SIZEINT;
1210 goto rflag;
1211 case 'c':
1212 *(cp = bf) = va_arg(ap, int);
1213 size = 1;
1214 sign = '\0';
1215 break;
1216 case 'D':
1217 flags |= LONGINT;
1218 /*FALLTHROUGH*/
1219 case 'd':
1220 case 'i':
1221 _uquad = SARG();
1222 if ((quad_t)_uquad < 0) {
1223 _uquad = -_uquad;
1224 sign = '-';
1225 }
1226 base = DEC;
1227 goto number;
1228 case 'n':
1229 if (flags & MAXINT)
1230 *va_arg(ap, intmax_t *) = ret;
1231 else if (flags & PTRINT)
1232 *va_arg(ap, intptr_t *) = ret;
1233 else if (flags & SIZEINT)
1234 *va_arg(ap, ssize_t *) = ret;
1235 else if (flags & QUADINT)
1236 *va_arg(ap, quad_t *) = ret;
1237 else if (flags & LONGINT)
1238 *va_arg(ap, long *) = ret;
1239 else if (flags & SHORTINT)
1240 *va_arg(ap, short *) = ret;
1241 else
1242 *va_arg(ap, int *) = ret;
1243 continue; /* no output */
1244 case 'O':
1245 flags |= LONGINT;
1246 /*FALLTHROUGH*/
1247 case 'o':
1248 _uquad = UARG();
1249 base = OCT;
1250 goto nosign;
1251 case 'p':
1252 /*
1253 * ``The argument shall be a pointer to void. The
1254 * value of the pointer is converted to a sequence
1255 * of printable characters, in an implementation-
1256 * defined manner.''
1257 * -- ANSI X3J11
1258 */
1259 /* NOSTRICT */
1260 _uquad = (u_long)va_arg(ap, void *);
1261 base = HEX;
1262 xdigs = hexdigits;
1263 flags |= HEXPREFIX;
1264 ch = 'x';
1265 goto nosign;
1266 case 's':
1267 if ((cp = va_arg(ap, char *)) == NULL)
1268 /*XXXUNCONST*/
1269 cp = __UNCONST("(null)");
1270 if (prec >= 0) {
1271 /*
1272 * can't use strlen; can only look for the
1273 * NUL in the first `prec' characters, and
1274 * strlen() will go further.
1275 */
1276 char *p = memchr(cp, 0, prec);
1277
1278 if (p != NULL) {
1279 size = p - cp;
1280 if (size > prec)
1281 size = prec;
1282 } else
1283 size = prec;
1284 } else
1285 size = strlen(cp);
1286 sign = '\0';
1287 break;
1288 case 'U':
1289 flags |= LONGINT;
1290 /*FALLTHROUGH*/
1291 case 'u':
1292 _uquad = UARG();
1293 base = DEC;
1294 goto nosign;
1295 case 'X':
1296 xdigs = hexdigits;
1297 goto hex;
1298 case 'x':
1299 xdigs = hexdigits;
1300 hex: _uquad = UARG();
1301 base = HEX;
1302 /* leading 0x/X only if non-zero */
1303 if (flags & ALT && _uquad != 0)
1304 flags |= HEXPREFIX;
1305
1306 /* unsigned conversions */
1307 nosign: sign = '\0';
1308 /*
1309 * ``... diouXx conversions ... if a precision is
1310 * specified, the 0 flag will be ignored.''
1311 * -- ANSI X3J11
1312 */
1313 number: if ((dprec = prec) >= 0)
1314 flags &= ~ZEROPAD;
1315
1316 /*
1317 * ``The result of converting a zero value with an
1318 * explicit precision of zero is no characters.''
1319 * -- ANSI X3J11
1320 */
1321 cp = bf + KPRINTF_BUFSIZE;
1322 if (_uquad != 0 || prec != 0) {
1323 /*
1324 * Unsigned mod is hard, and unsigned mod
1325 * by a constant is easier than that by
1326 * a variable; hence this switch.
1327 */
1328 switch (base) {
1329 case OCT:
1330 do {
1331 *--cp = to_char(_uquad & 7);
1332 _uquad >>= 3;
1333 } while (_uquad);
1334 /* handle octal leading 0 */
1335 if (flags & ALT && *cp != '0')
1336 *--cp = '0';
1337 break;
1338
1339 case DEC:
1340 /* many numbers are 1 digit */
1341 while (_uquad >= 10) {
1342 *--cp = to_char(_uquad % 10);
1343 _uquad /= 10;
1344 }
1345 *--cp = to_char(_uquad);
1346 break;
1347
1348 case HEX:
1349 do {
1350 *--cp = xdigs[_uquad & 15];
1351 _uquad >>= 4;
1352 } while (_uquad);
1353 break;
1354
1355 default:
1356 /*XXXUNCONST*/
1357 cp = __UNCONST("bug in kprintf: bad base");
1358 size = strlen(cp);
1359 goto skipsize;
1360 }
1361 }
1362 size = bf + KPRINTF_BUFSIZE - cp;
1363 skipsize:
1364 break;
1365 default: /* "%?" prints ?, unless ? is NUL */
1366 if (ch == '\0')
1367 goto done;
1368 /* pretend it was %c with argument ch */
1369 cp = bf;
1370 *cp = ch;
1371 size = 1;
1372 sign = '\0';
1373 break;
1374 }
1375
1376 /*
1377 * All reasonable formats wind up here. At this point, `cp'
1378 * points to a string which (if not flags&LADJUST) should be
1379 * padded out to `width' places. If flags&ZEROPAD, it should
1380 * first be prefixed by any sign or other prefix; otherwise,
1381 * it should be blank padded before the prefix is emitted.
1382 * After any left-hand padding and prefixing, emit zeroes
1383 * required by a decimal [diouxX] precision, then print the
1384 * string proper, then emit zeroes required by any leftover
1385 * floating precision; finally, if LADJUST, pad with blanks.
1386 *
1387 * Compute actual size, so we know how much to pad.
1388 * size excludes decimal prec; realsz includes it.
1389 */
1390 realsz = dprec > size ? dprec : size;
1391 if (sign)
1392 realsz++;
1393 else if (flags & HEXPREFIX)
1394 realsz+= 2;
1395
1396 /* adjust ret */
1397 ret += width > realsz ? width : realsz;
1398
1399 /* right-adjusting blank padding */
1400 if ((flags & (LADJUST|ZEROPAD)) == 0) {
1401 n = width - realsz;
1402 while (n-- > 0)
1403 KPRINTF_PUTCHAR(' ');
1404 }
1405
1406 /* prefix */
1407 if (sign) {
1408 KPRINTF_PUTCHAR(sign);
1409 } else if (flags & HEXPREFIX) {
1410 KPRINTF_PUTCHAR('0');
1411 KPRINTF_PUTCHAR(ch);
1412 }
1413
1414 /* right-adjusting zero padding */
1415 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) {
1416 n = width - realsz;
1417 while (n-- > 0)
1418 KPRINTF_PUTCHAR('0');
1419 }
1420
1421 /* leading zeroes from decimal precision */
1422 n = dprec - size;
1423 while (n-- > 0)
1424 KPRINTF_PUTCHAR('0');
1425
1426 /* the string or number proper */
1427 while (size--)
1428 KPRINTF_PUTCHAR(*cp++);
1429 /* left-adjusting padding (always blank) */
1430 if (flags & LADJUST) {
1431 n = width - realsz;
1432 while (n-- > 0)
1433 KPRINTF_PUTCHAR(' ');
1434 }
1435 }
1436
1437 done:
1438 if ((oflags == TOBUFONLY) && (vp != NULL))
1439 *(char **)vp = sbuf;
1440 (*v_flush)();
1441 overflow:
1442 return (ret);
1443 /* NOTREACHED */
1444 }
1445