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