kern_acct.c revision 139895
1/*-
2 * Copyright (c) 1994 Christopher G. Demetriou
3 * Copyright (c) 1982, 1986, 1989, 1993
4 *	The Regents of the University of California.  All rights reserved.
5 * (c) UNIX System Laboratories, Inc.
6 * All or some portions of this file are derived from material licensed
7 * to the University of California by American Telephone and Telegraph
8 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
9 * the permission of UNIX System Laboratories, Inc.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 *    must display the following acknowledgement:
21 *	This product includes software developed by the University of
22 *	California, Berkeley and its contributors.
23 * 4. 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.
26 *
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
37 * SUCH DAMAGE.
38 *
39 *	@(#)kern_acct.c	8.1 (Berkeley) 6/14/93
40 */
41
42#include <sys/cdefs.h>
43__FBSDID("$FreeBSD: head/sys/kern/kern_acct.c 139895 2005-01-08 04:45:57Z rwatson $");
44
45#include "opt_mac.h"
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/lock.h>
50#include <sys/mutex.h>
51#include <sys/sysproto.h>
52#include <sys/proc.h>
53#include <sys/mac.h>
54#include <sys/mount.h>
55#include <sys/vnode.h>
56#include <sys/fcntl.h>
57#include <sys/syslog.h>
58#include <sys/kernel.h>
59#include <sys/sysent.h>
60#include <sys/sysctl.h>
61#include <sys/namei.h>
62#include <sys/acct.h>
63#include <sys/resourcevar.h>
64#include <sys/tty.h>
65
66/*
67 * The routines implemented in this file are described in:
68 *      Leffler, et al.: The Design and Implementation of the 4.3BSD
69 *	    UNIX Operating System (Addison Welley, 1989)
70 * on pages 62-63.
71 *
72 * Arguably, to simplify accounting operations, this mechanism should
73 * be replaced by one in which an accounting log file (similar to /dev/klog)
74 * is read by a user process, etc.  However, that has its own problems.
75 */
76
77/*
78 * Internal accounting functions.
79 * The former's operation is described in Leffler, et al., and the latter
80 * was provided by UCB with the 4.4BSD-Lite release
81 */
82static comp_t	encode_comp_t(u_long, u_long);
83static void	acctwatch(void *);
84
85/*
86 * Accounting callout used for periodic scheduling of acctwatch.
87 */
88static struct	callout acctwatch_callout;
89
90/*
91 * Accounting vnode pointer, saved vnode pointer, and flags for each.
92 */
93static struct	vnode *acctp;
94static struct	ucred *acctcred;
95static int	acctflags;
96static struct	vnode *savacctp;
97static struct	ucred *savacctcred;
98static int	savacctflags;
99
100static struct mtx	acct_mtx;
101MTX_SYSINIT(acct, &acct_mtx, "accounting", MTX_DEF);
102
103/*
104 * Values associated with enabling and disabling accounting
105 */
106static int acctsuspend = 2;	/* stop accounting when < 2% free space left */
107SYSCTL_INT(_kern, OID_AUTO, acct_suspend, CTLFLAG_RW,
108	&acctsuspend, 0, "percentage of free disk space below which accounting stops");
109
110static int acctresume = 4;	/* resume when free space risen to > 4% */
111SYSCTL_INT(_kern, OID_AUTO, acct_resume, CTLFLAG_RW,
112	&acctresume, 0, "percentage of free disk space above which accounting resumes");
113
114static int acctchkfreq = 15;	/* frequency (in seconds) to check space */
115SYSCTL_INT(_kern, OID_AUTO, acct_chkfreq, CTLFLAG_RW,
116	&acctchkfreq, 0, "frequency for checking the free space");
117
118/*
119 * Accounting system call.  Written based on the specification and
120 * previous implementation done by Mark Tinguely.
121 *
122 * MPSAFE
123 */
124int
125acct(td, uap)
126	struct thread *td;
127	struct acct_args /* {
128		char *path;
129	} */ *uap;
130{
131	struct nameidata nd;
132	int error, flags;
133
134	/* Make sure that the caller is root. */
135	error = suser(td);
136	if (error)
137		return (error);
138
139	mtx_lock(&Giant);
140
141	/*
142	 * If accounting is to be started to a file, open that file for
143	 * appending and make sure it's a 'normal'.
144	 */
145	if (uap->path != NULL) {
146		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, uap->path, td);
147		flags = FWRITE | O_APPEND;
148		error = vn_open(&nd, &flags, 0, -1);
149		if (error)
150			goto done2;
151		NDFREE(&nd, NDF_ONLY_PNBUF);
152#ifdef MAC
153		error = mac_check_system_acct(td->td_ucred, nd.ni_vp);
154		if (error) {
155			vn_close(nd.ni_vp, flags, td->td_ucred, td);
156			goto done2;
157		}
158#endif
159		VOP_UNLOCK(nd.ni_vp, 0, td);
160		if (nd.ni_vp->v_type != VREG) {
161			vn_close(nd.ni_vp, flags, td->td_ucred, td);
162			error = EACCES;
163			goto done2;
164		}
165#ifdef MAC
166	} else {
167		error = mac_check_system_acct(td->td_ucred, NULL);
168		if (error)
169			goto done2;
170#endif
171	}
172
173	mtx_lock(&acct_mtx);
174
175	/*
176	 * If accounting was previously enabled, kill the old space-watcher,
177	 * close the file, and (if no new file was specified, leave).
178	 *
179	 * XXX arr: should not hold lock over vnode operation.
180	 */
181	if (acctp != NULLVP || savacctp != NULLVP) {
182		callout_stop(&acctwatch_callout);
183		error = vn_close((acctp != NULLVP ? acctp : savacctp),
184		    (acctp != NULLVP ? acctflags : savacctflags),
185		    (acctcred != NOCRED ? acctcred : savacctcred), td);
186		acctp = savacctp = NULLVP;
187		crfree(acctcred != NOCRED ? acctcred : savacctcred);
188		acctcred = savacctcred = NOCRED;
189		log(LOG_NOTICE, "Accounting disabled\n");
190	}
191	if (uap->path == NULL) {
192		mtx_unlock(&acct_mtx);
193		goto done2;
194	}
195
196	/*
197	 * Save the new accounting file vnode, and schedule the new
198	 * free space watcher.
199	 */
200	acctp = nd.ni_vp;
201	acctcred = crhold(td->td_ucred);
202	acctflags = flags;
203	callout_init(&acctwatch_callout, 0);
204	mtx_unlock(&acct_mtx);
205	log(LOG_NOTICE, "Accounting enabled\n");
206	acctwatch(NULL);
207
208done2:
209	mtx_unlock(&Giant);
210	return (error);
211}
212
213/*
214 * Write out process accounting information, on process exit.
215 * Data to be written out is specified in Leffler, et al.
216 * and are enumerated below.  (They're also noted in the system
217 * "acct.h" header file.)
218 */
219int
220acct_process(td)
221	struct thread *td;
222{
223	struct acct acct;
224	struct timeval ut, st, tmp;
225	struct plimit *newlim, *oldlim;
226	struct proc *p;
227	struct rusage *r;
228	struct ucred *uc;
229	struct vnode *vp;
230	int t, ret;
231
232	/*
233	 * Lockless check of accounting condition before doing the hard
234	 * work.
235	 */
236	if (acctp == NULLVP)
237		return (0);
238
239	mtx_lock(&acct_mtx);
240
241	/*
242	 * If accounting isn't enabled, don't bother.  Have to check again
243	 * once we own the lock in case we raced with disabling of accounting
244	 * by another thread.
245	 */
246	vp = acctp;
247	if (vp == NULLVP) {
248		mtx_unlock(&acct_mtx);
249		return (0);
250	}
251
252	p = td->td_proc;
253
254	/*
255	 * Get process accounting information.
256	 */
257
258	PROC_LOCK(p);
259	/* (1) The name of the command that ran */
260	bcopy(p->p_comm, acct.ac_comm, sizeof acct.ac_comm);
261
262	/* (2) The amount of user and system time that was used */
263	calcru(p, &ut, &st);
264	acct.ac_utime = encode_comp_t(ut.tv_sec, ut.tv_usec);
265	acct.ac_stime = encode_comp_t(st.tv_sec, st.tv_usec);
266
267	/* (3) The elapsed time the command ran (and its starting time) */
268	tmp = boottime;
269	timevaladd(&tmp, &p->p_stats->p_start);
270	acct.ac_btime = tmp.tv_sec;
271	microuptime(&tmp);
272	timevalsub(&tmp, &p->p_stats->p_start);
273	acct.ac_etime = encode_comp_t(tmp.tv_sec, tmp.tv_usec);
274
275	/* (4) The average amount of memory used */
276	r = &p->p_stats->p_ru;
277	tmp = ut;
278	timevaladd(&tmp, &st);
279	t = tmp.tv_sec * hz + tmp.tv_usec / tick;
280	if (t)
281		acct.ac_mem = (r->ru_ixrss + r->ru_idrss + r->ru_isrss) / t;
282	else
283		acct.ac_mem = 0;
284
285	/* (5) The number of disk I/O operations done */
286	acct.ac_io = encode_comp_t(r->ru_inblock + r->ru_oublock, 0);
287
288	/* (6) The UID and GID of the process */
289	acct.ac_uid = p->p_ucred->cr_ruid;
290	acct.ac_gid = p->p_ucred->cr_rgid;
291
292	/* (7) The terminal from which the process was started */
293	SESS_LOCK(p->p_session);
294	if ((p->p_flag & P_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
295		acct.ac_tty = dev2udev(p->p_pgrp->pg_session->s_ttyp->t_dev);
296	else
297		acct.ac_tty = NODEV;
298	SESS_UNLOCK(p->p_session);
299
300	/* (8) The boolean flags that tell how the process terminated, etc. */
301	acct.ac_flag = p->p_acflag;
302	PROC_UNLOCK(p);
303
304	/*
305	 * Finish doing things that require acct_mtx, and release acct_mtx.
306	 */
307	uc = crhold(acctcred);
308	vref(vp);
309	mtx_unlock(&acct_mtx);
310
311	/*
312	 * Eliminate any file size rlimit.
313	 */
314	newlim = lim_alloc();
315	PROC_LOCK(p);
316	oldlim = p->p_limit;
317	lim_copy(newlim, oldlim);
318	newlim->pl_rlimit[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
319	p->p_limit = newlim;
320	PROC_UNLOCK(p);
321	lim_free(oldlim);
322
323	/*
324	 * Write the accounting information to the file.
325	 */
326	VOP_LEASE(vp, td, uc, LEASE_WRITE);
327	ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)&acct, sizeof (acct),
328	    (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT, uc, NOCRED,
329	    (int *)0, td);
330	vrele(vp);
331	crfree(uc);
332	return (ret);
333}
334
335/*
336 * Encode_comp_t converts from ticks in seconds and microseconds
337 * to ticks in 1/AHZ seconds.  The encoding is described in
338 * Leffler, et al., on page 63.
339 */
340
341#define	MANTSIZE	13			/* 13 bit mantissa. */
342#define	EXPSIZE		3			/* Base 8 (3 bit) exponent. */
343#define	MAXFRACT	((1 << MANTSIZE) - 1)	/* Maximum fractional value. */
344
345static comp_t
346encode_comp_t(s, us)
347	u_long s, us;
348{
349	int exp, rnd;
350
351	exp = 0;
352	rnd = 0;
353	s *= AHZ;
354	s += us / (1000000 / AHZ);	/* Maximize precision. */
355
356	while (s > MAXFRACT) {
357	rnd = s & (1 << (EXPSIZE - 1));	/* Round up? */
358		s >>= EXPSIZE;		/* Base 8 exponent == 3 bit shift. */
359		exp++;
360	}
361
362	/* If we need to round up, do it (and handle overflow correctly). */
363	if (rnd && (++s > MAXFRACT)) {
364		s >>= EXPSIZE;
365		exp++;
366	}
367
368	/* Clean it up and polish it off. */
369	exp <<= MANTSIZE;		/* Shift the exponent into place */
370	exp += s;			/* and add on the mantissa. */
371	return (exp);
372}
373
374/*
375 * Periodically check the filesystem to see if accounting
376 * should be turned on or off.  Beware the case where the vnode
377 * has been vgone()'d out from underneath us, e.g. when the file
378 * system containing the accounting file has been forcibly unmounted.
379 */
380/* ARGSUSED */
381static void
382acctwatch(a)
383	void *a;
384{
385	struct statfs sb;
386
387	mtx_lock(&acct_mtx);
388
389	/*
390	 * XXX arr: need to fix the issue of holding acct_mtx over
391	 * the below vnode operations.
392	 */
393	if (savacctp != NULLVP) {
394		if (savacctp->v_type == VBAD) {
395			(void) vn_close(savacctp, savacctflags, savacctcred,
396			    NULL);
397			savacctp = NULLVP;
398			savacctcred = NOCRED;
399			mtx_unlock(&acct_mtx);
400			return;
401		}
402		(void)VFS_STATFS(savacctp->v_mount, &sb, (struct thread *)0);
403		if (sb.f_bavail > acctresume * sb.f_blocks / 100) {
404			acctp = savacctp;
405			acctcred = savacctcred;
406			acctflags = savacctflags;
407			savacctp = NULLVP;
408			savacctcred = NOCRED;
409			log(LOG_NOTICE, "Accounting resumed\n");
410		}
411	} else {
412		if (acctp == NULLVP) {
413			mtx_unlock(&acct_mtx);
414			return;
415		}
416		if (acctp->v_type == VBAD) {
417			(void) vn_close(acctp, acctflags, acctcred, NULL);
418			acctp = NULLVP;
419			crfree(acctcred);
420			acctcred = NOCRED;
421			mtx_unlock(&acct_mtx);
422			return;
423		}
424		(void)VFS_STATFS(acctp->v_mount, &sb, (struct thread *)0);
425		if (sb.f_bavail <= acctsuspend * sb.f_blocks / 100) {
426			savacctp = acctp;
427			savacctflags = acctflags;
428			savacctcred = acctcred;
429			acctp = NULLVP;
430			acctcred = NOCRED;
431			log(LOG_NOTICE, "Accounting suspended\n");
432		}
433	}
434	callout_reset(&acctwatch_callout, acctchkfreq * hz, acctwatch, NULL);
435	mtx_unlock(&acct_mtx);
436}
437