The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/kern_acct.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 1982, 1986, 1989, 1993
    3  *      The Regents of the University of California.  All rights reserved.
    4  * (c) UNIX System Laboratories, Inc.
    5  * All or some portions of this file are derived from material licensed
    6  * to the University of California by American Telephone and Telegraph
    7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
    8  * the permission of UNIX System Laboratories, Inc.
    9  *
   10  * Copyright (c) 1994 Christopher G. Demetriou
   11  * Copyright (c) 2005 Robert N. M. Watson
   12  *
   13  * Redistribution and use in source and binary forms, with or without
   14  * modification, are permitted provided that the following conditions
   15  * are met:
   16  * 1. Redistributions of source code must retain the above copyright
   17  *    notice, this list of conditions and the following disclaimer.
   18  * 2. Redistributions in binary form must reproduce the above copyright
   19  *    notice, this list of conditions and the following disclaimer in the
   20  *    documentation and/or other materials provided with the distribution.
   21  * 3. All advertising materials mentioning features or use of this software
   22  *    must display the following acknowledgement:
   23  *      This product includes software developed by the University of
   24  *      California, Berkeley and its contributors.
   25  * 4. Neither the name of the University nor the names of its contributors
   26  *    may be used to endorse or promote products derived from this software
   27  *    without specific prior written permission.
   28  *
   29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   39  * SUCH DAMAGE.
   40  *
   41  *      @(#)kern_acct.c 8.1 (Berkeley) 6/14/93
   42  */
   43 
   44 #include <sys/cdefs.h>
   45 __FBSDID("$FreeBSD: releng/6.2/sys/kern/kern_acct.c 164286 2006-11-14 20:42:41Z cvs2svn $");
   46 
   47 #include "opt_mac.h"
   48 
   49 #include <sys/param.h>
   50 #include <sys/systm.h>
   51 #include <sys/acct.h>
   52 #include <sys/fcntl.h>
   53 #include <sys/kernel.h>
   54 #include <sys/kthread.h>
   55 #include <sys/lock.h>
   56 #include <sys/mac.h>
   57 #include <sys/mount.h>
   58 #include <sys/mutex.h>
   59 #include <sys/namei.h>
   60 #include <sys/proc.h>
   61 #include <sys/resourcevar.h>
   62 #include <sys/sched.h>
   63 #include <sys/sx.h>
   64 #include <sys/sysctl.h>
   65 #include <sys/sysent.h>
   66 #include <sys/syslog.h>
   67 #include <sys/sysproto.h>
   68 #include <sys/tty.h>
   69 #include <sys/vnode.h>
   70 
   71 /*
   72  * The routines implemented in this file are described in:
   73  *      Leffler, et al.: The Design and Implementation of the 4.3BSD
   74  *          UNIX Operating System (Addison Welley, 1989)
   75  * on pages 62-63.
   76  *
   77  * Arguably, to simplify accounting operations, this mechanism should
   78  * be replaced by one in which an accounting log file (similar to /dev/klog)
   79  * is read by a user process, etc.  However, that has its own problems.
   80  */
   81 
   82 /*
   83  * Internal accounting functions.
   84  * The former's operation is described in Leffler, et al., and the latter
   85  * was provided by UCB with the 4.4BSD-Lite release
   86  */
   87 static comp_t   encode_comp_t(u_long, u_long);
   88 static void     acctwatch(void);
   89 static void     acct_thread(void *);
   90 static int      acct_disable(struct thread *);
   91 
   92 /*
   93  * Accounting vnode pointer, saved vnode pointer, and flags for each.
   94  * acct_sx protects against changes to the active vnode and credentials
   95  * while accounting records are being committed to disk.
   96  */
   97 static int               acct_suspended;
   98 static struct vnode     *acct_vp;
   99 static struct ucred     *acct_cred;
  100 static int               acct_flags;
  101 static struct sx         acct_sx;
  102 
  103 SX_SYSINIT(acct, &acct_sx, "acct_sx");
  104 
  105 /*
  106  * State of the accounting kthread.
  107  */
  108 static int               acct_state;
  109 
  110 #define ACCT_RUNNING    1       /* Accounting kthread is running. */
  111 #define ACCT_EXITREQ    2       /* Accounting kthread should exit. */
  112 
  113 /*
  114  * Values associated with enabling and disabling accounting
  115  */
  116 static int acctsuspend = 2;     /* stop accounting when < 2% free space left */
  117 SYSCTL_INT(_kern, OID_AUTO, acct_suspend, CTLFLAG_RW,
  118         &acctsuspend, 0, "percentage of free disk space below which accounting stops");
  119 
  120 static int acctresume = 4;      /* resume when free space risen to > 4% */
  121 SYSCTL_INT(_kern, OID_AUTO, acct_resume, CTLFLAG_RW,
  122         &acctresume, 0, "percentage of free disk space above which accounting resumes");
  123 
  124 static int acctchkfreq = 15;    /* frequency (in seconds) to check space */
  125 
  126 static int
  127 sysctl_acct_chkfreq(SYSCTL_HANDLER_ARGS)
  128 {
  129         int error, value;
  130 
  131         /* Write out the old value. */
  132         error = SYSCTL_OUT(req, &acctchkfreq, sizeof(int));
  133         if (error || req->newptr == NULL)
  134                 return (error);
  135 
  136         /* Read in and verify the new value. */
  137         error = SYSCTL_IN(req, &value, sizeof(int));
  138         if (error)
  139                 return (error);
  140         if (value <= 0)
  141                 return (EINVAL);
  142         acctchkfreq = value;
  143         return (0);
  144 }
  145 SYSCTL_PROC(_kern, OID_AUTO, acct_chkfreq, CTLTYPE_INT|CTLFLAG_RW,
  146     &acctchkfreq, 0, sysctl_acct_chkfreq, "I",
  147     "frequency for checking the free space");
  148 
  149 SYSCTL_INT(_kern, OID_AUTO, acct_suspended, CTLFLAG_RD, &acct_suspended, 0,
  150         "Accounting suspended or not");
  151 
  152 /*
  153  * Accounting system call.  Written based on the specification and
  154  * previous implementation done by Mark Tinguely.
  155  *
  156  * MPSAFE
  157  */
  158 int
  159 acct(struct thread *td, struct acct_args *uap)
  160 {
  161         struct nameidata nd;
  162         int error, flags;
  163 
  164         /* Make sure that the caller is root. */
  165         error = suser(td);
  166         if (error)
  167                 return (error);
  168 
  169         /*
  170          * If accounting is to be started to a file, open that file for
  171          * appending and make sure it's a 'normal'.  While we could
  172          * conditionally acquire Giant here, we're actually interacting with
  173          * vnodes from possibly two file systems, making the logic a bit
  174          * complicated.  For now, use Giant unconditionally.
  175          */
  176         mtx_lock(&Giant);
  177         if (uap->path != NULL) {
  178                 NDINIT(&nd, LOOKUP, NOFOLLOW | AUDITVNODE1, UIO_USERSPACE,
  179                     uap->path, td);
  180                 flags = FWRITE | O_APPEND;
  181                 error = vn_open(&nd, &flags, 0, -1);
  182                 if (error)
  183                         goto done;
  184                 NDFREE(&nd, NDF_ONLY_PNBUF);
  185 #ifdef MAC
  186                 error = mac_check_system_acct(td->td_ucred, nd.ni_vp);
  187                 if (error) {
  188                         VOP_UNLOCK(nd.ni_vp, 0, td);
  189                         vn_close(nd.ni_vp, flags, td->td_ucred, td);
  190                         goto done;
  191                 }
  192 #endif
  193                 VOP_UNLOCK(nd.ni_vp, 0, td);
  194                 if (nd.ni_vp->v_type != VREG) {
  195                         vn_close(nd.ni_vp, flags, td->td_ucred, td);
  196                         error = EACCES;
  197                         goto done;
  198                 }
  199 #ifdef MAC
  200         } else {
  201                 error = mac_check_system_acct(td->td_ucred, NULL);
  202                 if (error)
  203                         goto done;
  204 #endif
  205         }
  206 
  207         /*
  208          * Disallow concurrent access to the accounting vnode while we swap
  209          * it out, in order to prevent access after close.
  210          */
  211         sx_xlock(&acct_sx);
  212 
  213         /*
  214          * If accounting was previously enabled, kill the old space-watcher,
  215          * close the file, and (if no new file was specified, leave).  Reset
  216          * the suspended state regardless of whether accounting remains
  217          * enabled.
  218          */
  219         acct_suspended = 0;
  220         if (acct_vp != NULL)
  221                 error = acct_disable(td);
  222         if (uap->path == NULL) {
  223                 if (acct_state & ACCT_RUNNING) {
  224                         acct_state |= ACCT_EXITREQ;
  225                         wakeup(&acct_state);
  226                 }
  227                 sx_xunlock(&acct_sx);
  228                 goto done;
  229         }
  230 
  231         /*
  232          * Save the new accounting file vnode, and schedule the new
  233          * free space watcher.
  234          */
  235         acct_vp = nd.ni_vp;
  236         acct_cred = crhold(td->td_ucred);
  237         acct_flags = flags;
  238         if (acct_state & ACCT_RUNNING)
  239                 acct_state &= ~ACCT_EXITREQ;
  240         else {
  241                 /*
  242                  * Try to start up an accounting kthread.  We may start more
  243                  * than one, but if so the extras will commit suicide as
  244                  * soon as they start up.
  245                  */
  246                 error = kthread_create(acct_thread, NULL, NULL, 0, 0,
  247                     "accounting");
  248                 if (error) {
  249                         (void) vn_close(acct_vp, acct_flags, acct_cred, td);
  250                         crfree(acct_cred);
  251                         acct_vp = NULL;
  252                         acct_cred = NULL;
  253                         acct_flags = 0;
  254                         sx_xunlock(&acct_sx);
  255                         log(LOG_NOTICE, "Unable to start accounting thread\n");
  256                         goto done;
  257                 }
  258         }
  259         sx_xunlock(&acct_sx);
  260         log(LOG_NOTICE, "Accounting enabled\n");
  261 done:
  262         mtx_unlock(&Giant);
  263         return (error);
  264 }
  265 
  266 /*
  267  * Disable currently in-progress accounting by closing the vnode, dropping
  268  * our reference to the credential, and clearing the vnode's flags.
  269  */
  270 static int
  271 acct_disable(struct thread *td)
  272 {
  273         int error;
  274 
  275         sx_assert(&acct_sx, SX_XLOCKED);
  276         error = vn_close(acct_vp, acct_flags, acct_cred, td);
  277         crfree(acct_cred);
  278         acct_vp = NULL;
  279         acct_cred = NULL;
  280         acct_flags = 0;
  281         log(LOG_NOTICE, "Accounting disabled\n");
  282         return (error);
  283 }
  284 
  285 /*
  286  * Write out process accounting information, on process exit.
  287  * Data to be written out is specified in Leffler, et al.
  288  * and are enumerated below.  (They're also noted in the system
  289  * "acct.h" header file.)
  290  */
  291 int
  292 acct_process(struct thread *td)
  293 {
  294         struct acct acct;
  295         struct timeval ut, st, tmp;
  296         struct plimit *newlim, *oldlim;
  297         struct proc *p;
  298         struct rusage *r;
  299         int t, ret, vfslocked;
  300 
  301         /*
  302          * Lockless check of accounting condition before doing the hard
  303          * work.
  304          */
  305         if (acct_vp == NULL || acct_suspended)
  306                 return (0);
  307 
  308         sx_slock(&acct_sx);
  309 
  310         /*
  311          * If accounting isn't enabled, don't bother.  Have to check again
  312          * once we own the lock in case we raced with disabling of accounting
  313          * by another thread.
  314          */
  315         if (acct_vp == NULL || acct_suspended) {
  316                 sx_sunlock(&acct_sx);
  317                 return (0);
  318         }
  319 
  320         p = td->td_proc;
  321 
  322         /*
  323          * Get process accounting information.
  324          */
  325 
  326         PROC_LOCK(p);
  327         /* (1) The name of the command that ran */
  328         bcopy(p->p_comm, acct.ac_comm, sizeof acct.ac_comm);
  329 
  330         /* (2) The amount of user and system time that was used */
  331         calcru(p, &ut, &st);
  332         acct.ac_utime = encode_comp_t(ut.tv_sec, ut.tv_usec);
  333         acct.ac_stime = encode_comp_t(st.tv_sec, st.tv_usec);
  334 
  335         /* (3) The elapsed time the command ran (and its starting time) */
  336         tmp = boottime;
  337         timevaladd(&tmp, &p->p_stats->p_start);
  338         acct.ac_btime = tmp.tv_sec;
  339         microuptime(&tmp);
  340         timevalsub(&tmp, &p->p_stats->p_start);
  341         acct.ac_etime = encode_comp_t(tmp.tv_sec, tmp.tv_usec);
  342 
  343         /* (4) The average amount of memory used */
  344         r = &p->p_stats->p_ru;
  345         tmp = ut;
  346         timevaladd(&tmp, &st);
  347         t = tmp.tv_sec * hz + tmp.tv_usec / tick;
  348         if (t)
  349                 acct.ac_mem = (r->ru_ixrss + r->ru_idrss + r->ru_isrss) / t;
  350         else
  351                 acct.ac_mem = 0;
  352 
  353         /* (5) The number of disk I/O operations done */
  354         acct.ac_io = encode_comp_t(r->ru_inblock + r->ru_oublock, 0);
  355 
  356         /* (6) The UID and GID of the process */
  357         acct.ac_uid = p->p_ucred->cr_ruid;
  358         acct.ac_gid = p->p_ucred->cr_rgid;
  359 
  360         /* (7) The terminal from which the process was started */
  361         SESS_LOCK(p->p_session);
  362         if ((p->p_flag & P_CONTROLT) && p->p_pgrp->pg_session->s_ttyp)
  363                 acct.ac_tty = dev2udev(p->p_pgrp->pg_session->s_ttyp->t_dev);
  364         else
  365                 acct.ac_tty = NODEV;
  366         SESS_UNLOCK(p->p_session);
  367 
  368         /* (8) The boolean flags that tell how the process terminated, etc. */
  369         acct.ac_flag = p->p_acflag;
  370         PROC_UNLOCK(p);
  371 
  372         /*
  373          * Eliminate any file size rlimit.
  374          */
  375         newlim = lim_alloc();
  376         PROC_LOCK(p);
  377         oldlim = p->p_limit;
  378         lim_copy(newlim, oldlim);
  379         newlim->pl_rlimit[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
  380         p->p_limit = newlim;
  381         PROC_UNLOCK(p);
  382         lim_free(oldlim);
  383 
  384         /*
  385          * Write the accounting information to the file.
  386          */
  387         vfslocked = VFS_LOCK_GIANT(acct_vp->v_mount);
  388         VOP_LEASE(acct_vp, td, acct_cred, LEASE_WRITE);
  389         ret = vn_rdwr(UIO_WRITE, acct_vp, (caddr_t)&acct, sizeof (acct),
  390             (off_t)0, UIO_SYSSPACE, IO_APPEND|IO_UNIT, acct_cred, NOCRED,
  391             (int *)0, td);
  392         VFS_UNLOCK_GIANT(vfslocked);
  393         sx_sunlock(&acct_sx);
  394         return (ret);
  395 }
  396 
  397 /*
  398  * Encode_comp_t converts from ticks in seconds and microseconds
  399  * to ticks in 1/AHZ seconds.  The encoding is described in
  400  * Leffler, et al., on page 63.
  401  */
  402 
  403 #define MANTSIZE        13                      /* 13 bit mantissa. */
  404 #define EXPSIZE         3                       /* Base 8 (3 bit) exponent. */
  405 #define MAXFRACT        ((1 << MANTSIZE) - 1)   /* Maximum fractional value. */
  406 
  407 static comp_t
  408 encode_comp_t(u_long s, u_long us)
  409 {
  410         int exp, rnd;
  411 
  412         exp = 0;
  413         rnd = 0;
  414         s *= AHZ;
  415         s += us / (1000000 / AHZ);      /* Maximize precision. */
  416 
  417         while (s > MAXFRACT) {
  418         rnd = s & (1 << (EXPSIZE - 1)); /* Round up? */
  419                 s >>= EXPSIZE;          /* Base 8 exponent == 3 bit shift. */
  420                 exp++;
  421         }
  422 
  423         /* If we need to round up, do it (and handle overflow correctly). */
  424         if (rnd && (++s > MAXFRACT)) {
  425                 s >>= EXPSIZE;
  426                 exp++;
  427         }
  428 
  429         /* Clean it up and polish it off. */
  430         exp <<= MANTSIZE;               /* Shift the exponent into place */
  431         exp += s;                       /* and add on the mantissa. */
  432         return (exp);
  433 }
  434 
  435 /*
  436  * Periodically check the filesystem to see if accounting
  437  * should be turned on or off.  Beware the case where the vnode
  438  * has been vgone()'d out from underneath us, e.g. when the file
  439  * system containing the accounting file has been forcibly unmounted.
  440  */
  441 /* ARGSUSED */
  442 static void
  443 acctwatch(void)
  444 {
  445         struct statfs sb;
  446         int vfslocked;
  447 
  448         sx_assert(&acct_sx, SX_XLOCKED);
  449 
  450         /*
  451          * If accounting was disabled before our kthread was scheduled,
  452          * then acct_vp might be NULL.  If so, just ask our kthread to
  453          * exit and return.
  454          */
  455         if (acct_vp == NULL) {
  456                 acct_state |= ACCT_EXITREQ;
  457                 return;
  458         }
  459 
  460         /*
  461          * If our vnode is no longer valid, tear it down and signal the
  462          * accounting thread to die.
  463          */
  464         vfslocked = VFS_LOCK_GIANT(acct_vp->v_mount);
  465         if (acct_vp->v_type == VBAD) {
  466                 (void) acct_disable(NULL);
  467                 VFS_UNLOCK_GIANT(vfslocked);
  468                 acct_state |= ACCT_EXITREQ;
  469                 return;
  470         }
  471 
  472         /*
  473          * Stopping here is better than continuing, maybe it will be VBAD
  474          * next time around.
  475          */
  476         if (VFS_STATFS(acct_vp->v_mount, &sb, curthread) < 0) {
  477                 VFS_UNLOCK_GIANT(vfslocked);
  478                 return;
  479         }
  480         VFS_UNLOCK_GIANT(vfslocked);
  481         if (acct_suspended) {
  482                 if (sb.f_bavail > (int64_t)(acctresume * sb.f_blocks /
  483                     100)) {
  484                         acct_suspended = 0;
  485                         log(LOG_NOTICE, "Accounting resumed\n");
  486                 }
  487         } else {
  488                 if (sb.f_bavail <= (int64_t)(acctsuspend * sb.f_blocks /
  489                     100)) {
  490                         acct_suspended = 1;
  491                         log(LOG_NOTICE, "Accounting suspended\n");
  492                 }
  493         }
  494 }
  495 
  496 /*
  497  * The main loop for the dedicated kernel thread that periodically calls
  498  * acctwatch().
  499  */
  500 static void
  501 acct_thread(void *dummy)
  502 {
  503         u_char pri;
  504 
  505         /* This is a low-priority kernel thread. */
  506         pri = PRI_MAX_KERN;
  507         mtx_lock_spin(&sched_lock);
  508         sched_prio(curthread, pri);
  509         mtx_unlock_spin(&sched_lock);
  510 
  511         /* If another accounting kthread is already running, just die. */
  512         sx_xlock(&acct_sx);
  513         if (acct_state & ACCT_RUNNING) {
  514                 sx_xunlock(&acct_sx);
  515                 kthread_exit(0);
  516         }
  517         acct_state |= ACCT_RUNNING;
  518 
  519         /* Loop until we are asked to exit. */
  520         while (!(acct_state & ACCT_EXITREQ)) {
  521 
  522                 /* Perform our periodic checks. */
  523                 acctwatch();
  524 
  525                 /*
  526                  * We check this flag again before sleeping since the
  527                  * acctwatch() might have shut down accounting and asked us
  528                  * to exit.
  529                  */
  530                 if (!(acct_state & ACCT_EXITREQ)) {
  531                         sx_xunlock(&acct_sx);
  532                         tsleep(&acct_state, pri, "-", acctchkfreq * hz);
  533                         sx_xlock(&acct_sx);
  534                 }
  535         }
  536 
  537         /*
  538          * Acknowledge the exit request and shutdown.  We clear both the
  539          * exit request and running flags.
  540          */
  541         acct_state = 0;
  542         sx_xunlock(&acct_sx);
  543         kthread_exit(0);
  544 }

Cache object: da91b7b85e121c8c6f1ae1cbb0976cba


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.