xref: /openbsd-src/sys/kern/kern_acct.c (revision 42ac1f71ddfc8f2b1ea1555399aa1e1ffc2faced)
1 /*	$OpenBSD: kern_acct.c,v 1.46 2022/02/22 17:22:29 deraadt Exp $	*/
2 /*	$NetBSD: kern_acct.c,v 1.42 1996/02/04 02:15:12 christos Exp $	*/
3 
4 /*-
5  * Copyright (c) 1994 Christopher G. Demetriou
6  * Copyright (c) 1982, 1986, 1989, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  * (c) UNIX System Laboratories, Inc.
9  * All or some portions of this file are derived from material licensed
10  * to the University of California by American Telephone and Telegraph
11  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
12  * the permission of UNIX System Laboratories, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_acct.c	8.1 (Berkeley) 6/14/93
39  */
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/proc.h>
44 #include <sys/mount.h>
45 #include <sys/vnode.h>
46 #include <sys/fcntl.h>
47 #include <sys/syslog.h>
48 #include <sys/kernel.h>
49 #include <sys/namei.h>
50 #include <sys/errno.h>
51 #include <sys/acct.h>
52 #include <sys/resourcevar.h>
53 #include <sys/ioctl.h>
54 #include <sys/tty.h>
55 #include <sys/kthread.h>
56 #include <sys/rwlock.h>
57 
58 #include <sys/syscallargs.h>
59 
60 /*
61  * The routines implemented in this file are described in:
62  *      Leffler, et al.: The Design and Implementation of the 4.3BSD
63  *	    UNIX Operating System (Addison Welley, 1989)
64  * on pages 62-63.
65  *
66  * Arguably, to simplify accounting operations, this mechanism should
67  * be replaced by one in which an accounting log file (similar to /dev/klog)
68  * is read by a user process, etc.  However, that has its own problems.
69  */
70 
71 /*
72  * Internal accounting functions.
73  */
74 comp_t	encode_comp_t(u_long, u_long);
75 int	acct_start(void);
76 void	acct_thread(void *);
77 void	acct_shutdown(void);
78 
79 /*
80  * Accounting vnode pointer, and saved vnode pointer.
81  */
82 struct	vnode *acctp;
83 struct	vnode *savacctp;
84 
85 /*
86  * Lock protecting acctp and savacctp.
87  */
88 struct	rwlock acct_lock = RWLOCK_INITIALIZER("acctlk");
89 
90 /*
91  * Values associated with enabling and disabling accounting
92  */
93 int	acctsuspend = 2;	/* stop accounting when < 2% free space left */
94 int	acctresume = 4;		/* resume when free space risen to > 4% */
95 int	acctrate = 15;		/* delay (in seconds) between space checks */
96 
97 struct proc *acct_proc;
98 
99 /*
100  * Accounting system call.  Written based on the specification and
101  * previous implementation done by Mark Tinguely.
102  */
103 int
104 sys_acct(struct proc *p, void *v, register_t *retval)
105 {
106 	struct sys_acct_args /* {
107 		syscallarg(const char *) path;
108 	} */ *uap = v;
109 	struct nameidata nd;
110 	int error;
111 
112 	/* Make sure that the caller is root. */
113 	if ((error = suser(p)) != 0)
114 		return (error);
115 
116 	/*
117 	 * If accounting is to be started to a file, open that file for
118 	 * writing and make sure it's 'normal'.
119 	 */
120 	if (SCARG(uap, path) != NULL) {
121 		NDINIT(&nd, 0, 0, UIO_USERSPACE, SCARG(uap, path), p);
122 		if ((error = vn_open(&nd, FWRITE|O_APPEND, 0)) != 0)
123 			return (error);
124 		VOP_UNLOCK(nd.ni_vp);
125 		if (nd.ni_vp->v_type != VREG) {
126 			vn_close(nd.ni_vp, FWRITE, p->p_ucred, p);
127 			return (EACCES);
128 		}
129 	}
130 
131 	rw_enter_write(&acct_lock);
132 
133 	/*
134 	 * If accounting was previously enabled, kill the old space-watcher,
135 	 * close the file, and (if no new file was specified, leave).
136 	 */
137 	if (acctp != NULL || savacctp != NULL) {
138 		wakeup(&acct_proc);
139 		(void)vn_close((acctp != NULL ? acctp : savacctp), FWRITE,
140 		    p->p_ucred, p);
141 		acctp = savacctp = NULL;
142 	}
143 	if (SCARG(uap, path) == NULL)
144 		goto out;
145 
146 	/*
147 	 * Save the new accounting file vnode, and schedule the new
148 	 * free space watcher.
149 	 */
150 	acctp = nd.ni_vp;
151 	if ((error = acct_start()) != 0) {
152 		acctp = NULL;
153 		(void)vn_close(nd.ni_vp, FWRITE, p->p_ucred, p);
154 	}
155 
156 out:
157 	rw_exit_write(&acct_lock);
158 	return (error);
159 }
160 
161 /*
162  * Write out process accounting information, on process exit.
163  * Data to be written out is specified in Leffler, et al.
164  * and are enumerated below.  (They're also noted in the system
165  * "acct.h" header file.)
166  */
167 int
168 acct_process(struct proc *p)
169 {
170 	struct acct acct;
171 	struct process *pr = p->p_p;
172 	struct rusage *r;
173 	struct timespec booted, elapsed, realstart, st, tmp, uptime, ut;
174 	int t;
175 	struct vnode *vp;
176 	int error = 0;
177 
178 	/* If accounting isn't enabled, don't bother */
179 	if (acctp == NULL)
180 		return (0);
181 
182 	rw_enter_read(&acct_lock);
183 
184 	/*
185 	 * Check the vnode again in case accounting got disabled while waiting
186 	 * for the lock.
187 	 */
188 	vp = acctp;
189 	if (vp == NULL)
190 		goto out;
191 
192 	/*
193 	 * Get process accounting information.
194 	 */
195 
196 	/* (1) The name of the command that ran */
197 	memcpy(acct.ac_comm, pr->ps_comm, sizeof acct.ac_comm);
198 
199 	/* (2) The amount of user and system time that was used */
200 	calctsru(&pr->ps_tu, &ut, &st, NULL);
201 	acct.ac_utime = encode_comp_t(ut.tv_sec, ut.tv_nsec);
202 	acct.ac_stime = encode_comp_t(st.tv_sec, st.tv_nsec);
203 
204 	/* (3) The elapsed time the command ran (and its starting time) */
205 	nanouptime(&uptime);
206 	nanoboottime(&booted);
207 	timespecadd(&booted, &pr->ps_start, &realstart);
208 	acct.ac_btime = realstart.tv_sec;
209 	timespecsub(&uptime, &pr->ps_start, &elapsed);
210 	acct.ac_etime = encode_comp_t(elapsed.tv_sec, elapsed.tv_nsec);
211 
212 	/* (4) The average amount of memory used */
213 	r = &p->p_ru;
214 	timespecadd(&ut, &st, &tmp);
215 	t = tmp.tv_sec * hz + tmp.tv_nsec / (1000 * tick);
216 	if (t)
217 		acct.ac_mem = (r->ru_ixrss + r->ru_idrss + r->ru_isrss) / t;
218 	else
219 		acct.ac_mem = 0;
220 
221 	/* (5) The number of disk I/O operations done */
222 	acct.ac_io = encode_comp_t(r->ru_inblock + r->ru_oublock, 0);
223 
224 	/* (6) The UID and GID of the process */
225 	acct.ac_uid = pr->ps_ucred->cr_ruid;
226 	acct.ac_gid = pr->ps_ucred->cr_rgid;
227 
228 	/* (7) The terminal from which the process was started */
229 	if ((pr->ps_flags & PS_CONTROLT) &&
230 	    pr->ps_pgrp->pg_session->s_ttyp)
231 		acct.ac_tty = pr->ps_pgrp->pg_session->s_ttyp->t_dev;
232 	else
233 		acct.ac_tty = -1;
234 
235 	/* (8) The boolean flags that tell how process terminated or misbehaved. */
236 	acct.ac_flag = pr->ps_acflag;
237 
238 	/* Extensions */
239 	acct.ac_pid = pr->ps_pid;
240 
241 	/*
242 	 * Now, just write the accounting information to the file.
243 	 */
244 	error = vn_rdwr(UIO_WRITE, vp, (caddr_t)&acct, sizeof (acct),
245 	    (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT|IO_NOLIMIT,
246 	    p->p_ucred, NULL, p);
247 
248 out:
249 	rw_exit_read(&acct_lock);
250 	return (error);
251 }
252 
253 /*
254  * Encode_comp_t converts from ticks in seconds and microseconds
255  * to ticks in 1/AHZ seconds.  The encoding is described in
256  * Leffler, et al., on page 63.
257  */
258 
259 #define	MANTSIZE	13			/* 13 bit mantissa. */
260 #define	EXPSIZE		3			/* Base 8 (3 bit) exponent. */
261 #define	MAXFRACT	((1 << MANTSIZE) - 1)	/* Maximum fractional value. */
262 
263 comp_t
264 encode_comp_t(u_long s, u_long ns)
265 {
266 	int exp, rnd;
267 
268 	exp = 0;
269 	rnd = 0;
270 	s *= AHZ;
271 	s += ns / (1000000000 / AHZ);	/* Maximize precision. */
272 
273 	while (s > MAXFRACT) {
274 	rnd = s & (1 << (EXPSIZE - 1));	/* Round up? */
275 		s >>= EXPSIZE;		/* Base 8 exponent == 3 bit shift. */
276 		exp++;
277 	}
278 
279 	/* If we need to round up, do it (and handle overflow correctly). */
280 	if (rnd && (++s > MAXFRACT)) {
281 		s >>= EXPSIZE;
282 		exp++;
283 	}
284 
285 	/* Clean it up and polish it off. */
286 	exp <<= MANTSIZE;		/* Shift the exponent into place */
287 	exp += s;			/* and add on the mantissa. */
288 	return (exp);
289 }
290 
291 int
292 acct_start(void)
293 {
294 	/* Already running. */
295 	if (acct_proc != NULL)
296 		return (0);
297 
298 	return (kthread_create(acct_thread, NULL, &acct_proc, "acct"));
299 }
300 
301 /*
302  * Periodically check the file system to see if accounting
303  * should be turned on or off.  Beware the case where the vnode
304  * has been vgone()'d out from underneath us, e.g. when the file
305  * system containing the accounting file has been forcibly unmounted.
306  */
307 void
308 acct_thread(void *arg)
309 {
310 	struct statfs sb;
311 	struct proc *p = curproc;
312 
313 	rw_enter_write(&acct_lock);
314 	for (;;) {
315 		if (savacctp != NULL) {
316 			if (savacctp->v_type == VBAD) {
317 				(void) vn_close(savacctp, FWRITE, NOCRED, p);
318 				savacctp = NULL;
319 				break;
320 			}
321 			(void)VFS_STATFS(savacctp->v_mount, &sb, NULL);
322 			if (sb.f_bavail > acctresume * sb.f_blocks / 100) {
323 				acctp = savacctp;
324 				savacctp = NULL;
325 				log(LOG_NOTICE, "Accounting resumed\n");
326 			}
327 		} else if (acctp != NULL) {
328 			if (acctp->v_type == VBAD) {
329 				(void) vn_close(acctp, FWRITE, NOCRED, p);
330 				acctp = NULL;
331 				break;
332 			}
333 			(void)VFS_STATFS(acctp->v_mount, &sb, NULL);
334 			if (sb.f_bavail <= acctsuspend * sb.f_blocks / 100) {
335 				savacctp = acctp;
336 				acctp = NULL;
337 				log(LOG_NOTICE, "Accounting suspended\n");
338 			}
339 		} else {
340 			break;
341 		}
342 		rwsleep_nsec(&acct_proc, &acct_lock, PPAUSE, "acct",
343 		    SEC_TO_NSEC(acctrate));
344 	}
345 	acct_proc = NULL;
346 	rw_exit_write(&acct_lock);
347 	kthread_exit(0);
348 }
349 
350 void
351 acct_shutdown(void)
352 {
353 
354 	struct proc *p = curproc;
355 
356 	rw_enter_write(&acct_lock);
357 	if (acctp != NULL || savacctp != NULL) {
358 		vn_close((acctp != NULL ? acctp : savacctp), FWRITE,
359 		    NOCRED, p);
360 		acctp = savacctp = NULL;
361 	}
362 	rw_exit_write(&acct_lock);
363 }
364