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