xref: /openbsd-src/sys/kern/kern_acct.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$OpenBSD: kern_acct.c,v 1.9 2000/05/05 08:38:23 art Exp $	*/
2 /*	$NetBSD: kern_acct.c,v 1.42 1996/02/04 02:15:12 christos Exp $	*/
3 
4 /*-
5  * Copyright (c) 1994 Christopher G. Demetriou
6  * Copyright (c) 1982, 1986, 1989, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  * (c) UNIX System Laboratories, Inc.
9  * All or some portions of this file are derived from material licensed
10  * to the University of California by American Telephone and Telegraph
11  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
12  * the permission of UNIX System Laboratories, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. All advertising materials mentioning features or use of this software
23  *    must display the following acknowledgement:
24  *	This product includes software developed by the University of
25  *	California, Berkeley and its contributors.
26  * 4. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  *	@(#)kern_acct.c	8.1 (Berkeley) 6/14/93
43  */
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/proc.h>
48 #include <sys/mount.h>
49 #include <sys/vnode.h>
50 #include <sys/file.h>
51 #include <sys/syslog.h>
52 #include <sys/kernel.h>
53 #include <sys/namei.h>
54 #include <sys/errno.h>
55 #include <sys/acct.h>
56 #include <sys/resourcevar.h>
57 #include <sys/ioctl.h>
58 #include <sys/tty.h>
59 #include <sys/timeout.h>
60 
61 #include <sys/syscallargs.h>
62 
63 /*
64  * The routines implemented in this file are described in:
65  *      Leffler, et al.: The Design and Implementation of the 4.3BSD
66  *	    UNIX Operating System (Addison Welley, 1989)
67  * on pages 62-63.
68  *
69  * Arguably, to simplify accounting operations, this mechanism should
70  * be replaced by one in which an accounting log file (similar to /dev/klog)
71  * is read by a user process, etc.  However, that has its own problems.
72  */
73 
74 /*
75  * Internal accounting functions.
76  * The former's operation is described in Leffler, et al., and the latter
77  * was provided by UCB with the 4.4BSD-Lite release
78  */
79 comp_t	encode_comp_t __P((u_long, u_long));
80 void	acctwatch __P((void *));
81 
82 /*
83  * Accounting vnode pointer, and saved vnode pointer.
84  */
85 struct	vnode *acctp;
86 struct	vnode *savacctp;
87 
88 /*
89  * Values associated with enabling and disabling accounting
90  */
91 int	acctsuspend = 2;	/* stop accounting when < 2% free space left */
92 int	acctresume = 4;		/* resume when free space risen to > 4% */
93 int	acctchkfreq = 15;	/* frequency (in seconds) to check space */
94 
95 /*
96  * Accounting system call.  Written based on the specification and
97  * previous implementation done by Mark Tinguely.
98  */
99 int
100 sys_acct(p, v, retval)
101 	struct proc *p;
102 	void *v;
103 	register_t *retval;
104 {
105 	struct sys_acct_args /* {
106 		syscallarg(char *) path;
107 	} */ *uap = v;
108 	struct nameidata nd;
109 	int error;
110 	static struct timeout acct_timeout;
111 
112 	/* Make sure that the caller is root. */
113 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
114 		return (error);
115 
116 	/*
117 	 * If accounting is to be started to a file, open that file for
118 	 * writing and make sure it's a 'normal'.
119 	 */
120 	if (SCARG(uap, path) != NULL) {
121 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, SCARG(uap, path),
122 		    p);
123 		if ((error = vn_open(&nd, FWRITE|O_APPEND, 0)) != 0)
124 			return (error);
125 		VOP_UNLOCK(nd.ni_vp, 0, p);
126 		if (nd.ni_vp->v_type != VREG) {
127 			vn_close(nd.ni_vp, FWRITE, p->p_ucred, p);
128 			return (EACCES);
129 		}
130 	}
131 
132 	/*
133 	 * If accounting was previously enabled, kill the old space-watcher,
134 	 * close the file, and (if no new file was specified, leave).
135 	 */
136 	if (acctp != NULLVP || savacctp != NULLVP) {
137 		timeout_del(&acct_timeout);
138 		error = vn_close((acctp != NULLVP ? acctp : savacctp), FWRITE,
139 		    p->p_ucred, p);
140 		acctp = savacctp = NULLVP;
141 	}
142 	if (SCARG(uap, path) == NULL)
143 		return (error);
144 
145 	/*
146 	 * Save the new accounting file vnode, and schedule the new
147 	 * free space watcher.
148 	 */
149 	acctp = nd.ni_vp;
150 	if (!timeout_initialized(&acct_timeout))
151 		timeout_set(&acct_timeout, acctwatch, &acct_timeout);
152 	acctwatch(&acct_timeout);
153 	return (error);
154 }
155 
156 /*
157  * Write out process accounting information, on process exit.
158  * Data to be written out is specified in Leffler, et al.
159  * and are enumerated below.  (They're also noted in the system
160  * "acct.h" header file.)
161  */
162 int
163 acct_process(p)
164 	struct proc *p;
165 {
166 	struct acct acct;
167 	struct rusage *r;
168 	struct timeval ut, st, tmp;
169 	int s, t;
170 	struct vnode *vp;
171 	struct plimit *oplim = NULL;
172 	int error;
173 
174 	/* If accounting isn't enabled, don't bother */
175 	vp = acctp;
176 	if (vp == NULLVP)
177 		return (0);
178 
179 	/*
180 	 * Raise the file limit so that accounting can't be stopped by the
181 	 * user. (XXX - we should think about the cpu limit too).
182 	 */
183 	if (p->p_limit->p_refcnt > 1) {
184 		oplim = p->p_limit;
185 		p->p_limit = limcopy(p->p_limit);
186 	}
187 	p->p_rlimit[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
188 
189 	/*
190 	 * Get process accounting information.
191 	 */
192 
193 	/* (1) The name of the command that ran */
194 	bcopy(p->p_comm, acct.ac_comm, sizeof acct.ac_comm);
195 
196 	/* (2) The amount of user and system time that was used */
197 	calcru(p, &ut, &st, NULL);
198 	acct.ac_utime = encode_comp_t(ut.tv_sec, ut.tv_usec);
199 	acct.ac_stime = encode_comp_t(st.tv_sec, st.tv_usec);
200 
201 	/* (3) The elapsed time the commmand ran (and its starting time) */
202 	acct.ac_btime = p->p_stats->p_start.tv_sec;
203 	s = splclock();
204 	timersub(&time, &p->p_stats->p_start, &tmp);
205 	splx(s);
206 	acct.ac_etime = encode_comp_t(tmp.tv_sec, tmp.tv_usec);
207 
208 	/* (4) The average amount of memory used */
209 	r = &p->p_stats->p_ru;
210 	timeradd(&ut, &st, &tmp);
211 	t = tmp.tv_sec * hz + tmp.tv_usec / tick;
212 	if (t)
213 		acct.ac_mem = (r->ru_ixrss + r->ru_idrss + r->ru_isrss) / t;
214 	else
215 		acct.ac_mem = 0;
216 
217 	/* (5) The number of disk I/O operations done */
218 	acct.ac_io = encode_comp_t(r->ru_inblock + r->ru_oublock, 0);
219 
220 	/* (6) The UID and GID of the process */
221 	acct.ac_uid = p->p_cred->p_ruid;
222 	acct.ac_gid = p->p_cred->p_rgid;
223 
224 	/* (7) The terminal from which the process was started */
225 	if ((p->p_flag & P_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
226 		acct.ac_tty = p->p_pgrp->pg_session->s_ttyp->t_dev;
227 	else
228 		acct.ac_tty = NODEV;
229 
230 	/* (8) The boolean flags that tell how the process terminated, etc. */
231 	acct.ac_flag = p->p_acflag;
232 
233 	/*
234 	 * Now, just write the accounting information to the file.
235 	 */
236 	VOP_LEASE(vp, p, p->p_ucred, LEASE_WRITE);
237 	error = vn_rdwr(UIO_WRITE, vp, (caddr_t)&acct, sizeof (acct),
238 	    (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT, p->p_ucred, NULL, p);
239 
240 	if (oplim) {
241 		limfree(p->p_limit);
242 		p->p_limit = oplim;
243 	}
244 
245 	return error;
246 }
247 
248 /*
249  * Encode_comp_t converts from ticks in seconds and microseconds
250  * to ticks in 1/AHZ seconds.  The encoding is described in
251  * Leffler, et al., on page 63.
252  */
253 
254 #define	MANTSIZE	13			/* 13 bit mantissa. */
255 #define	EXPSIZE		3			/* Base 8 (3 bit) exponent. */
256 #define	MAXFRACT	((1 << MANTSIZE) - 1)	/* Maximum fractional value. */
257 
258 comp_t
259 encode_comp_t(s, us)
260 	u_long s, us;
261 {
262 	int exp, rnd;
263 
264 	exp = 0;
265 	rnd = 0;
266 	s *= AHZ;
267 	s += us / (1000000 / AHZ);	/* Maximize precision. */
268 
269 	while (s > MAXFRACT) {
270 	rnd = s & (1 << (EXPSIZE - 1));	/* Round up? */
271 		s >>= EXPSIZE;		/* Base 8 exponent == 3 bit shift. */
272 		exp++;
273 	}
274 
275 	/* If we need to round up, do it (and handle overflow correctly). */
276 	if (rnd && (++s > MAXFRACT)) {
277 		s >>= EXPSIZE;
278 		exp++;
279 	}
280 
281 	/* Clean it up and polish it off. */
282 	exp <<= MANTSIZE;		/* Shift the exponent into place */
283 	exp += s;			/* and add on the mantissa. */
284 	return (exp);
285 }
286 
287 /*
288  * Periodically check the file system to see if accounting
289  * should be turned on or off.  Beware the case where the vnode
290  * has been vgone()'d out from underneath us, e.g. when the file
291  * system containing the accounting file has been forcibly unmounted.
292  */
293 /* ARGSUSED */
294 void
295 acctwatch(arg)
296 	void *arg;
297 {
298 	struct timeout *to = (struct timeout *)arg;
299 	struct statfs sb;
300 
301 	if (savacctp != NULLVP) {
302 		if (savacctp->v_type == VBAD) {
303 			(void) vn_close(savacctp, FWRITE, NOCRED, NULL);
304 			savacctp = NULLVP;
305 			return;
306 		}
307 		(void)VFS_STATFS(savacctp->v_mount, &sb, (struct proc *)0);
308 		if (sb.f_bavail > acctresume * sb.f_blocks / 100) {
309 			acctp = savacctp;
310 			savacctp = NULLVP;
311 			log(LOG_NOTICE, "Accounting resumed\n");
312 		}
313 	} else if (acctp != NULLVP) {
314 		if (acctp->v_type == VBAD) {
315 			(void) vn_close(acctp, FWRITE, NOCRED, NULL);
316 			acctp = NULLVP;
317 			return;
318 		}
319 		(void)VFS_STATFS(acctp->v_mount, &sb, (struct proc *)0);
320 		if (sb.f_bavail <= acctsuspend * sb.f_blocks / 100) {
321 			savacctp = acctp;
322 			acctp = NULLVP;
323 			log(LOG_NOTICE, "Accounting suspended\n");
324 		}
325 	} else
326 		return;
327 	timeout_add(to, acctchkfreq * hz);
328 }
329