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