xref: /linux-6.15/kernel/acct.c (revision 56d5f3eb)
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 <[email protected]>
8  *
9  *  Some code based on ideas and code from:
10  *  Thomas K. Dyas <[email protected]>
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 const 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 static __init int kernel_acct_sysctls_init(void)
90 {
91 	register_sysctl_init("kernel", kern_acct_table);
92 	return 0;
93 }
94 late_initcall(kernel_acct_sysctls_init);
95 #endif /* CONFIG_SYSCTL */
96 
97 /*
98  * External references and all of the globals.
99  */
100 
101 struct bsd_acct_struct {
102 	struct fs_pin		pin;
103 	atomic_long_t		count;
104 	struct rcu_head		rcu;
105 	struct mutex		lock;
106 	bool			active;
107 	bool			check_space;
108 	unsigned long		needcheck;
109 	struct file		*file;
110 	struct pid_namespace	*ns;
111 	struct work_struct	work;
112 	struct completion	done;
113 	acct_t			ac;
114 };
115 
116 static void fill_ac(struct bsd_acct_struct *acct);
117 static void acct_write_process(struct bsd_acct_struct *acct);
118 
119 /*
120  * Check the amount of free space and suspend/resume accordingly.
121  */
122 static bool check_free_space(struct bsd_acct_struct *acct)
123 {
124 	struct kstatfs sbuf;
125 
126 	if (!acct->check_space)
127 		return acct->active;
128 
129 	/* May block */
130 	if (vfs_statfs(&acct->file->f_path, &sbuf))
131 		return acct->active;
132 
133 	if (acct->active) {
134 		u64 suspend = sbuf.f_blocks * SUSPEND;
135 		do_div(suspend, 100);
136 		if (sbuf.f_bavail <= suspend) {
137 			acct->active = false;
138 			pr_info("Process accounting paused\n");
139 		}
140 	} else {
141 		u64 resume = sbuf.f_blocks * RESUME;
142 		do_div(resume, 100);
143 		if (sbuf.f_bavail >= resume) {
144 			acct->active = true;
145 			pr_info("Process accounting resumed\n");
146 		}
147 	}
148 
149 	acct->needcheck = jiffies + ACCT_TIMEOUT*HZ;
150 	return acct->active;
151 }
152 
153 static void acct_put(struct bsd_acct_struct *p)
154 {
155 	if (atomic_long_dec_and_test(&p->count))
156 		kfree_rcu(p, rcu);
157 }
158 
159 static inline struct bsd_acct_struct *to_acct(struct fs_pin *p)
160 {
161 	return p ? container_of(p, struct bsd_acct_struct, pin) : NULL;
162 }
163 
164 static struct bsd_acct_struct *acct_get(struct pid_namespace *ns)
165 {
166 	struct bsd_acct_struct *res;
167 again:
168 	smp_rmb();
169 	rcu_read_lock();
170 	res = to_acct(READ_ONCE(ns->bacct));
171 	if (!res) {
172 		rcu_read_unlock();
173 		return NULL;
174 	}
175 	if (!atomic_long_inc_not_zero(&res->count)) {
176 		rcu_read_unlock();
177 		cpu_relax();
178 		goto again;
179 	}
180 	rcu_read_unlock();
181 	mutex_lock(&res->lock);
182 	if (res != to_acct(READ_ONCE(ns->bacct))) {
183 		mutex_unlock(&res->lock);
184 		acct_put(res);
185 		goto again;
186 	}
187 	return res;
188 }
189 
190 static void acct_pin_kill(struct fs_pin *pin)
191 {
192 	struct bsd_acct_struct *acct = to_acct(pin);
193 	mutex_lock(&acct->lock);
194 	/*
195 	 * Fill the accounting struct with the exiting task's info
196 	 * before punting to the workqueue.
197 	 */
198 	fill_ac(acct);
199 	schedule_work(&acct->work);
200 	wait_for_completion(&acct->done);
201 	cmpxchg(&acct->ns->bacct, pin, NULL);
202 	mutex_unlock(&acct->lock);
203 	pin_remove(pin);
204 	acct_put(acct);
205 }
206 
207 static void close_work(struct work_struct *work)
208 {
209 	struct bsd_acct_struct *acct = container_of(work, struct bsd_acct_struct, work);
210 	struct file *file = acct->file;
211 
212 	/* We were fired by acct_pin_kill() which holds acct->lock. */
213 	acct_write_process(acct);
214 	if (file->f_op->flush)
215 		file->f_op->flush(file, NULL);
216 	__fput_sync(file);
217 	complete(&acct->done);
218 }
219 
220 static int acct_on(struct filename *pathname)
221 {
222 	struct file *file;
223 	struct vfsmount *mnt, *internal;
224 	struct pid_namespace *ns = task_active_pid_ns(current);
225 	struct bsd_acct_struct *acct;
226 	struct fs_pin *old;
227 	int err;
228 
229 	acct = kzalloc(sizeof(struct bsd_acct_struct), GFP_KERNEL);
230 	if (!acct)
231 		return -ENOMEM;
232 
233 	/* Difference from BSD - they don't do O_APPEND */
234 	file = file_open_name(pathname, O_WRONLY|O_APPEND|O_LARGEFILE, 0);
235 	if (IS_ERR(file)) {
236 		kfree(acct);
237 		return PTR_ERR(file);
238 	}
239 
240 	if (!S_ISREG(file_inode(file)->i_mode)) {
241 		kfree(acct);
242 		filp_close(file, NULL);
243 		return -EACCES;
244 	}
245 
246 	if (!(file->f_mode & FMODE_CAN_WRITE)) {
247 		kfree(acct);
248 		filp_close(file, NULL);
249 		return -EIO;
250 	}
251 	internal = mnt_clone_internal(&file->f_path);
252 	if (IS_ERR(internal)) {
253 		kfree(acct);
254 		filp_close(file, NULL);
255 		return PTR_ERR(internal);
256 	}
257 	err = mnt_get_write_access(internal);
258 	if (err) {
259 		mntput(internal);
260 		kfree(acct);
261 		filp_close(file, NULL);
262 		return err;
263 	}
264 	mnt = file->f_path.mnt;
265 	file->f_path.mnt = internal;
266 
267 	atomic_long_set(&acct->count, 1);
268 	init_fs_pin(&acct->pin, acct_pin_kill);
269 	acct->file = file;
270 	acct->needcheck = jiffies;
271 	acct->ns = ns;
272 	mutex_init(&acct->lock);
273 	INIT_WORK(&acct->work, close_work);
274 	init_completion(&acct->done);
275 	mutex_lock_nested(&acct->lock, 1);	/* nobody has seen it yet */
276 	pin_insert(&acct->pin, mnt);
277 
278 	rcu_read_lock();
279 	old = xchg(&ns->bacct, &acct->pin);
280 	mutex_unlock(&acct->lock);
281 	pin_kill(old);
282 	mnt_put_write_access(mnt);
283 	mntput(mnt);
284 	return 0;
285 }
286 
287 static DEFINE_MUTEX(acct_on_mutex);
288 
289 /**
290  * sys_acct - enable/disable process accounting
291  * @name: file name for accounting records or NULL to shutdown accounting
292  *
293  * sys_acct() is the only system call needed to implement process
294  * accounting. It takes the name of the file where accounting records
295  * should be written. If the filename is NULL, accounting will be
296  * shutdown.
297  *
298  * Returns: 0 for success or negative errno values for failure.
299  */
300 SYSCALL_DEFINE1(acct, const char __user *, name)
301 {
302 	int error = 0;
303 
304 	if (!capable(CAP_SYS_PACCT))
305 		return -EPERM;
306 
307 	if (name) {
308 		struct filename *tmp = getname(name);
309 
310 		if (IS_ERR(tmp))
311 			return PTR_ERR(tmp);
312 		mutex_lock(&acct_on_mutex);
313 		error = acct_on(tmp);
314 		mutex_unlock(&acct_on_mutex);
315 		putname(tmp);
316 	} else {
317 		rcu_read_lock();
318 		pin_kill(task_active_pid_ns(current)->bacct);
319 	}
320 
321 	return error;
322 }
323 
324 void acct_exit_ns(struct pid_namespace *ns)
325 {
326 	rcu_read_lock();
327 	pin_kill(ns->bacct);
328 }
329 
330 /*
331  *  encode an u64 into a comp_t
332  *
333  *  This routine has been adopted from the encode_comp_t() function in
334  *  the kern_acct.c file of the FreeBSD operating system. The encoding
335  *  is a 13-bit fraction with a 3-bit (base 8) exponent.
336  */
337 
338 #define	MANTSIZE	13			/* 13 bit mantissa. */
339 #define	EXPSIZE		3			/* Base 8 (3 bit) exponent. */
340 #define	MAXFRACT	((1 << MANTSIZE) - 1)	/* Maximum fractional value. */
341 
342 static comp_t encode_comp_t(u64 value)
343 {
344 	int exp, rnd;
345 
346 	exp = rnd = 0;
347 	while (value > MAXFRACT) {
348 		rnd = value & (1 << (EXPSIZE - 1));	/* Round up? */
349 		value >>= EXPSIZE;	/* Base 8 exponent == 3 bit shift. */
350 		exp++;
351 	}
352 
353 	/*
354 	 * If we need to round up, do it (and handle overflow correctly).
355 	 */
356 	if (rnd && (++value > MAXFRACT)) {
357 		value >>= EXPSIZE;
358 		exp++;
359 	}
360 
361 	if (exp > (((comp_t) ~0U) >> MANTSIZE))
362 		return (comp_t) ~0U;
363 	/*
364 	 * Clean it up and polish it off.
365 	 */
366 	exp <<= MANTSIZE;		/* Shift the exponent into place */
367 	exp += value;			/* and add on the mantissa. */
368 	return exp;
369 }
370 
371 #if ACCT_VERSION == 1 || ACCT_VERSION == 2
372 /*
373  * encode an u64 into a comp2_t (24 bits)
374  *
375  * Format: 5 bit base 2 exponent, 20 bits mantissa.
376  * The leading bit of the mantissa is not stored, but implied for
377  * non-zero exponents.
378  * Largest encodable value is 50 bits.
379  */
380 
381 #define MANTSIZE2       20                      /* 20 bit mantissa. */
382 #define EXPSIZE2        5                       /* 5 bit base 2 exponent. */
383 #define MAXFRACT2       ((1ul << MANTSIZE2) - 1) /* Maximum fractional value. */
384 #define MAXEXP2         ((1 << EXPSIZE2) - 1)    /* Maximum exponent. */
385 
386 static comp2_t encode_comp2_t(u64 value)
387 {
388 	int exp, rnd;
389 
390 	exp = (value > (MAXFRACT2>>1));
391 	rnd = 0;
392 	while (value > MAXFRACT2) {
393 		rnd = value & 1;
394 		value >>= 1;
395 		exp++;
396 	}
397 
398 	/*
399 	 * If we need to round up, do it (and handle overflow correctly).
400 	 */
401 	if (rnd && (++value > MAXFRACT2)) {
402 		value >>= 1;
403 		exp++;
404 	}
405 
406 	if (exp > MAXEXP2) {
407 		/* Overflow. Return largest representable number instead. */
408 		return (1ul << (MANTSIZE2+EXPSIZE2-1)) - 1;
409 	} else {
410 		return (value & (MAXFRACT2>>1)) | (exp << (MANTSIZE2-1));
411 	}
412 }
413 #elif ACCT_VERSION == 3
414 /*
415  * encode an u64 into a 32 bit IEEE float
416  */
417 static u32 encode_float(u64 value)
418 {
419 	unsigned exp = 190;
420 	unsigned u;
421 
422 	if (value == 0)
423 		return 0;
424 	while ((s64)value > 0) {
425 		value <<= 1;
426 		exp--;
427 	}
428 	u = (u32)(value >> 40) & 0x7fffffu;
429 	return u | (exp << 23);
430 }
431 #endif
432 
433 /*
434  *  Write an accounting entry for an exiting process
435  *
436  *  The acct_process() call is the workhorse of the process
437  *  accounting system. The struct acct is built here and then written
438  *  into the accounting file. This function should only be called from
439  *  do_exit() or when switching to a different output file.
440  */
441 
442 static void fill_ac(struct bsd_acct_struct *acct)
443 {
444 	struct pacct_struct *pacct = &current->signal->pacct;
445 	struct file *file = acct->file;
446 	acct_t *ac = &acct->ac;
447 	u64 elapsed, run_time;
448 	time64_t btime;
449 	struct tty_struct *tty;
450 
451 	lockdep_assert_held(&acct->lock);
452 
453 	if (time_is_after_jiffies(acct->needcheck)) {
454 		acct->check_space = false;
455 
456 		/* Don't fill in @ac if nothing will be written. */
457 		if (!acct->active)
458 			return;
459 	} else {
460 		acct->check_space = true;
461 	}
462 
463 	/*
464 	 * Fill the accounting struct with the needed info as recorded
465 	 * by the different kernel functions.
466 	 */
467 	memset(ac, 0, sizeof(acct_t));
468 
469 	ac->ac_version = ACCT_VERSION | ACCT_BYTEORDER;
470 	strscpy(ac->ac_comm, current->comm, sizeof(ac->ac_comm));
471 
472 	/* calculate run_time in nsec*/
473 	run_time = ktime_get_ns();
474 	run_time -= current->group_leader->start_time;
475 	/* convert nsec -> AHZ */
476 	elapsed = nsec_to_AHZ(run_time);
477 #if ACCT_VERSION == 3
478 	ac->ac_etime = encode_float(elapsed);
479 #else
480 	ac->ac_etime = encode_comp_t(elapsed < (unsigned long) -1l ?
481 				(unsigned long) elapsed : (unsigned long) -1l);
482 #endif
483 #if ACCT_VERSION == 1 || ACCT_VERSION == 2
484 	{
485 		/* new enlarged etime field */
486 		comp2_t etime = encode_comp2_t(elapsed);
487 
488 		ac->ac_etime_hi = etime >> 16;
489 		ac->ac_etime_lo = (u16) etime;
490 	}
491 #endif
492 	do_div(elapsed, AHZ);
493 	btime = ktime_get_real_seconds() - elapsed;
494 	ac->ac_btime = clamp_t(time64_t, btime, 0, U32_MAX);
495 #if ACCT_VERSION == 2
496 	ac->ac_ahz = AHZ;
497 #endif
498 
499 	spin_lock_irq(&current->sighand->siglock);
500 	tty = current->signal->tty;	/* Safe as we hold the siglock */
501 	ac->ac_tty = tty ? old_encode_dev(tty_devnum(tty)) : 0;
502 	ac->ac_utime = encode_comp_t(nsec_to_AHZ(pacct->ac_utime));
503 	ac->ac_stime = encode_comp_t(nsec_to_AHZ(pacct->ac_stime));
504 	ac->ac_flag = pacct->ac_flag;
505 	ac->ac_mem = encode_comp_t(pacct->ac_mem);
506 	ac->ac_minflt = encode_comp_t(pacct->ac_minflt);
507 	ac->ac_majflt = encode_comp_t(pacct->ac_majflt);
508 	ac->ac_exitcode = pacct->ac_exitcode;
509 	spin_unlock_irq(&current->sighand->siglock);
510 
511 	/* we really need to bite the bullet and change layout */
512 	ac->ac_uid = from_kuid_munged(file->f_cred->user_ns, current_uid());
513 	ac->ac_gid = from_kgid_munged(file->f_cred->user_ns, current_gid());
514 #if ACCT_VERSION == 1 || ACCT_VERSION == 2
515 	/* backward-compatible 16 bit fields */
516 	ac->ac_uid16 = ac->ac_uid;
517 	ac->ac_gid16 = ac->ac_gid;
518 #elif ACCT_VERSION == 3
519 	{
520 		struct pid_namespace *ns = acct->ns;
521 
522 		ac->ac_pid = task_tgid_nr_ns(current, ns);
523 		rcu_read_lock();
524 		ac->ac_ppid = task_tgid_nr_ns(rcu_dereference(current->real_parent), ns);
525 		rcu_read_unlock();
526 	}
527 #endif
528 }
529 
530 static void acct_write_process(struct bsd_acct_struct *acct)
531 {
532 	struct file *file = acct->file;
533 	const struct cred *cred;
534 	acct_t *ac = &acct->ac;
535 
536 	/* Perform file operations on behalf of whoever enabled accounting */
537 	cred = override_creds(file->f_cred);
538 
539 	/*
540 	 * First check to see if there is enough free_space to continue
541 	 * the process accounting system. Then get freeze protection. If
542 	 * the fs is frozen, just skip the write as we could deadlock
543 	 * the system otherwise.
544 	 */
545 	if (check_free_space(acct) && file_start_write_trylock(file)) {
546 		/* it's been opened O_APPEND, so position is irrelevant */
547 		loff_t pos = 0;
548 		__kernel_write(file, ac, sizeof(acct_t), &pos);
549 		file_end_write(file);
550 	}
551 
552 	revert_creds(cred);
553 }
554 
555 static void do_acct_process(struct bsd_acct_struct *acct)
556 {
557 	unsigned long flim;
558 
559 	/* Accounting records are not subject to resource limits. */
560 	flim = rlimit(RLIMIT_FSIZE);
561 	current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
562 	fill_ac(acct);
563 	acct_write_process(acct);
564 	current->signal->rlim[RLIMIT_FSIZE].rlim_cur = flim;
565 }
566 
567 /**
568  * acct_collect - collect accounting information into pacct_struct
569  * @exitcode: task exit code
570  * @group_dead: not 0, if this thread is the last one in the process.
571  */
572 void acct_collect(long exitcode, int group_dead)
573 {
574 	struct pacct_struct *pacct = &current->signal->pacct;
575 	u64 utime, stime;
576 	unsigned long vsize = 0;
577 
578 	if (group_dead && current->mm) {
579 		struct mm_struct *mm = current->mm;
580 		VMA_ITERATOR(vmi, mm, 0);
581 		struct vm_area_struct *vma;
582 
583 		mmap_read_lock(mm);
584 		for_each_vma(vmi, vma)
585 			vsize += vma->vm_end - vma->vm_start;
586 		mmap_read_unlock(mm);
587 	}
588 
589 	spin_lock_irq(&current->sighand->siglock);
590 	if (group_dead)
591 		pacct->ac_mem = vsize / 1024;
592 	if (thread_group_leader(current)) {
593 		pacct->ac_exitcode = exitcode;
594 		if (current->flags & PF_FORKNOEXEC)
595 			pacct->ac_flag |= AFORK;
596 	}
597 	if (current->flags & PF_SUPERPRIV)
598 		pacct->ac_flag |= ASU;
599 	if (current->flags & PF_DUMPCORE)
600 		pacct->ac_flag |= ACORE;
601 	if (current->flags & PF_SIGNALED)
602 		pacct->ac_flag |= AXSIG;
603 
604 	task_cputime(current, &utime, &stime);
605 	pacct->ac_utime += utime;
606 	pacct->ac_stime += stime;
607 	pacct->ac_minflt += current->min_flt;
608 	pacct->ac_majflt += current->maj_flt;
609 	spin_unlock_irq(&current->sighand->siglock);
610 }
611 
612 static void slow_acct_process(struct pid_namespace *ns)
613 {
614 	for ( ; ns; ns = ns->parent) {
615 		struct bsd_acct_struct *acct = acct_get(ns);
616 		if (acct) {
617 			do_acct_process(acct);
618 			mutex_unlock(&acct->lock);
619 			acct_put(acct);
620 		}
621 	}
622 }
623 
624 /**
625  * acct_process - handles process accounting for an exiting task
626  */
627 void acct_process(void)
628 {
629 	struct pid_namespace *ns;
630 
631 	/*
632 	 * This loop is safe lockless, since current is still
633 	 * alive and holds its namespace, which in turn holds
634 	 * its parent.
635 	 */
636 	for (ns = task_active_pid_ns(current); ns != NULL; ns = ns->parent) {
637 		if (ns->bacct)
638 			break;
639 	}
640 	if (unlikely(ns))
641 		slow_acct_process(ns);
642 }
643