4 * BSD Process Accounting for Linux
6 * Author: Marco van Wieringen <mvw@planets.elm.net>
8 * Some code based on ideas and code from:
9 * Thomas K. Dyas <tdyas@eden.rutgers.edu>
11 * This file implements BSD-style process accounting. Whenever any
12 * process exits, an accounting record of type "struct acct" is
13 * written to the file specified with the acct() system call. It is
14 * up to user-level programs to do useful things with the accounting
15 * log. The kernel just provides the raw accounting information.
17 * (C) Copyright 1995 - 1997 Marco van Wieringen - ELM Consultancy B.V.
19 * Plugged two leaks. 1) It didn't return acct_file into the free_filps if
20 * the file happened to be read-only. 2) If the accounting was suspended
21 * due to the lack of space it happily allowed to reopen it and completely
22 * lost the old acct_file. 3/10/98, Al Viro.
24 * Now we silently close acct_file on attempt to reopen. Cleaned sys_acct().
25 * XTerms and EMACS are manifestations of pure evil. 21/10/98, AV.
27 * Fixed a nasty interaction with with sys_umount(). If the accointing
28 * was suspeneded we failed to stop it on umount(). Messy.
29 * Another one: remount to readonly didn't stop accounting.
30 * Question: what should we do if we have CAP_SYS_ADMIN but not
31 * CAP_SYS_PACCT? Current code does the following: umount returns -EBUSY
32 * unless we are messing with the root. In that case we are getting a
33 * real mess with do_remount_sb(). 9/11/98, AV.
35 * Fixed a bunch of races (and pair of leaks). Probably not the best way,
36 * but this one obviously doesn't introduce deadlocks. Later. BTW, found
37 * one race (and leak) in BSD implementation.
38 * OK, that's better. ANOTHER race and leak in BSD variant. There always
39 * is one more bug... 10/11/98, AV.
41 * Oh, fsck... Oopsable SMP race in do_process_acct() - we must hold
42 * ->mmap_sem to walk the vma list of current->mm. Nasty, since it leaks
43 * a struct file opened for write. Fixed. 2/6/2000, AV.
47 #include <linux/slab.h>
48 #include <linux/acct.h>
49 #include <linux/capability.h>
50 #include <linux/file.h>
51 #include <linux/tty.h>
52 #include <linux/security.h>
53 #include <linux/vfs.h>
54 #include <linux/jiffies.h>
55 #include <linux/times.h>
56 #include <linux/syscalls.h>
57 #include <linux/mount.h>
58 #include <linux/uaccess.h>
59 #include <asm/div64.h>
60 #include <linux/blkdev.h> /* sector_div */
61 #include <linux/pid_namespace.h>
64 * These constants control the amount of freespace that suspend and
65 * resume the process accounting system, and the time delay between
67 * Turned into sysctl-controllable parameters. AV, 12/11/98
70 int acct_parm[3] = {4, 2, 30};
71 #define RESUME (acct_parm[0]) /* >foo% free space - resume */
72 #define SUSPEND (acct_parm[1]) /* <foo% free space - suspend */
73 #define ACCT_TIMEOUT (acct_parm[2]) /* foo second timeout between checks */
76 * External references and all of the globals.
78 static void do_acct_process(struct bsd_acct_struct *acct,
79 struct pid_namespace *ns, struct file *);
82 * This structure is used so that all the data protected by lock
83 * can be placed in the same cache line as the lock. This primes
84 * the cache line to have the data after getting the lock.
86 struct bsd_acct_struct {
88 unsigned long needcheck;
90 struct pid_namespace *ns;
91 struct list_head list;
94 static DEFINE_SPINLOCK(acct_lock);
95 static LIST_HEAD(acct_list);
96 static LIST_HEAD(acct_close_list);
99 * Check the amount of free space and suspend/resume accordingly.
101 static int check_free_space(struct bsd_acct_struct *acct, struct file *file)
109 spin_lock(&acct_lock);
111 if (!file || time_is_before_jiffies(acct->needcheck))
113 spin_unlock(&acct_lock);
116 if (vfs_statfs(&file->f_path, &sbuf))
118 suspend = sbuf.f_blocks * SUSPEND;
119 resume = sbuf.f_blocks * RESUME;
121 do_div(suspend, 100);
124 if (sbuf.f_bavail <= suspend)
126 else if (sbuf.f_bavail >= resume)
132 * If some joker switched acct->file under us we'ld better be
133 * silent and _not_ touch anything.
135 spin_lock(&acct_lock);
136 if (file != acct->file) {
145 printk(KERN_INFO "Process accounting paused\n");
150 printk(KERN_INFO "Process accounting resumed\n");
154 acct->needcheck = jiffies + ACCT_TIMEOUT*HZ;
157 spin_unlock(&acct_lock);
162 * Close the old accounting file (if currently open) and then replace
163 * it with file (if non-NULL).
165 * NOTE: acct_lock MUST be held on entry and exit.
167 static void acct_file_reopen(struct bsd_acct_struct *acct, struct file *file,
168 struct pid_namespace *ns)
170 struct file *old_acct = NULL;
171 struct pid_namespace *old_ns = NULL;
174 old_acct = acct->file;
179 list_del(&acct->list);
184 acct->needcheck = jiffies + ACCT_TIMEOUT*HZ;
186 list_add(&acct->list, &acct_list);
189 mnt_unpin(old_acct->f_path.mnt);
190 spin_unlock(&acct_lock);
191 do_acct_process(acct, old_ns, old_acct);
192 filp_close(old_acct, NULL);
193 spin_lock(&acct_lock);
197 static int acct_on(struct filename *pathname)
200 struct vfsmount *mnt;
201 struct pid_namespace *ns;
202 struct bsd_acct_struct *acct = NULL;
204 /* Difference from BSD - they don't do O_APPEND */
205 file = file_open_name(pathname, O_WRONLY|O_APPEND|O_LARGEFILE, 0);
207 return PTR_ERR(file);
209 if (!S_ISREG(file_inode(file)->i_mode)) {
210 filp_close(file, NULL);
214 if (!file->f_op->write) {
215 filp_close(file, NULL);
219 ns = task_active_pid_ns(current);
220 if (ns->bacct == NULL) {
221 acct = kzalloc(sizeof(struct bsd_acct_struct), GFP_KERNEL);
223 filp_close(file, NULL);
228 spin_lock(&acct_lock);
229 if (ns->bacct == NULL) {
234 mnt = file->f_path.mnt;
236 acct_file_reopen(ns->bacct, file, ns);
237 spin_unlock(&acct_lock);
239 mntput(mnt); /* it's pinned, now give up active reference */
246 * sys_acct - enable/disable process accounting
247 * @name: file name for accounting records or NULL to shutdown accounting
249 * Returns 0 for success or negative errno values for failure.
251 * sys_acct() is the only system call needed to implement process
252 * accounting. It takes the name of the file where accounting records
253 * should be written. If the filename is NULL, accounting will be
256 SYSCALL_DEFINE1(acct, const char __user *, name)
260 if (!capable(CAP_SYS_PACCT))
264 struct filename *tmp = getname(name);
267 error = acct_on(tmp);
270 struct bsd_acct_struct *acct;
272 acct = task_active_pid_ns(current)->bacct;
276 spin_lock(&acct_lock);
277 acct_file_reopen(acct, NULL, NULL);
278 spin_unlock(&acct_lock);
284 static void acct_close_mnts(struct work_struct *unused)
286 struct bsd_acct_struct *acct;
288 spin_lock(&acct_lock);
290 list_for_each_entry(acct, &acct_close_list, list) {
291 acct_file_reopen(acct, NULL, NULL);
294 spin_unlock(&acct_lock);
296 static DECLARE_WORK(acct_close_work, acct_close_mnts);
299 * acct_auto_close - turn off a filesystem's accounting if it is on
300 * @m: vfsmount being shut down
302 * If the accounting is turned on for a file in the subtree pointed to
303 * to by m, turn accounting off. Done when m is about to die.
305 void acct_auto_close_mnt(struct vfsmount *m)
307 struct bsd_acct_struct *acct, *tmp;
309 spin_lock(&acct_lock);
310 list_for_each_entry_safe(acct, tmp, &acct_list, list) {
311 if (acct->file && acct->file->f_path.mnt == m) {
312 list_move_tail(&acct->list, &acct_close_list);
313 schedule_work(&acct_close_work);
316 spin_unlock(&acct_lock);
320 * acct_auto_close - turn off a filesystem's accounting if it is on
321 * @sb: super block for the filesystem
323 * If the accounting is turned on for a file in the filesystem pointed
324 * to by sb, turn accounting off.
326 void acct_auto_close(struct super_block *sb)
328 struct bsd_acct_struct *acct;
330 spin_lock(&acct_lock);
332 list_for_each_entry(acct, &acct_list, list)
333 if (acct->file && acct->file->f_path.dentry->d_sb == sb) {
334 acct_file_reopen(acct, NULL, NULL);
337 spin_unlock(&acct_lock);
340 void acct_exit_ns(struct pid_namespace *ns)
342 struct bsd_acct_struct *acct = ns->bacct;
347 spin_lock(&acct_lock);
348 if (acct->file != NULL)
349 acct_file_reopen(acct, NULL, NULL);
350 spin_unlock(&acct_lock);
356 * encode an unsigned long into a comp_t
358 * This routine has been adopted from the encode_comp_t() function in
359 * the kern_acct.c file of the FreeBSD operating system. The encoding
360 * is a 13-bit fraction with a 3-bit (base 8) exponent.
363 #define MANTSIZE 13 /* 13 bit mantissa. */
364 #define EXPSIZE 3 /* Base 8 (3 bit) exponent. */
365 #define MAXFRACT ((1 << MANTSIZE) - 1) /* Maximum fractional value. */
367 static comp_t encode_comp_t(unsigned long value)
372 while (value > MAXFRACT) {
373 rnd = value & (1 << (EXPSIZE - 1)); /* Round up? */
374 value >>= EXPSIZE; /* Base 8 exponent == 3 bit shift. */
379 * If we need to round up, do it (and handle overflow correctly).
381 if (rnd && (++value > MAXFRACT)) {
387 * Clean it up and polish it off.
389 exp <<= MANTSIZE; /* Shift the exponent into place */
390 exp += value; /* and add on the mantissa. */
394 #if ACCT_VERSION==1 || ACCT_VERSION==2
396 * encode an u64 into a comp2_t (24 bits)
398 * Format: 5 bit base 2 exponent, 20 bits mantissa.
399 * The leading bit of the mantissa is not stored, but implied for
400 * non-zero exponents.
401 * Largest encodable value is 50 bits.
404 #define MANTSIZE2 20 /* 20 bit mantissa. */
405 #define EXPSIZE2 5 /* 5 bit base 2 exponent. */
406 #define MAXFRACT2 ((1ul << MANTSIZE2) - 1) /* Maximum fractional value. */
407 #define MAXEXP2 ((1 <<EXPSIZE2) - 1) /* Maximum exponent. */
409 static comp2_t encode_comp2_t(u64 value)
413 exp = (value > (MAXFRACT2>>1));
415 while (value > MAXFRACT2) {
422 * If we need to round up, do it (and handle overflow correctly).
424 if (rnd && (++value > MAXFRACT2)) {
430 /* Overflow. Return largest representable number instead. */
431 return (1ul << (MANTSIZE2+EXPSIZE2-1)) - 1;
433 return (value & (MAXFRACT2>>1)) | (exp << (MANTSIZE2-1));
440 * encode an u64 into a 32 bit IEEE float
442 static u32 encode_float(u64 value)
447 if (value==0) return 0;
448 while ((s64)value > 0){
452 u = (u32)(value >> 40) & 0x7fffffu;
453 return u | (exp << 23);
458 * Write an accounting entry for an exiting process
460 * The acct_process() call is the workhorse of the process
461 * accounting system. The struct acct is built here and then written
462 * into the accounting file. This function should only be called from
463 * do_exit() or when switching to a different output file.
467 * do_acct_process does all actual work. Caller holds the reference to file.
469 static void do_acct_process(struct bsd_acct_struct *acct,
470 struct pid_namespace *ns, struct file *file)
472 struct pacct_struct *pacct = ¤t->signal->pacct;
478 struct timespec uptime;
479 struct tty_struct *tty;
480 const struct cred *orig_cred;
482 /* Perform file operations on behalf of whoever enabled accounting */
483 orig_cred = override_creds(file->f_cred);
486 * First check to see if there is enough free_space to continue
487 * the process accounting system.
489 if (!check_free_space(acct, file))
493 * Fill the accounting struct with the needed info as recorded
494 * by the different kernel functions.
496 memset(&ac, 0, sizeof(acct_t));
498 ac.ac_version = ACCT_VERSION | ACCT_BYTEORDER;
499 strlcpy(ac.ac_comm, current->comm, sizeof(ac.ac_comm));
501 /* calculate run_time in nsec*/
502 do_posix_clock_monotonic_gettime(&uptime);
503 run_time = (u64)uptime.tv_sec*NSEC_PER_SEC + uptime.tv_nsec;
504 run_time -= (u64)current->group_leader->start_time.tv_sec * NSEC_PER_SEC
505 + current->group_leader->start_time.tv_nsec;
506 /* convert nsec -> AHZ */
507 elapsed = nsec_to_AHZ(run_time);
509 ac.ac_etime = encode_float(elapsed);
511 ac.ac_etime = encode_comp_t(elapsed < (unsigned long) -1l ?
512 (unsigned long) elapsed : (unsigned long) -1l);
514 #if ACCT_VERSION==1 || ACCT_VERSION==2
516 /* new enlarged etime field */
517 comp2_t etime = encode_comp2_t(elapsed);
518 ac.ac_etime_hi = etime >> 16;
519 ac.ac_etime_lo = (u16) etime;
522 do_div(elapsed, AHZ);
523 ac.ac_btime = get_seconds() - elapsed;
524 /* we really need to bite the bullet and change layout */
525 ac.ac_uid = from_kuid_munged(file->f_cred->user_ns, orig_cred->uid);
526 ac.ac_gid = from_kgid_munged(file->f_cred->user_ns, orig_cred->gid);
530 #if ACCT_VERSION==1 || ACCT_VERSION==2
531 /* backward-compatible 16 bit fields */
532 ac.ac_uid16 = ac.ac_uid;
533 ac.ac_gid16 = ac.ac_gid;
536 ac.ac_pid = task_tgid_nr_ns(current, ns);
538 ac.ac_ppid = task_tgid_nr_ns(rcu_dereference(current->real_parent), ns);
542 spin_lock_irq(¤t->sighand->siglock);
543 tty = current->signal->tty; /* Safe as we hold the siglock */
544 ac.ac_tty = tty ? old_encode_dev(tty_devnum(tty)) : 0;
545 ac.ac_utime = encode_comp_t(jiffies_to_AHZ(cputime_to_jiffies(pacct->ac_utime)));
546 ac.ac_stime = encode_comp_t(jiffies_to_AHZ(cputime_to_jiffies(pacct->ac_stime)));
547 ac.ac_flag = pacct->ac_flag;
548 ac.ac_mem = encode_comp_t(pacct->ac_mem);
549 ac.ac_minflt = encode_comp_t(pacct->ac_minflt);
550 ac.ac_majflt = encode_comp_t(pacct->ac_majflt);
551 ac.ac_exitcode = pacct->ac_exitcode;
552 spin_unlock_irq(¤t->sighand->siglock);
553 ac.ac_io = encode_comp_t(0 /* current->io_usage */); /* %% */
554 ac.ac_rw = encode_comp_t(ac.ac_io / 1024);
555 ac.ac_swaps = encode_comp_t(0);
558 * Get freeze protection. If the fs is frozen, just skip the write
559 * as we could deadlock the system otherwise.
561 if (!file_start_write_trylock(file))
564 * Kernel segment override to datasegment and write it
565 * to the accounting file.
570 * Accounting records are not subject to resource limits.
572 flim = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
573 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
574 file->f_op->write(file, (char *)&ac,
575 sizeof(acct_t), &file->f_pos);
576 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = flim;
578 file_end_write(file);
580 revert_creds(orig_cred);
584 * acct_collect - collect accounting information into pacct_struct
585 * @exitcode: task exit code
586 * @group_dead: not 0, if this thread is the last one in the process.
588 void acct_collect(long exitcode, int group_dead)
590 struct pacct_struct *pacct = ¤t->signal->pacct;
591 cputime_t utime, stime;
592 unsigned long vsize = 0;
594 if (group_dead && current->mm) {
595 struct vm_area_struct *vma;
596 down_read(¤t->mm->mmap_sem);
597 vma = current->mm->mmap;
599 vsize += vma->vm_end - vma->vm_start;
602 up_read(¤t->mm->mmap_sem);
605 spin_lock_irq(¤t->sighand->siglock);
607 pacct->ac_mem = vsize / 1024;
608 if (thread_group_leader(current)) {
609 pacct->ac_exitcode = exitcode;
610 if (current->flags & PF_FORKNOEXEC)
611 pacct->ac_flag |= AFORK;
613 if (current->flags & PF_SUPERPRIV)
614 pacct->ac_flag |= ASU;
615 if (current->flags & PF_DUMPCORE)
616 pacct->ac_flag |= ACORE;
617 if (current->flags & PF_SIGNALED)
618 pacct->ac_flag |= AXSIG;
619 task_cputime(current, &utime, &stime);
620 pacct->ac_utime += utime;
621 pacct->ac_stime += stime;
622 pacct->ac_minflt += current->min_flt;
623 pacct->ac_majflt += current->maj_flt;
624 spin_unlock_irq(¤t->sighand->siglock);
627 static void acct_process_in_ns(struct pid_namespace *ns)
629 struct file *file = NULL;
630 struct bsd_acct_struct *acct;
634 * accelerate the common fastpath:
636 if (!acct || !acct->file)
639 spin_lock(&acct_lock);
641 if (unlikely(!file)) {
642 spin_unlock(&acct_lock);
646 spin_unlock(&acct_lock);
648 do_acct_process(acct, ns, file);
653 * acct_process - now just a wrapper around acct_process_in_ns,
654 * which in turn is a wrapper around do_acct_process.
656 * handles process accounting for an exiting task
658 void acct_process(void)
660 struct pid_namespace *ns;
663 * This loop is safe lockless, since current is still
664 * alive and holds its namespace, which in turn holds
667 for (ns = task_active_pid_ns(current); ns != NULL; ns = ns->parent)
668 acct_process_in_ns(ns);