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