xref: /netbsd-src/sys/kern/kern_acct.c (revision 89c5a767f8fc7a4633b2d409966e2becbb98ff92)
1 /*	$NetBSD: kern_acct.c,v 1.48 2000/03/10 01:13:18 enami 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 
269 	ACCT_LOCK();
270 
271 	/* If accounting isn't enabled, don't bother */
272 	if (acct_state != ACCT_ACTIVE)
273 		goto out;
274 
275 	/*
276 	 * Get process accounting information.
277 	 */
278 
279 	/* (1) The name of the command that ran */
280 	memcpy(acct.ac_comm, p->p_comm, sizeof(acct.ac_comm));
281 
282 	/* (2) The amount of user and system time that was used */
283 	calcru(p, &ut, &st, NULL);
284 	acct.ac_utime = encode_comp_t(ut.tv_sec, ut.tv_usec);
285 	acct.ac_stime = encode_comp_t(st.tv_sec, st.tv_usec);
286 
287 	/* (3) The elapsed time the commmand ran (and its starting time) */
288 	acct.ac_btime = p->p_stats->p_start.tv_sec;
289 	s = splclock();
290 	timersub(&time, &p->p_stats->p_start, &tmp);
291 	splx(s);
292 	acct.ac_etime = encode_comp_t(tmp.tv_sec, tmp.tv_usec);
293 
294 	/* (4) The average amount of memory used */
295 	r = &p->p_stats->p_ru;
296 	timeradd(&ut, &st, &tmp);
297 	t = tmp.tv_sec * hz + tmp.tv_usec / tick;
298 	if (t)
299 		acct.ac_mem = (r->ru_ixrss + r->ru_idrss + r->ru_isrss) / t;
300 	else
301 		acct.ac_mem = 0;
302 
303 	/* (5) The number of disk I/O operations done */
304 	acct.ac_io = encode_comp_t(r->ru_inblock + r->ru_oublock, 0);
305 
306 	/* (6) The UID and GID of the process */
307 	acct.ac_uid = p->p_cred->p_ruid;
308 	acct.ac_gid = p->p_cred->p_rgid;
309 
310 	/* (7) The terminal from which the process was started */
311 	if ((p->p_flag & P_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
312 		acct.ac_tty = p->p_pgrp->pg_session->s_ttyp->t_dev;
313 	else
314 		acct.ac_tty = NODEV;
315 
316 	/* (8) The boolean flags that tell how the process terminated, etc. */
317 	acct.ac_flag = p->p_acflag;
318 
319 	/*
320 	 * Now, just write the accounting information to the file.
321 	 */
322 	VOP_LEASE(acct_vp, p, p->p_ucred, LEASE_WRITE);
323 	error = vn_rdwr(UIO_WRITE, acct_vp, (caddr_t)&acct,
324 	    sizeof(acct), (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT,
325 	    acct_ucred, NULL, p);
326 	if (error != 0)
327 		log(LOG_ERR, "Accounting: write failed %d\n", error);
328 
329  out:
330 	ACCT_UNLOCK();
331 	return (error);
332 }
333 
334 /*
335  * Encode_comp_t converts from ticks in seconds and microseconds
336  * to ticks in 1/AHZ seconds.  The encoding is described in
337  * Leffler, et al., on page 63.
338  */
339 
340 #define	MANTSIZE	13			/* 13 bit mantissa. */
341 #define	EXPSIZE		3			/* Base 8 (3 bit) exponent. */
342 #define	MAXFRACT	((1 << MANTSIZE) - 1)	/* Maximum fractional value. */
343 
344 comp_t
345 encode_comp_t(s, us)
346 	u_long s, us;
347 {
348 	int exp, rnd;
349 
350 	exp = 0;
351 	rnd = 0;
352 	s *= AHZ;
353 	s += us / (1000000 / AHZ);	/* Maximize precision. */
354 
355 	while (s > MAXFRACT) {
356 	rnd = s & (1 << (EXPSIZE - 1));	/* Round up? */
357 		s >>= EXPSIZE;		/* Base 8 exponent == 3 bit shift. */
358 		exp++;
359 	}
360 
361 	/* If we need to round up, do it (and handle overflow correctly). */
362 	if (rnd && (++s > MAXFRACT)) {
363 		s >>= EXPSIZE;
364 		exp++;
365 	}
366 
367 	/* Clean it up and polish it off. */
368 	exp <<= MANTSIZE;		/* Shift the exponent into place */
369 	exp += s;			/* and add on the mantissa. */
370 	return (exp);
371 }
372 
373 /*
374  * Periodically check the file system to see if accounting
375  * should be turned on or off.  Beware the case where the vnode
376  * has been vgone()'d out from underneath us, e.g. when the file
377  * system containing the accounting file has been forcibly unmounted.
378  */
379 void
380 acctwatch(arg)
381 	void *arg;
382 {
383 	int error;
384 
385 	log(LOG_NOTICE, "Accounting started\n");
386 	ACCT_LOCK();
387 	while (acct_state != ACCT_STOP) {
388 		if (acct_vp->v_type == VBAD) {
389 			log(LOG_NOTICE, "Accounting terminated\n");
390 			acct_stop();
391 			continue;
392 		}
393 
394 		error = acct_chkfree();
395 #ifdef DIAGNOSTIC
396 		if (error != 0)
397 			printf("acctwatch: failed to statfs, error = %d\n",
398 			    error);
399 #endif
400 
401 		ACCT_UNLOCK();
402 		error = tsleep(acctwatch, PSWP, "actwat", acctchkfreq * hz);
403 		ACCT_LOCK();
404 #ifdef DIAGNOSTIC
405 		if (error != 0 && error != EWOULDBLOCK)
406 			printf("acctwatch: sleep error %d\n", error);
407 #endif
408 	}
409 	acct_dkwatcher = NULL;
410 	ACCT_UNLOCK();
411 
412 	kthread_exit(0);
413 }
414