Home | History | Annotate | Line # | Download | only in kern
      1 /*	$NetBSD: subr_log.c,v 1.69 2026/11/24 17:35:55 msaitoh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2007, 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Andrew Doran.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1982, 1986, 1993
     34  *	The Regents of the University of California.  All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. Neither the name of the University nor the names of its contributors
     45  *    may be used to endorse or promote products derived from this software
     46  *    without specific prior written permission.
     47  *
     48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     58  * SUCH DAMAGE.
     59  *
     60  *	@(#)subr_log.c	8.3 (Berkeley) 2/14/95
     61  */
     62 
     63 /*
     64  * Error log buffer for kernel printf's.
     65  */
     66 
     67 #include <sys/cdefs.h>
     68 __KERNEL_RCSID(0, "$NetBSD: subr_log.c,v 1.69 2026/11/24 17:35:55 msaitoh Exp $");
     69 
     70 #include <sys/param.h>
     71 #include <sys/types.h>
     72 
     73 #include <sys/conf.h>
     74 #include <sys/file.h>
     75 #include <sys/intr.h>
     76 #include <sys/ioctl.h>
     77 #include <sys/kernel.h>
     78 #include <sys/ktrace.h>
     79 #include <sys/msgbuf.h>
     80 #include <sys/poll.h>
     81 #include <sys/proc.h>
     82 #include <sys/sdt.h>
     83 #include <sys/select.h>
     84 #include <sys/sysctl.h>
     85 #include <sys/syslog.h>
     86 #include <sys/systm.h>
     87 #include <sys/vnode.h>
     88 
     89 static int sysctl_msgbuf(SYSCTLFN_PROTO);
     90 
     91 static void	logsoftintr(void *);
     92 
     93 static bool	log_async;
     94 static struct selinfo log_selp;		/* process waiting on select call */
     95 static pid_t	log_pgid;		/* process/group for async I/O */
     96 static kcondvar_t log_cv;
     97 static void	*log_sih;
     98 
     99 static kmutex_t log_lock;
    100 int	log_open;			/* also used in log() */
    101 int	msgbufmapped;			/* is the message buffer mapped */
    102 int	msgbufenabled;			/* is logging to the buffer enabled */
    103 struct	kern_msgbuf *msgbufp;		/* the mapped buffer, itself. */
    104 
    105 void
    106 initmsgbuf(void *bf, size_t bufsize)
    107 {
    108 	struct kern_msgbuf *mbp;
    109 	long new_bufs;
    110 
    111 	/* Sanity-check the given size. */
    112 	if (bufsize < sizeof(struct kern_msgbuf))
    113 		return;
    114 
    115 	mbp = msgbufp = (struct kern_msgbuf *)bf;
    116 
    117 	new_bufs = bufsize - offsetof(struct kern_msgbuf, msg_bufc);
    118 	if ((mbp->msg_magic != MSG_MAGIC) || (mbp->msg_bufs != new_bufs) ||
    119 	    (mbp->msg_bufr < 0) || (mbp->msg_bufr >= mbp->msg_bufs) ||
    120 	    (mbp->msg_bufx < 0) || (mbp->msg_bufx >= mbp->msg_bufs)) {
    121 		/*
    122 		 * If the buffer magic number is wrong, has changed
    123 		 * size (which shouldn't happen often), or is
    124 		 * internally inconsistent, initialize it.
    125 		 */
    126 
    127 		memset(bf, 0, bufsize);
    128 		mbp->msg_magic = MSG_MAGIC;
    129 		mbp->msg_bufs = new_bufs;
    130 	}
    131 
    132 	/* mark it as ready for use. */
    133 	msgbufmapped = msgbufenabled = 1;
    134 }
    135 
    136 void
    137 loginit(void)
    138 {
    139 
    140 	mutex_init(&log_lock, MUTEX_DEFAULT, IPL_VM);
    141 	selinit(&log_selp);
    142 	cv_init(&log_cv, "klog");
    143 	log_sih = softint_establish(SOFTINT_CLOCK | SOFTINT_MPSAFE,
    144 	    logsoftintr, NULL);
    145 
    146 	sysctl_createv(NULL, 0, NULL, NULL,
    147 		       CTLFLAG_PERMANENT,
    148 		       CTLTYPE_INT, "msgbufsize",
    149 		       SYSCTL_DESCR("Size of the kernel message buffer"),
    150 		       sysctl_msgbuf, 0, NULL, 0,
    151 		       CTL_KERN, KERN_MSGBUFSIZE, CTL_EOL);
    152 	sysctl_createv(NULL, 0, NULL, NULL,
    153 		       CTLFLAG_PERMANENT,
    154 		       CTLTYPE_INT, "msgbuf",
    155 		       SYSCTL_DESCR("Kernel message buffer"),
    156 		       sysctl_msgbuf, 0, NULL, 0,
    157 		       CTL_KERN, KERN_MSGBUF, CTL_EOL);
    158 	sysctl_createv(NULL, 0, NULL, NULL,
    159 		       CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
    160 		       CTLTYPE_INT, "msgbuf_clear",
    161 		       SYSCTL_DESCR("Clear the kernel message buffer"),
    162 		       sysctl_msgbuf, 0, NULL, 0,
    163 		       CTL_KERN, KERN_MSGBUFCLR, CTL_EOL);
    164 }
    165 
    166 /*ARGSUSED*/
    167 static int
    168 logopen(dev_t dev, int flags, int mode, struct lwp *l)
    169 {
    170 	struct kern_msgbuf *mbp = msgbufp;
    171 	int error = 0;
    172 
    173 	mutex_spin_enter(&log_lock);
    174 	if (log_open) {
    175 		error = SET_ERROR(EBUSY);
    176 	} else {
    177 		log_open = 1;
    178 		log_pgid = l->l_proc->p_pid;	/* signal process only */
    179 		/*
    180 		 * The message buffer is initialized during system
    181 		 * configuration.  If it's been clobbered, note that
    182 		 * and return an error.  (This allows a user to read
    183 		 * the buffer via /dev/kmem, and try to figure out
    184 		 * what clobbered it.
    185 		 */
    186 		if (mbp->msg_magic != MSG_MAGIC) {
    187 			msgbufenabled = 0;
    188 			error = SET_ERROR(ENXIO);
    189 		}
    190 	}
    191 	mutex_spin_exit(&log_lock);
    192 
    193 	return error;
    194 }
    195 
    196 /*ARGSUSED*/
    197 static int
    198 logclose(dev_t dev, int flag, int mode, struct lwp *l)
    199 {
    200 
    201 	mutex_spin_enter(&log_lock);
    202 	log_pgid = 0;
    203 	log_open = 0;
    204 	log_async = 0;
    205 	mutex_spin_exit(&log_lock);
    206 
    207 	return 0;
    208 }
    209 
    210 /*ARGSUSED*/
    211 static int
    212 logread(dev_t dev, struct uio *uio, int flag)
    213 {
    214 	struct kern_msgbuf *mbp = msgbufp;
    215 	long l;
    216 	int error = 0;
    217 
    218 	mutex_spin_enter(&log_lock);
    219 	while (mbp->msg_bufr == mbp->msg_bufx) {
    220 		if (flag & IO_NDELAY) {
    221 			mutex_spin_exit(&log_lock);
    222 			return SET_ERROR(EWOULDBLOCK);
    223 		}
    224 		error = cv_wait_sig(&log_cv, &log_lock);
    225 		if (error) {
    226 			mutex_spin_exit(&log_lock);
    227 			return error;
    228 		}
    229 	}
    230 	while (uio->uio_resid > 0) {
    231 		char buf[128]; /* taken from FreeBSD */
    232 
    233 		l = mbp->msg_bufx - mbp->msg_bufr;
    234 		if (l < 0)
    235 			l = mbp->msg_bufs - mbp->msg_bufr;
    236 		l = ulmin(l, uio->uio_resid);
    237 		if (l == 0)
    238 			break;
    239 
    240 		l = ulmin(l, sizeof(buf));
    241 		memcpy(buf, &mbp->msg_bufc[mbp->msg_bufr], l);
    242 		mbp->msg_bufr += l;
    243 		if (mbp->msg_bufr < 0 || mbp->msg_bufr >= mbp->msg_bufs)
    244 			mbp->msg_bufr = 0;
    245 		mutex_spin_exit(&log_lock);
    246 		error = uiomove(buf, l, uio);
    247 		mutex_spin_enter(&log_lock);
    248 		if (error)
    249 			break;
    250 	}
    251 	mutex_spin_exit(&log_lock);
    252 
    253 	return error;
    254 }
    255 
    256 /*ARGSUSED*/
    257 static int
    258 logpoll(dev_t dev, int events, struct lwp *l)
    259 {
    260 	int revents = 0;
    261 
    262 	if (events & (POLLIN | POLLRDNORM)) {
    263 		mutex_spin_enter(&log_lock);
    264 		if (msgbufp->msg_bufr != msgbufp->msg_bufx)
    265 			revents |= events & (POLLIN | POLLRDNORM);
    266 		else
    267 			selrecord(l, &log_selp);
    268 		mutex_spin_exit(&log_lock);
    269 	}
    270 
    271 	return revents;
    272 }
    273 
    274 static void
    275 filt_logrdetach(struct knote *kn)
    276 {
    277 
    278 	mutex_spin_enter(&log_lock);
    279 	selremove_knote(&log_selp, kn);
    280 	mutex_spin_exit(&log_lock);
    281 }
    282 
    283 static int
    284 filt_logread(struct knote *kn, long hint)
    285 {
    286 	int rv;
    287 
    288 	if ((hint & NOTE_SUBMIT) == 0)
    289 		mutex_spin_enter(&log_lock);
    290 	if (msgbufp->msg_bufr == msgbufp->msg_bufx) {
    291 		rv = 0;
    292 	} else if (msgbufp->msg_bufr < msgbufp->msg_bufx) {
    293 		kn->kn_data = msgbufp->msg_bufx - msgbufp->msg_bufr;
    294 		rv = 1;
    295 	} else {
    296 		kn->kn_data = (msgbufp->msg_bufs - msgbufp->msg_bufr) +
    297 		    msgbufp->msg_bufx;
    298 		rv = 1;
    299 	}
    300 	if ((hint & NOTE_SUBMIT) == 0)
    301 		mutex_spin_exit(&log_lock);
    302 
    303 	return rv;
    304 }
    305 
    306 static const struct filterops logread_filtops = {
    307 	.f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
    308 	.f_attach = NULL,
    309 	.f_detach = filt_logrdetach,
    310 	.f_event = filt_logread,
    311 };
    312 
    313 static int
    314 logkqfilter(dev_t dev, struct knote *kn)
    315 {
    316 
    317 	switch (kn->kn_filter) {
    318 	case EVFILT_READ:
    319 		kn->kn_fop = &logread_filtops;
    320 		mutex_spin_enter(&log_lock);
    321 		selrecord_knote(&log_selp, kn);
    322 		mutex_spin_exit(&log_lock);
    323 		break;
    324 
    325 	default:
    326 		return SET_ERROR(EINVAL);
    327 	}
    328 
    329 	return 0;
    330 }
    331 
    332 void
    333 logwakeup(void)
    334 {
    335 
    336 	if (!cold && log_open) {
    337 		mutex_spin_enter(&log_lock);
    338 		selnotify(&log_selp, 0, NOTE_SUBMIT);
    339 		if (log_async)
    340 			softint_schedule(log_sih);
    341 		cv_broadcast(&log_cv);
    342 		mutex_spin_exit(&log_lock);
    343 	}
    344 }
    345 
    346 static void
    347 logsoftintr(void *cookie)
    348 {
    349 	pid_t pid;
    350 
    351 	if ((pid = log_pgid) != 0)
    352 		fownsignal(pid, SIGIO, 0, 0, NULL);
    353 }
    354 
    355 /*ARGSUSED*/
    356 static int
    357 logioctl(dev_t dev, u_long com, void *data, int flag, struct lwp *lwp)
    358 {
    359 	long l;
    360 
    361 	switch (com) {
    362 
    363 	/* return number of characters immediately available */
    364 	case FIONREAD:
    365 		mutex_spin_enter(&log_lock);
    366 		l = msgbufp->msg_bufx - msgbufp->msg_bufr;
    367 		if (l < 0)
    368 			l += msgbufp->msg_bufs;
    369 		mutex_spin_exit(&log_lock);
    370 		*(int *)data = l;
    371 		break;
    372 
    373 	case FIONBIO:
    374 		break;
    375 
    376 	case FIOASYNC:
    377 		/* No locking needed, 'thread private'. */
    378 		log_async = (*((int *)data) != 0);
    379 		break;
    380 
    381 	case TIOCSPGRP:
    382 	case FIOSETOWN:
    383 		return fsetown(&log_pgid, com, data);
    384 
    385 	case TIOCGPGRP:
    386 	case FIOGETOWN:
    387 		return fgetown(log_pgid, com, data);
    388 
    389 	default:
    390 		return (EPASSTHROUGH);
    391 	}
    392 	return (0);
    393 }
    394 
    395 static void
    396 logskip(struct kern_msgbuf *mbp)
    397 {
    398 	/*
    399 	 * Move forward read pointer to the next line
    400 	 * in the buffer.  Note that the buffer is
    401 	 * a ring buffer so we should reset msg_bufr
    402 	 * to 0 when msg_bufr exceeds msg_bufs.
    403 	 *
    404 	 * To prevent to loop forever, give up if we
    405 	 * cannot find a newline in mbp->msg_bufs
    406 	 * characters (the max size of the buffer).
    407 	 */
    408 	for (int i = 0; i < mbp->msg_bufs; i++) {
    409 		char c0 = mbp->msg_bufc[mbp->msg_bufr];
    410 		if (++mbp->msg_bufr >= mbp->msg_bufs)
    411 			mbp->msg_bufr = 0;
    412 		if (c0 == '\n')
    413 			break;
    414 	}
    415 }
    416 
    417 static void
    418 logaddchar(struct kern_msgbuf *mbp, int c)
    419 {
    420 	mbp->msg_bufc[mbp->msg_bufx++] = c;
    421 	if (mbp->msg_bufx < 0 || mbp->msg_bufx >= mbp->msg_bufs)
    422 		mbp->msg_bufx = 0;
    423 
    424 	/* If the buffer is full, keep the most recent data. */
    425 	if (mbp->msg_bufr == mbp->msg_bufx)
    426 		logskip(mbp);
    427 }
    428 
    429 void
    430 logputchar(int c)
    431 {
    432 	struct kern_msgbuf *mbp;
    433 
    434 	if (!cold)
    435 		mutex_spin_enter(&log_lock);
    436 
    437 	if (!msgbufenabled)
    438 		goto out;
    439 
    440 	mbp = msgbufp;
    441 	if (mbp->msg_magic != MSG_MAGIC) {
    442 		/*
    443 		 * Arguably should panic or somehow notify the
    444 		 * user...  but how?  Panic may be too drastic,
    445 		 * and would obliterate the message being kicked
    446 		 * out (maybe a panic itself), and printf
    447 		 * would invoke us recursively.  Silently punt
    448 		 * for now.  If syslog is running, it should
    449 		 * notice.
    450 		 */
    451 		msgbufenabled = 0;
    452 		goto out;
    453 
    454 	}
    455 
    456 	logaddchar(mbp, c);
    457 
    458 out:
    459 	if (!cold)
    460 		mutex_spin_exit(&log_lock);
    461 }
    462 
    463 /*
    464  * sysctl helper routine for kern.msgbufsize and kern.msgbuf. For the
    465  * former it merely checks the message buffer is set up. For the latter,
    466  * it also copies out the data if necessary.
    467  */
    468 static int
    469 sysctl_msgbuf(SYSCTLFN_ARGS)
    470 {
    471 	struct sysctlnode node = *rnode;
    472 	char *where = oldp;
    473 	size_t len, maxlen;
    474 	long beg, end;
    475 	int error, val;
    476 
    477 	if (!logenabled(msgbufp)) {
    478 		msgbufenabled = 0;
    479 		return (ENXIO);
    480 	}
    481 
    482 	switch (rnode->sysctl_num) {
    483 	case KERN_MSGBUFSIZE: {
    484 		int msg_bufs = (int)msgbufp->msg_bufs;
    485 		node.sysctl_data = &msg_bufs;
    486 		return (sysctl_lookup(SYSCTLFN_CALL(&node)));
    487 	}
    488 	case KERN_MSGBUFCLR:
    489 		val = 0;
    490 		node.sysctl_data = &val;
    491 		error = sysctl_lookup(SYSCTLFN_CALL(&node));
    492 		if (error || newp == NULL)
    493 			return error;
    494 
    495 		if (val == 0)
    496 			return EINVAL;
    497 
    498 		mutex_spin_enter(&log_lock);
    499 		msgbufp->msg_bufx = 0;
    500 		msgbufp->msg_bufr = 0;
    501 		memset(msgbufp->msg_bufc, 0, msgbufp->msg_bufs);
    502 		mutex_spin_exit(&log_lock);
    503 
    504 		return 0;
    505 	case KERN_MSGBUF:
    506 		break;
    507 	default:
    508 		return (EOPNOTSUPP);
    509 	}
    510 
    511 	if (newp != NULL)
    512 		return (EPERM);
    513 
    514 	if (oldp == NULL) {
    515 		/* always return full buffer size */
    516 		*oldlenp = msgbufp->msg_bufs;
    517 		return (0);
    518 	}
    519 
    520 	sysctl_unlock();
    521 
    522 	/*
    523 	 * First, copy from the write pointer to the end of
    524 	 * message buffer.
    525 	 */
    526 	error = 0;
    527 	mutex_spin_enter(&log_lock);
    528 	maxlen = MIN(msgbufp->msg_bufs, *oldlenp);
    529 	beg = msgbufp->msg_bufx;
    530 	end = msgbufp->msg_bufs;
    531 	mutex_spin_exit(&log_lock);
    532 
    533 	while (maxlen > 0) {
    534 		len = MIN(end - beg, maxlen);
    535 		if (len == 0)
    536 			break;
    537 		/* XXX unlocked, but hardly matters. */
    538 		error = copyout(&msgbufp->msg_bufc[beg], where, len);
    539 		ktrmibio(-1, UIO_READ, where, len, error);
    540 		if (error)
    541 			break;
    542 		where += len;
    543 		maxlen -= len;
    544 
    545 		/*
    546 		 * ... then, copy from the beginning of message buffer to
    547 		 * the write pointer.
    548 		 */
    549 		beg = 0;
    550 		end = msgbufp->msg_bufx;
    551 	}
    552 
    553 	sysctl_relock();
    554 	return (error);
    555 }
    556 
    557 const struct cdevsw log_cdevsw = {
    558 	.d_open = logopen,
    559 	.d_close = logclose,
    560 	.d_read = logread,
    561 	.d_write = nowrite,
    562 	.d_ioctl = logioctl,
    563 	.d_stop = nostop,
    564 	.d_tty = notty,
    565 	.d_poll = logpoll,
    566 	.d_mmap = nommap,
    567 	.d_kqfilter = logkqfilter,
    568 	.d_discard = nodiscard,
    569 	.d_flag = D_OTHER | D_MPSAFE
    570 };
    571