xref: /netbsd-src/sys/kern/kern_acct.c (revision d710132b4b8ce7f7cccaaf660cb16aa16b4077a0)
1 /*	$NetBSD: kern_acct.c,v 1.52 2003/04/20 03:20:18 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1994 Christopher G. Demetriou
5  * Copyright (c) 1982, 1986, 1989, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
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.8 (Berkeley) 5/14/95
42  */
43 
44 #include <sys/cdefs.h>
45 __KERNEL_RCSID(0, "$NetBSD: kern_acct.c,v 1.52 2003/04/20 03:20:18 christos Exp $");
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/proc.h>
50 #include <sys/mount.h>
51 #include <sys/vnode.h>
52 #include <sys/file.h>
53 #include <sys/syslog.h>
54 #include <sys/kernel.h>
55 #include <sys/kthread.h>
56 #include <sys/lock.h>
57 #include <sys/malloc.h>
58 #include <sys/namei.h>
59 #include <sys/errno.h>
60 #include <sys/acct.h>
61 #include <sys/resourcevar.h>
62 #include <sys/ioctl.h>
63 #include <sys/tty.h>
64 
65 #include <sys/sa.h>
66 #include <sys/syscallargs.h>
67 
68 /*
69  * The routines implemented in this file are described in:
70  *      Leffler, et al.: The Design and Implementation of the 4.3BSD
71  *	    UNIX Operating System (Addison Welley, 1989)
72  * on pages 62-63.
73  *
74  * Arguably, to simplify accounting operations, this mechanism should
75  * be replaced by one in which an accounting log file (similar to /dev/klog)
76  * is read by a user process, etc.  However, that has its own problems.
77  */
78 
79 /*
80  * The global accounting state and related data.  Gain the lock before
81  * accessing these variables.
82  */
83 enum {
84 	ACCT_STOP,
85 	ACCT_ACTIVE,
86 	ACCT_SUSPENDED
87 } acct_state;				/* The current accounting state. */
88 struct vnode *acct_vp;			/* Accounting vnode pointer. */
89 struct ucred *acct_ucred;		/* Credential of accounting file
90 					   owner (i.e root).  Used when
91  					   accounting file i/o.  */
92 struct proc *acct_dkwatcher;		/* Free disk space checker. */
93 
94 /*
95  * Lock to serialize system calls and kernel threads.
96  */
97 struct	lock acct_lock;
98 #define	ACCT_LOCK()						\
99 do {								\
100 	(void) lockmgr(&acct_lock, LK_EXCLUSIVE, NULL);		\
101 } while (/* CONSTCOND */0)
102 #define	ACCT_UNLOCK()						\
103 do {								\
104 	(void) lockmgr(&acct_lock, LK_RELEASE, NULL);		\
105 } while (/* CONSTCOND */0)
106 
107 /*
108  * Internal accounting functions.
109  * The former's operation is described in Leffler, et al., and the latter
110  * was provided by UCB with the 4.4BSD-Lite release
111  */
112 comp_t	encode_comp_t __P((u_long, u_long));
113 void	acctwatch __P((void *));
114 void	acct_stop __P((void));
115 int	acct_chkfree __P((void));
116 
117 /*
118  * Values associated with enabling and disabling accounting
119  */
120 int	acctsuspend = 2;	/* stop accounting when < 2% free space left */
121 int	acctresume = 4;		/* resume when free space risen to > 4% */
122 int	acctchkfreq = 15;	/* frequency (in seconds) to check space */
123 
124 void
125 acct_init()
126 {
127 
128 	acct_state = ACCT_STOP;
129 	acct_vp = NULLVP;
130 	acct_ucred = NULL;
131 	lockinit(&acct_lock, PWAIT, "acctlk", 0, 0);
132 }
133 
134 void
135 acct_stop()
136 {
137 	int error;
138 
139 	if (acct_vp != NULLVP && acct_vp->v_type != VBAD) {
140 		error = vn_close(acct_vp, FWRITE, acct_ucred, NULL);
141 #ifdef DIAGNOSTIC
142 		if (error != 0)
143 			printf("acct_stop: failed to close, errno = %d\n",
144 			    error);
145 #endif
146 		acct_vp = NULLVP;
147 	}
148 	if (acct_ucred != NULL) {
149 		crfree(acct_ucred);
150 		acct_ucred = NULL;
151 	}
152 	acct_state = ACCT_STOP;
153 }
154 
155 int
156 acct_chkfree()
157 {
158 	int error;
159 	struct statfs sb;
160 
161 	error = VFS_STATFS(acct_vp->v_mount, &sb, NULL);
162 	if (error != 0)
163 		return (error);
164 
165 	switch (acct_state) {
166 	case ACCT_SUSPENDED:
167 		if (sb.f_bavail > acctresume * sb.f_blocks / 100) {
168 			acct_state = ACCT_ACTIVE;
169 			log(LOG_NOTICE, "Accounting resumed\n");
170 		}
171 		break;
172 	case ACCT_ACTIVE:
173 		if (sb.f_bavail <= acctsuspend * sb.f_blocks / 100) {
174 			acct_state = ACCT_SUSPENDED;
175 			log(LOG_NOTICE, "Accounting suspended\n");
176 		}
177 		break;
178 	case ACCT_STOP:
179 		break;
180 	}
181 	return (0);
182 }
183 
184 /*
185  * Accounting system call.  Written based on the specification and
186  * previous implementation done by Mark Tinguely.
187  */
188 int
189 sys_acct(l, v, retval)
190 	struct lwp *l;
191 	void *v;
192 	register_t *retval;
193 {
194 	struct sys_acct_args /* {
195 		syscallarg(const char *) path;
196 	} */ *uap = v;
197 	struct nameidata nd;
198 	int error;
199 	struct proc *p = l->l_proc;
200 
201 	/* Make sure that the caller is root. */
202 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
203 		return (error);
204 
205 	/*
206 	 * If accounting is to be started to a file, open that file for
207 	 * writing and make sure it's a 'normal'.
208 	 */
209 	if (SCARG(uap, path) != NULL) {
210 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, SCARG(uap, path),
211 		    p);
212 		if ((error = vn_open(&nd, FWRITE|O_APPEND, 0)) != 0)
213 			return (error);
214 		VOP_UNLOCK(nd.ni_vp, 0);
215 		if (nd.ni_vp->v_type != VREG) {
216 			vn_close(nd.ni_vp, FWRITE, p->p_ucred, p);
217 			return (EACCES);
218 		}
219 	}
220 
221 	ACCT_LOCK();
222 
223 	/*
224 	 * If accounting was previously enabled, kill the old space-watcher,
225 	 * free credential for accounting file i/o,
226 	 * ... (and, if no new file was specified, leave).
227 	 */
228 	acct_stop();
229 	if (SCARG(uap, path) == NULL)
230 		goto out;
231 
232 	/*
233 	 * Save the new accounting file vnode and credential,
234 	 * and schedule the new free space watcher.
235 	 */
236 	acct_state = ACCT_ACTIVE;
237 	acct_vp = nd.ni_vp;
238 	acct_ucred = p->p_ucred;
239 	crhold(acct_ucred);
240 
241 	error = acct_chkfree();		/* Initial guess. */
242 	if (error != 0) {
243 		acct_stop();
244 		goto out;
245 	}
246 
247 	if (acct_dkwatcher == NULL) {
248 		error = kthread_create1(acctwatch, NULL, &acct_dkwatcher,
249 		    "acctwatch");
250 		if (error != 0)
251 			acct_stop();
252 	}
253 
254  out:
255 	ACCT_UNLOCK();
256 	return (error);
257 }
258 
259 /*
260  * Write out process accounting information, on process exit.
261  * Data to be written out is specified in Leffler, et al.
262  * and are enumerated below.  (They're also noted in the system
263  * "acct.h" header file.)
264  */
265 int
266 acct_process(p)
267 	struct proc *p;
268 {
269 	struct acct acct;
270 	struct rusage *r;
271 	struct timeval ut, st, tmp;
272 	int s, t, error = 0;
273 	struct plimit *oplim = NULL;
274 
275 	ACCT_LOCK();
276 
277 	/* If accounting isn't enabled, don't bother */
278 	if (acct_state != ACCT_ACTIVE)
279 		goto out;
280 
281 	/*
282 	 * Raise the file limit so that accounting can't be stopped by
283 	 * the user.
284 	 *
285 	 * XXX We should think about the CPU limit, too.
286 	 */
287 	if (p->p_limit->p_refcnt > 1) {
288 		oplim = p->p_limit;
289 		p->p_limit = limcopy(p->p_limit);
290 	}
291 	p->p_rlimit[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
292 
293 	/*
294 	 * Get process accounting information.
295 	 */
296 
297 	/* (1) The name of the command that ran */
298 	memcpy(acct.ac_comm, p->p_comm, sizeof(acct.ac_comm));
299 
300 	/* (2) The amount of user and system time that was used */
301 	calcru(p, &ut, &st, NULL);
302 	acct.ac_utime = encode_comp_t(ut.tv_sec, ut.tv_usec);
303 	acct.ac_stime = encode_comp_t(st.tv_sec, st.tv_usec);
304 
305 	/* (3) The elapsed time the commmand ran (and its starting time) */
306 	acct.ac_btime = p->p_stats->p_start.tv_sec;
307 	s = splclock();
308 	timersub(&time, &p->p_stats->p_start, &tmp);
309 	splx(s);
310 	acct.ac_etime = encode_comp_t(tmp.tv_sec, tmp.tv_usec);
311 
312 	/* (4) The average amount of memory used */
313 	r = &p->p_stats->p_ru;
314 	timeradd(&ut, &st, &tmp);
315 	t = tmp.tv_sec * hz + tmp.tv_usec / tick;
316 	if (t)
317 		acct.ac_mem = (r->ru_ixrss + r->ru_idrss + r->ru_isrss) / t;
318 	else
319 		acct.ac_mem = 0;
320 
321 	/* (5) The number of disk I/O operations done */
322 	acct.ac_io = encode_comp_t(r->ru_inblock + r->ru_oublock, 0);
323 
324 	/* (6) The UID and GID of the process */
325 	acct.ac_uid = p->p_cred->p_ruid;
326 	acct.ac_gid = p->p_cred->p_rgid;
327 
328 	/* (7) The terminal from which the process was started */
329 	if ((p->p_flag & P_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
330 		acct.ac_tty = p->p_pgrp->pg_session->s_ttyp->t_dev;
331 	else
332 		acct.ac_tty = NODEV;
333 
334 	/* (8) The boolean flags that tell how the process terminated, etc. */
335 	acct.ac_flag = p->p_acflag;
336 
337 	/*
338 	 * Now, just write the accounting information to the file.
339 	 */
340 	VOP_LEASE(acct_vp, p, p->p_ucred, LEASE_WRITE);
341 	error = vn_rdwr(UIO_WRITE, acct_vp, (caddr_t)&acct,
342 	    sizeof(acct), (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT,
343 	    acct_ucred, NULL, p);
344 	if (error != 0)
345 		log(LOG_ERR, "Accounting: write failed %d\n", error);
346 
347 	if (oplim) {
348 		limfree(p->p_limit);
349 		p->p_limit = oplim;
350 	}
351 
352  out:
353 	ACCT_UNLOCK();
354 	return (error);
355 }
356 
357 /*
358  * Encode_comp_t converts from ticks in seconds and microseconds
359  * to ticks in 1/AHZ seconds.  The encoding is described in
360  * Leffler, et al., on page 63.
361  */
362 
363 #define	MANTSIZE	13			/* 13 bit mantissa. */
364 #define	EXPSIZE		3			/* Base 8 (3 bit) exponent. */
365 #define	MAXFRACT	((1 << MANTSIZE) - 1)	/* Maximum fractional value. */
366 
367 comp_t
368 encode_comp_t(s, us)
369 	u_long s, us;
370 {
371 	int exp, rnd;
372 
373 	exp = 0;
374 	rnd = 0;
375 	s *= AHZ;
376 	s += us / (1000000 / AHZ);	/* Maximize precision. */
377 
378 	while (s > MAXFRACT) {
379 	rnd = s & (1 << (EXPSIZE - 1));	/* Round up? */
380 		s >>= EXPSIZE;		/* Base 8 exponent == 3 bit shift. */
381 		exp++;
382 	}
383 
384 	/* If we need to round up, do it (and handle overflow correctly). */
385 	if (rnd && (++s > MAXFRACT)) {
386 		s >>= EXPSIZE;
387 		exp++;
388 	}
389 
390 	/* Clean it up and polish it off. */
391 	exp <<= MANTSIZE;		/* Shift the exponent into place */
392 	exp += s;			/* and add on the mantissa. */
393 	return (exp);
394 }
395 
396 /*
397  * Periodically check the file system to see if accounting
398  * should be turned on or off.  Beware the case where the vnode
399  * has been vgone()'d out from underneath us, e.g. when the file
400  * system containing the accounting file has been forcibly unmounted.
401  */
402 void
403 acctwatch(arg)
404 	void *arg;
405 {
406 	int error;
407 
408 	log(LOG_NOTICE, "Accounting started\n");
409 	ACCT_LOCK();
410 	while (acct_state != ACCT_STOP) {
411 		if (acct_vp->v_type == VBAD) {
412 			log(LOG_NOTICE, "Accounting terminated\n");
413 			acct_stop();
414 			continue;
415 		}
416 
417 		error = acct_chkfree();
418 #ifdef DIAGNOSTIC
419 		if (error != 0)
420 			printf("acctwatch: failed to statfs, error = %d\n",
421 			    error);
422 #endif
423 
424 		ACCT_UNLOCK();
425 		error = tsleep(acctwatch, PSWP, "actwat", acctchkfreq * hz);
426 		ACCT_LOCK();
427 #ifdef DIAGNOSTIC
428 		if (error != 0 && error != EWOULDBLOCK)
429 			printf("acctwatch: sleep error %d\n", error);
430 #endif
431 	}
432 	acct_dkwatcher = NULL;
433 	ACCT_UNLOCK();
434 
435 	kthread_exit(0);
436 }
437