1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * linux/kernel/acct.c
4 *
5 * BSD Process Accounting for Linux
6 *
7 * Author: Marco van Wieringen <mvw@planets.elm.net>
8 *
9 * Some code based on ideas and code from:
10 * Thomas K. Dyas <tdyas@eden.rutgers.edu>
11 *
12 * This file implements BSD-style process accounting. Whenever any
13 * process exits, an accounting record of type "struct acct" is
14 * written to the file specified with the acct() system call. It is
15 * up to user-level programs to do useful things with the accounting
16 * log. The kernel just provides the raw accounting information.
17 *
18 * (C) Copyright 1995 - 1997 Marco van Wieringen - ELM Consultancy B.V.
19 *
20 * Plugged two leaks. 1) It didn't return acct_file into the free_filps if
21 * the file happened to be read-only. 2) If the accounting was suspended
22 * due to the lack of space it happily allowed to reopen it and completely
23 * lost the old acct_file. 3/10/98, Al Viro.
24 *
25 * Now we silently close acct_file on attempt to reopen. Cleaned sys_acct().
26 * XTerms and EMACS are manifestations of pure evil. 21/10/98, AV.
27 *
28 * Fixed a nasty interaction with sys_umount(). If the accounting
29 * was suspeneded we failed to stop it on umount(). Messy.
30 * Another one: remount to readonly didn't stop accounting.
31 * Question: what should we do if we have CAP_SYS_ADMIN but not
32 * CAP_SYS_PACCT? Current code does the following: umount returns -EBUSY
33 * unless we are messing with the root. In that case we are getting a
34 * real mess with do_remount_sb(). 9/11/98, AV.
35 *
36 * Fixed a bunch of races (and pair of leaks). Probably not the best way,
37 * but this one obviously doesn't introduce deadlocks. Later. BTW, found
38 * one race (and leak) in BSD implementation.
39 * OK, that's better. ANOTHER race and leak in BSD variant. There always
40 * is one more bug... 10/11/98, AV.
41 *
42 * Oh, fsck... Oopsable SMP race in do_process_acct() - we must hold
43 * ->mmap_lock to walk the vma list of current->mm. Nasty, since it leaks
44 * a struct file opened for write. Fixed. 2/6/2000, AV.
45 */
46
47 #include <linux/mm.h>
48 #include <linux/slab.h>
49 #include <linux/acct.h>
50 #include <linux/capability.h>
51 #include <linux/file.h>
52 #include <linux/tty.h>
53 #include <linux/security.h>
54 #include <linux/vfs.h>
55 #include <linux/jiffies.h>
56 #include <linux/times.h>
57 #include <linux/syscalls.h>
58 #include <linux/mount.h>
59 #include <linux/uaccess.h>
60 #include <linux/sched/cputime.h>
61
62 #include <asm/div64.h>
63 #include <linux/pid_namespace.h>
64 #include <linux/fs_pin.h>
65
66 /*
67 * These constants control the amount of freespace that suspend and
68 * resume the process accounting system, and the time delay between
69 * each check.
70 * Turned into sysctl-controllable parameters. AV, 12/11/98
71 */
72
73 static int acct_parm[3] = {4, 2, 30};
74 #define RESUME (acct_parm[0]) /* >foo% free space - resume */
75 #define SUSPEND (acct_parm[1]) /* <foo% free space - suspend */
76 #define ACCT_TIMEOUT (acct_parm[2]) /* foo second timeout between checks */
77
78 #ifdef CONFIG_SYSCTL
79 static struct ctl_table kern_acct_table[] = {
80 {
81 .procname = "acct",
82 .data = &acct_parm,
83 .maxlen = 3*sizeof(int),
84 .mode = 0644,
85 .proc_handler = proc_dointvec,
86 },
87 { }
88 };
89
kernel_acct_sysctls_init(void)90 static __init int kernel_acct_sysctls_init(void)
91 {
92 register_sysctl_init("kernel", kern_acct_table);
93 return 0;
94 }
95 late_initcall(kernel_acct_sysctls_init);
96 #endif /* CONFIG_SYSCTL */
97
98 /*
99 * External references and all of the globals.
100 */
101
102 struct bsd_acct_struct {
103 struct fs_pin pin;
104 atomic_long_t count;
105 struct rcu_head rcu;
106 struct mutex lock;
107 bool active;
108 bool check_space;
109 unsigned long needcheck;
110 struct file *file;
111 struct pid_namespace *ns;
112 struct work_struct work;
113 struct completion done;
114 acct_t ac;
115 };
116
117 static void fill_ac(struct bsd_acct_struct *acct);
118 static void acct_write_process(struct bsd_acct_struct *acct);
119
120 /*
121 * Check the amount of free space and suspend/resume accordingly.
122 */
check_free_space(struct bsd_acct_struct * acct)123 static bool check_free_space(struct bsd_acct_struct *acct)
124 {
125 struct kstatfs sbuf;
126
127 if (!acct->check_space)
128 return acct->active;
129
130 /* May block */
131 if (vfs_statfs(&acct->file->f_path, &sbuf))
132 return acct->active;
133
134 if (acct->active) {
135 u64 suspend = sbuf.f_blocks * SUSPEND;
136 do_div(suspend, 100);
137 if (sbuf.f_bavail <= suspend) {
138 acct->active = false;
139 pr_info("Process accounting paused\n");
140 }
141 } else {
142 u64 resume = sbuf.f_blocks * RESUME;
143 do_div(resume, 100);
144 if (sbuf.f_bavail >= resume) {
145 acct->active = true;
146 pr_info("Process accounting resumed\n");
147 }
148 }
149
150 acct->needcheck = jiffies + ACCT_TIMEOUT*HZ;
151 return acct->active;
152 }
153
acct_put(struct bsd_acct_struct * p)154 static void acct_put(struct bsd_acct_struct *p)
155 {
156 if (atomic_long_dec_and_test(&p->count))
157 kfree_rcu(p, rcu);
158 }
159
to_acct(struct fs_pin * p)160 static inline struct bsd_acct_struct *to_acct(struct fs_pin *p)
161 {
162 return p ? container_of(p, struct bsd_acct_struct, pin) : NULL;
163 }
164
acct_get(struct pid_namespace * ns)165 static struct bsd_acct_struct *acct_get(struct pid_namespace *ns)
166 {
167 struct bsd_acct_struct *res;
168 again:
169 smp_rmb();
170 rcu_read_lock();
171 res = to_acct(READ_ONCE(ns->bacct));
172 if (!res) {
173 rcu_read_unlock();
174 return NULL;
175 }
176 if (!atomic_long_inc_not_zero(&res->count)) {
177 rcu_read_unlock();
178 cpu_relax();
179 goto again;
180 }
181 rcu_read_unlock();
182 mutex_lock(&res->lock);
183 if (res != to_acct(READ_ONCE(ns->bacct))) {
184 mutex_unlock(&res->lock);
185 acct_put(res);
186 goto again;
187 }
188 return res;
189 }
190
acct_pin_kill(struct fs_pin * pin)191 static void acct_pin_kill(struct fs_pin *pin)
192 {
193 struct bsd_acct_struct *acct = to_acct(pin);
194 mutex_lock(&acct->lock);
195 /*
196 * Fill the accounting struct with the exiting task's info
197 * before punting to the workqueue.
198 */
199 fill_ac(acct);
200 schedule_work(&acct->work);
201 wait_for_completion(&acct->done);
202 cmpxchg(&acct->ns->bacct, pin, NULL);
203 mutex_unlock(&acct->lock);
204 pin_remove(pin);
205 acct_put(acct);
206 }
207
close_work(struct work_struct * work)208 static void close_work(struct work_struct *work)
209 {
210 struct bsd_acct_struct *acct = container_of(work, struct bsd_acct_struct, work);
211 struct file *file = acct->file;
212
213 /* We were fired by acct_pin_kill() which holds acct->lock. */
214 acct_write_process(acct);
215 if (file->f_op->flush)
216 file->f_op->flush(file, NULL);
217 __fput_sync(file);
218 complete(&acct->done);
219 }
220
acct_on(struct filename * pathname)221 static int acct_on(struct filename *pathname)
222 {
223 struct file *file;
224 struct vfsmount *mnt, *internal;
225 struct pid_namespace *ns = task_active_pid_ns(current);
226 struct bsd_acct_struct *acct;
227 struct fs_pin *old;
228 int err;
229
230 acct = kzalloc(sizeof(struct bsd_acct_struct), GFP_KERNEL);
231 if (!acct)
232 return -ENOMEM;
233
234 /* Difference from BSD - they don't do O_APPEND */
235 file = file_open_name(pathname, O_WRONLY|O_APPEND|O_LARGEFILE, 0);
236 if (IS_ERR(file)) {
237 kfree(acct);
238 return PTR_ERR(file);
239 }
240
241 if (!S_ISREG(file_inode(file)->i_mode)) {
242 kfree(acct);
243 filp_close(file, NULL);
244 return -EACCES;
245 }
246
247 /* Exclude kernel kernel internal filesystems. */
248 if (file_inode(file)->i_sb->s_flags & (SB_NOUSER | SB_KERNMOUNT)) {
249 kfree(acct);
250 filp_close(file, NULL);
251 return -EINVAL;
252 }
253
254 /* Exclude procfs and sysfs. */
255 if (file_inode(file)->i_sb->s_iflags & SB_I_USERNS_VISIBLE) {
256 kfree(acct);
257 filp_close(file, NULL);
258 return -EINVAL;
259 }
260
261 if (!(file->f_mode & FMODE_CAN_WRITE)) {
262 kfree(acct);
263 filp_close(file, NULL);
264 return -EIO;
265 }
266 internal = mnt_clone_internal(&file->f_path);
267 if (IS_ERR(internal)) {
268 kfree(acct);
269 filp_close(file, NULL);
270 return PTR_ERR(internal);
271 }
272 err = __mnt_want_write(internal);
273 if (err) {
274 mntput(internal);
275 kfree(acct);
276 filp_close(file, NULL);
277 return err;
278 }
279 mnt = file->f_path.mnt;
280 file->f_path.mnt = internal;
281
282 atomic_long_set(&acct->count, 1);
283 init_fs_pin(&acct->pin, acct_pin_kill);
284 acct->file = file;
285 acct->needcheck = jiffies;
286 acct->ns = ns;
287 mutex_init(&acct->lock);
288 INIT_WORK(&acct->work, close_work);
289 init_completion(&acct->done);
290 mutex_lock_nested(&acct->lock, 1); /* nobody has seen it yet */
291 pin_insert(&acct->pin, mnt);
292
293 rcu_read_lock();
294 old = xchg(&ns->bacct, &acct->pin);
295 mutex_unlock(&acct->lock);
296 pin_kill(old);
297 __mnt_drop_write(mnt);
298 mntput(mnt);
299 return 0;
300 }
301
302 static DEFINE_MUTEX(acct_on_mutex);
303
304 /**
305 * sys_acct - enable/disable process accounting
306 * @name: file name for accounting records or NULL to shutdown accounting
307 *
308 * sys_acct() is the only system call needed to implement process
309 * accounting. It takes the name of the file where accounting records
310 * should be written. If the filename is NULL, accounting will be
311 * shutdown.
312 *
313 * Returns: 0 for success or negative errno values for failure.
314 */
SYSCALL_DEFINE1(acct,const char __user *,name)315 SYSCALL_DEFINE1(acct, const char __user *, name)
316 {
317 int error = 0;
318
319 if (!capable(CAP_SYS_PACCT))
320 return -EPERM;
321
322 if (name) {
323 struct filename *tmp = getname(name);
324
325 if (IS_ERR(tmp))
326 return PTR_ERR(tmp);
327 mutex_lock(&acct_on_mutex);
328 error = acct_on(tmp);
329 mutex_unlock(&acct_on_mutex);
330 putname(tmp);
331 } else {
332 rcu_read_lock();
333 pin_kill(task_active_pid_ns(current)->bacct);
334 }
335
336 return error;
337 }
338
acct_exit_ns(struct pid_namespace * ns)339 void acct_exit_ns(struct pid_namespace *ns)
340 {
341 rcu_read_lock();
342 pin_kill(ns->bacct);
343 }
344
345 /*
346 * encode an u64 into a comp_t
347 *
348 * This routine has been adopted from the encode_comp_t() function in
349 * the kern_acct.c file of the FreeBSD operating system. The encoding
350 * is a 13-bit fraction with a 3-bit (base 8) exponent.
351 */
352
353 #define MANTSIZE 13 /* 13 bit mantissa. */
354 #define EXPSIZE 3 /* Base 8 (3 bit) exponent. */
355 #define MAXFRACT ((1 << MANTSIZE) - 1) /* Maximum fractional value. */
356
encode_comp_t(u64 value)357 static comp_t encode_comp_t(u64 value)
358 {
359 int exp, rnd;
360
361 exp = rnd = 0;
362 while (value > MAXFRACT) {
363 rnd = value & (1 << (EXPSIZE - 1)); /* Round up? */
364 value >>= EXPSIZE; /* Base 8 exponent == 3 bit shift. */
365 exp++;
366 }
367
368 /*
369 * If we need to round up, do it (and handle overflow correctly).
370 */
371 if (rnd && (++value > MAXFRACT)) {
372 value >>= EXPSIZE;
373 exp++;
374 }
375
376 if (exp > (((comp_t) ~0U) >> MANTSIZE))
377 return (comp_t) ~0U;
378 /*
379 * Clean it up and polish it off.
380 */
381 exp <<= MANTSIZE; /* Shift the exponent into place */
382 exp += value; /* and add on the mantissa. */
383 return exp;
384 }
385
386 #if ACCT_VERSION == 1 || ACCT_VERSION == 2
387 /*
388 * encode an u64 into a comp2_t (24 bits)
389 *
390 * Format: 5 bit base 2 exponent, 20 bits mantissa.
391 * The leading bit of the mantissa is not stored, but implied for
392 * non-zero exponents.
393 * Largest encodable value is 50 bits.
394 */
395
396 #define MANTSIZE2 20 /* 20 bit mantissa. */
397 #define EXPSIZE2 5 /* 5 bit base 2 exponent. */
398 #define MAXFRACT2 ((1ul << MANTSIZE2) - 1) /* Maximum fractional value. */
399 #define MAXEXP2 ((1 << EXPSIZE2) - 1) /* Maximum exponent. */
400
encode_comp2_t(u64 value)401 static comp2_t encode_comp2_t(u64 value)
402 {
403 int exp, rnd;
404
405 exp = (value > (MAXFRACT2>>1));
406 rnd = 0;
407 while (value > MAXFRACT2) {
408 rnd = value & 1;
409 value >>= 1;
410 exp++;
411 }
412
413 /*
414 * If we need to round up, do it (and handle overflow correctly).
415 */
416 if (rnd && (++value > MAXFRACT2)) {
417 value >>= 1;
418 exp++;
419 }
420
421 if (exp > MAXEXP2) {
422 /* Overflow. Return largest representable number instead. */
423 return (1ul << (MANTSIZE2+EXPSIZE2-1)) - 1;
424 } else {
425 return (value & (MAXFRACT2>>1)) | (exp << (MANTSIZE2-1));
426 }
427 }
428 #elif ACCT_VERSION == 3
429 /*
430 * encode an u64 into a 32 bit IEEE float
431 */
encode_float(u64 value)432 static u32 encode_float(u64 value)
433 {
434 unsigned exp = 190;
435 unsigned u;
436
437 if (value == 0)
438 return 0;
439 while ((s64)value > 0) {
440 value <<= 1;
441 exp--;
442 }
443 u = (u32)(value >> 40) & 0x7fffffu;
444 return u | (exp << 23);
445 }
446 #endif
447
448 /*
449 * Write an accounting entry for an exiting process
450 *
451 * The acct_process() call is the workhorse of the process
452 * accounting system. The struct acct is built here and then written
453 * into the accounting file. This function should only be called from
454 * do_exit() or when switching to a different output file.
455 */
456
fill_ac(struct bsd_acct_struct * acct)457 static void fill_ac(struct bsd_acct_struct *acct)
458 {
459 struct pacct_struct *pacct = ¤t->signal->pacct;
460 struct file *file = acct->file;
461 acct_t *ac = &acct->ac;
462 u64 elapsed, run_time;
463 time64_t btime;
464 struct tty_struct *tty;
465
466 lockdep_assert_held(&acct->lock);
467
468 if (time_is_after_jiffies(acct->needcheck)) {
469 acct->check_space = false;
470
471 /* Don't fill in @ac if nothing will be written. */
472 if (!acct->active)
473 return;
474 } else {
475 acct->check_space = true;
476 }
477
478 /*
479 * Fill the accounting struct with the needed info as recorded
480 * by the different kernel functions.
481 */
482 memset(ac, 0, sizeof(acct_t));
483
484 ac->ac_version = ACCT_VERSION | ACCT_BYTEORDER;
485 strscpy(ac->ac_comm, current->comm, sizeof(ac->ac_comm));
486
487 /* calculate run_time in nsec*/
488 run_time = ktime_get_ns();
489 run_time -= current->group_leader->start_time;
490 /* convert nsec -> AHZ */
491 elapsed = nsec_to_AHZ(run_time);
492 #if ACCT_VERSION == 3
493 ac->ac_etime = encode_float(elapsed);
494 #else
495 ac->ac_etime = encode_comp_t(elapsed < (unsigned long) -1l ?
496 (unsigned long) elapsed : (unsigned long) -1l);
497 #endif
498 #if ACCT_VERSION == 1 || ACCT_VERSION == 2
499 {
500 /* new enlarged etime field */
501 comp2_t etime = encode_comp2_t(elapsed);
502
503 ac->ac_etime_hi = etime >> 16;
504 ac->ac_etime_lo = (u16) etime;
505 }
506 #endif
507 do_div(elapsed, AHZ);
508 btime = ktime_get_real_seconds() - elapsed;
509 ac->ac_btime = clamp_t(time64_t, btime, 0, U32_MAX);
510 #if ACCT_VERSION == 2
511 ac->ac_ahz = AHZ;
512 #endif
513
514 spin_lock_irq(¤t->sighand->siglock);
515 tty = current->signal->tty; /* Safe as we hold the siglock */
516 ac->ac_tty = tty ? old_encode_dev(tty_devnum(tty)) : 0;
517 ac->ac_utime = encode_comp_t(nsec_to_AHZ(pacct->ac_utime));
518 ac->ac_stime = encode_comp_t(nsec_to_AHZ(pacct->ac_stime));
519 ac->ac_flag = pacct->ac_flag;
520 ac->ac_mem = encode_comp_t(pacct->ac_mem);
521 ac->ac_minflt = encode_comp_t(pacct->ac_minflt);
522 ac->ac_majflt = encode_comp_t(pacct->ac_majflt);
523 ac->ac_exitcode = pacct->ac_exitcode;
524 spin_unlock_irq(¤t->sighand->siglock);
525
526 /* we really need to bite the bullet and change layout */
527 ac->ac_uid = from_kuid_munged(file->f_cred->user_ns, current_uid());
528 ac->ac_gid = from_kgid_munged(file->f_cred->user_ns, current_gid());
529 #if ACCT_VERSION == 1 || ACCT_VERSION == 2
530 /* backward-compatible 16 bit fields */
531 ac->ac_uid16 = ac->ac_uid;
532 ac->ac_gid16 = ac->ac_gid;
533 #elif ACCT_VERSION == 3
534 {
535 struct pid_namespace *ns = acct->ns;
536
537 ac->ac_pid = task_tgid_nr_ns(current, ns);
538 rcu_read_lock();
539 ac->ac_ppid = task_tgid_nr_ns(rcu_dereference(current->real_parent), ns);
540 rcu_read_unlock();
541 }
542 #endif
543 }
544
acct_write_process(struct bsd_acct_struct * acct)545 static void acct_write_process(struct bsd_acct_struct *acct)
546 {
547 struct file *file = acct->file;
548 const struct cred *cred;
549 acct_t *ac = &acct->ac;
550
551 /* Perform file operations on behalf of whoever enabled accounting */
552 cred = override_creds(file->f_cred);
553
554 /*
555 * First check to see if there is enough free_space to continue
556 * the process accounting system. Then get freeze protection. If
557 * the fs is frozen, just skip the write as we could deadlock
558 * the system otherwise.
559 */
560 if (check_free_space(acct) && file_start_write_trylock(file)) {
561 /* it's been opened O_APPEND, so position is irrelevant */
562 loff_t pos = 0;
563 __kernel_write(file, ac, sizeof(acct_t), &pos);
564 file_end_write(file);
565 }
566
567 revert_creds(cred);
568 }
569
do_acct_process(struct bsd_acct_struct * acct)570 static void do_acct_process(struct bsd_acct_struct *acct)
571 {
572 unsigned long flim;
573
574 /* Accounting records are not subject to resource limits. */
575 flim = rlimit(RLIMIT_FSIZE);
576 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
577 fill_ac(acct);
578 acct_write_process(acct);
579 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = flim;
580 }
581
582 /**
583 * acct_collect - collect accounting information into pacct_struct
584 * @exitcode: task exit code
585 * @group_dead: not 0, if this thread is the last one in the process.
586 */
acct_collect(long exitcode,int group_dead)587 void acct_collect(long exitcode, int group_dead)
588 {
589 struct pacct_struct *pacct = ¤t->signal->pacct;
590 u64 utime, stime;
591 unsigned long vsize = 0;
592
593 if (group_dead && current->mm) {
594 struct mm_struct *mm = current->mm;
595 VMA_ITERATOR(vmi, mm, 0);
596 struct vm_area_struct *vma;
597
598 mmap_read_lock(mm);
599 for_each_vma(vmi, vma)
600 vsize += vma->vm_end - vma->vm_start;
601 mmap_read_unlock(mm);
602 }
603
604 spin_lock_irq(¤t->sighand->siglock);
605 if (group_dead)
606 pacct->ac_mem = vsize / 1024;
607 if (thread_group_leader(current)) {
608 pacct->ac_exitcode = exitcode;
609 if (current->flags & PF_FORKNOEXEC)
610 pacct->ac_flag |= AFORK;
611 }
612 if (current->flags & PF_SUPERPRIV)
613 pacct->ac_flag |= ASU;
614 if (current->flags & PF_DUMPCORE)
615 pacct->ac_flag |= ACORE;
616 if (current->flags & PF_SIGNALED)
617 pacct->ac_flag |= AXSIG;
618
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);
625 }
626
slow_acct_process(struct pid_namespace * ns)627 static void slow_acct_process(struct pid_namespace *ns)
628 {
629 for ( ; ns; ns = ns->parent) {
630 struct bsd_acct_struct *acct = acct_get(ns);
631 if (acct) {
632 do_acct_process(acct);
633 mutex_unlock(&acct->lock);
634 acct_put(acct);
635 }
636 }
637 }
638
639 /**
640 * acct_process - handles process accounting for an exiting task
641 */
acct_process(void)642 void acct_process(void)
643 {
644 struct pid_namespace *ns;
645
646 /*
647 * This loop is safe lockless, since current is still
648 * alive and holds its namespace, which in turn holds
649 * its parent.
650 */
651 for (ns = task_active_pid_ns(current); ns != NULL; ns = ns->parent) {
652 if (ns->bacct)
653 break;
654 }
655 if (unlikely(ns))
656 slow_acct_process(ns);
657 }
658