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