acct.c 16 KB

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