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