Back to home page

LXR

 
 

    


0001 /*
0002  *  linux/kernel/acct.c
0003  *
0004  *  BSD Process Accounting for Linux
0005  *
0006  *  Author: Marco van Wieringen <mvw@planets.elm.net>
0007  *
0008  *  Some code based on ideas and code from:
0009  *  Thomas K. Dyas <tdyas@eden.rutgers.edu>
0010  *
0011  *  This file implements BSD-style process accounting. Whenever any
0012  *  process exits, an accounting record of type "struct acct" is
0013  *  written to the file specified with the acct() system call. It is
0014  *  up to user-level programs to do useful things with the accounting
0015  *  log. The kernel just provides the raw accounting information.
0016  *
0017  * (C) Copyright 1995 - 1997 Marco van Wieringen - ELM Consultancy B.V.
0018  *
0019  *  Plugged two leaks. 1) It didn't return acct_file into the free_filps if
0020  *  the file happened to be read-only. 2) If the accounting was suspended
0021  *  due to the lack of space it happily allowed to reopen it and completely
0022  *  lost the old acct_file. 3/10/98, Al Viro.
0023  *
0024  *  Now we silently close acct_file on attempt to reopen. Cleaned sys_acct().
0025  *  XTerms and EMACS are manifestations of pure evil. 21/10/98, AV.
0026  *
0027  *  Fixed a nasty interaction with with sys_umount(). If the accointing
0028  *  was suspeneded we failed to stop it on umount(). Messy.
0029  *  Another one: remount to readonly didn't stop accounting.
0030  *  Question: what should we do if we have CAP_SYS_ADMIN but not
0031  *  CAP_SYS_PACCT? Current code does the following: umount returns -EBUSY
0032  *  unless we are messing with the root. In that case we are getting a
0033  *  real mess with do_remount_sb(). 9/11/98, AV.
0034  *
0035  *  Fixed a bunch of races (and pair of leaks). Probably not the best way,
0036  *  but this one obviously doesn't introduce deadlocks. Later. BTW, found
0037  *  one race (and leak) in BSD implementation.
0038  *  OK, that's better. ANOTHER race and leak in BSD variant. There always
0039  *  is one more bug... 10/11/98, AV.
0040  *
0041  *  Oh, fsck... Oopsable SMP race in do_process_acct() - we must hold
0042  * ->mmap_sem to walk the vma list of current->mm. Nasty, since it leaks
0043  * a struct file opened for write. Fixed. 2/6/2000, AV.
0044  */
0045 
0046 #include <linux/mm.h>
0047 #include <linux/slab.h>
0048 #include <linux/acct.h>
0049 #include <linux/capability.h>
0050 #include <linux/file.h>
0051 #include <linux/tty.h>
0052 #include <linux/security.h>
0053 #include <linux/vfs.h>
0054 #include <linux/jiffies.h>
0055 #include <linux/times.h>
0056 #include <linux/syscalls.h>
0057 #include <linux/mount.h>
0058 #include <linux/uaccess.h>
0059 #include <asm/div64.h>
0060 #include <linux/blkdev.h> /* sector_div */
0061 #include <linux/pid_namespace.h>
0062 #include <linux/fs_pin.h>
0063 
0064 /*
0065  * These constants control the amount of freespace that suspend and
0066  * resume the process accounting system, and the time delay between
0067  * each check.
0068  * Turned into sysctl-controllable parameters. AV, 12/11/98
0069  */
0070 
0071 int acct_parm[3] = {4, 2, 30};
0072 #define RESUME      (acct_parm[0])  /* >foo% free space - resume */
0073 #define SUSPEND     (acct_parm[1])  /* <foo% free space - suspend */
0074 #define ACCT_TIMEOUT    (acct_parm[2])  /* foo second timeout between checks */
0075 
0076 /*
0077  * External references and all of the globals.
0078  */
0079 
0080 struct bsd_acct_struct {
0081     struct fs_pin       pin;
0082     atomic_long_t       count;
0083     struct rcu_head     rcu;
0084     struct mutex        lock;
0085     int         active;
0086     unsigned long       needcheck;
0087     struct file     *file;
0088     struct pid_namespace    *ns;
0089     struct work_struct  work;
0090     struct completion   done;
0091 };
0092 
0093 static void do_acct_process(struct bsd_acct_struct *acct);
0094 
0095 /*
0096  * Check the amount of free space and suspend/resume accordingly.
0097  */
0098 static int check_free_space(struct bsd_acct_struct *acct)
0099 {
0100     struct kstatfs sbuf;
0101 
0102     if (time_is_before_jiffies(acct->needcheck))
0103         goto out;
0104 
0105     /* May block */
0106     if (vfs_statfs(&acct->file->f_path, &sbuf))
0107         goto out;
0108 
0109     if (acct->active) {
0110         u64 suspend = sbuf.f_blocks * SUSPEND;
0111         do_div(suspend, 100);
0112         if (sbuf.f_bavail <= suspend) {
0113             acct->active = 0;
0114             pr_info("Process accounting paused\n");
0115         }
0116     } else {
0117         u64 resume = sbuf.f_blocks * RESUME;
0118         do_div(resume, 100);
0119         if (sbuf.f_bavail >= resume) {
0120             acct->active = 1;
0121             pr_info("Process accounting resumed\n");
0122         }
0123     }
0124 
0125     acct->needcheck = jiffies + ACCT_TIMEOUT*HZ;
0126 out:
0127     return acct->active;
0128 }
0129 
0130 static void acct_put(struct bsd_acct_struct *p)
0131 {
0132     if (atomic_long_dec_and_test(&p->count))
0133         kfree_rcu(p, rcu);
0134 }
0135 
0136 static inline struct bsd_acct_struct *to_acct(struct fs_pin *p)
0137 {
0138     return p ? container_of(p, struct bsd_acct_struct, pin) : NULL;
0139 }
0140 
0141 static struct bsd_acct_struct *acct_get(struct pid_namespace *ns)
0142 {
0143     struct bsd_acct_struct *res;
0144 again:
0145     smp_rmb();
0146     rcu_read_lock();
0147     res = to_acct(ACCESS_ONCE(ns->bacct));
0148     if (!res) {
0149         rcu_read_unlock();
0150         return NULL;
0151     }
0152     if (!atomic_long_inc_not_zero(&res->count)) {
0153         rcu_read_unlock();
0154         cpu_relax();
0155         goto again;
0156     }
0157     rcu_read_unlock();
0158     mutex_lock(&res->lock);
0159     if (res != to_acct(ACCESS_ONCE(ns->bacct))) {
0160         mutex_unlock(&res->lock);
0161         acct_put(res);
0162         goto again;
0163     }
0164     return res;
0165 }
0166 
0167 static void acct_pin_kill(struct fs_pin *pin)
0168 {
0169     struct bsd_acct_struct *acct = to_acct(pin);
0170     mutex_lock(&acct->lock);
0171     do_acct_process(acct);
0172     schedule_work(&acct->work);
0173     wait_for_completion(&acct->done);
0174     cmpxchg(&acct->ns->bacct, pin, NULL);
0175     mutex_unlock(&acct->lock);
0176     pin_remove(pin);
0177     acct_put(acct);
0178 }
0179 
0180 static void close_work(struct work_struct *work)
0181 {
0182     struct bsd_acct_struct *acct = container_of(work, struct bsd_acct_struct, work);
0183     struct file *file = acct->file;
0184     if (file->f_op->flush)
0185         file->f_op->flush(file, NULL);
0186     __fput_sync(file);
0187     complete(&acct->done);
0188 }
0189 
0190 static int acct_on(struct filename *pathname)
0191 {
0192     struct file *file;
0193     struct vfsmount *mnt, *internal;
0194     struct pid_namespace *ns = task_active_pid_ns(current);
0195     struct bsd_acct_struct *acct;
0196     struct fs_pin *old;
0197     int err;
0198 
0199     acct = kzalloc(sizeof(struct bsd_acct_struct), GFP_KERNEL);
0200     if (!acct)
0201         return -ENOMEM;
0202 
0203     /* Difference from BSD - they don't do O_APPEND */
0204     file = file_open_name(pathname, O_WRONLY|O_APPEND|O_LARGEFILE, 0);
0205     if (IS_ERR(file)) {
0206         kfree(acct);
0207         return PTR_ERR(file);
0208     }
0209 
0210     if (!S_ISREG(file_inode(file)->i_mode)) {
0211         kfree(acct);
0212         filp_close(file, NULL);
0213         return -EACCES;
0214     }
0215 
0216     if (!(file->f_mode & FMODE_CAN_WRITE)) {
0217         kfree(acct);
0218         filp_close(file, NULL);
0219         return -EIO;
0220     }
0221     internal = mnt_clone_internal(&file->f_path);
0222     if (IS_ERR(internal)) {
0223         kfree(acct);
0224         filp_close(file, NULL);
0225         return PTR_ERR(internal);
0226     }
0227     err = mnt_want_write(internal);
0228     if (err) {
0229         mntput(internal);
0230         kfree(acct);
0231         filp_close(file, NULL);
0232         return err;
0233     }
0234     mnt = file->f_path.mnt;
0235     file->f_path.mnt = internal;
0236 
0237     atomic_long_set(&acct->count, 1);
0238     init_fs_pin(&acct->pin, acct_pin_kill);
0239     acct->file = file;
0240     acct->needcheck = jiffies;
0241     acct->ns = ns;
0242     mutex_init(&acct->lock);
0243     INIT_WORK(&acct->work, close_work);
0244     init_completion(&acct->done);
0245     mutex_lock_nested(&acct->lock, 1);  /* nobody has seen it yet */
0246     pin_insert(&acct->pin, mnt);
0247 
0248     rcu_read_lock();
0249     old = xchg(&ns->bacct, &acct->pin);
0250     mutex_unlock(&acct->lock);
0251     pin_kill(old);
0252     mnt_drop_write(mnt);
0253     mntput(mnt);
0254     return 0;
0255 }
0256 
0257 static DEFINE_MUTEX(acct_on_mutex);
0258 
0259 /**
0260  * sys_acct - enable/disable process accounting
0261  * @name: file name for accounting records or NULL to shutdown accounting
0262  *
0263  * Returns 0 for success or negative errno values for failure.
0264  *
0265  * sys_acct() is the only system call needed to implement process
0266  * accounting. It takes the name of the file where accounting records
0267  * should be written. If the filename is NULL, accounting will be
0268  * shutdown.
0269  */
0270 SYSCALL_DEFINE1(acct, const char __user *, name)
0271 {
0272     int error = 0;
0273 
0274     if (!capable(CAP_SYS_PACCT))
0275         return -EPERM;
0276 
0277     if (name) {
0278         struct filename *tmp = getname(name);
0279 
0280         if (IS_ERR(tmp))
0281             return PTR_ERR(tmp);
0282         mutex_lock(&acct_on_mutex);
0283         error = acct_on(tmp);
0284         mutex_unlock(&acct_on_mutex);
0285         putname(tmp);
0286     } else {
0287         rcu_read_lock();
0288         pin_kill(task_active_pid_ns(current)->bacct);
0289     }
0290 
0291     return error;
0292 }
0293 
0294 void acct_exit_ns(struct pid_namespace *ns)
0295 {
0296     rcu_read_lock();
0297     pin_kill(ns->bacct);
0298 }
0299 
0300 /*
0301  *  encode an unsigned long into a comp_t
0302  *
0303  *  This routine has been adopted from the encode_comp_t() function in
0304  *  the kern_acct.c file of the FreeBSD operating system. The encoding
0305  *  is a 13-bit fraction with a 3-bit (base 8) exponent.
0306  */
0307 
0308 #define MANTSIZE    13          /* 13 bit mantissa. */
0309 #define EXPSIZE     3           /* Base 8 (3 bit) exponent. */
0310 #define MAXFRACT    ((1 << MANTSIZE) - 1)   /* Maximum fractional value. */
0311 
0312 static comp_t encode_comp_t(unsigned long value)
0313 {
0314     int exp, rnd;
0315 
0316     exp = rnd = 0;
0317     while (value > MAXFRACT) {
0318         rnd = value & (1 << (EXPSIZE - 1)); /* Round up? */
0319         value >>= EXPSIZE;  /* Base 8 exponent == 3 bit shift. */
0320         exp++;
0321     }
0322 
0323     /*
0324      * If we need to round up, do it (and handle overflow correctly).
0325      */
0326     if (rnd && (++value > MAXFRACT)) {
0327         value >>= EXPSIZE;
0328         exp++;
0329     }
0330 
0331     /*
0332      * Clean it up and polish it off.
0333      */
0334     exp <<= MANTSIZE;       /* Shift the exponent into place */
0335     exp += value;           /* and add on the mantissa. */
0336     return exp;
0337 }
0338 
0339 #if ACCT_VERSION == 1 || ACCT_VERSION == 2
0340 /*
0341  * encode an u64 into a comp2_t (24 bits)
0342  *
0343  * Format: 5 bit base 2 exponent, 20 bits mantissa.
0344  * The leading bit of the mantissa is not stored, but implied for
0345  * non-zero exponents.
0346  * Largest encodable value is 50 bits.
0347  */
0348 
0349 #define MANTSIZE2       20                      /* 20 bit mantissa. */
0350 #define EXPSIZE2        5                       /* 5 bit base 2 exponent. */
0351 #define MAXFRACT2       ((1ul << MANTSIZE2) - 1) /* Maximum fractional value. */
0352 #define MAXEXP2         ((1 << EXPSIZE2) - 1)    /* Maximum exponent. */
0353 
0354 static comp2_t encode_comp2_t(u64 value)
0355 {
0356     int exp, rnd;
0357 
0358     exp = (value > (MAXFRACT2>>1));
0359     rnd = 0;
0360     while (value > MAXFRACT2) {
0361         rnd = value & 1;
0362         value >>= 1;
0363         exp++;
0364     }
0365 
0366     /*
0367      * If we need to round up, do it (and handle overflow correctly).
0368      */
0369     if (rnd && (++value > MAXFRACT2)) {
0370         value >>= 1;
0371         exp++;
0372     }
0373 
0374     if (exp > MAXEXP2) {
0375         /* Overflow. Return largest representable number instead. */
0376         return (1ul << (MANTSIZE2+EXPSIZE2-1)) - 1;
0377     } else {
0378         return (value & (MAXFRACT2>>1)) | (exp << (MANTSIZE2-1));
0379     }
0380 }
0381 #endif
0382 
0383 #if ACCT_VERSION == 3
0384 /*
0385  * encode an u64 into a 32 bit IEEE float
0386  */
0387 static u32 encode_float(u64 value)
0388 {
0389     unsigned exp = 190;
0390     unsigned u;
0391 
0392     if (value == 0)
0393         return 0;
0394     while ((s64)value > 0) {
0395         value <<= 1;
0396         exp--;
0397     }
0398     u = (u32)(value >> 40) & 0x7fffffu;
0399     return u | (exp << 23);
0400 }
0401 #endif
0402 
0403 /*
0404  *  Write an accounting entry for an exiting process
0405  *
0406  *  The acct_process() call is the workhorse of the process
0407  *  accounting system. The struct acct is built here and then written
0408  *  into the accounting file. This function should only be called from
0409  *  do_exit() or when switching to a different output file.
0410  */
0411 
0412 static void fill_ac(acct_t *ac)
0413 {
0414     struct pacct_struct *pacct = &current->signal->pacct;
0415     u64 elapsed, run_time;
0416     struct tty_struct *tty;
0417 
0418     /*
0419      * Fill the accounting struct with the needed info as recorded
0420      * by the different kernel functions.
0421      */
0422     memset(ac, 0, sizeof(acct_t));
0423 
0424     ac->ac_version = ACCT_VERSION | ACCT_BYTEORDER;
0425     strlcpy(ac->ac_comm, current->comm, sizeof(ac->ac_comm));
0426 
0427     /* calculate run_time in nsec*/
0428     run_time = ktime_get_ns();
0429     run_time -= current->group_leader->start_time;
0430     /* convert nsec -> AHZ */
0431     elapsed = nsec_to_AHZ(run_time);
0432 #if ACCT_VERSION == 3
0433     ac->ac_etime = encode_float(elapsed);
0434 #else
0435     ac->ac_etime = encode_comp_t(elapsed < (unsigned long) -1l ?
0436                 (unsigned long) elapsed : (unsigned long) -1l);
0437 #endif
0438 #if ACCT_VERSION == 1 || ACCT_VERSION == 2
0439     {
0440         /* new enlarged etime field */
0441         comp2_t etime = encode_comp2_t(elapsed);
0442 
0443         ac->ac_etime_hi = etime >> 16;
0444         ac->ac_etime_lo = (u16) etime;
0445     }
0446 #endif
0447     do_div(elapsed, AHZ);
0448     ac->ac_btime = get_seconds() - elapsed;
0449 #if ACCT_VERSION==2
0450     ac->ac_ahz = AHZ;
0451 #endif
0452 
0453     spin_lock_irq(&current->sighand->siglock);
0454     tty = current->signal->tty; /* Safe as we hold the siglock */
0455     ac->ac_tty = tty ? old_encode_dev(tty_devnum(tty)) : 0;
0456     ac->ac_utime = encode_comp_t(jiffies_to_AHZ(cputime_to_jiffies(pacct->ac_utime)));
0457     ac->ac_stime = encode_comp_t(jiffies_to_AHZ(cputime_to_jiffies(pacct->ac_stime)));
0458     ac->ac_flag = pacct->ac_flag;
0459     ac->ac_mem = encode_comp_t(pacct->ac_mem);
0460     ac->ac_minflt = encode_comp_t(pacct->ac_minflt);
0461     ac->ac_majflt = encode_comp_t(pacct->ac_majflt);
0462     ac->ac_exitcode = pacct->ac_exitcode;
0463     spin_unlock_irq(&current->sighand->siglock);
0464 }
0465 /*
0466  *  do_acct_process does all actual work. Caller holds the reference to file.
0467  */
0468 static void do_acct_process(struct bsd_acct_struct *acct)
0469 {
0470     acct_t ac;
0471     unsigned long flim;
0472     const struct cred *orig_cred;
0473     struct file *file = acct->file;
0474 
0475     /*
0476      * Accounting records are not subject to resource limits.
0477      */
0478     flim = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
0479     current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
0480     /* Perform file operations on behalf of whoever enabled accounting */
0481     orig_cred = override_creds(file->f_cred);
0482 
0483     /*
0484      * First check to see if there is enough free_space to continue
0485      * the process accounting system.
0486      */
0487     if (!check_free_space(acct))
0488         goto out;
0489 
0490     fill_ac(&ac);
0491     /* we really need to bite the bullet and change layout */
0492     ac.ac_uid = from_kuid_munged(file->f_cred->user_ns, orig_cred->uid);
0493     ac.ac_gid = from_kgid_munged(file->f_cred->user_ns, orig_cred->gid);
0494 #if ACCT_VERSION == 1 || ACCT_VERSION == 2
0495     /* backward-compatible 16 bit fields */
0496     ac.ac_uid16 = ac.ac_uid;
0497     ac.ac_gid16 = ac.ac_gid;
0498 #endif
0499 #if ACCT_VERSION == 3
0500     {
0501         struct pid_namespace *ns = acct->ns;
0502 
0503         ac.ac_pid = task_tgid_nr_ns(current, ns);
0504         rcu_read_lock();
0505         ac.ac_ppid = task_tgid_nr_ns(rcu_dereference(current->real_parent),
0506                          ns);
0507         rcu_read_unlock();
0508     }
0509 #endif
0510     /*
0511      * Get freeze protection. If the fs is frozen, just skip the write
0512      * as we could deadlock the system otherwise.
0513      */
0514     if (file_start_write_trylock(file)) {
0515         /* it's been opened O_APPEND, so position is irrelevant */
0516         loff_t pos = 0;
0517         __kernel_write(file, (char *)&ac, sizeof(acct_t), &pos);
0518         file_end_write(file);
0519     }
0520 out:
0521     current->signal->rlim[RLIMIT_FSIZE].rlim_cur = flim;
0522     revert_creds(orig_cred);
0523 }
0524 
0525 /**
0526  * acct_collect - collect accounting information into pacct_struct
0527  * @exitcode: task exit code
0528  * @group_dead: not 0, if this thread is the last one in the process.
0529  */
0530 void acct_collect(long exitcode, int group_dead)
0531 {
0532     struct pacct_struct *pacct = &current->signal->pacct;
0533     cputime_t utime, stime;
0534     unsigned long vsize = 0;
0535 
0536     if (group_dead && current->mm) {
0537         struct vm_area_struct *vma;
0538 
0539         down_read(&current->mm->mmap_sem);
0540         vma = current->mm->mmap;
0541         while (vma) {
0542             vsize += vma->vm_end - vma->vm_start;
0543             vma = vma->vm_next;
0544         }
0545         up_read(&current->mm->mmap_sem);
0546     }
0547 
0548     spin_lock_irq(&current->sighand->siglock);
0549     if (group_dead)
0550         pacct->ac_mem = vsize / 1024;
0551     if (thread_group_leader(current)) {
0552         pacct->ac_exitcode = exitcode;
0553         if (current->flags & PF_FORKNOEXEC)
0554             pacct->ac_flag |= AFORK;
0555     }
0556     if (current->flags & PF_SUPERPRIV)
0557         pacct->ac_flag |= ASU;
0558     if (current->flags & PF_DUMPCORE)
0559         pacct->ac_flag |= ACORE;
0560     if (current->flags & PF_SIGNALED)
0561         pacct->ac_flag |= AXSIG;
0562     task_cputime(current, &utime, &stime);
0563     pacct->ac_utime += utime;
0564     pacct->ac_stime += stime;
0565     pacct->ac_minflt += current->min_flt;
0566     pacct->ac_majflt += current->maj_flt;
0567     spin_unlock_irq(&current->sighand->siglock);
0568 }
0569 
0570 static void slow_acct_process(struct pid_namespace *ns)
0571 {
0572     for ( ; ns; ns = ns->parent) {
0573         struct bsd_acct_struct *acct = acct_get(ns);
0574         if (acct) {
0575             do_acct_process(acct);
0576             mutex_unlock(&acct->lock);
0577             acct_put(acct);
0578         }
0579     }
0580 }
0581 
0582 /**
0583  * acct_process
0584  *
0585  * handles process accounting for an exiting task
0586  */
0587 void acct_process(void)
0588 {
0589     struct pid_namespace *ns;
0590 
0591     /*
0592      * This loop is safe lockless, since current is still
0593      * alive and holds its namespace, which in turn holds
0594      * its parent.
0595      */
0596     for (ns = task_active_pid_ns(current); ns != NULL; ns = ns->parent) {
0597         if (ns->bacct)
0598             break;
0599     }
0600     if (unlikely(ns))
0601         slow_acct_process(ns);
0602 }