]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/kern_acct.c
7488f70dbe9043c1a4169c117809a841d29afb37
[apple/xnu.git] / bsd / kern / kern_acct.c
1 /*
2 * Copyright (c) 2000-2004 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29 /*-
30 * Copyright (c) 1982, 1986, 1989, 1993
31 * The Regents of the University of California. All rights reserved.
32 * (c) UNIX System Laboratories, Inc.
33 * All or some portions of this file are derived from material licensed
34 * to the University of California by American Telephone and Telegraph
35 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36 * the permission of UNIX System Laboratories, Inc.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
53 *
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 * SUCH DAMAGE.
65 *
66 * @(#)kern_acct.c 8.1 (Berkeley) 6/14/93
67 */
68 /* HISTORY
69 * 08-May-95 Mac Gillon (mgillon) at NeXT
70 * Purged old history
71 * New version based on 4.4
72 */
73
74
75 #include <sys/param.h>
76 #include <sys/proc_internal.h>
77 #include <sys/kauth.h>
78 #include <sys/mount_internal.h>
79 #include <sys/vnode_internal.h>
80 #include <sys/file_internal.h>
81 #include <sys/syslog.h>
82 #include <sys/kernel.h>
83 #include <sys/namei.h>
84 #include <sys/errno.h>
85 #include <sys/acct.h>
86 #include <sys/resourcevar.h>
87 #include <sys/ioctl.h>
88 #include <sys/tty.h>
89 #include <sys/sysproto.h>
90 #include <machine/spl.h>
91
92 /*
93 * The routines implemented in this file are described in:
94 * Leffler, et al.: The Design and Implementation of the 4.3BSD
95 * UNIX Operating System (Addison Welley, 1989)
96 * on pages 62-63.
97 *
98 * Arguably, to simplify accounting operations, this mechanism should
99 * be replaced by one in which an accounting log file (similar to /dev/klog)
100 * is read by a user process, etc. However, that has its own problems.
101 */
102
103 /*
104 * Internal accounting functions.
105 * The former's operation is described in Leffler, et al., and the latter
106 * was provided by UCB with the 4.4BSD-Lite release
107 */
108 comp_t encode_comp_t(u_long, u_long);
109 void acctwatch(void *);
110 void acctwatch_funnel(void *);
111
112 /*
113 * Accounting vnode pointer, and suspended accounting vnode pointer. States
114 * are as follows:
115 *
116 * acctp suspend_acctp state
117 * ------------- ------------ ------------------------------
118 * NULL NULL Accounting disabled
119 * !NULL NULL Accounting enabled
120 * NULL !NULL Accounting enabled, but suspended
121 * !NULL !NULL <not allowed>
122 */
123 struct vnode *acctp;
124 struct vnode *suspend_acctp;
125
126 /*
127 * Values associated with enabling and disabling accounting
128 */
129 int acctsuspend = 2; /* stop accounting when < 2% free space left */
130 int acctresume = 4; /* resume when free space risen to > 4% */
131 int acctchkfreq = 15; /* frequency (in seconds) to check space */
132
133 /*
134 * Accounting system call. Written based on the specification and
135 * previous implementation done by Mark Tinguely.
136 */
137 int
138 acct(struct proc *p, struct acct_args *uap, __unused int *retval)
139 {
140 struct nameidata nd;
141 int error;
142 struct vfs_context context;
143
144 context.vc_proc = p;
145 context.vc_ucred = kauth_cred_get();
146
147 /* Make sure that the caller is root. */
148 if ((error = suser(kauth_cred_get(), &p->p_acflag)))
149 return (error);
150
151 /*
152 * If accounting is to be started to a file, open that file for
153 * writing and make sure it's a 'normal'.
154 */
155 if (uap->path != USER_ADDR_NULL) {
156 NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, uap->path, &context);
157 if ((error = vn_open(&nd, FWRITE, 0)))
158 return (error);
159 vnode_put(nd.ni_vp);
160
161 if (nd.ni_vp->v_type != VREG) {
162 vn_close(nd.ni_vp, FWRITE, kauth_cred_get(), p);
163 return (EACCES);
164 }
165 }
166
167 /*
168 * If accounting was previously enabled, kill the old space-watcher,
169 * close the file, and (if no new file was specified, leave).
170 */
171 if (acctp != NULLVP || suspend_acctp != NULLVP) {
172 untimeout(acctwatch_funnel, NULL);
173 error = vn_close((acctp != NULLVP ? acctp : suspend_acctp), FWRITE,
174 kauth_cred_get(), p);
175
176 acctp = suspend_acctp = NULLVP;
177 }
178 if (uap->path == USER_ADDR_NULL)
179 return (error);
180
181 /*
182 * Save the new accounting file vnode, and schedule the new
183 * free space watcher.
184 */
185 acctp = nd.ni_vp;
186 acctwatch(NULL);
187 return (error);
188 }
189
190 /*
191 * Write out process accounting information, on process exit.
192 * Data to be written out is specified in Leffler, et al.
193 * and are enumerated below. (They're also noted in the system
194 * "acct.h" header file.)
195 */
196 int
197 acct_process(p)
198 struct proc *p;
199 {
200 struct acct an_acct;
201 struct rusage *r;
202 struct timeval ut, st, tmp;
203 int t;
204 int error;
205 struct vnode *vp;
206 kauth_cred_t safecred;
207
208 /* If accounting isn't enabled, don't bother */
209 vp = acctp;
210 if (vp == NULLVP)
211 return (0);
212
213 /*
214 * Get process accounting information.
215 */
216
217 /* (1) The name of the command that ran */
218 bcopy(p->p_comm, an_acct.ac_comm, sizeof an_acct.ac_comm);
219
220 /* (2) The amount of user and system time that was used */
221 calcru(p, &ut, &st, NULL);
222 an_acct.ac_utime = encode_comp_t(ut.tv_sec, ut.tv_usec);
223 an_acct.ac_stime = encode_comp_t(st.tv_sec, st.tv_usec);
224
225 /* (3) The elapsed time the commmand ran (and its starting time) */
226 an_acct.ac_btime = p->p_stats->p_start.tv_sec;
227 microtime(&tmp);
228 timevalsub(&tmp, &p->p_stats->p_start);
229 an_acct.ac_etime = encode_comp_t(tmp.tv_sec, tmp.tv_usec);
230
231 /* (4) The average amount of memory used */
232 r = &p->p_stats->p_ru;
233 tmp = ut;
234 timevaladd(&tmp, &st);
235 t = tmp.tv_sec * hz + tmp.tv_usec / tick;
236 if (t)
237 an_acct.ac_mem = (r->ru_ixrss + r->ru_idrss + r->ru_isrss) / t;
238 else
239 an_acct.ac_mem = 0;
240
241 /* (5) The number of disk I/O operations done */
242 an_acct.ac_io = encode_comp_t(r->ru_inblock + r->ru_oublock, 0);
243
244 /* (6) The UID and GID of the process */
245 an_acct.ac_uid = p->p_ucred->cr_ruid;
246 an_acct.ac_gid = p->p_ucred->cr_rgid;
247
248 /* (7) The terminal from which the process was started */
249 if ((p->p_flag & P_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
250 an_acct.ac_tty = p->p_pgrp->pg_session->s_ttyp->t_dev;
251 else
252 an_acct.ac_tty = NODEV;
253
254 /* (8) The boolean flags that tell how the process terminated, etc. */
255 an_acct.ac_flag = p->p_acflag;
256
257 safecred = kauth_cred_proc_ref(p);
258 /*
259 * Now, just write the accounting information to the file.
260 */
261 if ((error = vnode_getwithref(vp)) == 0) {
262 error = vn_rdwr(UIO_WRITE, vp, (caddr_t)&an_acct, sizeof (an_acct),
263 (off_t)0, UIO_SYSSPACE32, IO_APPEND|IO_UNIT, safecred,
264 (int *)0, p);
265 vnode_put(vp);
266 }
267 kauth_cred_unref(&safecred);
268 return (error);
269 }
270
271 /*
272 * Encode_comp_t converts from ticks in seconds and microseconds
273 * to ticks in 1/AHZ seconds. The encoding is described in
274 * Leffler, et al., on page 63.
275 */
276
277 #define MANTSIZE 13 /* 13 bit mantissa. */
278 #define EXPSIZE 3 /* Base 8 (3 bit) exponent. */
279 #define MAXFRACT ((1 << MANTSIZE) - 1) /* Maximum fractional value. */
280
281 comp_t
282 encode_comp_t(s, us)
283 u_long s, us;
284 {
285 int exp, rnd;
286
287 exp = 0;
288 rnd = 0;
289 s *= AHZ;
290 s += us / (1000000 / AHZ); /* Maximize precision. */
291
292 while (s > MAXFRACT) {
293 rnd = s & (1 << (EXPSIZE - 1)); /* Round up? */
294 s >>= EXPSIZE; /* Base 8 exponent == 3 bit shift. */
295 exp++;
296 }
297
298 /* If we need to round up, do it (and handle overflow correctly). */
299 if (rnd && (++s > MAXFRACT)) {
300 s >>= EXPSIZE;
301 exp++;
302 }
303
304 /* Clean it up and polish it off. */
305 exp <<= MANTSIZE; /* Shift the exponent into place */
306 exp += s; /* and add on the mantissa. */
307 return (exp);
308 }
309
310 void
311 acctwatch_funnel(a)
312 void *a;
313 {
314 thread_funnel_set(kernel_flock, TRUE);
315 acctwatch(a);
316 thread_funnel_set(kernel_flock, FALSE);
317 }
318
319
320 /*
321 * Periodically check the file system to see if accounting
322 * should be turned on or off. Beware the case where the vnode
323 * has been vgone()'d out from underneath us, e.g. when the file
324 * system containing the accounting file has been forcibly unmounted.
325 */
326 /* ARGSUSED */
327 void
328 acctwatch(__unused void *a)
329 {
330 struct vfs_context context;
331 struct vfs_attr va;
332
333 VFSATTR_INIT(&va);
334 VFSATTR_WANTED(&va, f_blocks);
335 VFSATTR_WANTED(&va, f_bavail);
336 context.vc_proc = current_proc();
337 context.vc_ucred = kauth_cred_get();
338
339 if (suspend_acctp != NULLVP) {
340 /*
341 * Resuming accounting when accounting is suspended, and the
342 * filesystem containing the suspended accounting file goes
343 * below a low watermark
344 */
345 if (suspend_acctp->v_type == VBAD) {
346 (void) vn_close(suspend_acctp, FWRITE, NOCRED, NULL);
347 suspend_acctp = NULLVP;
348 return;
349 }
350 (void)vfs_getattr(suspend_acctp->v_mount, &va, &context);
351 if (va.f_bavail > acctresume * va.f_blocks / 100) {
352 acctp = suspend_acctp;
353 suspend_acctp = NULLVP;
354 log(LOG_NOTICE, "Accounting resumed\n");
355 }
356 } else if (acctp != NULLVP) {
357 /*
358 * Suspending accounting when accounting is currently active,
359 * and the filesystem containing the active accounting file
360 * goes over a high watermark
361 */
362 if (acctp->v_type == VBAD) {
363 (void) vn_close(acctp, FWRITE, NOCRED, NULL);
364 acctp = NULLVP;
365 return;
366 }
367 (void)vfs_getattr(acctp->v_mount, &va, &context);
368 if (va.f_bavail <= acctsuspend * va.f_blocks / 100) {
369 suspend_acctp = acctp;
370 acctp = NULLVP;
371 log(LOG_NOTICE, "Accounting suspended\n");
372 }
373 } else {
374 return;
375 }
376
377 timeout(acctwatch_funnel, NULL, acctchkfreq * hz);
378 }