xref: /openbsd/sys/kern/subr_prf.c (revision 91f110e0)
1 /*	$OpenBSD: subr_prf.c,v 1.81 2013/12/12 21:00:09 guenther Exp $	*/
2 /*	$NetBSD: subr_prf.c,v 1.45 1997/10/24 18:14:25 chuck Exp $	*/
3 
4 /*-
5  * Copyright (c) 1986, 1988, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)subr_prf.c	8.3 (Berkeley) 1/21/94
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/buf.h>
43 #include <sys/conf.h>
44 #include <sys/reboot.h>
45 #include <sys/msgbuf.h>
46 #include <sys/proc.h>
47 #include <sys/ioctl.h>
48 #include <sys/vnode.h>
49 #include <sys/file.h>
50 #include <sys/tty.h>
51 #include <sys/tprintf.h>
52 #include <sys/syslog.h>
53 #include <sys/malloc.h>
54 #include <sys/pool.h>
55 #include <sys/mutex.h>
56 
57 #include <dev/cons.h>
58 
59 /*
60  * note that stdarg.h and the ansi style va_start macro is used for both
61  * ansi and traditional c compilers.
62  */
63 #include <sys/stdarg.h>
64 
65 #ifdef KGDB
66 #include <sys/kgdb.h>
67 #endif
68 #ifdef DDB
69 #include <ddb/db_output.h>	/* db_printf, db_putchar prototypes */
70 #include <ddb/db_var.h>		/* db_log, db_radix */
71 #endif
72 
73 
74 /*
75  * defines
76  */
77 
78 /* flags for kprintf */
79 #define TOCONS		0x01	/* to the console */
80 #define TOTTY		0x02	/* to the process' tty */
81 #define TOLOG		0x04	/* to the kernel message buffer */
82 #define TOBUFONLY	0x08	/* to the buffer (only) [for snprintf] */
83 #define TODDB		0x10	/* to ddb console */
84 #define TOCOUNT		0x20	/* act like [v]snprintf */
85 
86 /* max size buffer kprintf needs to print quad_t [size in base 8 + \0] */
87 #define KPRINTF_BUFSIZE		(sizeof(quad_t) * NBBY / 3 + 2)
88 
89 
90 /*
91  * local prototypes
92  */
93 
94 int	 kprintf(const char *, int, void *, char *, va_list);
95 void	 kputchar(int, int, struct tty *);
96 
97 struct mutex kprintf_mutex = MUTEX_INITIALIZER(IPL_HIGH);
98 
99 /*
100  * globals
101  */
102 
103 extern struct	tty *constty;	/* pointer to console "window" tty */
104 extern	int log_open;	/* subr_log: is /dev/klog open? */
105 const	char *panicstr; /* arg to first call to panic (used as a flag
106 			   to indicate that panic has already been called). */
107 #ifdef DDB
108 /*
109  * Enter ddb on panic.
110  */
111 int	db_panic = 1;
112 
113 /*
114  * db_console controls if we can be able to enter ddb by a special key
115  * combination (machine dependent).
116  * If DDB_SAFE_CONSOLE is defined in the kernel configuration it allows
117  * to break into console during boot. It's _really_ useful when debugging
118  * some things in the kernel that can cause init(8) to crash.
119  */
120 #ifdef DDB_SAFE_CONSOLE
121 int	db_console = 1;
122 #else
123 int	db_console = 0;
124 #endif
125 
126 /*
127  * flag to indicate if we are currently in ddb (on some processor)
128  */
129 int db_is_active;
130 #endif
131 
132 /*
133  * panic on spl assertion failure?
134  */
135 int splassert_ctl = 1;
136 
137 /*
138  * v_putc: routine to putc on virtual console
139  *
140  * the v_putc pointer can be used to redirect the console cnputc elsewhere
141  * [e.g. to a "virtual console"].
142  */
143 
144 void (*v_putc)(int) = cnputc;	/* start with cnputc (normal cons) */
145 
146 
147 /*
148  * functions
149  */
150 
151 /*
152  *	Partial support (the failure case) of the assertion facility
153  *	commonly found in userland.
154  */
155 void
156 __assert(const char *t, const char *f, int l, const char *e)
157 {
158 
159 	panic("kernel %sassertion \"%s\" failed: file \"%s\", line %d",
160 		t, e, f, l);
161 }
162 
163 /*
164  * tablefull: warn that a system table is full
165  */
166 
167 void
168 tablefull(const char *tab)
169 {
170 	log(LOG_ERR, "%s: table is full\n", tab);
171 }
172 
173 /*
174  * panic: handle an unresolvable fatal error
175  *
176  * prints "panic: <message>" and reboots.   if called twice (i.e. recursive
177  * call) we avoid trying to sync the disk and just reboot (to avoid
178  * recursive panics).
179  */
180 
181 void
182 panic(const char *fmt, ...)
183 {
184 	static char panicbuf[512];
185 	int bootopt;
186 	va_list ap;
187 
188 	/* do not trigger assertions, we know that we are inconsistent */
189 	splassert_ctl = 0;
190 
191 	bootopt = RB_AUTOBOOT | RB_DUMP;
192 	va_start(ap, fmt);
193 	if (panicstr)
194 		bootopt |= RB_NOSYNC;
195 	else {
196 		vsnprintf(panicbuf, sizeof panicbuf, fmt, ap);
197 		panicstr = panicbuf;
198 	}
199 	va_end(ap);
200 
201 	printf("panic: ");
202 	va_start(ap, fmt);
203 	vprintf(fmt, ap);
204 	printf("\n");
205 	va_end(ap);
206 
207 #ifdef KGDB
208 	kgdb_panic();
209 #endif
210 #ifdef KADB
211 	if (boothowto & RB_KDB)
212 		kdbpanic();
213 #endif
214 #ifdef DDB
215 	if (db_panic)
216 		Debugger();
217 	else
218 		db_stack_dump();
219 #endif
220 	boot(bootopt);
221 }
222 
223 /*
224  * We print only the function name. The file name is usually very long and
225  * would eat tons of space in the kernel.
226  */
227 void
228 splassert_fail(int wantipl, int haveipl, const char *func)
229 {
230 
231 	printf("splassert: %s: want %d have %d\n", func, wantipl, haveipl);
232 	switch (splassert_ctl) {
233 	case 1:
234 		break;
235 	case 2:
236 #ifdef DDB
237 		db_stack_dump();
238 #endif
239 		break;
240 	case 3:
241 #ifdef DDB
242 		db_stack_dump();
243 		Debugger();
244 #endif
245 		break;
246 	default:
247 		panic("spl assertion failure in %s", func);
248 	}
249 }
250 
251 /*
252  * kernel logging functions: log, logpri, addlog
253  */
254 
255 /*
256  * log: write to the log buffer
257  *
258  * => will not sleep [so safe to call from interrupt]
259  * => will log to console if /dev/klog isn't open
260  */
261 
262 void
263 log(int level, const char *fmt, ...)
264 {
265 	int s;
266 	va_list ap;
267 
268 	s = splhigh();
269 	logpri(level);		/* log the level first */
270 	va_start(ap, fmt);
271 	kprintf(fmt, TOLOG, NULL, NULL, ap);
272 	va_end(ap);
273 	splx(s);
274 	if (!log_open) {
275 		va_start(ap, fmt);
276 		kprintf(fmt, TOCONS, NULL, NULL, ap);
277 		va_end(ap);
278 	}
279 	logwakeup();		/* wake up anyone waiting for log msgs */
280 }
281 
282 /*
283  * logpri: log the priority level to the klog
284  */
285 
286 void
287 logpri(int level)
288 {
289 	char *p;
290 	char snbuf[KPRINTF_BUFSIZE];
291 
292 	kputchar('<', TOLOG, NULL);
293 	snprintf(snbuf, sizeof snbuf, "%d", level);
294 	for (p = snbuf ; *p ; p++)
295 		kputchar(*p, TOLOG, NULL);
296 	kputchar('>', TOLOG, NULL);
297 }
298 
299 /*
300  * addlog: add info to previous log message
301  */
302 
303 int
304 addlog(const char *fmt, ...)
305 {
306 	int s;
307 	va_list ap;
308 
309 	s = splhigh();
310 	va_start(ap, fmt);
311 	kprintf(fmt, TOLOG, NULL, NULL, ap);
312 	va_end(ap);
313 	splx(s);
314 	if (!log_open) {
315 		va_start(ap, fmt);
316 		kprintf(fmt, TOCONS, NULL, NULL, ap);
317 		va_end(ap);
318 	}
319 	logwakeup();
320 	return(0);
321 }
322 
323 
324 /*
325  * kputchar: print a single character on console or user terminal.
326  *
327  * => if console, then the last MSGBUFS chars are saved in msgbuf
328  *	for inspection later (e.g. dmesg/syslog)
329  */
330 void
331 kputchar(int c, int flags, struct tty *tp)
332 {
333 	extern int msgbufmapped;
334 	int ddb_active = 0;
335 
336 #ifdef DDB
337 	ddb_active = db_is_active;
338 #endif
339 
340 	if (panicstr)
341 		constty = NULL;
342 
343 	if ((flags & TOCONS) && tp == NULL && constty && !ddb_active) {
344 		tp = constty;
345 		flags |= TOTTY;
346 	}
347 	if ((flags & TOTTY) && tp && tputchar(c, tp) < 0 &&
348 	    (flags & TOCONS) && tp == constty)
349 		constty = NULL;
350 	if ((flags & TOLOG) &&
351 	    c != '\0' && c != '\r' && c != 0177 && msgbufmapped)
352 		msgbuf_putchar(c);
353 	if ((flags & TOCONS) && (constty == NULL || ddb_active) && c != '\0')
354 		(*v_putc)(c);
355 #ifdef DDB
356 	if (flags & TODDB)
357 		db_putchar(c);
358 #endif
359 }
360 
361 
362 /*
363  * uprintf: print to the controlling tty of the current process
364  *
365  * => we may block if the tty queue is full
366  * => no message is printed if the queue doesn't clear in a reasonable
367  *	time
368  */
369 
370 void
371 uprintf(const char *fmt, ...)
372 {
373 	struct process *pr = curproc->p_p;
374 	va_list ap;
375 
376 	if (pr->ps_flags & PS_CONTROLT && pr->ps_session->s_ttyvp) {
377 		va_start(ap, fmt);
378 		kprintf(fmt, TOTTY, pr->ps_session->s_ttyp, NULL, ap);
379 		va_end(ap);
380 	}
381 }
382 
383 #if defined(NFSSERVER) || defined(NFSCLIENT)
384 
385 /*
386  * tprintf functions: used to send messages to a specific process
387  *
388  * usage:
389  *   get a tpr_t handle on a process "p" by using "tprintf_open(p)"
390  *   use the handle when calling "tprintf"
391  *   when done, do a "tprintf_close" to drop the handle
392  */
393 
394 /*
395  * tprintf_open: get a tprintf handle on a process "p"
396  * XXX change s/proc/process
397  *
398  * => returns NULL if process can't be printed to
399  */
400 
401 tpr_t
402 tprintf_open(struct proc *p)
403 {
404 	struct process *pr = p->p_p;
405 
406 	if (pr->ps_flags & PS_CONTROLT && pr->ps_session->s_ttyvp) {
407 		SESSHOLD(pr->ps_session);
408 		return ((tpr_t)pr->ps_session);
409 	}
410 	return ((tpr_t) NULL);
411 }
412 
413 /*
414  * tprintf_close: dispose of a tprintf handle obtained with tprintf_open
415  */
416 
417 void
418 tprintf_close(tpr_t sess)
419 {
420 
421 	if (sess)
422 		SESSRELE((struct session *) sess);
423 }
424 
425 /*
426  * tprintf: given tprintf handle to a process [obtained with tprintf_open],
427  * send a message to the controlling tty for that process.
428  *
429  * => also sends message to /dev/klog
430  */
431 void
432 tprintf(tpr_t tpr, const char *fmt, ...)
433 {
434 	struct session *sess = (struct session *)tpr;
435 	struct tty *tp = NULL;
436 	int flags = TOLOG;
437 	va_list ap;
438 
439 	logpri(LOG_INFO);
440 	if (sess && sess->s_ttyvp && ttycheckoutq(sess->s_ttyp, 0)) {
441 		flags |= TOTTY;
442 		tp = sess->s_ttyp;
443 	}
444 	va_start(ap, fmt);
445 	kprintf(fmt, flags, tp, NULL, ap);
446 	va_end(ap);
447 	logwakeup();
448 }
449 
450 #endif	/* NFSSERVER || NFSCLIENT */
451 
452 
453 /*
454  * ttyprintf: send a message to a specific tty
455  *
456  * => should be used only by tty driver or anything that knows the
457  *	underlying tty will not be revoked(2)'d away.  [otherwise,
458  *	use tprintf]
459  */
460 void
461 ttyprintf(struct tty *tp, const char *fmt, ...)
462 {
463 	va_list ap;
464 
465 	va_start(ap, fmt);
466 	kprintf(fmt, TOTTY, tp, NULL, ap);
467 	va_end(ap);
468 }
469 
470 #ifdef DDB
471 
472 /*
473  * db_printf: printf for DDB (via db_putchar)
474  */
475 
476 int
477 db_printf(const char *fmt, ...)
478 {
479 	va_list ap;
480 	int retval;
481 
482 	va_start(ap, fmt);
483 	retval = db_vprintf(fmt, ap);
484 	va_end(ap);
485 	return(retval);
486 }
487 
488 int
489 db_vprintf(const char *fmt, va_list ap)
490 {
491 	int flags;
492 
493 	flags = TODDB;
494 	if (db_log)
495 		flags |= TOLOG;
496 	return (kprintf(fmt, flags, NULL, NULL, ap));
497 }
498 #endif /* DDB */
499 
500 
501 /*
502  * normal kernel printf functions: printf, vprintf, snprintf
503  */
504 
505 /*
506  * printf: print a message to the console and the log
507  */
508 int
509 printf(const char *fmt, ...)
510 {
511 	va_list ap;
512 	int retval;
513 
514 	mtx_enter(&kprintf_mutex);
515 
516 	va_start(ap, fmt);
517 	retval = kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
518 	va_end(ap);
519 	if (!panicstr)
520 		logwakeup();
521 
522 	mtx_leave(&kprintf_mutex);
523 
524 	return(retval);
525 }
526 
527 /*
528  * vprintf: print a message to the console and the log [already have a
529  *	va_list]
530  */
531 
532 int
533 vprintf(const char *fmt, va_list ap)
534 {
535 	int retval;
536 
537 	mtx_enter(&kprintf_mutex);
538 
539 	retval = kprintf(fmt, TOCONS | TOLOG, NULL, NULL, ap);
540 	if (!panicstr)
541 		logwakeup();
542 
543 	mtx_leave(&kprintf_mutex);
544 
545 	return (retval);
546 }
547 
548 /*
549  * snprintf: print a message to a buffer
550  */
551 int
552 snprintf(char *buf, size_t size, const char *fmt, ...)
553 {
554 	int retval;
555 	va_list ap;
556 	char *p;
557 
558 	p = buf + size - 1;
559 	if (size < 1)
560 		p = buf;
561 	va_start(ap, fmt);
562 	retval = kprintf(fmt, TOBUFONLY | TOCOUNT, &p, buf, ap);
563 	va_end(ap);
564 	if (size > 0)
565 		*(p) = 0;	/* null terminate */
566 	return(retval);
567 }
568 
569 /*
570  * vsnprintf: print a message to a buffer [already have va_alist]
571  */
572 int
573 vsnprintf(char *buf, size_t size, const char *fmt, va_list ap)
574 {
575 	int retval;
576 	char *p;
577 
578 	p = buf + size - 1;
579 	if (size < 1)
580 		p = buf;
581 	retval = kprintf(fmt, TOBUFONLY | TOCOUNT, &p, buf, ap);
582 	if (size > 0)
583 		*(p) = 0;	/* null terminate */
584 	return(retval);
585 }
586 
587 /*
588  * kprintf: scaled down version of printf(3).
589  *
590  * this version based on vfprintf() from libc which was derived from
591  * software contributed to Berkeley by Chris Torek.
592  *
593  * The additional format %b is supported to decode error registers.
594  * Its usage is:
595  *
596  *	printf("reg=%b\n", regval, "<base><arg>*");
597  *
598  * where <base> is the output base expressed as a control character, e.g.
599  * \10 gives octal; \20 gives hex.  Each arg is a sequence of characters,
600  * the first of which gives the bit number to be inspected (origin 1), and
601  * the next characters (up to a control character, i.e. a character <= 32),
602  * give the name of the register.  Thus:
603  *
604  *	kprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n");
605  *
606  * would produce output:
607  *
608  *	reg=3<BITTWO,BITONE>
609  *
610  * To support larger integers (> 32 bits), %b formatting will also accept
611  * control characters in the region 0x80 - 0xff.  0x80 refers to bit 0,
612  * 0x81 refers to bit 1, and so on.  The equivalent string to the above is:
613  *
614  *	kprintf("reg=%b\n", 3, "\10\201BITTWO\200BITONE\n");
615  *
616  * and would produce the same output.
617  *
618  * Like the rest of printf, %b can be prefixed to handle various size
619  * modifiers, eg. %b is for "int", %lb is for "long", and %llb supports
620  * "long long".
621  *
622  * This code is large and complicated...
623  */
624 
625 /*
626  * macros for converting digits to letters and vice versa
627  */
628 #define	to_digit(c)	((c) - '0')
629 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
630 #define	to_char(n)	((n) + '0')
631 
632 /*
633  * flags used during conversion.
634  */
635 #define	ALT		0x001		/* alternate form */
636 #define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
637 #define	LADJUST		0x004		/* left adjustment */
638 #define	LONGDBL		0x008		/* long double; unimplemented */
639 #define	LONGINT		0x010		/* long integer */
640 #define	QUADINT		0x020		/* quad integer */
641 #define	SHORTINT	0x040		/* short integer */
642 #define	ZEROPAD		0x080		/* zero (as opposed to blank) pad */
643 #define FPT		0x100		/* Floating point number */
644 #define SIZEINT		0x200		/* (signed) size_t */
645 
646 	/*
647 	 * To extend shorts properly, we need both signed and unsigned
648 	 * argument extraction methods.
649 	 */
650 #define	SARG() \
651 	(flags&QUADINT ? va_arg(ap, quad_t) : \
652 	    flags&LONGINT ? va_arg(ap, long) : \
653 	    flags&SIZEINT ? va_arg(ap, ssize_t) : \
654 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
655 	    (long)va_arg(ap, int))
656 #define	UARG() \
657 	(flags&QUADINT ? va_arg(ap, u_quad_t) : \
658 	    flags&LONGINT ? va_arg(ap, u_long) : \
659 	    flags&SIZEINT ? va_arg(ap, size_t) : \
660 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
661 	    (u_long)va_arg(ap, u_int))
662 
663 #define KPRINTF_PUTCHAR(C) do {					\
664 	int chr = (C);							\
665 	ret += 1;							\
666 	if (oflags & TOBUFONLY) {					\
667 		if ((vp != NULL) && (sbuf == tailp)) {			\
668 			if (!(oflags & TOCOUNT))				\
669 				goto overflow;				\
670 		} else							\
671 			*sbuf++ = chr;					\
672 	} else {							\
673 		kputchar(chr, oflags, (struct tty *)vp);			\
674 	}								\
675 } while(0)
676 
677 int
678 kprintf(const char *fmt0, int oflags, void *vp, char *sbuf, va_list ap)
679 {
680 	char *fmt;		/* format string */
681 	int ch;			/* character from fmt */
682 	int n;			/* handy integer (short term usage) */
683 	char *cp = NULL;	/* handy char pointer (short term usage) */
684 	int flags;		/* flags as above */
685 	int ret;		/* return value accumulator */
686 	int width;		/* width from format (%8d), or 0 */
687 	int prec;		/* precision from format (%.3d), or -1 */
688 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
689 
690 	u_quad_t _uquad;	/* integer arguments %[diouxX] */
691 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
692 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
693 	int realsz;		/* field size expanded by dprec */
694 	int size = 0;		/* size of converted field or string */
695 	char *xdigs = NULL;	/* digits for [xX] conversion */
696 	char buf[KPRINTF_BUFSIZE]; /* space for %c, %[diouxX] */
697 	char *tailp = NULL;	/* tail pointer for snprintf */
698 
699 	if ((oflags & TOBUFONLY) && (vp != NULL))
700 		tailp = *(char **)vp;
701 
702 	fmt = (char *)fmt0;
703 	ret = 0;
704 
705 	/*
706 	 * Scan the format for conversions (`%' character).
707 	 */
708 	for (;;) {
709 		while (*fmt != '%' && *fmt) {
710 			KPRINTF_PUTCHAR(*fmt++);
711 		}
712 		if (*fmt == 0)
713 			goto done;
714 
715 		fmt++;		/* skip over '%' */
716 
717 		flags = 0;
718 		dprec = 0;
719 		width = 0;
720 		prec = -1;
721 		sign = '\0';
722 
723 rflag:		ch = *fmt++;
724 reswitch:	switch (ch) {
725 		/* XXX: non-standard '%b' format */
726 		case 'b': {
727 			char *b, *z;
728 			int tmp;
729 			_uquad = UARG();
730 			b = va_arg(ap, char *);
731 			if (*b == 8)
732 				snprintf(buf, sizeof buf, "%llo", _uquad);
733 			else if (*b == 10)
734 				snprintf(buf, sizeof buf, "%lld", _uquad);
735 			else if (*b == 16)
736 				snprintf(buf, sizeof buf, "%llx", _uquad);
737 			else
738 				break;
739 			b++;
740 
741 			z = buf;
742 			while (*z) {
743 				KPRINTF_PUTCHAR(*z++);
744 			}
745 
746 			if (_uquad) {
747 				tmp = 0;
748 				while ((n = *b++) != 0) {
749 					if (n & 0x80)
750 						n &= 0x7f;
751 					else if (n <= ' ')
752 						n = n - 1;
753 					if (_uquad & (1LL << n)) {
754 						KPRINTF_PUTCHAR(tmp ? ',':'<');
755 						while (*b > ' ' &&
756 						    (*b & 0x80) == 0) {
757 							KPRINTF_PUTCHAR(*b);
758 							b++;
759 						}
760 						tmp = 1;
761 					} else {
762 						while (*b > ' ' &&
763 						    (*b & 0x80) == 0)
764 							b++;
765 					}
766 				}
767 				if (tmp) {
768 					KPRINTF_PUTCHAR('>');
769 				}
770 			}
771 			continue;	/* no output */
772 		}
773 
774 		case ' ':
775 			/*
776 			 * ``If the space and + flags both appear, the space
777 			 * flag will be ignored.''
778 			 *	-- ANSI X3J11
779 			 */
780 			if (!sign)
781 				sign = ' ';
782 			goto rflag;
783 		case '#':
784 			flags |= ALT;
785 			goto rflag;
786 		case '*':
787 			/*
788 			 * ``A negative field width argument is taken as a
789 			 * - flag followed by a positive field width.''
790 			 *	-- ANSI X3J11
791 			 * They don't exclude field widths read from args.
792 			 */
793 			if ((width = va_arg(ap, int)) >= 0)
794 				goto rflag;
795 			width = -width;
796 			/* FALLTHROUGH */
797 		case '-':
798 			flags |= LADJUST;
799 			goto rflag;
800 		case '+':
801 			sign = '+';
802 			goto rflag;
803 		case '.':
804 			if ((ch = *fmt++) == '*') {
805 				n = va_arg(ap, int);
806 				prec = n < 0 ? -1 : n;
807 				goto rflag;
808 			}
809 			n = 0;
810 			while (is_digit(ch)) {
811 				n = 10 * n + to_digit(ch);
812 				ch = *fmt++;
813 			}
814 			prec = n < 0 ? -1 : n;
815 			goto reswitch;
816 		case '0':
817 			/*
818 			 * ``Note that 0 is taken as a flag, not as the
819 			 * beginning of a field width.''
820 			 *	-- ANSI X3J11
821 			 */
822 			flags |= ZEROPAD;
823 			goto rflag;
824 		case '1': case '2': case '3': case '4':
825 		case '5': case '6': case '7': case '8': case '9':
826 			n = 0;
827 			do {
828 				n = 10 * n + to_digit(ch);
829 				ch = *fmt++;
830 			} while (is_digit(ch));
831 			width = n;
832 			goto reswitch;
833 		case 'h':
834 			flags |= SHORTINT;
835 			goto rflag;
836 		case 'l':
837 			if (*fmt == 'l') {
838 				fmt++;
839 				flags |= QUADINT;
840 			} else {
841 				flags |= LONGINT;
842 			}
843 			goto rflag;
844 		case 'q':
845 			flags |= QUADINT;
846 			goto rflag;
847 		case 'z':
848 			flags |= SIZEINT;
849 			goto rflag;
850 		case 'c':
851 			*(cp = buf) = va_arg(ap, int);
852 			size = 1;
853 			sign = '\0';
854 			break;
855 		case 't':
856 			/* ptrdiff_t */
857 			/* FALLTHROUGH */
858 		case 'D':
859 			flags |= LONGINT;
860 			/*FALLTHROUGH*/
861 		case 'd':
862 		case 'i':
863 			_uquad = SARG();
864 			if ((quad_t)_uquad < 0) {
865 				_uquad = -_uquad;
866 				sign = '-';
867 			}
868 			base = DEC;
869 			goto number;
870 		case 'n':
871 			/* %n is unsupported in the kernel; just skip it */
872 			if (flags & QUADINT)
873 				(void)va_arg(ap, quad_t *);
874 			else if (flags & LONGINT)
875 				(void)va_arg(ap, long *);
876 			else if (flags & SHORTINT)
877 				(void)va_arg(ap, short *);
878 			else if (flags & SIZEINT)
879 				(void)va_arg(ap, ssize_t *);
880 			else
881 				(void)va_arg(ap, int *);
882 			continue;	/* no output */
883 		case 'O':
884 			flags |= LONGINT;
885 			/*FALLTHROUGH*/
886 		case 'o':
887 			_uquad = UARG();
888 			base = OCT;
889 			goto nosign;
890 		case 'p':
891 			/*
892 			 * ``The argument shall be a pointer to void.  The
893 			 * value of the pointer is converted to a sequence
894 			 * of printable characters, in an implementation-
895 			 * defined manner.''
896 			 *	-- ANSI X3J11
897 			 */
898 			/* NOSTRICT */
899 			_uquad = (u_long)va_arg(ap, void *);
900 			base = HEX;
901 			xdigs = "0123456789abcdef";
902 			flags |= HEXPREFIX;
903 			ch = 'x';
904 			goto nosign;
905 		case 's':
906 			if ((cp = va_arg(ap, char *)) == NULL)
907 				cp = "(null)";
908 			if (prec >= 0) {
909 				/*
910 				 * can't use strlen; can only look for the
911 				 * NUL in the first `prec' characters, and
912 				 * strlen() will go further.
913 				 */
914 				char *p = memchr(cp, 0, prec);
915 
916 				if (p != NULL) {
917 					size = p - cp;
918 					if (size > prec)
919 						size = prec;
920 				} else
921 					size = prec;
922 			} else
923 				size = strlen(cp);
924 			sign = '\0';
925 			break;
926 		case 'U':
927 			flags |= LONGINT;
928 			/*FALLTHROUGH*/
929 		case 'u':
930 			_uquad = UARG();
931 			base = DEC;
932 			goto nosign;
933 		case 'X':
934 			xdigs = "0123456789ABCDEF";
935 			goto hex;
936 		case 'x':
937 			xdigs = "0123456789abcdef";
938 hex:			_uquad = UARG();
939 			base = HEX;
940 			/* leading 0x/X only if non-zero */
941 			if (flags & ALT && _uquad != 0)
942 				flags |= HEXPREFIX;
943 
944 			/* unsigned conversions */
945 nosign:			sign = '\0';
946 			/*
947 			 * ``... diouXx conversions ... if a precision is
948 			 * specified, the 0 flag will be ignored.''
949 			 *	-- ANSI X3J11
950 			 */
951 number:			if ((dprec = prec) >= 0)
952 				flags &= ~ZEROPAD;
953 
954 			/*
955 			 * ``The result of converting a zero value with an
956 			 * explicit precision of zero is no characters.''
957 			 *	-- ANSI X3J11
958 			 */
959 			cp = buf + KPRINTF_BUFSIZE;
960 			if (_uquad != 0 || prec != 0) {
961 				/*
962 				 * Unsigned mod is hard, and unsigned mod
963 				 * by a constant is easier than that by
964 				 * a variable; hence this switch.
965 				 */
966 				switch (base) {
967 				case OCT:
968 					do {
969 						*--cp = to_char(_uquad & 7);
970 						_uquad >>= 3;
971 					} while (_uquad);
972 					/* handle octal leading 0 */
973 					if (flags & ALT && *cp != '0')
974 						*--cp = '0';
975 					break;
976 
977 				case DEC:
978 					/* many numbers are 1 digit */
979 					while (_uquad >= 10) {
980 						*--cp = to_char(_uquad % 10);
981 						_uquad /= 10;
982 					}
983 					*--cp = to_char(_uquad);
984 					break;
985 
986 				case HEX:
987 					do {
988 						*--cp = xdigs[_uquad & 15];
989 						_uquad >>= 4;
990 					} while (_uquad);
991 					break;
992 
993 				default:
994 					cp = "bug in kprintf: bad base";
995 					size = strlen(cp);
996 					goto skipsize;
997 				}
998 			}
999 			size = buf + KPRINTF_BUFSIZE - cp;
1000 		skipsize:
1001 			break;
1002 		default:	/* "%?" prints ?, unless ? is NUL */
1003 			if (ch == '\0')
1004 				goto done;
1005 			/* pretend it was %c with argument ch */
1006 			cp = buf;
1007 			*cp = ch;
1008 			size = 1;
1009 			sign = '\0';
1010 			break;
1011 		}
1012 
1013 		/*
1014 		 * All reasonable formats wind up here.  At this point, `cp'
1015 		 * points to a string which (if not flags&LADJUST) should be
1016 		 * padded out to `width' places.  If flags&ZEROPAD, it should
1017 		 * first be prefixed by any sign or other prefix; otherwise,
1018 		 * it should be blank padded before the prefix is emitted.
1019 		 * After any left-hand padding and prefixing, emit zeroes
1020 		 * required by a decimal [diouxX] precision, then print the
1021 		 * string proper, then emit zeroes required by any leftover
1022 		 * floating precision; finally, if LADJUST, pad with blanks.
1023 		 *
1024 		 * Compute actual size, so we know how much to pad.
1025 		 * size excludes decimal prec; realsz includes it.
1026 		 */
1027 		realsz = dprec > size ? dprec : size;
1028 		if (sign)
1029 			realsz++;
1030 		else if (flags & HEXPREFIX)
1031 			realsz+= 2;
1032 
1033 		/* right-adjusting blank padding */
1034 		if ((flags & (LADJUST|ZEROPAD)) == 0) {
1035 			n = width - realsz;
1036 			while (n-- > 0)
1037 				KPRINTF_PUTCHAR(' ');
1038 		}
1039 
1040 		/* prefix */
1041 		if (sign) {
1042 			KPRINTF_PUTCHAR(sign);
1043 		} else if (flags & HEXPREFIX) {
1044 			KPRINTF_PUTCHAR('0');
1045 			KPRINTF_PUTCHAR(ch);
1046 		}
1047 
1048 		/* right-adjusting zero padding */
1049 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD) {
1050 			n = width - realsz;
1051 			while (n-- > 0)
1052 				KPRINTF_PUTCHAR('0');
1053 		}
1054 
1055 		/* leading zeroes from decimal precision */
1056 		n = dprec - size;
1057 		while (n-- > 0)
1058 			KPRINTF_PUTCHAR('0');
1059 
1060 		/* the string or number proper */
1061 		while (size--)
1062 			KPRINTF_PUTCHAR(*cp++);
1063 		/* left-adjusting padding (always blank) */
1064 		if (flags & LADJUST) {
1065 			n = width - realsz;
1066 			while (n-- > 0)
1067 				KPRINTF_PUTCHAR(' ');
1068 		}
1069 	}
1070 
1071 done:
1072 	if ((oflags & TOBUFONLY) && (vp != NULL))
1073 		*(char **)vp = sbuf;
1074 overflow:
1075 	return (ret);
1076 	/* NOTREACHED */
1077 }
1078 
1079 #if __GNUC_PREREQ__(2,96)
1080 /*
1081  * XXX - these functions shouldn't be in the kernel, but gcc 3.X feels like
1082  *       translating some printf calls to puts and since it doesn't seem
1083  *       possible to just turn off parts of those optimizations (some of
1084  *       them are really useful), we have to provide a dummy puts and putchar
1085  *	 that are wrappers around printf.
1086  */
1087 int	puts(const char *);
1088 int	putchar(int c);
1089 
1090 int
1091 puts(const char *str)
1092 {
1093 	printf("%s\n", str);
1094 
1095 	return (0);
1096 }
1097 
1098 int
1099 putchar(int c)
1100 {
1101 	printf("%c", c);
1102 
1103 	return (c);
1104 }
1105 
1106 
1107 #endif
1108