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