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