2 * SPDX-License-Identifier: BSD-4-Clause
4 * Copyright (c) 1982, 1986, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * Copyright (c) 2005 Robert N. M. Watson
10 * All or some portions of this file are derived from material licensed
11 * to the University of California by American Telephone and Telegraph
12 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
13 * the permission of UNIX System Laboratories, Inc.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 3. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * Copyright (c) 1994 Christopher G. Demetriou
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
49 * 3. All advertising materials mentioning features or use of this software
50 * must display the following acknowledgement:
51 * This product includes software developed by the University of
52 * California, Berkeley and its contributors.
53 * 4. Neither the name of the University nor the names of its contributors
54 * may be used to endorse or promote products derived from this software
55 * without specific prior written permission.
57 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
58 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
59 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
60 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
61 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
62 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
63 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
64 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
65 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * @(#)kern_acct.c 8.1 (Berkeley) 6/14/93
72 #include <sys/cdefs.h>
73 __FBSDID("$FreeBSD$");
75 #include <sys/param.h>
76 #include <sys/systm.h>
78 #include <sys/fcntl.h>
79 #include <sys/kernel.h>
80 #include <sys/kthread.h>
81 #include <sys/limits.h>
83 #include <sys/malloc.h>
84 #include <sys/mount.h>
85 #include <sys/mutex.h>
86 #include <sys/namei.h>
89 #include <sys/resourcevar.h>
90 #include <sys/sched.h>
92 #include <sys/sysctl.h>
93 #include <sys/sysent.h>
94 #include <sys/syslog.h>
95 #include <sys/sysproto.h>
97 #include <sys/vnode.h>
99 #include <security/mac/mac_framework.h>
101 _Static_assert(sizeof(struct acctv3) - offsetof(struct acctv3, ac_trailer) ==
102 sizeof(struct acctv2) - offsetof(struct acctv2, ac_trailer), "trailer");
103 _Static_assert(sizeof(struct acctv3) - offsetof(struct acctv3, ac_len2) ==
104 sizeof(struct acctv2) - offsetof(struct acctv2, ac_len2), "len2");
107 * The routines implemented in this file are described in:
108 * Leffler, et al.: The Design and Implementation of the 4.3BSD
109 * UNIX Operating System (Addison Welley, 1989)
111 * On May 2007 the historic 3 bits base 8 exponent, 13 bit fraction
112 * compt_t representation described in the above reference was replaced
113 * with that of IEEE-754 floats.
115 * Arguably, to simplify accounting operations, this mechanism should
116 * be replaced by one in which an accounting log file (similar to /dev/klog)
117 * is read by a user process, etc. However, that has its own problems.
120 /* Floating point definitions from <float.h>. */
121 #define FLT_MANT_DIG 24 /* p */
122 #define FLT_MAX_EXP 128 /* emax */
125 * Internal accounting functions.
126 * The former's operation is described in Leffler, et al., and the latter
127 * was provided by UCB with the 4.4BSD-Lite release
129 static uint32_t encode_timeval(struct timeval);
130 static uint32_t encode_long(long);
131 static void acctwatch(void);
132 static void acct_thread(void *);
133 static int acct_disable(struct thread *, int);
136 * Accounting vnode pointer, saved vnode pointer, and flags for each.
137 * acct_sx protects against changes to the active vnode and credentials
138 * while accounting records are being committed to disk.
140 static int acct_configured;
141 static int acct_suspended;
142 static struct vnode *acct_vp;
143 static struct ucred *acct_cred;
144 static struct plimit *acct_limit;
145 static int acct_flags;
146 static struct sx acct_sx;
148 SX_SYSINIT(acct, &acct_sx, "acct_sx");
151 * State of the accounting kthread.
153 static int acct_state;
155 #define ACCT_RUNNING 1 /* Accounting kthread is running. */
156 #define ACCT_EXITREQ 2 /* Accounting kthread should exit. */
159 * Values associated with enabling and disabling accounting
161 static int acctsuspend = 2; /* stop accounting when < 2% free space left */
162 SYSCTL_INT(_kern, OID_AUTO, acct_suspend, CTLFLAG_RW,
163 &acctsuspend, 0, "percentage of free disk space below which accounting stops");
165 static int acctresume = 4; /* resume when free space risen to > 4% */
166 SYSCTL_INT(_kern, OID_AUTO, acct_resume, CTLFLAG_RW,
167 &acctresume, 0, "percentage of free disk space above which accounting resumes");
169 static int acctchkfreq = 15; /* frequency (in seconds) to check space */
172 sysctl_acct_chkfreq(SYSCTL_HANDLER_ARGS)
176 /* Write out the old value. */
177 error = SYSCTL_OUT(req, &acctchkfreq, sizeof(int));
178 if (error || req->newptr == NULL)
181 /* Read in and verify the new value. */
182 error = SYSCTL_IN(req, &value, sizeof(int));
190 SYSCTL_PROC(_kern, OID_AUTO, acct_chkfreq, CTLTYPE_INT|CTLFLAG_RW,
191 &acctchkfreq, 0, sysctl_acct_chkfreq, "I",
192 "frequency for checking the free space");
194 SYSCTL_INT(_kern, OID_AUTO, acct_configured, CTLFLAG_RD, &acct_configured, 0,
195 "Accounting configured or not");
197 SYSCTL_INT(_kern, OID_AUTO, acct_suspended, CTLFLAG_RD, &acct_suspended, 0,
198 "Accounting suspended or not");
201 * Accounting system call. Written based on the specification and previous
202 * implementation done by Mark Tinguely.
205 sys_acct(struct thread *td, struct acct_args *uap)
208 int error, flags, i, replacing;
210 error = priv_check(td, PRIV_ACCT);
215 * If accounting is to be started to a file, open that file for
216 * appending and make sure it's a 'normal'.
218 if (uap->path != NULL) {
219 NDINIT(&nd, LOOKUP, NOFOLLOW | AUDITVNODE1,
220 UIO_USERSPACE, uap->path, td);
221 flags = FWRITE | O_APPEND;
222 error = vn_open(&nd, &flags, 0, NULL);
225 NDFREE(&nd, NDF_ONLY_PNBUF);
227 error = mac_system_check_acct(td->td_ucred, nd.ni_vp);
229 VOP_UNLOCK(nd.ni_vp, 0);
230 vn_close(nd.ni_vp, flags, td->td_ucred, td);
234 VOP_UNLOCK(nd.ni_vp, 0);
235 if (nd.ni_vp->v_type != VREG) {
236 vn_close(nd.ni_vp, flags, td->td_ucred, td);
241 error = mac_system_check_acct(td->td_ucred, NULL);
248 * Disallow concurrent access to the accounting vnode while we swap
249 * it out, in order to prevent access after close.
254 * Don't log spurious disable/enable messages if we are
255 * switching from one accounting file to another due to log
258 replacing = (acct_vp != NULL && uap->path != NULL);
261 * If accounting was previously enabled, kill the old space-watcher,
262 * close the file, and (if no new file was specified, leave). Reset
263 * the suspended state regardless of whether accounting remains
268 error = acct_disable(td, !replacing);
269 if (uap->path == NULL) {
270 if (acct_state & ACCT_RUNNING) {
271 acct_state |= ACCT_EXITREQ;
274 sx_xunlock(&acct_sx);
279 * Create our own plimit object without limits. It will be assigned
280 * to exiting processes.
282 acct_limit = lim_alloc();
283 for (i = 0; i < RLIM_NLIMITS; i++)
284 acct_limit->pl_rlimit[i].rlim_cur =
285 acct_limit->pl_rlimit[i].rlim_max = RLIM_INFINITY;
288 * Save the new accounting file vnode, and schedule the new
289 * free space watcher.
292 acct_cred = crhold(td->td_ucred);
294 if (acct_state & ACCT_RUNNING)
295 acct_state &= ~ACCT_EXITREQ;
298 * Try to start up an accounting kthread. We may start more
299 * than one, but if so the extras will commit suicide as
300 * soon as they start up.
302 error = kproc_create(acct_thread, NULL, NULL, 0, 0,
305 (void) acct_disable(td, 0);
306 sx_xunlock(&acct_sx);
307 log(LOG_NOTICE, "Unable to start accounting thread\n");
312 sx_xunlock(&acct_sx);
314 log(LOG_NOTICE, "Accounting enabled\n");
319 * Disable currently in-progress accounting by closing the vnode, dropping
320 * our reference to the credential, and clearing the vnode's flags.
323 acct_disable(struct thread *td, int logging)
327 sx_assert(&acct_sx, SX_XLOCKED);
328 error = vn_close(acct_vp, acct_flags, acct_cred, td);
330 lim_free(acct_limit);
336 log(LOG_NOTICE, "Accounting disabled\n");
341 * Write out process accounting information, on process exit.
342 * Data to be written out is specified in Leffler, et al.
343 * and are enumerated below. (They're also noted in the system
344 * "acct.h" header file.)
347 acct_process(struct thread *td)
350 struct timeval ut, st, tmp;
351 struct plimit *oldlim;
357 * Lockless check of accounting condition before doing the hard
360 if (acct_vp == NULL || acct_suspended)
366 * If accounting isn't enabled, don't bother. Have to check again
367 * once we own the lock in case we raced with disabling of accounting
370 if (acct_vp == NULL || acct_suspended) {
371 sx_sunlock(&acct_sx);
378 * Get process accounting information.
381 sx_slock(&proctree_lock);
384 /* (1) The terminal from which the process was started */
385 if ((p->p_flag & P_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
386 acct.ac_tty = tty_udev(p->p_pgrp->pg_session->s_ttyp);
389 sx_sunlock(&proctree_lock);
391 /* (2) The name of the command that ran */
392 bcopy(p->p_comm, acct.ac_comm, sizeof acct.ac_comm);
394 /* (3) The amount of user and system time that was used */
395 rufetchcalc(p, &ru, &ut, &st);
396 acct.ac_utime = encode_timeval(ut);
397 acct.ac_stime = encode_timeval(st);
399 /* (4) The elapsed time the command ran (and its starting time) */
401 timevaladd(&tmp, &p->p_stats->p_start);
402 acct.ac_btime = tmp.tv_sec;
404 timevalsub(&tmp, &p->p_stats->p_start);
405 acct.ac_etime = encode_timeval(tmp);
407 /* (5) The average amount of memory used */
409 timevaladd(&tmp, &st);
410 /* Convert tmp (i.e. u + s) into hz units to match ru_i*. */
411 t = tmp.tv_sec * hz + tmp.tv_usec / tick;
413 acct.ac_mem = encode_long((ru.ru_ixrss + ru.ru_idrss +
418 /* (6) The number of disk I/O operations done */
419 acct.ac_io = encode_long(ru.ru_inblock + ru.ru_oublock);
421 /* (7) The UID and GID of the process */
422 acct.ac_uid = p->p_ucred->cr_ruid;
423 acct.ac_gid = p->p_ucred->cr_rgid;
425 /* (8) The boolean flags that tell how the process terminated, etc. */
426 acct.ac_flagx = p->p_acflag;
428 /* Setup ancillary structure fields. */
429 acct.ac_flagx |= ANVER;
432 acct.ac_len = acct.ac_len2 = sizeof(acct);
435 * Eliminate rlimits (file size limit in particular).
438 p->p_limit = lim_hold(acct_limit);
443 * Write the accounting information to the file.
445 ret = vn_rdwr(UIO_WRITE, acct_vp, (caddr_t)&acct, sizeof (acct),
446 (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT, acct_cred, NOCRED,
448 sx_sunlock(&acct_sx);
452 /* FLOAT_CONVERSION_START (Regression testing; don't remove this line.) */
454 /* Convert timevals and longs into IEEE-754 bit patterns. */
456 /* Mantissa mask (MSB is implied, so subtract 1). */
457 #define MANT_MASK ((1 << (FLT_MANT_DIG - 1)) - 1)
460 * We calculate integer values to a precision of approximately
462 * This is high-enough precision to fill the 24 float bits
463 * and low-enough to avoid overflowing the 32 int bits.
467 /* log_2(1000000). */
471 * Convert the elements of a timeval into a 32-bit word holding
472 * the bits of a IEEE-754 float.
473 * The float value represents the timeval's value in microsecond units.
476 encode_timeval(struct timeval tv)
479 int val, exp; /* Unnormalized value and exponent */
480 int norm_exp; /* Normalized exponent */
484 * First calculate value and exponent to about CALC_BITS precision.
485 * Note that the following conditionals have been ordered so that
486 * the most common cases appear first.
488 if (tv.tv_sec == 0) {
495 * Calculate the value to a precision of approximately
498 log2_s = fls(tv.tv_sec) - 1;
499 if (log2_s + LOG2_1M < CALC_BITS) {
501 val = 1000000 * tv.tv_sec + tv.tv_usec;
503 exp = log2_s + LOG2_1M - CALC_BITS;
504 val = (unsigned int)(((uint64_t)1000000 * tv.tv_sec +
508 /* Now normalize and pack the value into an IEEE-754 float. */
509 norm_exp = fls(val) - 1;
510 shift = FLT_MANT_DIG - norm_exp - 1;
512 printf("val=%d exp=%d shift=%d log2(val)=%d\n",
513 val, exp, shift, norm_exp);
514 printf("exp=%x mant=%x\n", FLT_MAX_EXP - 1 + exp + norm_exp,
515 ((shift > 0 ? (val << shift) : (val >> -shift)) & MANT_MASK));
517 return (((FLT_MAX_EXP - 1 + exp + norm_exp) << (FLT_MANT_DIG - 1)) |
518 ((shift > 0 ? val << shift : val >> -shift) & MANT_MASK));
522 * Convert a non-negative long value into the bit pattern of
523 * an IEEE-754 float value.
526 encode_long(long val)
528 int norm_exp; /* Normalized exponent */
535 "encode_long: negative value %ld in accounting record\n",
539 norm_exp = fls(val) - 1;
540 shift = FLT_MANT_DIG - norm_exp - 1;
542 printf("val=%d shift=%d log2(val)=%d\n",
543 val, shift, norm_exp);
544 printf("exp=%x mant=%x\n", FLT_MAX_EXP - 1 + exp + norm_exp,
545 ((shift > 0 ? (val << shift) : (val >> -shift)) & MANT_MASK));
547 return (((FLT_MAX_EXP - 1 + norm_exp) << (FLT_MANT_DIG - 1)) |
548 ((shift > 0 ? val << shift : val >> -shift) & MANT_MASK));
551 /* FLOAT_CONVERSION_END (Regression testing; don't remove this line.) */
554 * Periodically check the filesystem to see if accounting
555 * should be turned on or off. Beware the case where the vnode
556 * has been vgone()'d out from underneath us, e.g. when the file
557 * system containing the accounting file has been forcibly unmounted.
565 sx_assert(&acct_sx, SX_XLOCKED);
568 * If accounting was disabled before our kthread was scheduled,
569 * then acct_vp might be NULL. If so, just ask our kthread to
572 if (acct_vp == NULL) {
573 acct_state |= ACCT_EXITREQ;
578 * If our vnode is no longer valid, tear it down and signal the
579 * accounting thread to die.
581 if (acct_vp->v_type == VBAD) {
582 (void) acct_disable(NULL, 1);
583 acct_state |= ACCT_EXITREQ;
588 * Stopping here is better than continuing, maybe it will be VBAD
591 sp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
592 if (VFS_STATFS(acct_vp->v_mount, sp) < 0) {
596 if (acct_suspended) {
597 if (sp->f_bavail > (int64_t)(acctresume * sp->f_blocks /
600 log(LOG_NOTICE, "Accounting resumed\n");
603 if (sp->f_bavail <= (int64_t)(acctsuspend * sp->f_blocks /
606 log(LOG_NOTICE, "Accounting suspended\n");
613 * The main loop for the dedicated kernel thread that periodically calls
617 acct_thread(void *dummy)
621 /* This is a low-priority kernel thread. */
623 thread_lock(curthread);
624 sched_prio(curthread, pri);
625 thread_unlock(curthread);
627 /* If another accounting kthread is already running, just die. */
629 if (acct_state & ACCT_RUNNING) {
630 sx_xunlock(&acct_sx);
633 acct_state |= ACCT_RUNNING;
635 /* Loop until we are asked to exit. */
636 while (!(acct_state & ACCT_EXITREQ)) {
638 /* Perform our periodic checks. */
642 * We check this flag again before sleeping since the
643 * acctwatch() might have shut down accounting and asked us
646 if (!(acct_state & ACCT_EXITREQ)) {
647 sx_sleep(&acct_state, &acct_sx, 0, "-",
653 * Acknowledge the exit request and shutdown. We clear both the
654 * exit request and running flags.
657 sx_xunlock(&acct_sx);