2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)kern_resource.c 8.5 (Berkeley) 1/21/94
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/sysproto.h>
46 #include <sys/kernel.h>
48 #include <sys/malloc.h>
49 #include <sys/mutex.h>
52 #include <sys/refcount.h>
53 #include <sys/racct.h>
54 #include <sys/resourcevar.h>
55 #include <sys/rwlock.h>
56 #include <sys/sched.h>
58 #include <sys/syscallsubr.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysent.h>
65 #include <vm/vm_param.h>
67 #include <vm/vm_map.h>
70 static MALLOC_DEFINE(M_PLIMIT, "plimit", "plimit structures");
71 static MALLOC_DEFINE(M_UIDINFO, "uidinfo", "uidinfo structures");
72 #define UIHASH(uid) (&uihashtbl[(uid) & uihash])
73 static struct rwlock uihashtbl_lock;
74 static LIST_HEAD(uihashhead, uidinfo) *uihashtbl;
75 static u_long uihash; /* size of hash table - 1 */
77 static void calcru1(struct proc *p, struct rusage_ext *ruxp,
78 struct timeval *up, struct timeval *sp);
79 static int donice(struct thread *td, struct proc *chgp, int n);
80 static struct uidinfo *uilookup(uid_t uid);
81 static void ruxagg_locked(struct rusage_ext *rux, struct thread *td);
84 * Resource controls and accounting.
86 #ifndef _SYS_SYSPROTO_H_
87 struct getpriority_args {
93 sys_getpriority(struct thread *td, struct getpriority_args *uap)
101 switch (uap->which) {
105 low = td->td_proc->p_nice;
110 if (p_cansee(td, p) == 0)
117 sx_slock(&proctree_lock);
119 pg = td->td_proc->p_pgrp;
122 pg = pgfind(uap->who);
124 sx_sunlock(&proctree_lock);
128 sx_sunlock(&proctree_lock);
129 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
131 if (p->p_state == PRS_NORMAL &&
132 p_cansee(td, p) == 0) {
143 uap->who = td->td_ucred->cr_uid;
144 sx_slock(&allproc_lock);
145 FOREACH_PROC_IN_SYSTEM(p) {
147 if (p->p_state == PRS_NORMAL &&
148 p_cansee(td, p) == 0 &&
149 p->p_ucred->cr_uid == uap->who) {
155 sx_sunlock(&allproc_lock);
162 if (low == PRIO_MAX + 1 && error == 0)
164 td->td_retval[0] = low;
168 #ifndef _SYS_SYSPROTO_H_
169 struct setpriority_args {
176 sys_setpriority(struct thread *td, struct setpriority_args *uap)
178 struct proc *curp, *p;
180 int found = 0, error = 0;
183 switch (uap->which) {
187 error = donice(td, curp, uap->prio);
193 error = p_cansee(td, p);
195 error = donice(td, p, uap->prio);
202 sx_slock(&proctree_lock);
207 pg = pgfind(uap->who);
209 sx_sunlock(&proctree_lock);
213 sx_sunlock(&proctree_lock);
214 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
216 if (p->p_state == PRS_NORMAL &&
217 p_cansee(td, p) == 0) {
218 error = donice(td, p, uap->prio);
228 uap->who = td->td_ucred->cr_uid;
229 sx_slock(&allproc_lock);
230 FOREACH_PROC_IN_SYSTEM(p) {
232 if (p->p_state == PRS_NORMAL &&
233 p->p_ucred->cr_uid == uap->who &&
234 p_cansee(td, p) == 0) {
235 error = donice(td, p, uap->prio);
240 sx_sunlock(&allproc_lock);
247 if (found == 0 && error == 0)
253 * Set "nice" for a (whole) process.
256 donice(struct thread *td, struct proc *p, int n)
260 PROC_LOCK_ASSERT(p, MA_OWNED);
261 if ((error = p_cansched(td, p)))
267 if (n < p->p_nice && priv_check(td, PRIV_SCHED_SETPRIORITY) != 0)
273 static int unprivileged_idprio;
274 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_idprio, CTLFLAG_RW,
275 &unprivileged_idprio, 0, "Allow non-root users to set an idle priority");
278 * Set realtime priority for LWP.
280 #ifndef _SYS_SYSPROTO_H_
281 struct rtprio_thread_args {
288 sys_rtprio_thread(struct thread *td, struct rtprio_thread_args *uap)
295 /* Perform copyin before acquiring locks if needed. */
296 if (uap->function == RTP_SET)
297 cierror = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
301 if (uap->lwpid == 0 || uap->lwpid == td->td_tid) {
306 td1 = tdfind(uap->lwpid, -1);
312 switch (uap->function) {
314 if ((error = p_cansee(td, p)))
316 pri_to_rtp(td1, &rtp);
318 return (copyout(&rtp, uap->rtp, sizeof(struct rtprio)));
320 if ((error = p_cansched(td, p)) || (error = cierror))
323 /* Disallow setting rtprio in most cases if not superuser. */
326 * Realtime priority has to be restricted for reasons which
327 * should be obvious. However, for idleprio processes, there is
328 * a potential for system deadlock if an idleprio process gains
329 * a lock on a resource that other processes need (and the
330 * idleprio process can't run due to a CPU-bound normal
331 * process). Fix me! XXX
333 * This problem is not only related to idleprio process.
334 * A user level program can obtain a file lock and hold it
335 * indefinitely. Additionally, without idleprio processes it is
336 * still conceivable that a program with low priority will never
337 * get to run. In short, allowing this feature might make it
338 * easier to lock a resource indefinitely, but it is not the
339 * only thing that makes it possible.
341 if (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_REALTIME ||
342 (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_IDLE &&
343 unprivileged_idprio == 0)) {
344 error = priv_check(td, PRIV_SCHED_RTPRIO);
348 error = rtp_to_pri(&rtp, td1);
359 * Set realtime priority.
361 #ifndef _SYS_SYSPROTO_H_
369 sys_rtprio(struct thread *td, struct rtprio_args *uap)
376 /* Perform copyin before acquiring locks if needed. */
377 if (uap->function == RTP_SET)
378 cierror = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
391 switch (uap->function) {
393 if ((error = p_cansee(td, p)))
396 * Return OUR priority if no pid specified,
397 * or if one is, report the highest priority
398 * in the process. There isn't much more you can do as
399 * there is only room to return a single priority.
400 * Note: specifying our own pid is not the same
401 * as leaving it zero.
404 pri_to_rtp(td, &rtp);
408 rtp.type = RTP_PRIO_IDLE;
409 rtp.prio = RTP_PRIO_MAX;
410 FOREACH_THREAD_IN_PROC(p, tdp) {
411 pri_to_rtp(tdp, &rtp2);
412 if (rtp2.type < rtp.type ||
413 (rtp2.type == rtp.type &&
414 rtp2.prio < rtp.prio)) {
415 rtp.type = rtp2.type;
416 rtp.prio = rtp2.prio;
421 return (copyout(&rtp, uap->rtp, sizeof(struct rtprio)));
423 if ((error = p_cansched(td, p)) || (error = cierror))
427 * Disallow setting rtprio in most cases if not superuser.
428 * See the comment in sys_rtprio_thread about idprio
429 * threads holding a lock.
431 if (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_REALTIME ||
432 (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_IDLE &&
433 !unprivileged_idprio)) {
434 error = priv_check(td, PRIV_SCHED_RTPRIO);
440 * If we are setting our own priority, set just our
441 * thread but if we are doing another process,
442 * do all the threads on that process. If we
443 * specify our own pid we do the latter.
446 error = rtp_to_pri(&rtp, td);
448 FOREACH_THREAD_IN_PROC(p, td) {
449 if ((error = rtp_to_pri(&rtp, td)) != 0)
463 rtp_to_pri(struct rtprio *rtp, struct thread *td)
465 u_char newpri, oldclass, oldpri;
467 switch (RTP_PRIO_BASE(rtp->type)) {
468 case RTP_PRIO_REALTIME:
469 if (rtp->prio > RTP_PRIO_MAX)
471 newpri = PRI_MIN_REALTIME + rtp->prio;
473 case RTP_PRIO_NORMAL:
474 if (rtp->prio > (PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE))
476 newpri = PRI_MIN_TIMESHARE + rtp->prio;
479 if (rtp->prio > RTP_PRIO_MAX)
481 newpri = PRI_MIN_IDLE + rtp->prio;
488 oldclass = td->td_pri_class;
489 sched_class(td, rtp->type); /* XXX fix */
490 oldpri = td->td_user_pri;
491 sched_user_prio(td, newpri);
492 if (td->td_user_pri != oldpri && (oldclass != RTP_PRIO_NORMAL ||
493 td->td_pri_class != RTP_PRIO_NORMAL))
494 sched_prio(td, td->td_user_pri);
495 if (TD_ON_UPILOCK(td) && oldpri != newpri) {
498 umtx_pi_adjust(td, oldpri);
506 pri_to_rtp(struct thread *td, struct rtprio *rtp)
510 switch (PRI_BASE(td->td_pri_class)) {
512 rtp->prio = td->td_base_user_pri - PRI_MIN_REALTIME;
515 rtp->prio = td->td_base_user_pri - PRI_MIN_TIMESHARE;
518 rtp->prio = td->td_base_user_pri - PRI_MIN_IDLE;
523 rtp->type = td->td_pri_class;
527 #if defined(COMPAT_43)
528 #ifndef _SYS_SYSPROTO_H_
529 struct osetrlimit_args {
535 osetrlimit(struct thread *td, struct osetrlimit_args *uap)
541 if ((error = copyin(uap->rlp, &olim, sizeof(struct orlimit))))
543 lim.rlim_cur = olim.rlim_cur;
544 lim.rlim_max = olim.rlim_max;
545 error = kern_setrlimit(td, uap->which, &lim);
549 #ifndef _SYS_SYSPROTO_H_
550 struct ogetrlimit_args {
556 ogetrlimit(struct thread *td, struct ogetrlimit_args *uap)
562 if (uap->which >= RLIM_NLIMITS)
564 lim_rlimit(td, uap->which, &rl);
567 * XXX would be more correct to convert only RLIM_INFINITY to the
568 * old RLIM_INFINITY and fail with EOVERFLOW for other larger
569 * values. Most 64->32 and 32->16 conversions, including not
570 * unimportant ones of uids are even more broken than what we
571 * do here (they blindly truncate). We don't do this correctly
572 * here since we have little experience with EOVERFLOW yet.
573 * Elsewhere, getuid() can't fail...
575 olim.rlim_cur = rl.rlim_cur > 0x7fffffff ? 0x7fffffff : rl.rlim_cur;
576 olim.rlim_max = rl.rlim_max > 0x7fffffff ? 0x7fffffff : rl.rlim_max;
577 error = copyout(&olim, uap->rlp, sizeof(olim));
580 #endif /* COMPAT_43 */
582 #ifndef _SYS_SYSPROTO_H_
583 struct __setrlimit_args {
589 sys_setrlimit(struct thread *td, struct __setrlimit_args *uap)
594 if ((error = copyin(uap->rlp, &alim, sizeof(struct rlimit))))
596 error = kern_setrlimit(td, uap->which, &alim);
608 PROC_LOCK_ASSERT(p, MA_OWNED);
610 * Check if the process exceeds its cpu resource allocation. If
611 * it reaches the max, arrange to kill the process in ast().
613 if (p->p_cpulimit == RLIM_INFINITY)
616 FOREACH_THREAD_IN_PROC(p, td) {
620 if (p->p_rux.rux_runtime > p->p_cpulimit * cpu_tickrate()) {
621 lim_rlimit_proc(p, RLIMIT_CPU, &rlim);
622 if (p->p_rux.rux_runtime >= rlim.rlim_max * cpu_tickrate()) {
623 killproc(p, "exceeded maximum CPU limit");
625 if (p->p_cpulimit < rlim.rlim_max)
627 kern_psignal(p, SIGXCPU);
630 if ((p->p_flag & P_WEXIT) == 0)
631 callout_reset_sbt(&p->p_limco, SBT_1S, 0,
632 lim_cb, p, C_PREL(1));
636 kern_setrlimit(struct thread *td, u_int which, struct rlimit *limp)
639 return (kern_proc_setrlimit(td, td->td_proc, which, limp));
643 kern_proc_setrlimit(struct thread *td, struct proc *p, u_int which,
646 struct plimit *newlim, *oldlim;
647 struct rlimit *alimp;
648 struct rlimit oldssiz;
651 if (which >= RLIM_NLIMITS)
655 * Preserve historical bugs by treating negative limits as unsigned.
657 if (limp->rlim_cur < 0)
658 limp->rlim_cur = RLIM_INFINITY;
659 if (limp->rlim_max < 0)
660 limp->rlim_max = RLIM_INFINITY;
662 oldssiz.rlim_cur = 0;
663 newlim = lim_alloc();
666 alimp = &oldlim->pl_rlimit[which];
667 if (limp->rlim_cur > alimp->rlim_max ||
668 limp->rlim_max > alimp->rlim_max)
669 if ((error = priv_check(td, PRIV_PROC_SETRLIMIT))) {
674 if (limp->rlim_cur > limp->rlim_max)
675 limp->rlim_cur = limp->rlim_max;
676 lim_copy(newlim, oldlim);
677 alimp = &newlim->pl_rlimit[which];
682 if (limp->rlim_cur != RLIM_INFINITY &&
683 p->p_cpulimit == RLIM_INFINITY)
684 callout_reset_sbt(&p->p_limco, SBT_1S, 0,
685 lim_cb, p, C_PREL(1));
686 p->p_cpulimit = limp->rlim_cur;
689 if (limp->rlim_cur > maxdsiz)
690 limp->rlim_cur = maxdsiz;
691 if (limp->rlim_max > maxdsiz)
692 limp->rlim_max = maxdsiz;
696 if (limp->rlim_cur > maxssiz)
697 limp->rlim_cur = maxssiz;
698 if (limp->rlim_max > maxssiz)
699 limp->rlim_max = maxssiz;
701 if (p->p_sysent->sv_fixlimit != NULL)
702 p->p_sysent->sv_fixlimit(&oldssiz,
707 if (limp->rlim_cur > maxfilesperproc)
708 limp->rlim_cur = maxfilesperproc;
709 if (limp->rlim_max > maxfilesperproc)
710 limp->rlim_max = maxfilesperproc;
714 if (limp->rlim_cur > maxprocperuid)
715 limp->rlim_cur = maxprocperuid;
716 if (limp->rlim_max > maxprocperuid)
717 limp->rlim_max = maxprocperuid;
718 if (limp->rlim_cur < 1)
720 if (limp->rlim_max < 1)
724 if (p->p_sysent->sv_fixlimit != NULL)
725 p->p_sysent->sv_fixlimit(limp, which);
732 if (which == RLIMIT_STACK &&
734 * Skip calls from exec_new_vmspace(), done when stack is
737 (td != curthread || (p->p_flag & P_INEXEC) == 0)) {
739 * Stack is allocated to the max at exec time with only
740 * "rlim_cur" bytes accessible. If stack limit is going
741 * up make more accessible, if going down make inaccessible.
743 if (limp->rlim_cur != oldssiz.rlim_cur) {
748 if (limp->rlim_cur > oldssiz.rlim_cur) {
749 prot = p->p_sysent->sv_stackprot;
750 size = limp->rlim_cur - oldssiz.rlim_cur;
751 addr = p->p_sysent->sv_usrstack -
755 size = oldssiz.rlim_cur - limp->rlim_cur;
756 addr = p->p_sysent->sv_usrstack -
759 addr = trunc_page(addr);
760 size = round_page(size);
761 (void)vm_map_protect(&p->p_vmspace->vm_map,
762 addr, addr + size, prot, FALSE);
769 #ifndef _SYS_SYSPROTO_H_
770 struct __getrlimit_args {
777 sys_getrlimit(struct thread *td, struct __getrlimit_args *uap)
782 if (uap->which >= RLIM_NLIMITS)
784 lim_rlimit(td, uap->which, &rlim);
785 error = copyout(&rlim, uap->rlp, sizeof(struct rlimit));
790 * Transform the running time and tick information for children of proc p
791 * into user and system time usage.
794 calccru(struct proc *p, struct timeval *up, struct timeval *sp)
797 PROC_LOCK_ASSERT(p, MA_OWNED);
798 calcru1(p, &p->p_crux, up, sp);
802 * Transform the running time and tick information in proc p into user
803 * and system time usage. If appropriate, include the current time slice
807 calcru(struct proc *p, struct timeval *up, struct timeval *sp)
812 PROC_LOCK_ASSERT(p, MA_OWNED);
813 PROC_STATLOCK_ASSERT(p, MA_OWNED);
815 * If we are getting stats for the current process, then add in the
816 * stats that this thread has accumulated in its current time slice.
817 * We reset the thread and CPU state as if we had performed a context
821 if (td->td_proc == p) {
823 runtime = u - PCPU_GET(switchtime);
824 td->td_runtime += runtime;
825 td->td_incruntime += runtime;
826 PCPU_SET(switchtime, u);
828 /* Make sure the per-thread stats are current. */
829 FOREACH_THREAD_IN_PROC(p, td) {
830 if (td->td_incruntime == 0)
834 calcru1(p, &p->p_rux, up, sp);
837 /* Collect resource usage for a single thread. */
839 rufetchtd(struct thread *td, struct rusage *ru)
845 PROC_STATLOCK_ASSERT(p, MA_OWNED);
846 THREAD_LOCK_ASSERT(td, MA_OWNED);
848 * If we are getting stats for the current thread, then add in the
849 * stats that this thread has accumulated in its current time slice.
850 * We reset the thread and CPU state as if we had performed a context
853 if (td == curthread) {
855 runtime = u - PCPU_GET(switchtime);
856 td->td_runtime += runtime;
857 td->td_incruntime += runtime;
858 PCPU_SET(switchtime, u);
862 calcru1(p, &td->td_rux, &ru->ru_utime, &ru->ru_stime);
865 /* XXX: the MI version is too slow to use: */
866 #ifndef __HAVE_INLINE_FLSLL
867 #define flsll(x) (fls((x) >> 32) != 0 ? fls((x) >> 32) + 32 : fls(x))
871 mul64_by_fraction(uint64_t a, uint64_t b, uint64_t c)
873 uint64_t acc, bh, bl;
877 * Calculate (a * b) / c accurately enough without overflowing. c
878 * must be nonzero, and its top bit must be 0. a or b must be
879 * <= c, and the implementation is tuned for b <= c.
881 * The comments about times are for use in calcru1() with units of
882 * microseconds for 'a' and stathz ticks at 128 Hz for b and c.
884 * Let n be the number of top zero bits in c. Each iteration
885 * either returns, or reduces b by right shifting it by at least n.
886 * The number of iterations is at most 1 + 64 / n, and the error is
887 * at most the number of iterations.
889 * It is very unusual to need even 2 iterations. Previous
890 * implementations overflowed essentially by returning early in the
891 * first iteration, with n = 38 giving overflow at 105+ hours and
892 * n = 32 giving overlow at at 388+ days despite a more careful
893 * calculation. 388 days is a reasonable uptime, and the calculation
894 * needs to work for the uptime times the number of CPUs since 'a'
897 if (a >= (uint64_t)1 << 63)
898 return (0); /* Unsupported arg -- can't happen. */
900 for (i = 0; i < 128; i++) {
904 /* Up to 105 hours on first iteration. */
905 return (acc + (a * b) / c);
908 * This reduction is based on a = q * c + r, with the
909 * remainder r < c. 'a' may be large to start, and
910 * moving bits from b into 'a' at the end of the loop
911 * sets the top bit of 'a', so the reduction makes
912 * significant progress.
918 /* Up to 388 days on first iteration. */
919 return (acc + (a * b) / c);
923 * This step writes a * b as a * ((bh << s) + bl) =
924 * a * (bh << s) + a * bl = (a << s) * bh + a * bl. The 2
925 * additive terms are handled separately. Splitting in
926 * this way is linear except for rounding errors.
928 * s = 64 - sa is the maximum such that a << s fits in 64
929 * bits. Since a < c and c has at least 1 zero top bit,
930 * sa < 64 and s > 0. Thus this step makes progress by
931 * reducing b (it increases 'a', but taking remainders on
932 * the next iteration completes the reduction).
934 * Finally, the choice for s is just what is needed to keep
935 * a * bl from overflowing, so we don't need complications
936 * like a recursive call mul64_by_fraction(a, bl, c) to
937 * handle the second additive term.
946 return (0); /* Algorithm failure -- can't happen. */
950 calcru1(struct proc *p, struct rusage_ext *ruxp, struct timeval *up,
953 /* {user, system, interrupt, total} {ticks, usec}: */
954 uint64_t ut, uu, st, su, it, tt, tu;
956 ut = ruxp->rux_uticks;
957 st = ruxp->rux_sticks;
958 it = ruxp->rux_iticks;
961 /* Avoid divide by zero */
965 tu = cputick2usec(ruxp->rux_runtime);
966 if ((int64_t)tu < 0) {
967 /* XXX: this should be an assert /phk */
968 printf("calcru: negative runtime of %jd usec for pid %d (%s)\n",
969 (intmax_t)tu, p->p_pid, p->p_comm);
973 /* Subdivide tu. Avoid overflow in the multiplications. */
974 if (__predict_true(tu <= ((uint64_t)1 << 38) && tt <= (1 << 26))) {
975 /* Up to 76 hours when stathz is 128. */
979 uu = mul64_by_fraction(tu, ut, tt);
980 su = mul64_by_fraction(tu, st, tt);
983 if (tu >= ruxp->rux_tu) {
985 * The normal case, time increased.
986 * Enforce monotonicity of bucketed numbers.
988 if (uu < ruxp->rux_uu)
990 if (su < ruxp->rux_su)
992 } else if (tu + 3 > ruxp->rux_tu || 101 * tu > 100 * ruxp->rux_tu) {
994 * When we calibrate the cputicker, it is not uncommon to
995 * see the presumably fixed frequency increase slightly over
996 * time as a result of thermal stabilization and NTP
997 * discipline (of the reference clock). We therefore ignore
998 * a bit of backwards slop because we expect to catch up
999 * shortly. We use a 3 microsecond limit to catch low
1000 * counts and a 1% limit for high counts.
1005 } else { /* tu < ruxp->rux_tu */
1007 * What happened here was likely that a laptop, which ran at
1008 * a reduced clock frequency at boot, kicked into high gear.
1009 * The wisdom of spamming this message in that case is
1010 * dubious, but it might also be indicative of something
1011 * serious, so lets keep it and hope laptops can be made
1012 * more truthful about their CPU speed via ACPI.
1014 printf("calcru: runtime went backwards from %ju usec "
1015 "to %ju usec for pid %d (%s)\n",
1016 (uintmax_t)ruxp->rux_tu, (uintmax_t)tu,
1017 p->p_pid, p->p_comm);
1024 up->tv_sec = uu / 1000000;
1025 up->tv_usec = uu % 1000000;
1026 sp->tv_sec = su / 1000000;
1027 sp->tv_usec = su % 1000000;
1030 #ifndef _SYS_SYSPROTO_H_
1031 struct getrusage_args {
1033 struct rusage *rusage;
1037 sys_getrusage(struct thread *td, struct getrusage_args *uap)
1042 error = kern_getrusage(td, uap->who, &ru);
1044 error = copyout(&ru, uap->rusage, sizeof(struct rusage));
1049 kern_getrusage(struct thread *td, int who, struct rusage *rup)
1059 rufetchcalc(p, rup, &rup->ru_utime,
1063 case RUSAGE_CHILDREN:
1064 *rup = p->p_stats->p_cru;
1065 calccru(p, &rup->ru_utime, &rup->ru_stime);
1084 rucollect(struct rusage *ru, struct rusage *ru2)
1089 if (ru->ru_maxrss < ru2->ru_maxrss)
1090 ru->ru_maxrss = ru2->ru_maxrss;
1092 ip2 = &ru2->ru_first;
1093 for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--)
1098 ruadd(struct rusage *ru, struct rusage_ext *rux, struct rusage *ru2,
1099 struct rusage_ext *rux2)
1102 rux->rux_runtime += rux2->rux_runtime;
1103 rux->rux_uticks += rux2->rux_uticks;
1104 rux->rux_sticks += rux2->rux_sticks;
1105 rux->rux_iticks += rux2->rux_iticks;
1106 rux->rux_uu += rux2->rux_uu;
1107 rux->rux_su += rux2->rux_su;
1108 rux->rux_tu += rux2->rux_tu;
1113 * Aggregate tick counts into the proc's rusage_ext.
1116 ruxagg_locked(struct rusage_ext *rux, struct thread *td)
1119 THREAD_LOCK_ASSERT(td, MA_OWNED);
1120 PROC_STATLOCK_ASSERT(td->td_proc, MA_OWNED);
1121 rux->rux_runtime += td->td_incruntime;
1122 rux->rux_uticks += td->td_uticks;
1123 rux->rux_sticks += td->td_sticks;
1124 rux->rux_iticks += td->td_iticks;
1128 ruxagg(struct proc *p, struct thread *td)
1132 ruxagg_locked(&p->p_rux, td);
1133 ruxagg_locked(&td->td_rux, td);
1134 td->td_incruntime = 0;
1142 * Update the rusage_ext structure and fetch a valid aggregate rusage
1143 * for proc p if storage for one is supplied.
1146 rufetch(struct proc *p, struct rusage *ru)
1150 PROC_STATLOCK_ASSERT(p, MA_OWNED);
1153 if (p->p_numthreads > 0) {
1154 FOREACH_THREAD_IN_PROC(p, td) {
1156 rucollect(ru, &td->td_ru);
1162 * Atomically perform a rufetch and a calcru together.
1163 * Consumers, can safely assume the calcru is executed only once
1164 * rufetch is completed.
1167 rufetchcalc(struct proc *p, struct rusage *ru, struct timeval *up,
1178 * Allocate a new resource limits structure and initialize its
1179 * reference count and mutex pointer.
1184 struct plimit *limp;
1186 limp = malloc(sizeof(struct plimit), M_PLIMIT, M_WAITOK);
1187 refcount_init(&limp->pl_refcnt, 1);
1192 lim_hold(struct plimit *limp)
1195 refcount_acquire(&limp->pl_refcnt);
1200 lim_fork(struct proc *p1, struct proc *p2)
1203 PROC_LOCK_ASSERT(p1, MA_OWNED);
1204 PROC_LOCK_ASSERT(p2, MA_OWNED);
1206 p2->p_limit = lim_hold(p1->p_limit);
1207 callout_init_mtx(&p2->p_limco, &p2->p_mtx, 0);
1208 if (p1->p_cpulimit != RLIM_INFINITY)
1209 callout_reset_sbt(&p2->p_limco, SBT_1S, 0,
1210 lim_cb, p2, C_PREL(1));
1214 lim_free(struct plimit *limp)
1217 if (refcount_release(&limp->pl_refcnt))
1218 free((void *)limp, M_PLIMIT);
1222 * Make a copy of the plimit structure.
1223 * We share these structures copy-on-write after fork.
1226 lim_copy(struct plimit *dst, struct plimit *src)
1229 KASSERT(dst->pl_refcnt <= 1, ("lim_copy to shared limit"));
1230 bcopy(src->pl_rlimit, dst->pl_rlimit, sizeof(src->pl_rlimit));
1234 * Return the hard limit for a particular system resource. The
1235 * which parameter specifies the index into the rlimit array.
1238 lim_max(struct thread *td, int which)
1242 lim_rlimit(td, which, &rl);
1243 return (rl.rlim_max);
1247 lim_max_proc(struct proc *p, int which)
1251 lim_rlimit_proc(p, which, &rl);
1252 return (rl.rlim_max);
1256 * Return the current (soft) limit for a particular system resource.
1257 * The which parameter which specifies the index into the rlimit array
1260 lim_cur(struct thread *td, int which)
1264 lim_rlimit(td, which, &rl);
1265 return (rl.rlim_cur);
1269 lim_cur_proc(struct proc *p, int which)
1273 lim_rlimit_proc(p, which, &rl);
1274 return (rl.rlim_cur);
1278 * Return a copy of the entire rlimit structure for the system limit
1279 * specified by 'which' in the rlimit structure pointed to by 'rlp'.
1282 lim_rlimit(struct thread *td, int which, struct rlimit *rlp)
1284 struct proc *p = td->td_proc;
1286 MPASS(td == curthread);
1287 KASSERT(which >= 0 && which < RLIM_NLIMITS,
1288 ("request for invalid resource limit"));
1289 *rlp = td->td_limit->pl_rlimit[which];
1290 if (p->p_sysent->sv_fixlimit != NULL)
1291 p->p_sysent->sv_fixlimit(rlp, which);
1295 lim_rlimit_proc(struct proc *p, int which, struct rlimit *rlp)
1298 PROC_LOCK_ASSERT(p, MA_OWNED);
1299 KASSERT(which >= 0 && which < RLIM_NLIMITS,
1300 ("request for invalid resource limit"));
1301 *rlp = p->p_limit->pl_rlimit[which];
1302 if (p->p_sysent->sv_fixlimit != NULL)
1303 p->p_sysent->sv_fixlimit(rlp, which);
1310 uihashtbl = hashinit(maxproc / 16, M_UIDINFO, &uihash);
1311 rw_init(&uihashtbl_lock, "uidinfo hash");
1315 * Look up a uidinfo struct for the parameter uid.
1316 * uihashtbl_lock must be locked.
1317 * Increase refcount on uidinfo struct returned.
1319 static struct uidinfo *
1322 struct uihashhead *uipp;
1323 struct uidinfo *uip;
1325 rw_assert(&uihashtbl_lock, RA_LOCKED);
1327 LIST_FOREACH(uip, uipp, ui_hash)
1328 if (uip->ui_uid == uid) {
1337 * Find or allocate a struct uidinfo for a particular uid.
1338 * Returns with uidinfo struct referenced.
1339 * uifree() should be called on a struct uidinfo when released.
1344 struct uidinfo *new_uip, *uip;
1347 cred = curthread->td_ucred;
1348 if (cred->cr_uidinfo->ui_uid == uid) {
1349 uip = cred->cr_uidinfo;
1352 } else if (cred->cr_ruidinfo->ui_uid == uid) {
1353 uip = cred->cr_ruidinfo;
1358 rw_rlock(&uihashtbl_lock);
1359 uip = uilookup(uid);
1360 rw_runlock(&uihashtbl_lock);
1364 new_uip = malloc(sizeof(*new_uip), M_UIDINFO, M_WAITOK | M_ZERO);
1365 racct_create(&new_uip->ui_racct);
1366 refcount_init(&new_uip->ui_ref, 1);
1367 new_uip->ui_uid = uid;
1369 rw_wlock(&uihashtbl_lock);
1371 * There's a chance someone created our uidinfo while we
1372 * were in malloc and not holding the lock, so we have to
1373 * make sure we don't insert a duplicate uidinfo.
1375 if ((uip = uilookup(uid)) == NULL) {
1376 LIST_INSERT_HEAD(UIHASH(uid), new_uip, ui_hash);
1377 rw_wunlock(&uihashtbl_lock);
1380 rw_wunlock(&uihashtbl_lock);
1381 racct_destroy(&new_uip->ui_racct);
1382 free(new_uip, M_UIDINFO);
1388 * Place another refcount on a uidinfo struct.
1391 uihold(struct uidinfo *uip)
1394 refcount_acquire(&uip->ui_ref);
1398 * Since uidinfo structs have a long lifetime, we use an
1399 * opportunistic refcounting scheme to avoid locking the lookup hash
1402 * If the refcount hits 0, we need to free the structure,
1403 * which means we need to lock the hash.
1405 * After locking the struct and lowering the refcount, if we find
1406 * that we don't need to free, simply unlock and return.
1408 * If refcount lowering results in need to free, bump the count
1409 * back up, lose the lock and acquire the locks in the proper
1410 * order to try again.
1413 uifree(struct uidinfo *uip)
1417 /* Prepare for optimal case. */
1419 if (old > 1 && atomic_cmpset_int(&uip->ui_ref, old, old - 1))
1422 /* Prepare for suboptimal case. */
1423 rw_wlock(&uihashtbl_lock);
1424 if (refcount_release(&uip->ui_ref) == 0) {
1425 rw_wunlock(&uihashtbl_lock);
1429 racct_destroy(&uip->ui_racct);
1430 LIST_REMOVE(uip, ui_hash);
1431 rw_wunlock(&uihashtbl_lock);
1433 if (uip->ui_sbsize != 0)
1434 printf("freeing uidinfo: uid = %d, sbsize = %ld\n",
1435 uip->ui_uid, uip->ui_sbsize);
1436 if (uip->ui_proccnt != 0)
1437 printf("freeing uidinfo: uid = %d, proccnt = %ld\n",
1438 uip->ui_uid, uip->ui_proccnt);
1439 if (uip->ui_vmsize != 0)
1440 printf("freeing uidinfo: uid = %d, swapuse = %lld\n",
1441 uip->ui_uid, (unsigned long long)uip->ui_vmsize);
1442 free(uip, M_UIDINFO);
1447 ui_racct_foreach(void (*callback)(struct racct *racct,
1448 void *arg2, void *arg3), void (*pre)(void), void (*post)(void),
1449 void *arg2, void *arg3)
1451 struct uidinfo *uip;
1452 struct uihashhead *uih;
1454 rw_rlock(&uihashtbl_lock);
1457 for (uih = &uihashtbl[uihash]; uih >= uihashtbl; uih--) {
1458 LIST_FOREACH(uip, uih, ui_hash) {
1459 (callback)(uip->ui_racct, arg2, arg3);
1464 rw_runlock(&uihashtbl_lock);
1469 chglimit(struct uidinfo *uip, long *limit, int diff, rlim_t max, const char *name)
1473 /* Don't allow them to exceed max, but allow subtraction. */
1474 new = atomic_fetchadd_long(limit, (long)diff) + diff;
1475 if (diff > 0 && max != 0) {
1476 if (new < 0 || new > max) {
1477 atomic_subtract_long(limit, (long)diff);
1481 printf("negative %s for uid = %d\n", name, uip->ui_uid);
1486 * Change the count associated with number of processes
1487 * a given user is using. When 'max' is 0, don't enforce a limit
1490 chgproccnt(struct uidinfo *uip, int diff, rlim_t max)
1493 return (chglimit(uip, &uip->ui_proccnt, diff, max, "proccnt"));
1497 * Change the total socket buffer size a user has used.
1500 chgsbsize(struct uidinfo *uip, u_int *hiwat, u_int to, rlim_t max)
1505 if (diff > 0 && max == 0) {
1508 rv = chglimit(uip, &uip->ui_sbsize, diff, max, "sbsize");
1516 * Change the count associated with number of pseudo-terminals
1517 * a given user is using. When 'max' is 0, don't enforce a limit
1520 chgptscnt(struct uidinfo *uip, int diff, rlim_t max)
1523 return (chglimit(uip, &uip->ui_ptscnt, diff, max, "ptscnt"));
1527 chgkqcnt(struct uidinfo *uip, int diff, rlim_t max)
1530 return (chglimit(uip, &uip->ui_kqcnt, diff, max, "kqcnt"));
1534 chgumtxcnt(struct uidinfo *uip, int diff, rlim_t max)
1537 return (chglimit(uip, &uip->ui_umtxcnt, diff, max, "umtxcnt"));