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