xref: /freebsd/sys/kern/kern_acct.c (revision 2a4a1db342263067035ce69a4017c645da63455d)
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  * $FreeBSD$
41  */
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/lock.h>
46 #include <sys/mutex.h>
47 #include <sys/sysproto.h>
48 #include <sys/proc.h>
49 #include <sys/mount.h>
50 #include <sys/vnode.h>
51 #include <sys/fcntl.h>
52 #include <sys/syslog.h>
53 #include <sys/kernel.h>
54 #include <sys/sysent.h>
55 #include <sys/sysctl.h>
56 #include <sys/namei.h>
57 #include <sys/acct.h>
58 #include <sys/resourcevar.h>
59 #include <sys/tty.h>
60 
61 /*
62  * The routines implemented in this file are described in:
63  *      Leffler, et al.: The Design and Implementation of the 4.3BSD
64  *	    UNIX Operating System (Addison Welley, 1989)
65  * on pages 62-63.
66  *
67  * Arguably, to simplify accounting operations, this mechanism should
68  * be replaced by one in which an accounting log file (similar to /dev/klog)
69  * is read by a user process, etc.  However, that has its own problems.
70  */
71 
72 /*
73  * Internal accounting functions.
74  * The former's operation is described in Leffler, et al., and the latter
75  * was provided by UCB with the 4.4BSD-Lite release
76  */
77 static comp_t	encode_comp_t(u_long, u_long);
78 static void	acctwatch(void *);
79 
80 /*
81  * Accounting callout used for periodic scheduling of acctwatch.
82  */
83 static struct	callout acctwatch_callout;
84 
85 /*
86  * Accounting vnode pointer, and saved vnode pointer.
87  */
88 static struct	vnode *acctp;
89 static struct	vnode *savacctp;
90 
91 /*
92  * Values associated with enabling and disabling accounting
93  */
94 static int acctsuspend = 2;	/* stop accounting when < 2% free space left */
95 SYSCTL_INT(_kern, OID_AUTO, acct_suspend, CTLFLAG_RW,
96 	&acctsuspend, 0, "percentage of free disk space below which accounting stops");
97 
98 static int acctresume = 4;	/* resume when free space risen to > 4% */
99 SYSCTL_INT(_kern, OID_AUTO, acct_resume, CTLFLAG_RW,
100 	&acctresume, 0, "percentage of free disk space above which accounting resumes");
101 
102 static int acctchkfreq = 15;	/* frequency (in seconds) to check space */
103 SYSCTL_INT(_kern, OID_AUTO, acct_chkfreq, CTLFLAG_RW,
104 	&acctchkfreq, 0, "frequency for checking the free space");
105 
106 /*
107  * Accounting system call.  Written based on the specification and
108  * previous implementation done by Mark Tinguely.
109  *
110  * MPSAFE
111  */
112 int
113 acct(td, uap)
114 	struct thread *td;
115 	struct acct_args /* {
116 		syscallarg(char *) path;
117 	} */ *uap;
118 {
119 	struct nameidata nd;
120 	int error, flags;
121 
122 	/* Make sure that the caller is root. */
123 	error = suser(td);
124 	if (error)
125 		return (error);
126 
127 	mtx_lock(&Giant);
128 	/*
129 	 * If accounting is to be started to a file, open that file for
130 	 * writing and make sure it's a 'normal'.
131 	 */
132 	if (SCARG(uap, path) != NULL) {
133 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, SCARG(uap, path),
134 		       td);
135 		flags = FWRITE;
136 		error = vn_open(&nd, &flags, 0);
137 		if (error)
138 			goto done2;
139 		NDFREE(&nd, NDF_ONLY_PNBUF);
140 		VOP_UNLOCK(nd.ni_vp, 0, td);
141 		if (nd.ni_vp->v_type != VREG) {
142 			vn_close(nd.ni_vp, FWRITE, td->td_ucred, td);
143 			error = EACCES;
144 			goto done2;
145 		}
146 	}
147 
148 	/*
149 	 * If accounting was previously enabled, kill the old space-watcher,
150 	 * close the file, and (if no new file was specified, leave).
151 	 */
152 	if (acctp != NULLVP || savacctp != NULLVP) {
153 		callout_stop(&acctwatch_callout);
154 		error = vn_close((acctp != NULLVP ? acctp : savacctp), FWRITE,
155 		    td->td_ucred, td);
156 		acctp = savacctp = NULLVP;
157 	}
158 	if (SCARG(uap, path) == NULL)
159 		goto done2;
160 
161 	/*
162 	 * Save the new accounting file vnode, and schedule the new
163 	 * free space watcher.
164 	 */
165 	acctp = nd.ni_vp;
166 	callout_init(&acctwatch_callout, 0);
167 	acctwatch(NULL);
168 done2:
169 	mtx_unlock(&Giant);
170 	return (error);
171 }
172 
173 /*
174  * Write out process accounting information, on process exit.
175  * Data to be written out is specified in Leffler, et al.
176  * and are enumerated below.  (They're also noted in the system
177  * "acct.h" header file.)
178  */
179 
180 int
181 acct_process(td)
182 	struct thread *td;
183 {
184 	struct proc *p = td->td_proc;
185 	struct acct acct;
186 	struct rusage *r;
187 	struct timeval ut, st, tmp;
188 	int t;
189 	struct vnode *vp;
190 
191 	/* If accounting isn't enabled, don't bother */
192 	vp = acctp;
193 	if (vp == NULLVP)
194 		return (0);
195 
196 	/*
197 	 * Get process accounting information.
198 	 */
199 
200 	/* (1) The name of the command that ran */
201 	bcopy(p->p_comm, acct.ac_comm, sizeof acct.ac_comm);
202 
203 	/* (2) The amount of user and system time that was used */
204 	mtx_lock_spin(&sched_lock);
205 	calcru(p, &ut, &st, NULL);
206 	mtx_unlock_spin(&sched_lock);
207 	acct.ac_utime = encode_comp_t(ut.tv_sec, ut.tv_usec);
208 	acct.ac_stime = encode_comp_t(st.tv_sec, st.tv_usec);
209 
210 	/* (3) The elapsed time the commmand ran (and its starting time) */
211 	acct.ac_btime = p->p_stats->p_start.tv_sec;
212 	microtime(&tmp);
213 	timevalsub(&tmp, &p->p_stats->p_start);
214 	acct.ac_etime = encode_comp_t(tmp.tv_sec, tmp.tv_usec);
215 
216 	/* (4) The average amount of memory used */
217 	r = &p->p_stats->p_ru;
218 	tmp = ut;
219 	timevaladd(&tmp, &st);
220 	t = tmp.tv_sec * hz + tmp.tv_usec / tick;
221 	if (t)
222 		acct.ac_mem = (r->ru_ixrss + r->ru_idrss + r->ru_isrss) / t;
223 	else
224 		acct.ac_mem = 0;
225 
226 	/* (5) The number of disk I/O operations done */
227 	acct.ac_io = encode_comp_t(r->ru_inblock + r->ru_oublock, 0);
228 
229 	/* (6) The UID and GID of the process */
230 	acct.ac_uid = p->p_ucred->cr_ruid;
231 	acct.ac_gid = p->p_ucred->cr_rgid;
232 
233 	/* (7) The terminal from which the process was started */
234 	PROC_LOCK(p);
235 	SESS_LOCK(p->p_session);
236 	if ((p->p_flag & P_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
237 		acct.ac_tty = dev2udev(p->p_pgrp->pg_session->s_ttyp->t_dev);
238 	else
239 		acct.ac_tty = NOUDEV;
240 	SESS_UNLOCK(p->p_session);
241 	PROC_UNLOCK(p);
242 
243 	/* (8) The boolean flags that tell how the process terminated, etc. */
244 	acct.ac_flag = p->p_acflag;
245 
246 	/*
247 	 * Eliminate any file size rlimit.
248 	 */
249 	if (p->p_limit->p_refcnt > 1 &&
250 	    (p->p_limit->p_lflags & PL_SHAREMOD) == 0) {
251 		p->p_limit->p_refcnt--;
252 		p->p_limit = limcopy(p->p_limit);
253 	}
254 	p->p_rlimit[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
255 
256 	/*
257 	 * Write the accounting information to the file.
258 	 */
259 	VOP_LEASE(vp, td, td->td_ucred, LEASE_WRITE);
260 	return (vn_rdwr(UIO_WRITE, vp, (caddr_t)&acct, sizeof (acct),
261 	    (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT, td->td_ucred,
262 	    (int *)0, td));
263 }
264 
265 /*
266  * Encode_comp_t converts from ticks in seconds and microseconds
267  * to ticks in 1/AHZ seconds.  The encoding is described in
268  * Leffler, et al., on page 63.
269  */
270 
271 #define	MANTSIZE	13			/* 13 bit mantissa. */
272 #define	EXPSIZE		3			/* Base 8 (3 bit) exponent. */
273 #define	MAXFRACT	((1 << MANTSIZE) - 1)	/* Maximum fractional value. */
274 
275 static comp_t
276 encode_comp_t(s, us)
277 	u_long s, us;
278 {
279 	int exp, rnd;
280 
281 	exp = 0;
282 	rnd = 0;
283 	s *= AHZ;
284 	s += us / (1000000 / AHZ);	/* Maximize precision. */
285 
286 	while (s > MAXFRACT) {
287 	rnd = s & (1 << (EXPSIZE - 1));	/* Round up? */
288 		s >>= EXPSIZE;		/* Base 8 exponent == 3 bit shift. */
289 		exp++;
290 	}
291 
292 	/* If we need to round up, do it (and handle overflow correctly). */
293 	if (rnd && (++s > MAXFRACT)) {
294 		s >>= EXPSIZE;
295 		exp++;
296 	}
297 
298 	/* Clean it up and polish it off. */
299 	exp <<= MANTSIZE;		/* Shift the exponent into place */
300 	exp += s;			/* and add on the mantissa. */
301 	return (exp);
302 }
303 
304 /*
305  * Periodically check the filesystem to see if accounting
306  * should be turned on or off.  Beware the case where the vnode
307  * has been vgone()'d out from underneath us, e.g. when the file
308  * system containing the accounting file has been forcibly unmounted.
309  */
310 /* ARGSUSED */
311 static void
312 acctwatch(a)
313 	void *a;
314 {
315 	struct statfs sb;
316 
317 	if (savacctp != NULLVP) {
318 		if (savacctp->v_type == VBAD) {
319 			(void) vn_close(savacctp, FWRITE, NOCRED, NULL);
320 			savacctp = NULLVP;
321 			return;
322 		}
323 		(void)VFS_STATFS(savacctp->v_mount, &sb, (struct thread *)0);
324 		if (sb.f_bavail > acctresume * sb.f_blocks / 100) {
325 			acctp = savacctp;
326 			savacctp = NULLVP;
327 			log(LOG_NOTICE, "Accounting resumed\n");
328 		}
329 	} else {
330 		if (acctp == NULLVP)
331 			return;
332 		if (acctp->v_type == VBAD) {
333 			(void) vn_close(acctp, FWRITE, NOCRED, NULL);
334 			acctp = NULLVP;
335 			return;
336 		}
337 		(void)VFS_STATFS(acctp->v_mount, &sb, (struct thread *)0);
338 		if (sb.f_bavail <= acctsuspend * sb.f_blocks / 100) {
339 			savacctp = acctp;
340 			acctp = NULLVP;
341 			log(LOG_NOTICE, "Accounting suspended\n");
342 		}
343 	}
344 	callout_reset(&acctwatch_callout, acctchkfreq * hz, acctwatch, NULL);
345 }
346