xref: /freebsd/sys/kern/kern_acct.c (revision 2b743a9e9ddc6736208dc8ca1ce06ce64ad20a19)
1 /*-
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
6  * All rights reserved.
7  *
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  * 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.
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  * Copyright (c) 1994 Christopher G. Demetriou
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions
41  * are met:
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.
54  *
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
65  * SUCH DAMAGE.
66  *
67  *	@(#)kern_acct.c	8.1 (Berkeley) 6/14/93
68  */
69 
70 #include <sys/cdefs.h>
71 __FBSDID("$FreeBSD$");
72 
73 #include "opt_mac.h"
74 
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/acct.h>
78 #include <sys/fcntl.h>
79 #include <sys/kernel.h>
80 #include <sys/kthread.h>
81 #include <sys/lock.h>
82 #include <sys/mount.h>
83 #include <sys/mutex.h>
84 #include <sys/namei.h>
85 #include <sys/priv.h>
86 #include <sys/proc.h>
87 #include <sys/resourcevar.h>
88 #include <sys/sched.h>
89 #include <sys/sx.h>
90 #include <sys/sysctl.h>
91 #include <sys/sysent.h>
92 #include <sys/syslog.h>
93 #include <sys/sysproto.h>
94 #include <sys/tty.h>
95 #include <sys/vnode.h>
96 
97 #include <security/mac/mac_framework.h>
98 
99 /*
100  * The routines implemented in this file are described in:
101  *      Leffler, et al.: The Design and Implementation of the 4.3BSD
102  *	    UNIX Operating System (Addison Welley, 1989)
103  * on pages 62-63.
104  *
105  * Arguably, to simplify accounting operations, this mechanism should
106  * be replaced by one in which an accounting log file (similar to /dev/klog)
107  * is read by a user process, etc.  However, that has its own problems.
108  */
109 
110 /*
111  * Internal accounting functions.
112  * The former's operation is described in Leffler, et al., and the latter
113  * was provided by UCB with the 4.4BSD-Lite release
114  */
115 static comp_t	encode_comp_t(u_long, u_long);
116 static void	acctwatch(void);
117 static void	acct_thread(void *);
118 static int	acct_disable(struct thread *);
119 
120 /*
121  * Accounting vnode pointer, saved vnode pointer, and flags for each.
122  * acct_sx protects against changes to the active vnode and credentials
123  * while accounting records are being committed to disk.
124  */
125 static int		 acct_configured;
126 static int		 acct_suspended;
127 static struct vnode	*acct_vp;
128 static struct ucred	*acct_cred;
129 static int		 acct_flags;
130 static struct sx	 acct_sx;
131 
132 SX_SYSINIT(acct, &acct_sx, "acct_sx");
133 
134 /*
135  * State of the accounting kthread.
136  */
137 static int		 acct_state;
138 
139 #define	ACCT_RUNNING	1	/* Accounting kthread is running. */
140 #define	ACCT_EXITREQ	2	/* Accounting kthread should exit. */
141 
142 /*
143  * Values associated with enabling and disabling accounting
144  */
145 static int acctsuspend = 2;	/* stop accounting when < 2% free space left */
146 SYSCTL_INT(_kern, OID_AUTO, acct_suspend, CTLFLAG_RW,
147 	&acctsuspend, 0, "percentage of free disk space below which accounting stops");
148 
149 static int acctresume = 4;	/* resume when free space risen to > 4% */
150 SYSCTL_INT(_kern, OID_AUTO, acct_resume, CTLFLAG_RW,
151 	&acctresume, 0, "percentage of free disk space above which accounting resumes");
152 
153 static int acctchkfreq = 15;	/* frequency (in seconds) to check space */
154 
155 static int
156 sysctl_acct_chkfreq(SYSCTL_HANDLER_ARGS)
157 {
158 	int error, value;
159 
160 	/* Write out the old value. */
161 	error = SYSCTL_OUT(req, &acctchkfreq, sizeof(int));
162 	if (error || req->newptr == NULL)
163 		return (error);
164 
165 	/* Read in and verify the new value. */
166 	error = SYSCTL_IN(req, &value, sizeof(int));
167 	if (error)
168 		return (error);
169 	if (value <= 0)
170 		return (EINVAL);
171 	acctchkfreq = value;
172 	return (0);
173 }
174 SYSCTL_PROC(_kern, OID_AUTO, acct_chkfreq, CTLTYPE_INT|CTLFLAG_RW,
175     &acctchkfreq, 0, sysctl_acct_chkfreq, "I",
176     "frequency for checking the free space");
177 
178 SYSCTL_INT(_kern, OID_AUTO, acct_configured, CTLFLAG_RD, &acct_configured, 0,
179 	"Accounting configured or not");
180 
181 SYSCTL_INT(_kern, OID_AUTO, acct_suspended, CTLFLAG_RD, &acct_suspended, 0,
182 	"Accounting suspended or not");
183 
184 /*
185  * Accounting system call.  Written based on the specification and
186  * previous implementation done by Mark Tinguely.
187  *
188  * MPSAFE
189  */
190 int
191 acct(struct thread *td, struct acct_args *uap)
192 {
193 	struct nameidata nd;
194 	int error, flags, vfslocked;
195 
196 	error = priv_check(td, PRIV_ACCT);
197 	if (error)
198 		return (error);
199 
200 	/*
201 	 * If accounting is to be started to a file, open that file for
202 	 * appending and make sure it's a 'normal'.
203 	 */
204 	if (uap->path != NULL) {
205 		NDINIT(&nd, LOOKUP, NOFOLLOW | MPSAFE | AUDITVNODE1,
206 		    UIO_USERSPACE, uap->path, td);
207 		flags = FWRITE | O_APPEND;
208 		error = vn_open(&nd, &flags, 0, -1);
209 		if (error)
210 			return (error);
211 		vfslocked = NDHASGIANT(&nd);
212 		NDFREE(&nd, NDF_ONLY_PNBUF);
213 #ifdef MAC
214 		error = mac_check_system_acct(td->td_ucred, nd.ni_vp);
215 		if (error) {
216 			VOP_UNLOCK(nd.ni_vp, 0, td);
217 			vn_close(nd.ni_vp, flags, td->td_ucred, td);
218 			VFS_UNLOCK_GIANT(vfslocked);
219 			return (error);
220 		}
221 #endif
222 		VOP_UNLOCK(nd.ni_vp, 0, td);
223 		if (nd.ni_vp->v_type != VREG) {
224 			vn_close(nd.ni_vp, flags, td->td_ucred, td);
225 			VFS_UNLOCK_GIANT(vfslocked);
226 			return (EACCES);
227 		}
228 		VFS_UNLOCK_GIANT(vfslocked);
229 #ifdef MAC
230 	} else {
231 		error = mac_check_system_acct(td->td_ucred, NULL);
232 		if (error)
233 			return (error);
234 #endif
235 	}
236 
237 	/*
238 	 * Disallow concurrent access to the accounting vnode while we swap
239 	 * it out, in order to prevent access after close.
240 	 */
241 	sx_xlock(&acct_sx);
242 
243 	/*
244 	 * If accounting was previously enabled, kill the old space-watcher,
245 	 * close the file, and (if no new file was specified, leave).  Reset
246 	 * the suspended state regardless of whether accounting remains
247 	 * enabled.
248 	 */
249 	acct_suspended = 0;
250 	if (acct_vp != NULL) {
251 		vfslocked = VFS_LOCK_GIANT(acct_vp->v_mount);
252 		error = acct_disable(td);
253 		VFS_UNLOCK_GIANT(vfslocked);
254 	}
255 	if (uap->path == NULL) {
256 		if (acct_state & ACCT_RUNNING) {
257 			acct_state |= ACCT_EXITREQ;
258 			wakeup(&acct_state);
259 		}
260 		sx_xunlock(&acct_sx);
261 		return (error);
262 	}
263 
264 	/*
265 	 * Save the new accounting file vnode, and schedule the new
266 	 * free space watcher.
267 	 */
268 	acct_vp = nd.ni_vp;
269 	acct_cred = crhold(td->td_ucred);
270 	acct_flags = flags;
271 	if (acct_state & ACCT_RUNNING)
272 		acct_state &= ~ACCT_EXITREQ;
273 	else {
274 		/*
275 		 * Try to start up an accounting kthread.  We may start more
276 		 * than one, but if so the extras will commit suicide as
277 		 * soon as they start up.
278 		 */
279 		error = kthread_create(acct_thread, NULL, NULL, 0, 0,
280 		    "accounting");
281 		if (error) {
282 			vfslocked = VFS_LOCK_GIANT(acct_vp->v_mount);
283 			(void) vn_close(acct_vp, acct_flags, acct_cred, td);
284 			VFS_UNLOCK_GIANT(vfslocked);
285 			crfree(acct_cred);
286 			acct_configured = 0;
287 			acct_vp = NULL;
288 			acct_cred = NULL;
289 			acct_flags = 0;
290 			sx_xunlock(&acct_sx);
291 			log(LOG_NOTICE, "Unable to start accounting thread\n");
292 			return (error);
293 		}
294 	}
295 	acct_configured = 1;
296 	sx_xunlock(&acct_sx);
297 	log(LOG_NOTICE, "Accounting enabled\n");
298 	return (error);
299 }
300 
301 /*
302  * Disable currently in-progress accounting by closing the vnode, dropping
303  * our reference to the credential, and clearing the vnode's flags.
304  */
305 static int
306 acct_disable(struct thread *td)
307 {
308 	int error;
309 
310 	sx_assert(&acct_sx, SX_XLOCKED);
311 	error = vn_close(acct_vp, acct_flags, acct_cred, td);
312 	crfree(acct_cred);
313 	acct_configured = 0;
314 	acct_vp = NULL;
315 	acct_cred = NULL;
316 	acct_flags = 0;
317 	log(LOG_NOTICE, "Accounting disabled\n");
318 	return (error);
319 }
320 
321 /*
322  * Write out process accounting information, on process exit.
323  * Data to be written out is specified in Leffler, et al.
324  * and are enumerated below.  (They're also noted in the system
325  * "acct.h" header file.)
326  */
327 int
328 acct_process(struct thread *td)
329 {
330 	struct acct acct;
331 	struct timeval ut, st, tmp;
332 	struct plimit *newlim, *oldlim;
333 	struct proc *p;
334 	struct rusage *r;
335 	int t, ret, vfslocked;
336 
337 	/*
338 	 * Lockless check of accounting condition before doing the hard
339 	 * work.
340 	 */
341 	if (acct_vp == NULL || acct_suspended)
342 		return (0);
343 
344 	sx_slock(&acct_sx);
345 
346 	/*
347 	 * If accounting isn't enabled, don't bother.  Have to check again
348 	 * once we own the lock in case we raced with disabling of accounting
349 	 * by another thread.
350 	 */
351 	if (acct_vp == NULL || acct_suspended) {
352 		sx_sunlock(&acct_sx);
353 		return (0);
354 	}
355 
356 	p = td->td_proc;
357 
358 	/*
359 	 * Get process accounting information.
360 	 */
361 
362 	PROC_LOCK(p);
363 	/* (1) The name of the command that ran */
364 	bcopy(p->p_comm, acct.ac_comm, sizeof acct.ac_comm);
365 
366 	/* (2) The amount of user and system time that was used */
367 	calcru(p, &ut, &st);
368 	acct.ac_utime = encode_comp_t(ut.tv_sec, ut.tv_usec);
369 	acct.ac_stime = encode_comp_t(st.tv_sec, st.tv_usec);
370 
371 	/* (3) The elapsed time the command ran (and its starting time) */
372 	tmp = boottime;
373 	timevaladd(&tmp, &p->p_stats->p_start);
374 	acct.ac_btime = tmp.tv_sec;
375 	microuptime(&tmp);
376 	timevalsub(&tmp, &p->p_stats->p_start);
377 	acct.ac_etime = encode_comp_t(tmp.tv_sec, tmp.tv_usec);
378 
379 	/* (4) The average amount of memory used */
380 	r = &p->p_stats->p_ru;
381 	tmp = ut;
382 	timevaladd(&tmp, &st);
383 	t = tmp.tv_sec * hz + tmp.tv_usec / tick;
384 	if (t)
385 		acct.ac_mem = (r->ru_ixrss + r->ru_idrss + r->ru_isrss) / t;
386 	else
387 		acct.ac_mem = 0;
388 
389 	/* (5) The number of disk I/O operations done */
390 	acct.ac_io = encode_comp_t(r->ru_inblock + r->ru_oublock, 0);
391 
392 	/* (6) The UID and GID of the process */
393 	acct.ac_uid = p->p_ucred->cr_ruid;
394 	acct.ac_gid = p->p_ucred->cr_rgid;
395 
396 	/* (7) The terminal from which the process was started */
397 	SESS_LOCK(p->p_session);
398 	if ((p->p_flag & P_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
399 		acct.ac_tty = dev2udev(p->p_pgrp->pg_session->s_ttyp->t_dev);
400 	else
401 		acct.ac_tty = NODEV;
402 	SESS_UNLOCK(p->p_session);
403 
404 	/* (8) The boolean flags that tell how the process terminated, etc. */
405 	acct.ac_flag = p->p_acflag;
406 	PROC_UNLOCK(p);
407 
408 	/*
409 	 * Eliminate any file size rlimit.
410 	 */
411 	newlim = lim_alloc();
412 	PROC_LOCK(p);
413 	oldlim = p->p_limit;
414 	lim_copy(newlim, oldlim);
415 	newlim->pl_rlimit[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
416 	p->p_limit = newlim;
417 	PROC_UNLOCK(p);
418 	lim_free(oldlim);
419 
420 	/*
421 	 * Write the accounting information to the file.
422 	 */
423 	vfslocked = VFS_LOCK_GIANT(acct_vp->v_mount);
424 	VOP_LEASE(acct_vp, td, acct_cred, LEASE_WRITE);
425 	ret = vn_rdwr(UIO_WRITE, acct_vp, (caddr_t)&acct, sizeof (acct),
426 	    (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT, acct_cred, NOCRED,
427 	    (int *)0, td);
428 	VFS_UNLOCK_GIANT(vfslocked);
429 	sx_sunlock(&acct_sx);
430 	return (ret);
431 }
432 
433 /*
434  * Encode_comp_t converts from ticks in seconds and microseconds
435  * to ticks in 1/AHZ seconds.  The encoding is described in
436  * Leffler, et al., on page 63.
437  */
438 
439 #define	MANTSIZE	13			/* 13 bit mantissa. */
440 #define	EXPSIZE		3			/* Base 8 (3 bit) exponent. */
441 #define	MAXFRACT	((1 << MANTSIZE) - 1)	/* Maximum fractional value. */
442 
443 static comp_t
444 encode_comp_t(u_long s, u_long us)
445 {
446 	int exp, rnd;
447 
448 	exp = 0;
449 	rnd = 0;
450 	s *= AHZ;
451 	s += us / (1000000 / AHZ);	/* Maximize precision. */
452 
453 	while (s > MAXFRACT) {
454 	rnd = s & (1 << (EXPSIZE - 1));	/* Round up? */
455 		s >>= EXPSIZE;		/* Base 8 exponent == 3 bit shift. */
456 		exp++;
457 	}
458 
459 	/* If we need to round up, do it (and handle overflow correctly). */
460 	if (rnd && (++s > MAXFRACT)) {
461 		s >>= EXPSIZE;
462 		exp++;
463 	}
464 
465 	/* Clean it up and polish it off. */
466 	exp <<= MANTSIZE;		/* Shift the exponent into place */
467 	exp += s;			/* and add on the mantissa. */
468 	return (exp);
469 }
470 
471 /*
472  * Periodically check the filesystem to see if accounting
473  * should be turned on or off.  Beware the case where the vnode
474  * has been vgone()'d out from underneath us, e.g. when the file
475  * system containing the accounting file has been forcibly unmounted.
476  */
477 /* ARGSUSED */
478 static void
479 acctwatch(void)
480 {
481 	struct statfs sb;
482 	int vfslocked;
483 
484 	sx_assert(&acct_sx, SX_XLOCKED);
485 
486 	/*
487 	 * If accounting was disabled before our kthread was scheduled,
488 	 * then acct_vp might be NULL.  If so, just ask our kthread to
489 	 * exit and return.
490 	 */
491 	if (acct_vp == NULL) {
492 		acct_state |= ACCT_EXITREQ;
493 		return;
494 	}
495 
496 	/*
497 	 * If our vnode is no longer valid, tear it down and signal the
498 	 * accounting thread to die.
499 	 */
500 	vfslocked = VFS_LOCK_GIANT(acct_vp->v_mount);
501 	if (acct_vp->v_type == VBAD) {
502 		(void) acct_disable(NULL);
503 		VFS_UNLOCK_GIANT(vfslocked);
504 		acct_state |= ACCT_EXITREQ;
505 		return;
506 	}
507 
508 	/*
509 	 * Stopping here is better than continuing, maybe it will be VBAD
510 	 * next time around.
511 	 */
512 	if (VFS_STATFS(acct_vp->v_mount, &sb, curthread) < 0) {
513 		VFS_UNLOCK_GIANT(vfslocked);
514 		return;
515 	}
516 	VFS_UNLOCK_GIANT(vfslocked);
517 	if (acct_suspended) {
518 		if (sb.f_bavail > (int64_t)(acctresume * sb.f_blocks /
519 		    100)) {
520 			acct_suspended = 0;
521 			log(LOG_NOTICE, "Accounting resumed\n");
522 		}
523 	} else {
524 		if (sb.f_bavail <= (int64_t)(acctsuspend * sb.f_blocks /
525 		    100)) {
526 			acct_suspended = 1;
527 			log(LOG_NOTICE, "Accounting suspended\n");
528 		}
529 	}
530 }
531 
532 /*
533  * The main loop for the dedicated kernel thread that periodically calls
534  * acctwatch().
535  */
536 static void
537 acct_thread(void *dummy)
538 {
539 	u_char pri;
540 
541 	/* This is a low-priority kernel thread. */
542 	pri = PRI_MAX_KERN;
543 	mtx_lock_spin(&sched_lock);
544 	sched_prio(curthread, pri);
545 	mtx_unlock_spin(&sched_lock);
546 
547 	/* If another accounting kthread is already running, just die. */
548 	sx_xlock(&acct_sx);
549 	if (acct_state & ACCT_RUNNING) {
550 		sx_xunlock(&acct_sx);
551 		kthread_exit(0);
552 	}
553 	acct_state |= ACCT_RUNNING;
554 
555 	/* Loop until we are asked to exit. */
556 	while (!(acct_state & ACCT_EXITREQ)) {
557 
558 		/* Perform our periodic checks. */
559 		acctwatch();
560 
561 		/*
562 		 * We check this flag again before sleeping since the
563 		 * acctwatch() might have shut down accounting and asked us
564 		 * to exit.
565 		 */
566 		if (!(acct_state & ACCT_EXITREQ)) {
567 			sx_xunlock(&acct_sx);
568 			tsleep(&acct_state, pri, "-", acctchkfreq * hz);
569 			sx_xlock(&acct_sx);
570 		}
571 	}
572 
573 	/*
574 	 * Acknowledge the exit request and shutdown.  We clear both the
575 	 * exit request and running flags.
576 	 */
577 	acct_state = 0;
578 	sx_xunlock(&acct_sx);
579 	kthread_exit(0);
580 }
581