kern_acct.c revision 1.74 1 /* $NetBSD: kern_acct.c,v 1.74 2007/04/22 08:30:00 dsl 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.74 2007/04/22 08:30:00 dsl 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/malloc.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 * Mutex to serialize system calls and kernel threads.
109 */
110 kmutex_t acct_mutex;
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 proc *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
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
173 acct_chkfree(void)
174 {
175 int error;
176 struct statvfs *sb;
177 int64_t bavail;
178
179 sb = malloc(sizeof(*sb), M_TEMP, M_WAITOK);
180 error = VFS_STATVFS(acct_vp->v_mount, sb, NULL);
181 if (error != 0)
182 return (error);
183
184 bavail = sb->f_bfree - sb->f_bresvd;
185
186 switch (acct_state) {
187 case ACCT_SUSPENDED:
188 if (bavail > acctresume * sb->f_blocks / 100) {
189 acct_state = ACCT_ACTIVE;
190 log(LOG_NOTICE, "Accounting resumed\n");
191 }
192 break;
193 case ACCT_ACTIVE:
194 if (bavail <= acctsuspend * sb->f_blocks / 100) {
195 acct_state = ACCT_SUSPENDED;
196 log(LOG_NOTICE, "Accounting suspended\n");
197 }
198 break;
199 case ACCT_STOP:
200 break;
201 }
202 free(sb, M_TEMP);
203 return (0);
204 }
205
206 static void
207 acct_stop(void)
208 {
209 int error;
210
211 if (acct_vp != NULLVP && acct_vp->v_type != VBAD) {
212 error = vn_close(acct_vp, FWRITE, acct_cred, NULL);
213 #ifdef DIAGNOSTIC
214 if (error != 0)
215 printf("acct_stop: failed to close, errno = %d\n",
216 error);
217 #endif
218 acct_vp = NULLVP;
219 }
220 if (acct_cred != NULL) {
221 kauth_cred_free(acct_cred);
222 acct_cred = NULL;
223 }
224 acct_state = ACCT_STOP;
225 }
226
227 /*
228 * Periodically check the file system to see if accounting
229 * should be turned on or off. Beware the case where the vnode
230 * has been vgone()'d out from underneath us, e.g. when the file
231 * system containing the accounting file has been forcibly unmounted.
232 */
233 static void
234 acctwatch(void *arg)
235 {
236 int error;
237
238 log(LOG_NOTICE, "Accounting started\n");
239 mutex_enter(&acct_mutex);
240 while (acct_state != ACCT_STOP) {
241 if (acct_vp->v_type == VBAD) {
242 log(LOG_NOTICE, "Accounting terminated\n");
243 acct_stop();
244 continue;
245 }
246
247 error = acct_chkfree();
248 #ifdef DIAGNOSTIC
249 if (error != 0)
250 printf("acctwatch: failed to statvfs, error = %d\n",
251 error);
252 #endif
253 error = kpause("actwat", false, acctchkfreq * hz, &acct_mutex);
254 #ifdef DIAGNOSTIC
255 if (error != 0 && error != EWOULDBLOCK)
256 printf("acctwatch: sleep error %d\n", error);
257 #endif
258 }
259 acct_dkwatcher = NULL;
260 mutex_exit(&acct_mutex);
261
262 kthread_exit(0);
263 }
264
265 void
266 acct_init(void)
267 {
268
269 acct_state = ACCT_STOP;
270 acct_vp = NULLVP;
271 acct_cred = NULL;
272 mutex_init(&acct_mutex, MUTEX_DEFAULT, IPL_NONE);
273 }
274
275 /*
276 * Accounting system call. Written based on the specification and
277 * previous implementation done by Mark Tinguely.
278 */
279 int
280 sys_acct(struct lwp *l, void *v, register_t *retval)
281 {
282 struct sys_acct_args /* {
283 syscallarg(const char *) path;
284 } */ *uap = v;
285 struct nameidata nd;
286 int error;
287
288 /* Make sure that the caller is root. */
289 if ((error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_ACCOUNTING,
290 0, NULL, NULL, NULL)))
291 return (error);
292
293 /*
294 * If accounting is to be started to a file, open that file for
295 * writing and make sure it's a 'normal'.
296 */
297 if (SCARG(uap, path) != NULL) {
298 struct vattr va;
299 size_t pad;
300 NDINIT(&nd, LOOKUP, NOFOLLOW | TRYEMULROOT, UIO_USERSPACE, SCARG(uap, path),
301 l);
302 if ((error = vn_open(&nd, FWRITE|O_APPEND, 0)) != 0)
303 return (error);
304 if (nd.ni_vp->v_type != VREG) {
305 VOP_UNLOCK(nd.ni_vp, 0);
306 error = EACCES;
307 goto bad;
308 }
309 if ((error = VOP_GETATTR(nd.ni_vp, &va, l->l_cred, l)) != 0) {
310 VOP_UNLOCK(nd.ni_vp, 0);
311 goto bad;
312 }
313
314 if ((pad = (va.va_size % sizeof(struct acct))) != 0) {
315 u_quad_t size = va.va_size - pad;
316 #ifdef DIAGNOSTIC
317 printf("Size of accounting file not a multiple of "
318 "%lu - incomplete record truncated\n",
319 (unsigned long)sizeof(struct acct));
320 #endif
321 VATTR_NULL(&va);
322 va.va_size = size;
323 error = VOP_SETATTR(nd.ni_vp, &va, l->l_cred, l);
324 if (error != 0) {
325 VOP_UNLOCK(nd.ni_vp, 0);
326 goto bad;
327 }
328 }
329 VOP_UNLOCK(nd.ni_vp, 0);
330 }
331
332 mutex_enter(&acct_mutex);
333
334 /*
335 * If accounting was previously enabled, kill the old space-watcher,
336 * free credential for accounting file i/o,
337 * ... (and, if no new file was specified, leave).
338 */
339 acct_stop();
340 if (SCARG(uap, path) == NULL)
341 goto out;
342
343 /*
344 * Save the new accounting file vnode and credential,
345 * and schedule the new free space watcher.
346 */
347 acct_state = ACCT_ACTIVE;
348 acct_vp = nd.ni_vp;
349 acct_cred = l->l_cred;
350 kauth_cred_hold(acct_cred);
351
352 error = acct_chkfree(); /* Initial guess. */
353 if (error != 0) {
354 acct_stop();
355 goto out;
356 }
357
358 if (acct_dkwatcher == NULL) {
359 error = kthread_create1(acctwatch, NULL, &acct_dkwatcher,
360 "acctwatch");
361 if (error != 0)
362 acct_stop();
363 }
364
365 out:
366 mutex_exit(&acct_mutex);
367 return (error);
368 bad:
369 vn_close(nd.ni_vp, FWRITE, l->l_cred, l);
370 return error;
371 }
372
373 /*
374 * Write out process accounting information, on process exit.
375 * Data to be written out is specified in Leffler, et al.
376 * and are enumerated below. (They're also noted in the system
377 * "acct.h" header file.)
378 */
379 int
380 acct_process(struct lwp *l)
381 {
382 struct acct acct;
383 struct timeval ut, st, tmp;
384 struct rusage *r;
385 int t, error = 0;
386 struct plimit *oplim = NULL;
387 struct proc *p = l->l_proc;
388
389 mutex_enter(&acct_mutex);
390
391 /* If accounting isn't enabled, don't bother */
392 if (acct_state != ACCT_ACTIVE)
393 goto out;
394
395 /*
396 * Raise the file limit so that accounting can't be stopped by
397 * the user.
398 *
399 * XXX We should think about the CPU limit, too.
400 */
401 mutex_enter(&p->p_mutex);
402 if (p->p_limit->p_refcnt > 1) {
403 oplim = p->p_limit;
404 p->p_limit = limcopy(p);
405 }
406 p->p_rlimit[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
407 mutex_exit(&p->p_mutex);
408
409 /*
410 * Get process accounting information.
411 */
412
413 /* (1) The name of the command that ran */
414 memcpy(acct.ac_comm, p->p_comm, sizeof(acct.ac_comm));
415
416 /* (2) The amount of user and system time that was used */
417 mutex_enter(&p->p_smutex);
418 calcru(p, &ut, &st, NULL, NULL);
419 mutex_exit(&p->p_smutex);
420 acct.ac_utime = encode_comp_t(ut.tv_sec, ut.tv_usec);
421 acct.ac_stime = encode_comp_t(st.tv_sec, st.tv_usec);
422
423 /* (3) The elapsed time the commmand ran (and its starting time) */
424 acct.ac_btime = p->p_stats->p_start.tv_sec;
425 getmicrotime(&tmp);
426 timersub(&tmp, &p->p_stats->p_start, &tmp);
427 acct.ac_etime = encode_comp_t(tmp.tv_sec, tmp.tv_usec);
428
429 /* (4) The average amount of memory used */
430 r = &p->p_stats->p_ru;
431 timeradd(&ut, &st, &tmp);
432 t = tmp.tv_sec * hz + tmp.tv_usec / tick;
433 if (t)
434 acct.ac_mem = (r->ru_ixrss + r->ru_idrss + r->ru_isrss) / t;
435 else
436 acct.ac_mem = 0;
437
438 /* (5) The number of disk I/O operations done */
439 acct.ac_io = encode_comp_t(r->ru_inblock + r->ru_oublock, 0);
440
441 /* (6) The UID and GID of the process */
442 acct.ac_uid = kauth_cred_getuid(l->l_cred);
443 acct.ac_gid = kauth_cred_getgid(l->l_cred);
444
445 /* (7) The terminal from which the process was started */
446 mutex_enter(&proclist_lock);
447 if ((p->p_lflag & PL_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
448 acct.ac_tty = p->p_pgrp->pg_session->s_ttyp->t_dev;
449 else
450 acct.ac_tty = NODEV;
451 mutex_exit(&proclist_lock);
452
453 /* (8) The boolean flags that tell how the process terminated, etc. */
454 acct.ac_flag = p->p_acflag;
455
456 /*
457 * Now, just write the accounting information to the file.
458 */
459 VOP_LEASE(acct_vp, l, l->l_cred, LEASE_WRITE);
460 error = vn_rdwr(UIO_WRITE, acct_vp, (void *)&acct,
461 sizeof(acct), (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT,
462 acct_cred, NULL, NULL);
463 if (error != 0)
464 log(LOG_ERR, "Accounting: write failed %d\n", error);
465
466 if (oplim) {
467 mutex_enter(&p->p_mutex);
468 limfree(p->p_limit);
469 p->p_limit = oplim;
470 mutex_exit(&p->p_mutex);
471 }
472
473 out:
474 mutex_exit(&acct_mutex);
475 return (error);
476 }
477