Home | History | Annotate | Line # | Download | only in kern
kern_acct.c revision 1.54.2.6
      1 /*	$NetBSD: kern_acct.c,v 1.54.2.6 2004/12/18 09:32:35 skrll Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1982, 1986, 1989, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * (c) UNIX System Laboratories, Inc.
      7  * All or some portions of this file are derived from material licensed
      8  * to the University of California by American Telephone and Telegraph
      9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     10  * the permission of UNIX System Laboratories, Inc.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)kern_acct.c	8.8 (Berkeley) 5/14/95
     37  */
     38 
     39 /*-
     40  * Copyright (c) 1994 Christopher G. Demetriou
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. All advertising materials mentioning features or use of this software
     51  *    must display the following acknowledgement:
     52  *	This product includes software developed by the University of
     53  *	California, Berkeley and its contributors.
     54  * 4. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  *
     70  *	@(#)kern_acct.c	8.8 (Berkeley) 5/14/95
     71  */
     72 
     73 #include <sys/cdefs.h>
     74 __KERNEL_RCSID(0, "$NetBSD: kern_acct.c,v 1.54.2.6 2004/12/18 09:32:35 skrll Exp $");
     75 
     76 #include <sys/param.h>
     77 #include <sys/systm.h>
     78 #include <sys/proc.h>
     79 #include <sys/mount.h>
     80 #include <sys/vnode.h>
     81 #include <sys/file.h>
     82 #include <sys/syslog.h>
     83 #include <sys/kernel.h>
     84 #include <sys/kthread.h>
     85 #include <sys/lock.h>
     86 #include <sys/malloc.h>
     87 #include <sys/namei.h>
     88 #include <sys/errno.h>
     89 #include <sys/acct.h>
     90 #include <sys/resourcevar.h>
     91 #include <sys/ioctl.h>
     92 #include <sys/tty.h>
     93 
     94 #include <sys/sa.h>
     95 #include <sys/syscallargs.h>
     96 
     97 /*
     98  * The routines implemented in this file are described in:
     99  *      Leffler, et al.: The Design and Implementation of the 4.3BSD
    100  *	    UNIX Operating System (Addison Welley, 1989)
    101  * on pages 62-63.
    102  *
    103  * Arguably, to simplify accounting operations, this mechanism should
    104  * be replaced by one in which an accounting log file (similar to /dev/klog)
    105  * is read by a user process, etc.  However, that has its own problems.
    106  */
    107 
    108 /*
    109  * The global accounting state and related data.  Gain the lock before
    110  * accessing these variables.
    111  */
    112 enum {
    113 	ACCT_STOP,
    114 	ACCT_ACTIVE,
    115 	ACCT_SUSPENDED
    116 } acct_state;				/* The current accounting state. */
    117 struct vnode *acct_vp;			/* Accounting vnode pointer. */
    118 struct ucred *acct_ucred;		/* Credential of accounting file
    119 					   owner (i.e root).  Used when
    120  					   accounting file i/o.  */
    121 struct proc *acct_dkwatcher;		/* Free disk space checker. */
    122 
    123 /*
    124  * Lock to serialize system calls and kernel threads.
    125  */
    126 struct	lock acct_lock;
    127 #define	ACCT_LOCK()						\
    128 do {								\
    129 	(void) lockmgr(&acct_lock, LK_EXCLUSIVE, NULL);		\
    130 } while (/* CONSTCOND */0)
    131 #define	ACCT_UNLOCK()						\
    132 do {								\
    133 	(void) lockmgr(&acct_lock, LK_RELEASE, NULL);		\
    134 } while (/* CONSTCOND */0)
    135 
    136 /*
    137  * Internal accounting functions.
    138  * The former's operation is described in Leffler, et al., and the latter
    139  * was provided by UCB with the 4.4BSD-Lite release
    140  */
    141 comp_t	encode_comp_t(u_long, u_long);
    142 void	acctwatch(void *);
    143 void	acct_stop(void);
    144 int	acct_chkfree(void);
    145 
    146 /*
    147  * Values associated with enabling and disabling accounting
    148  */
    149 int	acctsuspend = 2;	/* stop accounting when < 2% free space left */
    150 int	acctresume = 4;		/* resume when free space risen to > 4% */
    151 int	acctchkfreq = 15;	/* frequency (in seconds) to check space */
    152 
    153 void
    154 acct_init()
    155 {
    156 
    157 	acct_state = ACCT_STOP;
    158 	acct_vp = NULLVP;
    159 	acct_ucred = NULL;
    160 	lockinit(&acct_lock, PWAIT, "acctlk", 0, 0);
    161 }
    162 
    163 void
    164 acct_stop()
    165 {
    166 	int error;
    167 
    168 	if (acct_vp != NULLVP && acct_vp->v_type != VBAD) {
    169 		error = vn_close(acct_vp, FWRITE, acct_ucred, NULL);
    170 #ifdef DIAGNOSTIC
    171 		if (error != 0)
    172 			printf("acct_stop: failed to close, errno = %d\n",
    173 			    error);
    174 #endif
    175 		acct_vp = NULLVP;
    176 	}
    177 	if (acct_ucred != NULL) {
    178 		crfree(acct_ucred);
    179 		acct_ucred = NULL;
    180 	}
    181 	acct_state = ACCT_STOP;
    182 }
    183 
    184 int
    185 acct_chkfree()
    186 {
    187 	int error;
    188 	struct statvfs sb;
    189 	int64_t bavail;
    190 
    191 	error = VFS_STATVFS(acct_vp->v_mount, &sb, NULL);
    192 	if (error != 0)
    193 		return (error);
    194 
    195 	bavail = sb.f_bfree - sb.f_bresvd;
    196 
    197 	switch (acct_state) {
    198 	case ACCT_SUSPENDED:
    199 		if (bavail > acctresume * sb.f_blocks / 100) {
    200 			acct_state = ACCT_ACTIVE;
    201 			log(LOG_NOTICE, "Accounting resumed\n");
    202 		}
    203 		break;
    204 	case ACCT_ACTIVE:
    205 		if (bavail <= acctsuspend * sb.f_blocks / 100) {
    206 			acct_state = ACCT_SUSPENDED;
    207 			log(LOG_NOTICE, "Accounting suspended\n");
    208 		}
    209 		break;
    210 	case ACCT_STOP:
    211 		break;
    212 	}
    213 	return (0);
    214 }
    215 
    216 /*
    217  * Accounting system call.  Written based on the specification and
    218  * previous implementation done by Mark Tinguely.
    219  */
    220 int
    221 sys_acct(l, v, retval)
    222 	struct lwp *l;
    223 	void *v;
    224 	register_t *retval;
    225 {
    226 	struct sys_acct_args /* {
    227 		syscallarg(const char *) path;
    228 	} */ *uap = v;
    229 	struct nameidata nd;
    230 	int error;
    231 	struct proc *p = l->l_proc;
    232 
    233 	/* Make sure that the caller is root. */
    234 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
    235 		return (error);
    236 
    237 	/*
    238 	 * If accounting is to be started to a file, open that file for
    239 	 * writing and make sure it's a 'normal'.
    240 	 */
    241 	if (SCARG(uap, path) != NULL) {
    242 		struct vattr va;
    243 		size_t pad;
    244 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, SCARG(uap, path),
    245 		    l);
    246 		if ((error = vn_open(&nd, FWRITE|O_APPEND, 0)) != 0)
    247 			return (error);
    248 		if (nd.ni_vp->v_type != VREG) {
    249 			VOP_UNLOCK(nd.ni_vp, 0);
    250 			error = EACCES;
    251 			goto bad;
    252 		}
    253 		if ((error = VOP_GETATTR(nd.ni_vp, &va, p->p_ucred, l)) != 0) {
    254 			VOP_UNLOCK(nd.ni_vp, 0);
    255 			goto bad;
    256 		}
    257 
    258 		if ((pad = (va.va_size % sizeof(struct acct))) != 0) {
    259 			u_quad_t size = va.va_size - pad;
    260 #ifdef DIAGNOSTIC
    261 			printf("Size of accounting file not a multiple of "
    262 			    "%lu - incomplete record truncated\n",
    263 			    (unsigned long)sizeof(struct acct));
    264 #endif
    265 			VATTR_NULL(&va);
    266 			va.va_size = size;
    267 			error = VOP_SETATTR(nd.ni_vp, &va, p->p_ucred, l);
    268 			if (error != 0) {
    269 				VOP_UNLOCK(nd.ni_vp, 0);
    270 				goto bad;
    271 			}
    272 		}
    273 		VOP_UNLOCK(nd.ni_vp, 0);
    274 	}
    275 
    276 	ACCT_LOCK();
    277 
    278 	/*
    279 	 * If accounting was previously enabled, kill the old space-watcher,
    280 	 * free credential for accounting file i/o,
    281 	 * ... (and, if no new file was specified, leave).
    282 	 */
    283 	acct_stop();
    284 	if (SCARG(uap, path) == NULL)
    285 		goto out;
    286 
    287 	/*
    288 	 * Save the new accounting file vnode and credential,
    289 	 * and schedule the new free space watcher.
    290 	 */
    291 	acct_state = ACCT_ACTIVE;
    292 	acct_vp = nd.ni_vp;
    293 	acct_ucred = p->p_ucred;
    294 	crhold(acct_ucred);
    295 
    296 	error = acct_chkfree();		/* Initial guess. */
    297 	if (error != 0) {
    298 		acct_stop();
    299 		goto out;
    300 	}
    301 
    302 	if (acct_dkwatcher == NULL) {
    303 		error = kthread_create1(acctwatch, NULL, &acct_dkwatcher,
    304 		    "acctwatch");
    305 		if (error != 0)
    306 			acct_stop();
    307 	}
    308 
    309  out:
    310 	ACCT_UNLOCK();
    311 	return (error);
    312  bad:
    313 	vn_close(nd.ni_vp, FWRITE, p->p_ucred, l);
    314 	return error;
    315 }
    316 
    317 /*
    318  * Write out process accounting information, on process exit.
    319  * Data to be written out is specified in Leffler, et al.
    320  * and are enumerated below.  (They're also noted in the system
    321  * "acct.h" header file.)
    322  */
    323 int
    324 acct_process(l)
    325 	struct lwp *l;
    326 {
    327 	struct acct acct;
    328 	struct rusage *r;
    329 	struct timeval ut, st, tmp;
    330 	int s, t, error = 0;
    331 	struct plimit *oplim = NULL;
    332 	struct proc *p = l->l_proc;
    333 
    334 	ACCT_LOCK();
    335 
    336 	/* If accounting isn't enabled, don't bother */
    337 	if (acct_state != ACCT_ACTIVE)
    338 		goto out;
    339 
    340 	/*
    341 	 * Raise the file limit so that accounting can't be stopped by
    342 	 * the user.
    343 	 *
    344 	 * XXX We should think about the CPU limit, too.
    345 	 */
    346 	if (p->p_limit->p_refcnt > 1) {
    347 		oplim = p->p_limit;
    348 		p->p_limit = limcopy(p->p_limit);
    349 	}
    350 	p->p_rlimit[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
    351 
    352 	/*
    353 	 * Get process accounting information.
    354 	 */
    355 
    356 	/* (1) The name of the command that ran */
    357 	memcpy(acct.ac_comm, p->p_comm, sizeof(acct.ac_comm));
    358 
    359 	/* (2) The amount of user and system time that was used */
    360 	calcru(p, &ut, &st, NULL);
    361 	acct.ac_utime = encode_comp_t(ut.tv_sec, ut.tv_usec);
    362 	acct.ac_stime = encode_comp_t(st.tv_sec, st.tv_usec);
    363 
    364 	/* (3) The elapsed time the commmand ran (and its starting time) */
    365 	acct.ac_btime = p->p_stats->p_start.tv_sec;
    366 	s = splclock();
    367 	timersub(&time, &p->p_stats->p_start, &tmp);
    368 	splx(s);
    369 	acct.ac_etime = encode_comp_t(tmp.tv_sec, tmp.tv_usec);
    370 
    371 	/* (4) The average amount of memory used */
    372 	r = &p->p_stats->p_ru;
    373 	timeradd(&ut, &st, &tmp);
    374 	t = tmp.tv_sec * hz + tmp.tv_usec / tick;
    375 	if (t)
    376 		acct.ac_mem = (r->ru_ixrss + r->ru_idrss + r->ru_isrss) / t;
    377 	else
    378 		acct.ac_mem = 0;
    379 
    380 	/* (5) The number of disk I/O operations done */
    381 	acct.ac_io = encode_comp_t(r->ru_inblock + r->ru_oublock, 0);
    382 
    383 	/* (6) The UID and GID of the process */
    384 	acct.ac_uid = p->p_cred->p_ruid;
    385 	acct.ac_gid = p->p_cred->p_rgid;
    386 
    387 	/* (7) The terminal from which the process was started */
    388 	if ((p->p_flag & P_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
    389 		acct.ac_tty = p->p_pgrp->pg_session->s_ttyp->t_dev;
    390 	else
    391 		acct.ac_tty = NODEV;
    392 
    393 	/* (8) The boolean flags that tell how the process terminated, etc. */
    394 	acct.ac_flag = p->p_acflag;
    395 
    396 	/*
    397 	 * Now, just write the accounting information to the file.
    398 	 */
    399 	VOP_LEASE(acct_vp, l, p->p_ucred, LEASE_WRITE);
    400 	error = vn_rdwr(UIO_WRITE, acct_vp, (caddr_t)&acct,
    401 	    sizeof(acct), (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT,
    402 	    acct_ucred, NULL, NULL);
    403 	if (error != 0)
    404 		log(LOG_ERR, "Accounting: write failed %d\n", error);
    405 
    406 	if (oplim) {
    407 		limfree(p->p_limit);
    408 		p->p_limit = oplim;
    409 	}
    410 
    411  out:
    412 	ACCT_UNLOCK();
    413 	return (error);
    414 }
    415 
    416 /*
    417  * Encode_comp_t converts from ticks in seconds and microseconds
    418  * to ticks in 1/AHZ seconds.  The encoding is described in
    419  * Leffler, et al., on page 63.
    420  */
    421 
    422 #define	MANTSIZE	13			/* 13 bit mantissa. */
    423 #define	EXPSIZE		3			/* Base 8 (3 bit) exponent. */
    424 #define	MAXFRACT	((1 << MANTSIZE) - 1)	/* Maximum fractional value. */
    425 
    426 comp_t
    427 encode_comp_t(s, us)
    428 	u_long s, us;
    429 {
    430 	int exp, rnd;
    431 
    432 	exp = 0;
    433 	rnd = 0;
    434 	s *= AHZ;
    435 	s += us / (1000000 / AHZ);	/* Maximize precision. */
    436 
    437 	while (s > MAXFRACT) {
    438 	rnd = s & (1 << (EXPSIZE - 1));	/* Round up? */
    439 		s >>= EXPSIZE;		/* Base 8 exponent == 3 bit shift. */
    440 		exp++;
    441 	}
    442 
    443 	/* If we need to round up, do it (and handle overflow correctly). */
    444 	if (rnd && (++s > MAXFRACT)) {
    445 		s >>= EXPSIZE;
    446 		exp++;
    447 	}
    448 
    449 	/* Clean it up and polish it off. */
    450 	exp <<= MANTSIZE;		/* Shift the exponent into place */
    451 	exp += s;			/* and add on the mantissa. */
    452 	return (exp);
    453 }
    454 
    455 /*
    456  * Periodically check the file system to see if accounting
    457  * should be turned on or off.  Beware the case where the vnode
    458  * has been vgone()'d out from underneath us, e.g. when the file
    459  * system containing the accounting file has been forcibly unmounted.
    460  */
    461 void
    462 acctwatch(arg)
    463 	void *arg;
    464 {
    465 	int error;
    466 
    467 	log(LOG_NOTICE, "Accounting started\n");
    468 	ACCT_LOCK();
    469 	while (acct_state != ACCT_STOP) {
    470 		if (acct_vp->v_type == VBAD) {
    471 			log(LOG_NOTICE, "Accounting terminated\n");
    472 			acct_stop();
    473 			continue;
    474 		}
    475 
    476 		error = acct_chkfree();
    477 #ifdef DIAGNOSTIC
    478 		if (error != 0)
    479 			printf("acctwatch: failed to statvfs, error = %d\n",
    480 			    error);
    481 #endif
    482 
    483 		ACCT_UNLOCK();
    484 		error = tsleep(acctwatch, PSWP, "actwat", acctchkfreq * hz);
    485 		ACCT_LOCK();
    486 #ifdef DIAGNOSTIC
    487 		if (error != 0 && error != EWOULDBLOCK)
    488 			printf("acctwatch: sleep error %d\n", error);
    489 #endif
    490 	}
    491 	acct_dkwatcher = NULL;
    492 	ACCT_UNLOCK();
    493 
    494 	kthread_exit(0);
    495 }
    496