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