kern_acct.c revision 155431
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 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
9 *
10 * Copyright (c) 1994 Christopher G. Demetriou
11 * Copyright (c) 2005 Robert N. M. Watson
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. All advertising materials mentioning features or use of this software
22 *    must display the following acknowledgement:
23 *	This product includes software developed by the University of
24 *	California, Berkeley and its contributors.
25 * 4. Neither the name of the University nor the names of its contributors
26 *    may be used to endorse or promote products derived from this software
27 *    without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * SUCH DAMAGE.
40 *
41 *	@(#)kern_acct.c	8.1 (Berkeley) 6/14/93
42 */
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD: head/sys/kern/kern_acct.c 155431 2006-02-07 16:04:03Z jhb $");
46
47#include "opt_mac.h"
48
49#include <sys/param.h>
50#include <sys/systm.h>
51#include <sys/acct.h>
52#include <sys/fcntl.h>
53#include <sys/kernel.h>
54#include <sys/kthread.h>
55#include <sys/lock.h>
56#include <sys/mac.h>
57#include <sys/mount.h>
58#include <sys/mutex.h>
59#include <sys/namei.h>
60#include <sys/proc.h>
61#include <sys/resourcevar.h>
62#include <sys/sched.h>
63#include <sys/sx.h>
64#include <sys/sysctl.h>
65#include <sys/sysent.h>
66#include <sys/syslog.h>
67#include <sys/sysproto.h>
68#include <sys/tty.h>
69#include <sys/vnode.h>
70
71/*
72 * The routines implemented in this file are described in:
73 *      Leffler, et al.: The Design and Implementation of the 4.3BSD
74 *	    UNIX Operating System (Addison Welley, 1989)
75 * on pages 62-63.
76 *
77 * Arguably, to simplify accounting operations, this mechanism should
78 * be replaced by one in which an accounting log file (similar to /dev/klog)
79 * is read by a user process, etc.  However, that has its own problems.
80 */
81
82/*
83 * Internal accounting functions.
84 * The former's operation is described in Leffler, et al., and the latter
85 * was provided by UCB with the 4.4BSD-Lite release
86 */
87static comp_t	encode_comp_t(u_long, u_long);
88static void	acctwatch(void);
89static void	acct_thread(void *);
90static int	acct_disable(struct thread *);
91
92/*
93 * Accounting vnode pointer, saved vnode pointer, and flags for each.
94 * acct_sx protects against changes to the active vnode and credentials
95 * while accounting records are being committed to disk.
96 */
97static int		 acct_suspended;
98static struct vnode	*acct_vp;
99static struct ucred	*acct_cred;
100static int		 acct_flags;
101static struct sx	 acct_sx;
102
103SX_SYSINIT(acct, &acct_sx, "acct_sx");
104
105/*
106 * State of the accounting kthread.
107 */
108static int		 acct_state;
109
110#define	ACCT_RUNNING	1	/* Accounting kthread is running. */
111#define	ACCT_EXITREQ	2	/* Accounting kthread should exit. */
112
113/*
114 * Values associated with enabling and disabling accounting
115 */
116static int acctsuspend = 2;	/* stop accounting when < 2% free space left */
117SYSCTL_INT(_kern, OID_AUTO, acct_suspend, CTLFLAG_RW,
118	&acctsuspend, 0, "percentage of free disk space below which accounting stops");
119
120static int acctresume = 4;	/* resume when free space risen to > 4% */
121SYSCTL_INT(_kern, OID_AUTO, acct_resume, CTLFLAG_RW,
122	&acctresume, 0, "percentage of free disk space above which accounting resumes");
123
124static int acctchkfreq = 15;	/* frequency (in seconds) to check space */
125SYSCTL_INT(_kern, OID_AUTO, acct_chkfreq, CTLFLAG_RW,
126	&acctchkfreq, 0, "frequency for checking the free space");
127
128SYSCTL_INT(_kern, OID_AUTO, acct_suspended, CTLFLAG_RD, &acct_suspended, 0,
129	"Accounting suspended or not");
130
131/*
132 * Accounting system call.  Written based on the specification and
133 * previous implementation done by Mark Tinguely.
134 *
135 * MPSAFE
136 */
137int
138acct(struct thread *td, struct acct_args *uap)
139{
140	struct nameidata nd;
141	int error, flags;
142
143	/* Make sure that the caller is root. */
144	error = suser(td);
145	if (error)
146		return (error);
147
148	/*
149	 * If accounting is to be started to a file, open that file for
150	 * appending and make sure it's a 'normal'.  While we could
151	 * conditionally acquire Giant here, we're actually interacting with
152	 * vnodes from possibly two file systems, making the logic a bit
153	 * complicated.  For now, use Giant unconditionally.
154	 */
155	mtx_lock(&Giant);
156	if (uap->path != NULL) {
157		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, uap->path, td);
158		flags = FWRITE | O_APPEND;
159		error = vn_open(&nd, &flags, 0, -1);
160		if (error)
161			goto done;
162		NDFREE(&nd, NDF_ONLY_PNBUF);
163#ifdef MAC
164		error = mac_check_system_acct(td->td_ucred, nd.ni_vp);
165		if (error) {
166			VOP_UNLOCK(nd.ni_vp, 0, td);
167			vn_close(nd.ni_vp, flags, td->td_ucred, td);
168			goto done;
169		}
170#endif
171		VOP_UNLOCK(nd.ni_vp, 0, td);
172		if (nd.ni_vp->v_type != VREG) {
173			vn_close(nd.ni_vp, flags, td->td_ucred, td);
174			error = EACCES;
175			goto done;
176		}
177#ifdef MAC
178	} else {
179		error = mac_check_system_acct(td->td_ucred, NULL);
180		if (error)
181			goto done;
182#endif
183	}
184
185	/*
186	 * Disallow concurrent access to the accounting vnode while we swap
187	 * it out, in order to prevent access after close.
188	 */
189	sx_xlock(&acct_sx);
190
191	/*
192	 * If accounting was previously enabled, kill the old space-watcher,
193	 * close the file, and (if no new file was specified, leave).  Reset
194	 * the suspended state regardless of whether accounting remains
195	 * enabled.
196	 */
197	acct_suspended = 0;
198	if (acct_vp != NULL)
199		error = acct_disable(td);
200	if (uap->path == NULL) {
201		if (acct_state & ACCT_RUNNING) {
202			acct_state |= ACCT_EXITREQ;
203			wakeup(&acct_state);
204		}
205		sx_xunlock(&acct_sx);
206		goto done;
207	}
208
209	/*
210	 * Save the new accounting file vnode, and schedule the new
211	 * free space watcher.
212	 */
213	acct_vp = nd.ni_vp;
214	acct_cred = crhold(td->td_ucred);
215	acct_flags = flags;
216	if (acct_state & ACCT_RUNNING)
217		acct_state &= ~ACCT_EXITREQ;
218	else {
219		/*
220		 * Try to start up an accounting kthread.  We may start more
221		 * than one, but if so the extras will commit suicide as
222		 * soon as they start up.
223		 */
224		error = kthread_create(acct_thread, NULL, NULL, 0, 0,
225		    "accounting");
226		if (error) {
227			(void) vn_close(acct_vp, acct_flags, acct_cred, td);
228			crfree(acct_cred);
229			acct_vp = NULL;
230			acct_cred = NULL;
231			acct_flags = 0;
232			sx_xunlock(&acct_sx);
233			log(LOG_NOTICE, "Unable to start accounting thread\n");
234			goto done;
235		}
236	}
237	sx_xunlock(&acct_sx);
238	log(LOG_NOTICE, "Accounting enabled\n");
239done:
240	mtx_unlock(&Giant);
241	return (error);
242}
243
244/*
245 * Disable currently in-progress accounting by closing the vnode, dropping
246 * our reference to the credential, and clearing the vnode's flags.
247 */
248static int
249acct_disable(struct thread *td)
250{
251	int error;
252
253	sx_assert(&acct_sx, SX_XLOCKED);
254	error = vn_close(acct_vp, acct_flags, acct_cred, td);
255	crfree(acct_cred);
256	acct_vp = NULL;
257	acct_cred = NULL;
258	acct_flags = 0;
259	log(LOG_NOTICE, "Accounting disabled\n");
260	return (error);
261}
262
263/*
264 * Write out process accounting information, on process exit.
265 * Data to be written out is specified in Leffler, et al.
266 * and are enumerated below.  (They're also noted in the system
267 * "acct.h" header file.)
268 */
269int
270acct_process(struct thread *td)
271{
272	struct acct acct;
273	struct timeval ut, st, tmp;
274	struct plimit *newlim, *oldlim;
275	struct proc *p;
276	struct rusage *r;
277	int t, ret, vfslocked;
278
279	/*
280	 * Lockless check of accounting condition before doing the hard
281	 * work.
282	 */
283	if (acct_vp == NULL || acct_suspended)
284		return (0);
285
286	sx_slock(&acct_sx);
287
288	/*
289	 * If accounting isn't enabled, don't bother.  Have to check again
290	 * once we own the lock in case we raced with disabling of accounting
291	 * by another thread.
292	 */
293	if (acct_vp == NULL || acct_suspended) {
294		sx_sunlock(&acct_sx);
295		return (0);
296	}
297
298	p = td->td_proc;
299
300	/*
301	 * Get process accounting information.
302	 */
303
304	PROC_LOCK(p);
305	/* (1) The name of the command that ran */
306	bcopy(p->p_comm, acct.ac_comm, sizeof acct.ac_comm);
307
308	/* (2) The amount of user and system time that was used */
309	calcru(p, &ut, &st);
310	acct.ac_utime = encode_comp_t(ut.tv_sec, ut.tv_usec);
311	acct.ac_stime = encode_comp_t(st.tv_sec, st.tv_usec);
312
313	/* (3) The elapsed time the command ran (and its starting time) */
314	tmp = boottime;
315	timevaladd(&tmp, &p->p_stats->p_start);
316	acct.ac_btime = tmp.tv_sec;
317	microuptime(&tmp);
318	timevalsub(&tmp, &p->p_stats->p_start);
319	acct.ac_etime = encode_comp_t(tmp.tv_sec, tmp.tv_usec);
320
321	/* (4) The average amount of memory used */
322	r = &p->p_stats->p_ru;
323	tmp = ut;
324	timevaladd(&tmp, &st);
325	t = tmp.tv_sec * hz + tmp.tv_usec / tick;
326	if (t)
327		acct.ac_mem = (r->ru_ixrss + r->ru_idrss + r->ru_isrss) / t;
328	else
329		acct.ac_mem = 0;
330
331	/* (5) The number of disk I/O operations done */
332	acct.ac_io = encode_comp_t(r->ru_inblock + r->ru_oublock, 0);
333
334	/* (6) The UID and GID of the process */
335	acct.ac_uid = p->p_ucred->cr_ruid;
336	acct.ac_gid = p->p_ucred->cr_rgid;
337
338	/* (7) The terminal from which the process was started */
339	SESS_LOCK(p->p_session);
340	if ((p->p_flag & P_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
341		acct.ac_tty = dev2udev(p->p_pgrp->pg_session->s_ttyp->t_dev);
342	else
343		acct.ac_tty = NODEV;
344	SESS_UNLOCK(p->p_session);
345
346	/* (8) The boolean flags that tell how the process terminated, etc. */
347	acct.ac_flag = p->p_acflag;
348	PROC_UNLOCK(p);
349
350	/*
351	 * Eliminate any file size rlimit.
352	 */
353	newlim = lim_alloc();
354	PROC_LOCK(p);
355	oldlim = p->p_limit;
356	lim_copy(newlim, oldlim);
357	newlim->pl_rlimit[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
358	p->p_limit = newlim;
359	PROC_UNLOCK(p);
360	lim_free(oldlim);
361
362	/*
363	 * Write the accounting information to the file.
364	 */
365	vfslocked = VFS_LOCK_GIANT(acct_vp->v_mount);
366	VOP_LEASE(acct_vp, td, acct_cred, LEASE_WRITE);
367	ret = vn_rdwr(UIO_WRITE, acct_vp, (caddr_t)&acct, sizeof (acct),
368	    (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT, acct_cred, NOCRED,
369	    (int *)0, td);
370	VFS_UNLOCK_GIANT(vfslocked);
371	sx_sunlock(&acct_sx);
372	return (ret);
373}
374
375/*
376 * Encode_comp_t converts from ticks in seconds and microseconds
377 * to ticks in 1/AHZ seconds.  The encoding is described in
378 * Leffler, et al., on page 63.
379 */
380
381#define	MANTSIZE	13			/* 13 bit mantissa. */
382#define	EXPSIZE		3			/* Base 8 (3 bit) exponent. */
383#define	MAXFRACT	((1 << MANTSIZE) - 1)	/* Maximum fractional value. */
384
385static comp_t
386encode_comp_t(u_long s, u_long us)
387{
388	int exp, rnd;
389
390	exp = 0;
391	rnd = 0;
392	s *= AHZ;
393	s += us / (1000000 / AHZ);	/* Maximize precision. */
394
395	while (s > MAXFRACT) {
396	rnd = s & (1 << (EXPSIZE - 1));	/* Round up? */
397		s >>= EXPSIZE;		/* Base 8 exponent == 3 bit shift. */
398		exp++;
399	}
400
401	/* If we need to round up, do it (and handle overflow correctly). */
402	if (rnd && (++s > MAXFRACT)) {
403		s >>= EXPSIZE;
404		exp++;
405	}
406
407	/* Clean it up and polish it off. */
408	exp <<= MANTSIZE;		/* Shift the exponent into place */
409	exp += s;			/* and add on the mantissa. */
410	return (exp);
411}
412
413/*
414 * Periodically check the filesystem to see if accounting
415 * should be turned on or off.  Beware the case where the vnode
416 * has been vgone()'d out from underneath us, e.g. when the file
417 * system containing the accounting file has been forcibly unmounted.
418 */
419/* ARGSUSED */
420static void
421acctwatch(void)
422{
423	struct statfs sb;
424	int vfslocked;
425
426	sx_assert(&acct_sx, SX_XLOCKED);
427
428	/*
429	 * If accounting was disabled before our kthread was scheduled,
430	 * then acct_vp might be NULL.  If so, just ask our kthread to
431	 * exit and return.
432	 */
433	if (acct_vp == NULL) {
434		acct_state |= ACCT_EXITREQ;
435		return;
436	}
437
438	/*
439	 * If our vnode is no longer valid, tear it down and signal the
440	 * accounting thread to die.
441	 */
442	vfslocked = VFS_LOCK_GIANT(acct_vp->v_mount);
443	if (acct_vp->v_type == VBAD) {
444		(void) acct_disable(NULL);
445		VFS_UNLOCK_GIANT(vfslocked);
446		acct_state |= ACCT_EXITREQ;
447		return;
448	}
449
450	/*
451	 * Stopping here is better than continuing, maybe it will be VBAD
452	 * next time around.
453	 */
454	if (VFS_STATFS(acct_vp->v_mount, &sb, curthread) < 0) {
455		VFS_UNLOCK_GIANT(vfslocked);
456		return;
457	}
458	VFS_UNLOCK_GIANT(vfslocked);
459	if (acct_suspended) {
460		if (sb.f_bavail > (int64_t)(acctresume * sb.f_blocks /
461		    100)) {
462			acct_suspended = 0;
463			log(LOG_NOTICE, "Accounting resumed\n");
464		}
465	} else {
466		if (sb.f_bavail <= (int64_t)(acctsuspend * sb.f_blocks /
467		    100)) {
468			acct_suspended = 1;
469			log(LOG_NOTICE, "Accounting suspended\n");
470		}
471	}
472}
473
474/*
475 * The main loop for the dedicated kernel thread that periodically calls
476 * acctwatch().
477 */
478static void
479acct_thread(void *dummy)
480{
481	u_char pri;
482
483	/* This is a low-priority kernel thread. */
484	pri = PRI_MAX_KERN;
485	mtx_lock_spin(&sched_lock);
486	sched_prio(curthread, pri);
487	mtx_unlock_spin(&sched_lock);
488
489	/* If another accounting kthread is already running, just die. */
490	sx_xlock(&acct_sx);
491	if (acct_state & ACCT_RUNNING) {
492		sx_xunlock(&acct_sx);
493		kthread_exit(0);
494	}
495	acct_state |= ACCT_RUNNING;
496
497	/* Loop until we are asked to exit. */
498	while (!(acct_state & ACCT_EXITREQ)) {
499
500		/* Perform our periodic checks. */
501		acctwatch();
502
503		/*
504		 * We check this flag again before sleeping since the
505		 * acctwatch() might have shut down accounting and asked us
506		 * to exit.
507		 */
508		if (!(acct_state & ACCT_EXITREQ)) {
509			sx_xunlock(&acct_sx);
510			tsleep(&acct_state, pri, "-", acctchkfreq * hz);
511			sx_xlock(&acct_sx);
512		}
513	}
514
515	/*
516	 * Acknowledge the exit request and shutdown.  We clear both the
517	 * exit request and running flags.
518	 */
519	acct_state = 0;
520	sx_xunlock(&acct_sx);
521	kthread_exit(0);
522}
523