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