2 * Copyright (c) 1982, 1986, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * Copyright (c) 2005 Robert N. M. Watson
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.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
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 * 4. 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.
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
37 * Copyright (c) 1994 Christopher G. Demetriou
39 * Redistribution and use in source and binary forms, with or without
40 * modification, are permitted provided that the following conditions
42 * 1. Redistributions of source code must retain the above copyright
43 * notice, this list of conditions and the following disclaimer.
44 * 2. Redistributions in binary form must reproduce the above copyright
45 * notice, this list of conditions and the following disclaimer in the
46 * documentation and/or other materials provided with the distribution.
47 * 3. All advertising materials mentioning features or use of this software
48 * must display the following acknowledgement:
49 * This product includes software developed by the University of
50 * California, Berkeley and its contributors.
51 * 4. Neither the name of the University nor the names of its contributors
52 * may be used to endorse or promote products derived from this software
53 * without specific prior written permission.
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67 * @(#)kern_acct.c 8.1 (Berkeley) 6/14/93
70 #include <sys/cdefs.h>
71 __FBSDID("$FreeBSD$");
73 #include <sys/param.h>
74 #include <sys/systm.h>
76 #include <sys/fcntl.h>
77 #include <sys/kernel.h>
78 #include <sys/kthread.h>
79 #include <sys/limits.h>
81 #include <sys/mount.h>
82 #include <sys/mutex.h>
83 #include <sys/namei.h>
86 #include <sys/resourcevar.h>
87 #include <sys/sched.h>
89 #include <sys/sysctl.h>
90 #include <sys/sysent.h>
91 #include <sys/syslog.h>
92 #include <sys/sysproto.h>
94 #include <sys/vnode.h>
96 #include <security/mac/mac_framework.h>
99 * The routines implemented in this file are described in:
100 * Leffler, et al.: The Design and Implementation of the 4.3BSD
101 * UNIX Operating System (Addison Welley, 1989)
103 * On May 2007 the historic 3 bits base 8 exponent, 13 bit fraction
104 * compt_t representation described in the above reference was replaced
105 * with that of IEEE-754 floats.
107 * Arguably, to simplify accounting operations, this mechanism should
108 * be replaced by one in which an accounting log file (similar to /dev/klog)
109 * is read by a user process, etc. However, that has its own problems.
112 /* Floating point definitions from <float.h>. */
113 #define FLT_MANT_DIG 24 /* p */
114 #define FLT_MAX_EXP 128 /* emax */
117 * Internal accounting functions.
118 * The former's operation is described in Leffler, et al., and the latter
119 * was provided by UCB with the 4.4BSD-Lite release
121 static uint32_t encode_timeval(struct timeval);
122 static uint32_t encode_long(long);
123 static void acctwatch(void);
124 static void acct_thread(void *);
125 static int acct_disable(struct thread *);
128 * Accounting vnode pointer, saved vnode pointer, and flags for each.
129 * acct_sx protects against changes to the active vnode and credentials
130 * while accounting records are being committed to disk.
132 static int acct_configured;
133 static int acct_suspended;
134 static struct vnode *acct_vp;
135 static struct ucred *acct_cred;
136 static int acct_flags;
137 static struct sx acct_sx;
139 SX_SYSINIT(acct, &acct_sx, "acct_sx");
142 * State of the accounting kthread.
144 static int acct_state;
146 #define ACCT_RUNNING 1 /* Accounting kthread is running. */
147 #define ACCT_EXITREQ 2 /* Accounting kthread should exit. */
150 * Values associated with enabling and disabling accounting
152 static int acctsuspend = 2; /* stop accounting when < 2% free space left */
153 SYSCTL_INT(_kern, OID_AUTO, acct_suspend, CTLFLAG_RW,
154 &acctsuspend, 0, "percentage of free disk space below which accounting stops");
156 static int acctresume = 4; /* resume when free space risen to > 4% */
157 SYSCTL_INT(_kern, OID_AUTO, acct_resume, CTLFLAG_RW,
158 &acctresume, 0, "percentage of free disk space above which accounting resumes");
160 static int acctchkfreq = 15; /* frequency (in seconds) to check space */
163 sysctl_acct_chkfreq(SYSCTL_HANDLER_ARGS)
167 /* Write out the old value. */
168 error = SYSCTL_OUT(req, &acctchkfreq, sizeof(int));
169 if (error || req->newptr == NULL)
172 /* Read in and verify the new value. */
173 error = SYSCTL_IN(req, &value, sizeof(int));
181 SYSCTL_PROC(_kern, OID_AUTO, acct_chkfreq, CTLTYPE_INT|CTLFLAG_RW,
182 &acctchkfreq, 0, sysctl_acct_chkfreq, "I",
183 "frequency for checking the free space");
185 SYSCTL_INT(_kern, OID_AUTO, acct_configured, CTLFLAG_RD, &acct_configured, 0,
186 "Accounting configured or not");
188 SYSCTL_INT(_kern, OID_AUTO, acct_suspended, CTLFLAG_RD, &acct_suspended, 0,
189 "Accounting suspended or not");
192 * Accounting system call. Written based on the specification and previous
193 * implementation done by Mark Tinguely.
196 sys_acct(struct thread *td, struct acct_args *uap)
199 int error, flags, vfslocked;
201 error = priv_check(td, PRIV_ACCT);
206 * If accounting is to be started to a file, open that file for
207 * appending and make sure it's a 'normal'.
209 if (uap->path != NULL) {
210 NDINIT(&nd, LOOKUP, NOFOLLOW | MPSAFE | AUDITVNODE1,
211 UIO_USERSPACE, uap->path, td);
212 flags = FWRITE | O_APPEND;
213 error = vn_open(&nd, &flags, 0, NULL);
216 vfslocked = NDHASGIANT(&nd);
217 NDFREE(&nd, NDF_ONLY_PNBUF);
219 error = mac_system_check_acct(td->td_ucred, nd.ni_vp);
221 VOP_UNLOCK(nd.ni_vp, 0);
222 vn_close(nd.ni_vp, flags, td->td_ucred, td);
223 VFS_UNLOCK_GIANT(vfslocked);
227 VOP_UNLOCK(nd.ni_vp, 0);
228 if (nd.ni_vp->v_type != VREG) {
229 vn_close(nd.ni_vp, flags, td->td_ucred, td);
230 VFS_UNLOCK_GIANT(vfslocked);
233 VFS_UNLOCK_GIANT(vfslocked);
236 error = mac_system_check_acct(td->td_ucred, NULL);
243 * Disallow concurrent access to the accounting vnode while we swap
244 * it out, in order to prevent access after close.
249 * If accounting was previously enabled, kill the old space-watcher,
250 * close the file, and (if no new file was specified, leave). Reset
251 * the suspended state regardless of whether accounting remains
255 if (acct_vp != NULL) {
256 vfslocked = VFS_LOCK_GIANT(acct_vp->v_mount);
257 error = acct_disable(td);
258 VFS_UNLOCK_GIANT(vfslocked);
260 if (uap->path == NULL) {
261 if (acct_state & ACCT_RUNNING) {
262 acct_state |= ACCT_EXITREQ;
265 sx_xunlock(&acct_sx);
270 * Save the new accounting file vnode, and schedule the new
271 * free space watcher.
274 acct_cred = crhold(td->td_ucred);
276 if (acct_state & ACCT_RUNNING)
277 acct_state &= ~ACCT_EXITREQ;
280 * Try to start up an accounting kthread. We may start more
281 * than one, but if so the extras will commit suicide as
282 * soon as they start up.
284 error = kproc_create(acct_thread, NULL, NULL, 0, 0,
287 vfslocked = VFS_LOCK_GIANT(acct_vp->v_mount);
288 (void) vn_close(acct_vp, acct_flags, acct_cred, td);
289 VFS_UNLOCK_GIANT(vfslocked);
295 sx_xunlock(&acct_sx);
296 log(LOG_NOTICE, "Unable to start accounting thread\n");
301 sx_xunlock(&acct_sx);
302 log(LOG_NOTICE, "Accounting enabled\n");
307 * Disable currently in-progress accounting by closing the vnode, dropping
308 * our reference to the credential, and clearing the vnode's flags.
311 acct_disable(struct thread *td)
315 sx_assert(&acct_sx, SX_XLOCKED);
316 error = vn_close(acct_vp, acct_flags, acct_cred, td);
322 log(LOG_NOTICE, "Accounting disabled\n");
327 * Write out process accounting information, on process exit.
328 * Data to be written out is specified in Leffler, et al.
329 * and are enumerated below. (They're also noted in the system
330 * "acct.h" header file.)
333 acct_process(struct thread *td)
336 struct timeval ut, st, tmp;
337 struct plimit *newlim, *oldlim;
340 int t, ret, vfslocked;
343 * Lockless check of accounting condition before doing the hard
346 if (acct_vp == NULL || acct_suspended)
352 * If accounting isn't enabled, don't bother. Have to check again
353 * once we own the lock in case we raced with disabling of accounting
356 if (acct_vp == NULL || acct_suspended) {
357 sx_sunlock(&acct_sx);
364 * Get process accounting information.
367 sx_slock(&proctree_lock);
370 /* (1) The terminal from which the process was started */
371 if ((p->p_flag & P_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
372 acct.ac_tty = tty_udev(p->p_pgrp->pg_session->s_ttyp);
375 sx_sunlock(&proctree_lock);
377 /* (2) The name of the command that ran */
378 bcopy(p->p_comm, acct.ac_comm, sizeof acct.ac_comm);
380 /* (3) The amount of user and system time that was used */
381 rufetchcalc(p, &ru, &ut, &st);
382 acct.ac_utime = encode_timeval(ut);
383 acct.ac_stime = encode_timeval(st);
385 /* (4) The elapsed time the command ran (and its starting time) */
387 timevaladd(&tmp, &p->p_stats->p_start);
388 acct.ac_btime = tmp.tv_sec;
390 timevalsub(&tmp, &p->p_stats->p_start);
391 acct.ac_etime = encode_timeval(tmp);
393 /* (5) The average amount of memory used */
395 timevaladd(&tmp, &st);
396 /* Convert tmp (i.e. u + s) into hz units to match ru_i*. */
397 t = tmp.tv_sec * hz + tmp.tv_usec / tick;
399 acct.ac_mem = encode_long((ru.ru_ixrss + ru.ru_idrss +
404 /* (6) The number of disk I/O operations done */
405 acct.ac_io = encode_long(ru.ru_inblock + ru.ru_oublock);
407 /* (7) The UID and GID of the process */
408 acct.ac_uid = p->p_ucred->cr_ruid;
409 acct.ac_gid = p->p_ucred->cr_rgid;
411 /* (8) The boolean flags that tell how the process terminated, etc. */
412 acct.ac_flagx = p->p_acflag;
415 /* Setup ancillary structure fields. */
416 acct.ac_flagx |= ANVER;
419 acct.ac_len = acct.ac_len2 = sizeof(acct);
422 * Eliminate any file size rlimit.
424 newlim = lim_alloc();
427 lim_copy(newlim, oldlim);
428 newlim->pl_rlimit[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
434 * Write the accounting information to the file.
436 vfslocked = VFS_LOCK_GIANT(acct_vp->v_mount);
437 ret = vn_rdwr(UIO_WRITE, acct_vp, (caddr_t)&acct, sizeof (acct),
438 (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT, acct_cred, NOCRED,
440 VFS_UNLOCK_GIANT(vfslocked);
441 sx_sunlock(&acct_sx);
445 /* FLOAT_CONVERSION_START (Regression testing; don't remove this line.) */
447 /* Convert timevals and longs into IEEE-754 bit patterns. */
449 /* Mantissa mask (MSB is implied, so subtract 1). */
450 #define MANT_MASK ((1 << (FLT_MANT_DIG - 1)) - 1)
453 * We calculate integer values to a precision of approximately
455 * This is high-enough precision to fill the 24 float bits
456 * and low-enough to avoid overflowing the 32 int bits.
460 /* log_2(1000000). */
464 * Convert the elements of a timeval into a 32-bit word holding
465 * the bits of a IEEE-754 float.
466 * The float value represents the timeval's value in microsecond units.
469 encode_timeval(struct timeval tv)
472 int val, exp; /* Unnormalized value and exponent */
473 int norm_exp; /* Normalized exponent */
477 * First calculate value and exponent to about CALC_BITS precision.
478 * Note that the following conditionals have been ordered so that
479 * the most common cases appear first.
481 if (tv.tv_sec == 0) {
488 * Calculate the value to a precision of approximately
491 log2_s = fls(tv.tv_sec) - 1;
492 if (log2_s + LOG2_1M < CALC_BITS) {
494 val = 1000000 * tv.tv_sec + tv.tv_usec;
496 exp = log2_s + LOG2_1M - CALC_BITS;
497 val = (unsigned int)(((uint64_t)1000000 * tv.tv_sec +
501 /* Now normalize and pack the value into an IEEE-754 float. */
502 norm_exp = fls(val) - 1;
503 shift = FLT_MANT_DIG - norm_exp - 1;
505 printf("val=%d exp=%d shift=%d log2(val)=%d\n",
506 val, exp, shift, norm_exp);
507 printf("exp=%x mant=%x\n", FLT_MAX_EXP - 1 + exp + norm_exp,
508 ((shift > 0 ? (val << shift) : (val >> -shift)) & MANT_MASK));
510 return (((FLT_MAX_EXP - 1 + exp + norm_exp) << (FLT_MANT_DIG - 1)) |
511 ((shift > 0 ? val << shift : val >> -shift) & MANT_MASK));
515 * Convert a non-negative long value into the bit pattern of
516 * an IEEE-754 float value.
519 encode_long(long val)
521 int norm_exp; /* Normalized exponent */
528 "encode_long: negative value %ld in accounting record\n",
532 norm_exp = fls(val) - 1;
533 shift = FLT_MANT_DIG - norm_exp - 1;
535 printf("val=%d shift=%d log2(val)=%d\n",
536 val, shift, norm_exp);
537 printf("exp=%x mant=%x\n", FLT_MAX_EXP - 1 + exp + norm_exp,
538 ((shift > 0 ? (val << shift) : (val >> -shift)) & MANT_MASK));
540 return (((FLT_MAX_EXP - 1 + norm_exp) << (FLT_MANT_DIG - 1)) |
541 ((shift > 0 ? val << shift : val >> -shift) & MANT_MASK));
544 /* FLOAT_CONVERSION_END (Regression testing; don't remove this line.) */
547 * Periodically check the filesystem to see if accounting
548 * should be turned on or off. Beware the case where the vnode
549 * has been vgone()'d out from underneath us, e.g. when the file
550 * system containing the accounting file has been forcibly unmounted.
559 sx_assert(&acct_sx, SX_XLOCKED);
562 * If accounting was disabled before our kthread was scheduled,
563 * then acct_vp might be NULL. If so, just ask our kthread to
566 if (acct_vp == NULL) {
567 acct_state |= ACCT_EXITREQ;
572 * If our vnode is no longer valid, tear it down and signal the
573 * accounting thread to die.
575 vfslocked = VFS_LOCK_GIANT(acct_vp->v_mount);
576 if (acct_vp->v_type == VBAD) {
577 (void) acct_disable(NULL);
578 VFS_UNLOCK_GIANT(vfslocked);
579 acct_state |= ACCT_EXITREQ;
584 * Stopping here is better than continuing, maybe it will be VBAD
587 if (VFS_STATFS(acct_vp->v_mount, &sb) < 0) {
588 VFS_UNLOCK_GIANT(vfslocked);
591 VFS_UNLOCK_GIANT(vfslocked);
592 if (acct_suspended) {
593 if (sb.f_bavail > (int64_t)(acctresume * sb.f_blocks /
596 log(LOG_NOTICE, "Accounting resumed\n");
599 if (sb.f_bavail <= (int64_t)(acctsuspend * sb.f_blocks /
602 log(LOG_NOTICE, "Accounting suspended\n");
608 * The main loop for the dedicated kernel thread that periodically calls
612 acct_thread(void *dummy)
616 /* This is a low-priority kernel thread. */
618 thread_lock(curthread);
619 sched_prio(curthread, pri);
620 thread_unlock(curthread);
622 /* If another accounting kthread is already running, just die. */
624 if (acct_state & ACCT_RUNNING) {
625 sx_xunlock(&acct_sx);
628 acct_state |= ACCT_RUNNING;
630 /* Loop until we are asked to exit. */
631 while (!(acct_state & ACCT_EXITREQ)) {
633 /* Perform our periodic checks. */
637 * We check this flag again before sleeping since the
638 * acctwatch() might have shut down accounting and asked us
641 if (!(acct_state & ACCT_EXITREQ)) {
642 sx_sleep(&acct_state, &acct_sx, 0, "-",
648 * Acknowledge the exit request and shutdown. We clear both the
649 * exit request and running flags.
652 sx_xunlock(&acct_sx);