]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - kernel/acct.c
Merge branch 'akpm-current/current'
[karo-tx-linux.git] / kernel / acct.c
1 /*
2  *  linux/kernel/acct.c
3  *
4  *  BSD Process Accounting for Linux
5  *
6  *  Author: Marco van Wieringen <mvw@planets.elm.net>
7  *
8  *  Some code based on ideas and code from:
9  *  Thomas K. Dyas <tdyas@eden.rutgers.edu>
10  *
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.
16  *
17  * (C) Copyright 1995 - 1997 Marco van Wieringen - ELM Consultancy B.V.
18  *
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.
23  *
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.
26  *
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.
34  *
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.
40  *
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.
44  */
45
46 #include <linux/mm.h>
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>
62
63 /*
64  * These constants control the amount of freespace that suspend and
65  * resume the process accounting system, and the time delay between
66  * each check.
67  * Turned into sysctl-controllable parameters. AV, 12/11/98
68  */
69
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 */
74
75 /*
76  * External references and all of the globals.
77  */
78 static void do_acct_process(struct bsd_acct_struct *acct,
79                 struct pid_namespace *ns, struct file *);
80
81 /*
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.
85  */
86 struct bsd_acct_struct {
87         int                     active;
88         unsigned long           needcheck;
89         struct file             *file;
90         struct pid_namespace    *ns;
91         struct list_head        list;
92 };
93
94 static DEFINE_SPINLOCK(acct_lock);
95 static LIST_HEAD(acct_list);
96 static LIST_HEAD(acct_close_list);
97
98 /*
99  * Check the amount of free space and suspend/resume accordingly.
100  */
101 static int check_free_space(struct bsd_acct_struct *acct, struct file *file)
102 {
103         struct kstatfs sbuf;
104         int res;
105         int act;
106         u64 resume;
107         u64 suspend;
108
109         spin_lock(&acct_lock);
110         res = acct->active;
111         if (!file || time_is_before_jiffies(acct->needcheck))
112                 goto out;
113         spin_unlock(&acct_lock);
114
115         /* May block */
116         if (vfs_statfs(&file->f_path, &sbuf))
117                 return res;
118         suspend = sbuf.f_blocks * SUSPEND;
119         resume = sbuf.f_blocks * RESUME;
120
121         do_div(suspend, 100);
122         do_div(resume, 100);
123
124         if (sbuf.f_bavail <= suspend)
125                 act = -1;
126         else if (sbuf.f_bavail >= resume)
127                 act = 1;
128         else
129                 act = 0;
130
131         /*
132          * If some joker switched acct->file under us we'ld better be
133          * silent and _not_ touch anything.
134          */
135         spin_lock(&acct_lock);
136         if (file != acct->file) {
137                 if (act)
138                         res = act > 0;
139                 goto out;
140         }
141
142         if (acct->active) {
143                 if (act < 0) {
144                         acct->active = 0;
145                         printk(KERN_INFO "Process accounting paused\n");
146                 }
147         } else {
148                 if (act > 0) {
149                         acct->active = 1;
150                         printk(KERN_INFO "Process accounting resumed\n");
151                 }
152         }
153
154         acct->needcheck = jiffies + ACCT_TIMEOUT*HZ;
155         res = acct->active;
156 out:
157         spin_unlock(&acct_lock);
158         return res;
159 }
160
161 /*
162  * Close the old accounting file (if currently open) and then replace
163  * it with file (if non-NULL).
164  *
165  * NOTE: acct_lock MUST be held on entry and exit.
166  */
167 static void acct_file_reopen(struct bsd_acct_struct *acct, struct file *file,
168                 struct pid_namespace *ns)
169 {
170         struct file *old_acct = NULL;
171         struct pid_namespace *old_ns = NULL;
172
173         if (acct->file) {
174                 old_acct = acct->file;
175                 old_ns = acct->ns;
176                 acct->active = 0;
177                 acct->file = NULL;
178                 acct->ns = NULL;
179                 list_del(&acct->list);
180         }
181         if (file) {
182                 acct->file = file;
183                 acct->ns = ns;
184                 acct->needcheck = jiffies + ACCT_TIMEOUT*HZ;
185                 acct->active = 1;
186                 list_add(&acct->list, &acct_list);
187         }
188         if (old_acct) {
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);
194         }
195 }
196
197 static int acct_on(struct filename *pathname)
198 {
199         struct file *file;
200         struct vfsmount *mnt;
201         struct pid_namespace *ns;
202         struct bsd_acct_struct *acct = NULL;
203
204         /* Difference from BSD - they don't do O_APPEND */
205         file = file_open_name(pathname, O_WRONLY|O_APPEND|O_LARGEFILE, 0);
206         if (IS_ERR(file))
207                 return PTR_ERR(file);
208
209         if (!S_ISREG(file_inode(file)->i_mode)) {
210                 filp_close(file, NULL);
211                 return -EACCES;
212         }
213
214         if (!file->f_op->write) {
215                 filp_close(file, NULL);
216                 return -EIO;
217         }
218
219         ns = task_active_pid_ns(current);
220         if (ns->bacct == NULL) {
221                 acct = kzalloc(sizeof(struct bsd_acct_struct), GFP_KERNEL);
222                 if (acct == NULL) {
223                         filp_close(file, NULL);
224                         return -ENOMEM;
225                 }
226         }
227
228         spin_lock(&acct_lock);
229         if (ns->bacct == NULL) {
230                 ns->bacct = acct;
231                 acct = NULL;
232         }
233
234         mnt = file->f_path.mnt;
235         mnt_pin(mnt);
236         acct_file_reopen(ns->bacct, file, ns);
237         spin_unlock(&acct_lock);
238
239         mntput(mnt); /* it's pinned, now give up active reference */
240         kfree(acct);
241
242         return 0;
243 }
244
245 /**
246  * sys_acct - enable/disable process accounting
247  * @name: file name for accounting records or NULL to shutdown accounting
248  *
249  * Returns 0 for success or negative errno values for failure.
250  *
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
254  * shutdown.
255  */
256 SYSCALL_DEFINE1(acct, const char __user *, name)
257 {
258         int error = 0;
259
260         if (!capable(CAP_SYS_PACCT))
261                 return -EPERM;
262
263         if (name) {
264                 struct filename *tmp = getname(name);
265                 if (IS_ERR(tmp))
266                         return PTR_ERR(tmp);
267                 error = acct_on(tmp);
268                 putname(tmp);
269         } else {
270                 struct bsd_acct_struct *acct;
271
272                 acct = task_active_pid_ns(current)->bacct;
273                 if (acct == NULL)
274                         return 0;
275
276                 spin_lock(&acct_lock);
277                 acct_file_reopen(acct, NULL, NULL);
278                 spin_unlock(&acct_lock);
279         }
280
281         return error;
282 }
283
284 static void acct_close_mnts(struct work_struct *unused)
285 {
286         struct bsd_acct_struct *acct;
287
288         spin_lock(&acct_lock);
289 restart:
290         list_for_each_entry(acct, &acct_close_list, list) {
291                 acct_file_reopen(acct, NULL, NULL);
292                 goto restart;
293         }
294         spin_unlock(&acct_lock);
295 }
296 static DECLARE_WORK(acct_close_work, acct_close_mnts);
297
298 /**
299  * acct_auto_close - turn off a filesystem's accounting if it is on
300  * @m: vfsmount being shut down
301  *
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.
304  */
305 void acct_auto_close_mnt(struct vfsmount *m)
306 {
307         struct bsd_acct_struct *acct, *tmp;
308
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);
314                 }
315         }
316         spin_unlock(&acct_lock);
317 }
318
319 /**
320  * acct_auto_close - turn off a filesystem's accounting if it is on
321  * @sb: super block for the filesystem
322  *
323  * If the accounting is turned on for a file in the filesystem pointed
324  * to by sb, turn accounting off.
325  */
326 void acct_auto_close(struct super_block *sb)
327 {
328         struct bsd_acct_struct *acct;
329
330         spin_lock(&acct_lock);
331 restart:
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);
335                         goto restart;
336                 }
337         spin_unlock(&acct_lock);
338 }
339
340 void acct_exit_ns(struct pid_namespace *ns)
341 {
342         struct bsd_acct_struct *acct = ns->bacct;
343
344         if (acct == NULL)
345                 return;
346
347         spin_lock(&acct_lock);
348         if (acct->file != NULL)
349                 acct_file_reopen(acct, NULL, NULL);
350         spin_unlock(&acct_lock);
351
352         kfree(acct);
353 }
354
355 /*
356  *  encode an unsigned long into a comp_t
357  *
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.
361  */
362
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. */
366
367 static comp_t encode_comp_t(unsigned long value)
368 {
369         int exp, rnd;
370
371         exp = rnd = 0;
372         while (value > MAXFRACT) {
373                 rnd = value & (1 << (EXPSIZE - 1));     /* Round up? */
374                 value >>= EXPSIZE;      /* Base 8 exponent == 3 bit shift. */
375                 exp++;
376         }
377
378         /*
379          * If we need to round up, do it (and handle overflow correctly).
380          */
381         if (rnd && (++value > MAXFRACT)) {
382                 value >>= EXPSIZE;
383                 exp++;
384         }
385
386         /*
387          * Clean it up and polish it off.
388          */
389         exp <<= MANTSIZE;               /* Shift the exponent into place */
390         exp += value;                   /* and add on the mantissa. */
391         return exp;
392 }
393
394 #if ACCT_VERSION==1 || ACCT_VERSION==2
395 /*
396  * encode an u64 into a comp2_t (24 bits)
397  *
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.
402  */
403
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. */
408
409 static comp2_t encode_comp2_t(u64 value)
410 {
411         int exp, rnd;
412
413         exp = (value > (MAXFRACT2>>1));
414         rnd = 0;
415         while (value > MAXFRACT2) {
416                 rnd = value & 1;
417                 value >>= 1;
418                 exp++;
419         }
420
421         /*
422          * If we need to round up, do it (and handle overflow correctly).
423          */
424         if (rnd && (++value > MAXFRACT2)) {
425                 value >>= 1;
426                 exp++;
427         }
428
429         if (exp > MAXEXP2) {
430                 /* Overflow. Return largest representable number instead. */
431                 return (1ul << (MANTSIZE2+EXPSIZE2-1)) - 1;
432         } else {
433                 return (value & (MAXFRACT2>>1)) | (exp << (MANTSIZE2-1));
434         }
435 }
436 #endif
437
438 #if ACCT_VERSION==3
439 /*
440  * encode an u64 into a 32 bit IEEE float
441  */
442 static u32 encode_float(u64 value)
443 {
444         unsigned exp = 190;
445         unsigned u;
446
447         if (value==0) return 0;
448         while ((s64)value > 0){
449                 value <<= 1;
450                 exp--;
451         }
452         u = (u32)(value >> 40) & 0x7fffffu;
453         return u | (exp << 23);
454 }
455 #endif
456
457 /*
458  *  Write an accounting entry for an exiting process
459  *
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.
464  */
465
466 /*
467  *  do_acct_process does all actual work. Caller holds the reference to file.
468  */
469 static void do_acct_process(struct bsd_acct_struct *acct,
470                 struct pid_namespace *ns, struct file *file)
471 {
472         struct pacct_struct *pacct = &current->signal->pacct;
473         acct_t ac;
474         mm_segment_t fs;
475         unsigned long flim;
476         u64 elapsed;
477         u64 run_time;
478         struct timespec uptime;
479         struct tty_struct *tty;
480         const struct cred *orig_cred;
481
482         /* Perform file operations on behalf of whoever enabled accounting */
483         orig_cred = override_creds(file->f_cred);
484
485         /*
486          * First check to see if there is enough free_space to continue
487          * the process accounting system.
488          */
489         if (!check_free_space(acct, file))
490                 goto out;
491
492         /*
493          * Fill the accounting struct with the needed info as recorded
494          * by the different kernel functions.
495          */
496         memset(&ac, 0, sizeof(acct_t));
497
498         ac.ac_version = ACCT_VERSION | ACCT_BYTEORDER;
499         strlcpy(ac.ac_comm, current->comm, sizeof(ac.ac_comm));
500
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);
508 #if ACCT_VERSION==3
509         ac.ac_etime = encode_float(elapsed);
510 #else
511         ac.ac_etime = encode_comp_t(elapsed < (unsigned long) -1l ?
512                                (unsigned long) elapsed : (unsigned long) -1l);
513 #endif
514 #if ACCT_VERSION==1 || ACCT_VERSION==2
515         {
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;
520         }
521 #endif
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);
527 #if ACCT_VERSION==2
528         ac.ac_ahz = AHZ;
529 #endif
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;
534 #endif
535 #if ACCT_VERSION==3
536         ac.ac_pid = task_tgid_nr_ns(current, ns);
537         rcu_read_lock();
538         ac.ac_ppid = task_tgid_nr_ns(rcu_dereference(current->real_parent), ns);
539         rcu_read_unlock();
540 #endif
541
542         spin_lock_irq(&current->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(&current->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);
556
557         /*
558          * Get freeze protection. If the fs is frozen, just skip the write
559          * as we could deadlock the system otherwise.
560          */
561         if (!file_start_write_trylock(file))
562                 goto out;
563         /*
564          * Kernel segment override to datasegment and write it
565          * to the accounting file.
566          */
567         fs = get_fs();
568         set_fs(KERNEL_DS);
569         /*
570          * Accounting records are not subject to resource limits.
571          */
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;
577         set_fs(fs);
578         file_end_write(file);
579 out:
580         revert_creds(orig_cred);
581 }
582
583 /**
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.
587  */
588 void acct_collect(long exitcode, int group_dead)
589 {
590         struct pacct_struct *pacct = &current->signal->pacct;
591         cputime_t utime, stime;
592         unsigned long vsize = 0;
593
594         if (group_dead && current->mm) {
595                 struct vm_area_struct *vma;
596                 down_read(&current->mm->mmap_sem);
597                 vma = current->mm->mmap;
598                 while (vma) {
599                         vsize += vma->vm_end - vma->vm_start;
600                         vma = vma->vm_next;
601                 }
602                 up_read(&current->mm->mmap_sem);
603         }
604
605         spin_lock_irq(&current->sighand->siglock);
606         if (group_dead)
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;
612         }
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(&current->sighand->siglock);
625 }
626
627 static void acct_process_in_ns(struct pid_namespace *ns)
628 {
629         struct file *file = NULL;
630         struct bsd_acct_struct *acct;
631
632         acct = ns->bacct;
633         /*
634          * accelerate the common fastpath:
635          */
636         if (!acct || !acct->file)
637                 return;
638
639         spin_lock(&acct_lock);
640         file = acct->file;
641         if (unlikely(!file)) {
642                 spin_unlock(&acct_lock);
643                 return;
644         }
645         get_file(file);
646         spin_unlock(&acct_lock);
647
648         do_acct_process(acct, ns, file);
649         fput(file);
650 }
651
652 /**
653  * acct_process - now just a wrapper around acct_process_in_ns,
654  * which in turn is a wrapper around do_acct_process.
655  *
656  * handles process accounting for an exiting task
657  */
658 void acct_process(void)
659 {
660         struct pid_namespace *ns;
661
662         /*
663          * This loop is safe lockless, since current is still
664          * alive and holds its namespace, which in turn holds
665          * its parent.
666          */
667         for (ns = task_active_pid_ns(current); ns != NULL; ns = ns->parent)
668                 acct_process_in_ns(ns);
669 }