xref: /freebsd/sys/kern/kern_resource.c (revision ff0ba87247820afbdfdc1b307c803f7923d0e4d3)
1 /*-
2  * Copyright (c) 1982, 1986, 1991, 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  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)kern_resource.c	8.5 (Berkeley) 1/21/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_compat.h"
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/sysproto.h>
45 #include <sys/file.h>
46 #include <sys/kernel.h>
47 #include <sys/lock.h>
48 #include <sys/malloc.h>
49 #include <sys/mutex.h>
50 #include <sys/priv.h>
51 #include <sys/proc.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>
57 #include <sys/sx.h>
58 #include <sys/syscallsubr.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysent.h>
61 #include <sys/time.h>
62 #include <sys/umtx.h>
63 
64 #include <vm/vm.h>
65 #include <vm/vm_param.h>
66 #include <vm/pmap.h>
67 #include <vm/vm_map.h>
68 
69 
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 */
76 
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);
82 
83 static __inline int	lim_shared(struct plimit *limp);
84 
85 /*
86  * Resource controls and accounting.
87  */
88 #ifndef _SYS_SYSPROTO_H_
89 struct getpriority_args {
90 	int	which;
91 	int	who;
92 };
93 #endif
94 int
95 sys_getpriority(struct thread *td, register struct getpriority_args *uap)
96 {
97 	struct proc *p;
98 	struct pgrp *pg;
99 	int error, low;
100 
101 	error = 0;
102 	low = PRIO_MAX + 1;
103 	switch (uap->which) {
104 
105 	case PRIO_PROCESS:
106 		if (uap->who == 0)
107 			low = td->td_proc->p_nice;
108 		else {
109 			p = pfind(uap->who);
110 			if (p == NULL)
111 				break;
112 			if (p_cansee(td, p) == 0)
113 				low = p->p_nice;
114 			PROC_UNLOCK(p);
115 		}
116 		break;
117 
118 	case PRIO_PGRP:
119 		sx_slock(&proctree_lock);
120 		if (uap->who == 0) {
121 			pg = td->td_proc->p_pgrp;
122 			PGRP_LOCK(pg);
123 		} else {
124 			pg = pgfind(uap->who);
125 			if (pg == NULL) {
126 				sx_sunlock(&proctree_lock);
127 				break;
128 			}
129 		}
130 		sx_sunlock(&proctree_lock);
131 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
132 			PROC_LOCK(p);
133 			if (p->p_state == PRS_NORMAL &&
134 			    p_cansee(td, p) == 0) {
135 				if (p->p_nice < low)
136 					low = p->p_nice;
137 			}
138 			PROC_UNLOCK(p);
139 		}
140 		PGRP_UNLOCK(pg);
141 		break;
142 
143 	case PRIO_USER:
144 		if (uap->who == 0)
145 			uap->who = td->td_ucred->cr_uid;
146 		sx_slock(&allproc_lock);
147 		FOREACH_PROC_IN_SYSTEM(p) {
148 			PROC_LOCK(p);
149 			if (p->p_state == PRS_NORMAL &&
150 			    p_cansee(td, p) == 0 &&
151 			    p->p_ucred->cr_uid == uap->who) {
152 				if (p->p_nice < low)
153 					low = p->p_nice;
154 			}
155 			PROC_UNLOCK(p);
156 		}
157 		sx_sunlock(&allproc_lock);
158 		break;
159 
160 	default:
161 		error = EINVAL;
162 		break;
163 	}
164 	if (low == PRIO_MAX + 1 && error == 0)
165 		error = ESRCH;
166 	td->td_retval[0] = low;
167 	return (error);
168 }
169 
170 #ifndef _SYS_SYSPROTO_H_
171 struct setpriority_args {
172 	int	which;
173 	int	who;
174 	int	prio;
175 };
176 #endif
177 int
178 sys_setpriority(struct thread *td, struct setpriority_args *uap)
179 {
180 	struct proc *curp, *p;
181 	struct pgrp *pg;
182 	int found = 0, error = 0;
183 
184 	curp = td->td_proc;
185 	switch (uap->which) {
186 	case PRIO_PROCESS:
187 		if (uap->who == 0) {
188 			PROC_LOCK(curp);
189 			error = donice(td, curp, uap->prio);
190 			PROC_UNLOCK(curp);
191 		} else {
192 			p = pfind(uap->who);
193 			if (p == NULL)
194 				break;
195 			error = p_cansee(td, p);
196 			if (error == 0)
197 				error = donice(td, p, uap->prio);
198 			PROC_UNLOCK(p);
199 		}
200 		found++;
201 		break;
202 
203 	case PRIO_PGRP:
204 		sx_slock(&proctree_lock);
205 		if (uap->who == 0) {
206 			pg = curp->p_pgrp;
207 			PGRP_LOCK(pg);
208 		} else {
209 			pg = pgfind(uap->who);
210 			if (pg == NULL) {
211 				sx_sunlock(&proctree_lock);
212 				break;
213 			}
214 		}
215 		sx_sunlock(&proctree_lock);
216 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
217 			PROC_LOCK(p);
218 			if (p->p_state == PRS_NORMAL &&
219 			    p_cansee(td, p) == 0) {
220 				error = donice(td, p, uap->prio);
221 				found++;
222 			}
223 			PROC_UNLOCK(p);
224 		}
225 		PGRP_UNLOCK(pg);
226 		break;
227 
228 	case PRIO_USER:
229 		if (uap->who == 0)
230 			uap->who = td->td_ucred->cr_uid;
231 		sx_slock(&allproc_lock);
232 		FOREACH_PROC_IN_SYSTEM(p) {
233 			PROC_LOCK(p);
234 			if (p->p_state == PRS_NORMAL &&
235 			    p->p_ucred->cr_uid == uap->who &&
236 			    p_cansee(td, p) == 0) {
237 				error = donice(td, p, uap->prio);
238 				found++;
239 			}
240 			PROC_UNLOCK(p);
241 		}
242 		sx_sunlock(&allproc_lock);
243 		break;
244 
245 	default:
246 		error = EINVAL;
247 		break;
248 	}
249 	if (found == 0 && error == 0)
250 		error = ESRCH;
251 	return (error);
252 }
253 
254 /*
255  * Set "nice" for a (whole) process.
256  */
257 static int
258 donice(struct thread *td, struct proc *p, int n)
259 {
260 	int error;
261 
262 	PROC_LOCK_ASSERT(p, MA_OWNED);
263 	if ((error = p_cansched(td, p)))
264 		return (error);
265 	if (n > PRIO_MAX)
266 		n = PRIO_MAX;
267 	if (n < PRIO_MIN)
268 		n = PRIO_MIN;
269 	if (n < p->p_nice && priv_check(td, PRIV_SCHED_SETPRIORITY) != 0)
270 		return (EACCES);
271 	sched_nice(p, n);
272 	return (0);
273 }
274 
275 static int unprivileged_idprio;
276 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_idprio, CTLFLAG_RW,
277     &unprivileged_idprio, 0, "Allow non-root users to set an idle priority");
278 
279 /*
280  * Set realtime priority for LWP.
281  */
282 #ifndef _SYS_SYSPROTO_H_
283 struct rtprio_thread_args {
284 	int		function;
285 	lwpid_t		lwpid;
286 	struct rtprio	*rtp;
287 };
288 #endif
289 int
290 sys_rtprio_thread(struct thread *td, struct rtprio_thread_args *uap)
291 {
292 	struct proc *p;
293 	struct rtprio rtp;
294 	struct thread *td1;
295 	int cierror, error;
296 
297 	/* Perform copyin before acquiring locks if needed. */
298 	if (uap->function == RTP_SET)
299 		cierror = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
300 	else
301 		cierror = 0;
302 
303 	if (uap->lwpid == 0 || uap->lwpid == td->td_tid) {
304 		p = td->td_proc;
305 		td1 = td;
306 		PROC_LOCK(p);
307 	} else {
308 		/* Only look up thread in current process */
309 		td1 = tdfind(uap->lwpid, curproc->p_pid);
310 		if (td1 == NULL)
311 			return (ESRCH);
312 		p = td1->td_proc;
313 	}
314 
315 	switch (uap->function) {
316 	case RTP_LOOKUP:
317 		if ((error = p_cansee(td, p)))
318 			break;
319 		pri_to_rtp(td1, &rtp);
320 		PROC_UNLOCK(p);
321 		return (copyout(&rtp, uap->rtp, sizeof(struct rtprio)));
322 	case RTP_SET:
323 		if ((error = p_cansched(td, p)) || (error = cierror))
324 			break;
325 
326 		/* Disallow setting rtprio in most cases if not superuser. */
327 
328 		/*
329 		 * Realtime priority has to be restricted for reasons which
330 		 * should be obvious.  However, for idleprio processes, there is
331 		 * a potential for system deadlock if an idleprio process gains
332 		 * a lock on a resource that other processes need (and the
333 		 * idleprio process can't run due to a CPU-bound normal
334 		 * process).  Fix me!  XXX
335 		 *
336 		 * This problem is not only related to idleprio process.
337 		 * A user level program can obtain a file lock and hold it
338 		 * indefinitely.  Additionally, without idleprio processes it is
339 		 * still conceivable that a program with low priority will never
340 		 * get to run.  In short, allowing this feature might make it
341 		 * easier to lock a resource indefinitely, but it is not the
342 		 * only thing that makes it possible.
343 		 */
344 		if (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_REALTIME ||
345 		    (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_IDLE &&
346 		    unprivileged_idprio == 0)) {
347 			error = priv_check(td, PRIV_SCHED_RTPRIO);
348 			if (error)
349 				break;
350 		}
351 		error = rtp_to_pri(&rtp, td1);
352 		break;
353 	default:
354 		error = EINVAL;
355 		break;
356 	}
357 	PROC_UNLOCK(p);
358 	return (error);
359 }
360 
361 /*
362  * Set realtime priority.
363  */
364 #ifndef _SYS_SYSPROTO_H_
365 struct rtprio_args {
366 	int		function;
367 	pid_t		pid;
368 	struct rtprio	*rtp;
369 };
370 #endif
371 int
372 sys_rtprio(struct thread *td, register struct rtprio_args *uap)
373 {
374 	struct proc *p;
375 	struct thread *tdp;
376 	struct rtprio rtp;
377 	int cierror, error;
378 
379 	/* Perform copyin before acquiring locks if needed. */
380 	if (uap->function == RTP_SET)
381 		cierror = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
382 	else
383 		cierror = 0;
384 
385 	if (uap->pid == 0) {
386 		p = td->td_proc;
387 		PROC_LOCK(p);
388 	} else {
389 		p = pfind(uap->pid);
390 		if (p == NULL)
391 			return (ESRCH);
392 	}
393 
394 	switch (uap->function) {
395 	case RTP_LOOKUP:
396 		if ((error = p_cansee(td, p)))
397 			break;
398 		/*
399 		 * Return OUR priority if no pid specified,
400 		 * or if one is, report the highest priority
401 		 * in the process.  There isn't much more you can do as
402 		 * there is only room to return a single priority.
403 		 * Note: specifying our own pid is not the same
404 		 * as leaving it zero.
405 		 */
406 		if (uap->pid == 0) {
407 			pri_to_rtp(td, &rtp);
408 		} else {
409 			struct rtprio rtp2;
410 
411 			rtp.type = RTP_PRIO_IDLE;
412 			rtp.prio = RTP_PRIO_MAX;
413 			FOREACH_THREAD_IN_PROC(p, tdp) {
414 				pri_to_rtp(tdp, &rtp2);
415 				if (rtp2.type <  rtp.type ||
416 				    (rtp2.type == rtp.type &&
417 				    rtp2.prio < rtp.prio)) {
418 					rtp.type = rtp2.type;
419 					rtp.prio = rtp2.prio;
420 				}
421 			}
422 		}
423 		PROC_UNLOCK(p);
424 		return (copyout(&rtp, uap->rtp, sizeof(struct rtprio)));
425 	case RTP_SET:
426 		if ((error = p_cansched(td, p)) || (error = cierror))
427 			break;
428 
429 		/*
430 		 * Disallow setting rtprio in most cases if not superuser.
431 		 * See the comment in sys_rtprio_thread about idprio
432 		 * threads holding a lock.
433 		 */
434 		if (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_REALTIME ||
435 		    (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_IDLE &&
436 		    !unprivileged_idprio)) {
437 			error = priv_check(td, PRIV_SCHED_RTPRIO);
438 			if (error)
439 				break;
440 		}
441 
442 		/*
443 		 * If we are setting our own priority, set just our
444 		 * thread but if we are doing another process,
445 		 * do all the threads on that process. If we
446 		 * specify our own pid we do the latter.
447 		 */
448 		if (uap->pid == 0) {
449 			error = rtp_to_pri(&rtp, td);
450 		} else {
451 			FOREACH_THREAD_IN_PROC(p, td) {
452 				if ((error = rtp_to_pri(&rtp, td)) != 0)
453 					break;
454 			}
455 		}
456 		break;
457 	default:
458 		error = EINVAL;
459 		break;
460 	}
461 	PROC_UNLOCK(p);
462 	return (error);
463 }
464 
465 int
466 rtp_to_pri(struct rtprio *rtp, struct thread *td)
467 {
468 	u_char  newpri, oldclass, oldpri;
469 
470 	switch (RTP_PRIO_BASE(rtp->type)) {
471 	case RTP_PRIO_REALTIME:
472 		if (rtp->prio > RTP_PRIO_MAX)
473 			return (EINVAL);
474 		newpri = PRI_MIN_REALTIME + rtp->prio;
475 		break;
476 	case RTP_PRIO_NORMAL:
477 		if (rtp->prio > (PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE))
478 			return (EINVAL);
479 		newpri = PRI_MIN_TIMESHARE + rtp->prio;
480 		break;
481 	case RTP_PRIO_IDLE:
482 		if (rtp->prio > RTP_PRIO_MAX)
483 			return (EINVAL);
484 		newpri = PRI_MIN_IDLE + rtp->prio;
485 		break;
486 	default:
487 		return (EINVAL);
488 	}
489 
490 	thread_lock(td);
491 	oldclass = td->td_pri_class;
492 	sched_class(td, rtp->type);	/* XXX fix */
493 	oldpri = td->td_user_pri;
494 	sched_user_prio(td, newpri);
495 	if (td->td_user_pri != oldpri && (oldclass != RTP_PRIO_NORMAL ||
496 	    td->td_pri_class != RTP_PRIO_NORMAL))
497 		sched_prio(td, td->td_user_pri);
498 	if (TD_ON_UPILOCK(td) && oldpri != newpri) {
499 		critical_enter();
500 		thread_unlock(td);
501 		umtx_pi_adjust(td, oldpri);
502 		critical_exit();
503 	} else
504 		thread_unlock(td);
505 	return (0);
506 }
507 
508 void
509 pri_to_rtp(struct thread *td, struct rtprio *rtp)
510 {
511 
512 	thread_lock(td);
513 	switch (PRI_BASE(td->td_pri_class)) {
514 	case PRI_REALTIME:
515 		rtp->prio = td->td_base_user_pri - PRI_MIN_REALTIME;
516 		break;
517 	case PRI_TIMESHARE:
518 		rtp->prio = td->td_base_user_pri - PRI_MIN_TIMESHARE;
519 		break;
520 	case PRI_IDLE:
521 		rtp->prio = td->td_base_user_pri - PRI_MIN_IDLE;
522 		break;
523 	default:
524 		break;
525 	}
526 	rtp->type = td->td_pri_class;
527 	thread_unlock(td);
528 }
529 
530 #if defined(COMPAT_43)
531 #ifndef _SYS_SYSPROTO_H_
532 struct osetrlimit_args {
533 	u_int	which;
534 	struct	orlimit *rlp;
535 };
536 #endif
537 int
538 osetrlimit(struct thread *td, register struct osetrlimit_args *uap)
539 {
540 	struct orlimit olim;
541 	struct rlimit lim;
542 	int error;
543 
544 	if ((error = copyin(uap->rlp, &olim, sizeof(struct orlimit))))
545 		return (error);
546 	lim.rlim_cur = olim.rlim_cur;
547 	lim.rlim_max = olim.rlim_max;
548 	error = kern_setrlimit(td, uap->which, &lim);
549 	return (error);
550 }
551 
552 #ifndef _SYS_SYSPROTO_H_
553 struct ogetrlimit_args {
554 	u_int	which;
555 	struct	orlimit *rlp;
556 };
557 #endif
558 int
559 ogetrlimit(struct thread *td, register struct ogetrlimit_args *uap)
560 {
561 	struct orlimit olim;
562 	struct rlimit rl;
563 	struct proc *p;
564 	int error;
565 
566 	if (uap->which >= RLIM_NLIMITS)
567 		return (EINVAL);
568 	p = td->td_proc;
569 	PROC_LOCK(p);
570 	lim_rlimit(p, uap->which, &rl);
571 	PROC_UNLOCK(p);
572 
573 	/*
574 	 * XXX would be more correct to convert only RLIM_INFINITY to the
575 	 * old RLIM_INFINITY and fail with EOVERFLOW for other larger
576 	 * values.  Most 64->32 and 32->16 conversions, including not
577 	 * unimportant ones of uids are even more broken than what we
578 	 * do here (they blindly truncate).  We don't do this correctly
579 	 * here since we have little experience with EOVERFLOW yet.
580 	 * Elsewhere, getuid() can't fail...
581 	 */
582 	olim.rlim_cur = rl.rlim_cur > 0x7fffffff ? 0x7fffffff : rl.rlim_cur;
583 	olim.rlim_max = rl.rlim_max > 0x7fffffff ? 0x7fffffff : rl.rlim_max;
584 	error = copyout(&olim, uap->rlp, sizeof(olim));
585 	return (error);
586 }
587 #endif /* COMPAT_43 */
588 
589 #ifndef _SYS_SYSPROTO_H_
590 struct __setrlimit_args {
591 	u_int	which;
592 	struct	rlimit *rlp;
593 };
594 #endif
595 int
596 sys_setrlimit(struct thread *td, register struct __setrlimit_args *uap)
597 {
598 	struct rlimit alim;
599 	int error;
600 
601 	if ((error = copyin(uap->rlp, &alim, sizeof(struct rlimit))))
602 		return (error);
603 	error = kern_setrlimit(td, uap->which, &alim);
604 	return (error);
605 }
606 
607 static void
608 lim_cb(void *arg)
609 {
610 	struct rlimit rlim;
611 	struct thread *td;
612 	struct proc *p;
613 
614 	p = arg;
615 	PROC_LOCK_ASSERT(p, MA_OWNED);
616 	/*
617 	 * Check if the process exceeds its cpu resource allocation.  If
618 	 * it reaches the max, arrange to kill the process in ast().
619 	 */
620 	if (p->p_cpulimit == RLIM_INFINITY)
621 		return;
622 	PROC_SLOCK(p);
623 	FOREACH_THREAD_IN_PROC(p, td) {
624 		ruxagg(p, td);
625 	}
626 	PROC_SUNLOCK(p);
627 	if (p->p_rux.rux_runtime > p->p_cpulimit * cpu_tickrate()) {
628 		lim_rlimit(p, RLIMIT_CPU, &rlim);
629 		if (p->p_rux.rux_runtime >= rlim.rlim_max * cpu_tickrate()) {
630 			killproc(p, "exceeded maximum CPU limit");
631 		} else {
632 			if (p->p_cpulimit < rlim.rlim_max)
633 				p->p_cpulimit += 5;
634 			kern_psignal(p, SIGXCPU);
635 		}
636 	}
637 	if ((p->p_flag & P_WEXIT) == 0)
638 		callout_reset_sbt(&p->p_limco, SBT_1S, 0,
639 		    lim_cb, p, C_PREL(1));
640 }
641 
642 int
643 kern_setrlimit(struct thread *td, u_int which, struct rlimit *limp)
644 {
645 
646 	return (kern_proc_setrlimit(td, td->td_proc, which, limp));
647 }
648 
649 int
650 kern_proc_setrlimit(struct thread *td, struct proc *p, u_int which,
651     struct rlimit *limp)
652 {
653 	struct plimit *newlim, *oldlim;
654 	register struct rlimit *alimp;
655 	struct rlimit oldssiz;
656 	int error;
657 
658 	if (which >= RLIM_NLIMITS)
659 		return (EINVAL);
660 
661 	/*
662 	 * Preserve historical bugs by treating negative limits as unsigned.
663 	 */
664 	if (limp->rlim_cur < 0)
665 		limp->rlim_cur = RLIM_INFINITY;
666 	if (limp->rlim_max < 0)
667 		limp->rlim_max = RLIM_INFINITY;
668 
669 	oldssiz.rlim_cur = 0;
670 	newlim = NULL;
671 	PROC_LOCK(p);
672 	if (lim_shared(p->p_limit)) {
673 		PROC_UNLOCK(p);
674 		newlim = lim_alloc();
675 		PROC_LOCK(p);
676 	}
677 	oldlim = p->p_limit;
678 	alimp = &oldlim->pl_rlimit[which];
679 	if (limp->rlim_cur > alimp->rlim_max ||
680 	    limp->rlim_max > alimp->rlim_max)
681 		if ((error = priv_check(td, PRIV_PROC_SETRLIMIT))) {
682 			PROC_UNLOCK(p);
683 			if (newlim != NULL)
684 				lim_free(newlim);
685 			return (error);
686 		}
687 	if (limp->rlim_cur > limp->rlim_max)
688 		limp->rlim_cur = limp->rlim_max;
689 	if (newlim != NULL) {
690 		lim_copy(newlim, oldlim);
691 		alimp = &newlim->pl_rlimit[which];
692 	}
693 
694 	switch (which) {
695 
696 	case RLIMIT_CPU:
697 		if (limp->rlim_cur != RLIM_INFINITY &&
698 		    p->p_cpulimit == RLIM_INFINITY)
699 			callout_reset_sbt(&p->p_limco, SBT_1S, 0,
700 			    lim_cb, p, C_PREL(1));
701 		p->p_cpulimit = limp->rlim_cur;
702 		break;
703 	case RLIMIT_DATA:
704 		if (limp->rlim_cur > maxdsiz)
705 			limp->rlim_cur = maxdsiz;
706 		if (limp->rlim_max > maxdsiz)
707 			limp->rlim_max = maxdsiz;
708 		break;
709 
710 	case RLIMIT_STACK:
711 		if (limp->rlim_cur > maxssiz)
712 			limp->rlim_cur = maxssiz;
713 		if (limp->rlim_max > maxssiz)
714 			limp->rlim_max = maxssiz;
715 		oldssiz = *alimp;
716 		if (p->p_sysent->sv_fixlimit != NULL)
717 			p->p_sysent->sv_fixlimit(&oldssiz,
718 			    RLIMIT_STACK);
719 		break;
720 
721 	case RLIMIT_NOFILE:
722 		if (limp->rlim_cur > maxfilesperproc)
723 			limp->rlim_cur = maxfilesperproc;
724 		if (limp->rlim_max > maxfilesperproc)
725 			limp->rlim_max = maxfilesperproc;
726 		break;
727 
728 	case RLIMIT_NPROC:
729 		if (limp->rlim_cur > maxprocperuid)
730 			limp->rlim_cur = maxprocperuid;
731 		if (limp->rlim_max > maxprocperuid)
732 			limp->rlim_max = maxprocperuid;
733 		if (limp->rlim_cur < 1)
734 			limp->rlim_cur = 1;
735 		if (limp->rlim_max < 1)
736 			limp->rlim_max = 1;
737 		break;
738 	}
739 	if (p->p_sysent->sv_fixlimit != NULL)
740 		p->p_sysent->sv_fixlimit(limp, which);
741 	*alimp = *limp;
742 	if (newlim != NULL)
743 		p->p_limit = newlim;
744 	PROC_UNLOCK(p);
745 	if (newlim != NULL)
746 		lim_free(oldlim);
747 
748 	if (which == RLIMIT_STACK) {
749 		/*
750 		 * Stack is allocated to the max at exec time with only
751 		 * "rlim_cur" bytes accessible.  If stack limit is going
752 		 * up make more accessible, if going down make inaccessible.
753 		 */
754 		if (limp->rlim_cur != oldssiz.rlim_cur) {
755 			vm_offset_t addr;
756 			vm_size_t size;
757 			vm_prot_t prot;
758 
759 			if (limp->rlim_cur > oldssiz.rlim_cur) {
760 				prot = p->p_sysent->sv_stackprot;
761 				size = limp->rlim_cur - oldssiz.rlim_cur;
762 				addr = p->p_sysent->sv_usrstack -
763 				    limp->rlim_cur;
764 			} else {
765 				prot = VM_PROT_NONE;
766 				size = oldssiz.rlim_cur - limp->rlim_cur;
767 				addr = p->p_sysent->sv_usrstack -
768 				    oldssiz.rlim_cur;
769 			}
770 			addr = trunc_page(addr);
771 			size = round_page(size);
772 			(void)vm_map_protect(&p->p_vmspace->vm_map,
773 			    addr, addr + size, prot, FALSE);
774 		}
775 	}
776 
777 	return (0);
778 }
779 
780 #ifndef _SYS_SYSPROTO_H_
781 struct __getrlimit_args {
782 	u_int	which;
783 	struct	rlimit *rlp;
784 };
785 #endif
786 /* ARGSUSED */
787 int
788 sys_getrlimit(struct thread *td, register struct __getrlimit_args *uap)
789 {
790 	struct rlimit rlim;
791 	struct proc *p;
792 	int error;
793 
794 	if (uap->which >= RLIM_NLIMITS)
795 		return (EINVAL);
796 	p = td->td_proc;
797 	PROC_LOCK(p);
798 	lim_rlimit(p, uap->which, &rlim);
799 	PROC_UNLOCK(p);
800 	error = copyout(&rlim, uap->rlp, sizeof(struct rlimit));
801 	return (error);
802 }
803 
804 /*
805  * Transform the running time and tick information for children of proc p
806  * into user and system time usage.
807  */
808 void
809 calccru(struct proc *p, struct timeval *up, struct timeval *sp)
810 {
811 
812 	PROC_LOCK_ASSERT(p, MA_OWNED);
813 	calcru1(p, &p->p_crux, up, sp);
814 }
815 
816 /*
817  * Transform the running time and tick information in proc p into user
818  * and system time usage.  If appropriate, include the current time slice
819  * on this CPU.
820  */
821 void
822 calcru(struct proc *p, struct timeval *up, struct timeval *sp)
823 {
824 	struct thread *td;
825 	uint64_t runtime, u;
826 
827 	PROC_LOCK_ASSERT(p, MA_OWNED);
828 	PROC_SLOCK_ASSERT(p, MA_OWNED);
829 	/*
830 	 * If we are getting stats for the current process, then add in the
831 	 * stats that this thread has accumulated in its current time slice.
832 	 * We reset the thread and CPU state as if we had performed a context
833 	 * switch right here.
834 	 */
835 	td = curthread;
836 	if (td->td_proc == p) {
837 		u = cpu_ticks();
838 		runtime = u - PCPU_GET(switchtime);
839 		td->td_runtime += runtime;
840 		td->td_incruntime += runtime;
841 		PCPU_SET(switchtime, u);
842 	}
843 	/* Make sure the per-thread stats are current. */
844 	FOREACH_THREAD_IN_PROC(p, td) {
845 		if (td->td_incruntime == 0)
846 			continue;
847 		ruxagg(p, td);
848 	}
849 	calcru1(p, &p->p_rux, up, sp);
850 }
851 
852 /* Collect resource usage for a single thread. */
853 void
854 rufetchtd(struct thread *td, struct rusage *ru)
855 {
856 	struct proc *p;
857 	uint64_t runtime, u;
858 
859 	p = td->td_proc;
860 	PROC_SLOCK_ASSERT(p, MA_OWNED);
861 	THREAD_LOCK_ASSERT(td, MA_OWNED);
862 	/*
863 	 * If we are getting stats for the current thread, then add in the
864 	 * stats that this thread has accumulated in its current time slice.
865 	 * We reset the thread and CPU state as if we had performed a context
866 	 * switch right here.
867 	 */
868 	if (td == curthread) {
869 		u = cpu_ticks();
870 		runtime = u - PCPU_GET(switchtime);
871 		td->td_runtime += runtime;
872 		td->td_incruntime += runtime;
873 		PCPU_SET(switchtime, u);
874 	}
875 	ruxagg(p, td);
876 	*ru = td->td_ru;
877 	calcru1(p, &td->td_rux, &ru->ru_utime, &ru->ru_stime);
878 }
879 
880 static void
881 calcru1(struct proc *p, struct rusage_ext *ruxp, struct timeval *up,
882     struct timeval *sp)
883 {
884 	/* {user, system, interrupt, total} {ticks, usec}: */
885 	uint64_t ut, uu, st, su, it, tt, tu;
886 
887 	ut = ruxp->rux_uticks;
888 	st = ruxp->rux_sticks;
889 	it = ruxp->rux_iticks;
890 	tt = ut + st + it;
891 	if (tt == 0) {
892 		/* Avoid divide by zero */
893 		st = 1;
894 		tt = 1;
895 	}
896 	tu = cputick2usec(ruxp->rux_runtime);
897 	if ((int64_t)tu < 0) {
898 		/* XXX: this should be an assert /phk */
899 		printf("calcru: negative runtime of %jd usec for pid %d (%s)\n",
900 		    (intmax_t)tu, p->p_pid, p->p_comm);
901 		tu = ruxp->rux_tu;
902 	}
903 
904 	if (tu >= ruxp->rux_tu) {
905 		/*
906 		 * The normal case, time increased.
907 		 * Enforce monotonicity of bucketed numbers.
908 		 */
909 		uu = (tu * ut) / tt;
910 		if (uu < ruxp->rux_uu)
911 			uu = ruxp->rux_uu;
912 		su = (tu * st) / tt;
913 		if (su < ruxp->rux_su)
914 			su = ruxp->rux_su;
915 	} else if (tu + 3 > ruxp->rux_tu || 101 * tu > 100 * ruxp->rux_tu) {
916 		/*
917 		 * When we calibrate the cputicker, it is not uncommon to
918 		 * see the presumably fixed frequency increase slightly over
919 		 * time as a result of thermal stabilization and NTP
920 		 * discipline (of the reference clock).  We therefore ignore
921 		 * a bit of backwards slop because we  expect to catch up
922 		 * shortly.  We use a 3 microsecond limit to catch low
923 		 * counts and a 1% limit for high counts.
924 		 */
925 		uu = ruxp->rux_uu;
926 		su = ruxp->rux_su;
927 		tu = ruxp->rux_tu;
928 	} else { /* tu < ruxp->rux_tu */
929 		/*
930 		 * What happened here was likely that a laptop, which ran at
931 		 * a reduced clock frequency at boot, kicked into high gear.
932 		 * The wisdom of spamming this message in that case is
933 		 * dubious, but it might also be indicative of something
934 		 * serious, so lets keep it and hope laptops can be made
935 		 * more truthful about their CPU speed via ACPI.
936 		 */
937 		printf("calcru: runtime went backwards from %ju usec "
938 		    "to %ju usec for pid %d (%s)\n",
939 		    (uintmax_t)ruxp->rux_tu, (uintmax_t)tu,
940 		    p->p_pid, p->p_comm);
941 		uu = (tu * ut) / tt;
942 		su = (tu * st) / tt;
943 	}
944 
945 	ruxp->rux_uu = uu;
946 	ruxp->rux_su = su;
947 	ruxp->rux_tu = tu;
948 
949 	up->tv_sec = uu / 1000000;
950 	up->tv_usec = uu % 1000000;
951 	sp->tv_sec = su / 1000000;
952 	sp->tv_usec = su % 1000000;
953 }
954 
955 #ifndef _SYS_SYSPROTO_H_
956 struct getrusage_args {
957 	int	who;
958 	struct	rusage *rusage;
959 };
960 #endif
961 int
962 sys_getrusage(register struct thread *td, register struct getrusage_args *uap)
963 {
964 	struct rusage ru;
965 	int error;
966 
967 	error = kern_getrusage(td, uap->who, &ru);
968 	if (error == 0)
969 		error = copyout(&ru, uap->rusage, sizeof(struct rusage));
970 	return (error);
971 }
972 
973 int
974 kern_getrusage(struct thread *td, int who, struct rusage *rup)
975 {
976 	struct proc *p;
977 	int error;
978 
979 	error = 0;
980 	p = td->td_proc;
981 	PROC_LOCK(p);
982 	switch (who) {
983 	case RUSAGE_SELF:
984 		rufetchcalc(p, rup, &rup->ru_utime,
985 		    &rup->ru_stime);
986 		break;
987 
988 	case RUSAGE_CHILDREN:
989 		*rup = p->p_stats->p_cru;
990 		calccru(p, &rup->ru_utime, &rup->ru_stime);
991 		break;
992 
993 	case RUSAGE_THREAD:
994 		PROC_SLOCK(p);
995 		thread_lock(td);
996 		rufetchtd(td, rup);
997 		thread_unlock(td);
998 		PROC_SUNLOCK(p);
999 		break;
1000 
1001 	default:
1002 		error = EINVAL;
1003 	}
1004 	PROC_UNLOCK(p);
1005 	return (error);
1006 }
1007 
1008 void
1009 rucollect(struct rusage *ru, struct rusage *ru2)
1010 {
1011 	long *ip, *ip2;
1012 	int i;
1013 
1014 	if (ru->ru_maxrss < ru2->ru_maxrss)
1015 		ru->ru_maxrss = ru2->ru_maxrss;
1016 	ip = &ru->ru_first;
1017 	ip2 = &ru2->ru_first;
1018 	for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--)
1019 		*ip++ += *ip2++;
1020 }
1021 
1022 void
1023 ruadd(struct rusage *ru, struct rusage_ext *rux, struct rusage *ru2,
1024     struct rusage_ext *rux2)
1025 {
1026 
1027 	rux->rux_runtime += rux2->rux_runtime;
1028 	rux->rux_uticks += rux2->rux_uticks;
1029 	rux->rux_sticks += rux2->rux_sticks;
1030 	rux->rux_iticks += rux2->rux_iticks;
1031 	rux->rux_uu += rux2->rux_uu;
1032 	rux->rux_su += rux2->rux_su;
1033 	rux->rux_tu += rux2->rux_tu;
1034 	rucollect(ru, ru2);
1035 }
1036 
1037 /*
1038  * Aggregate tick counts into the proc's rusage_ext.
1039  */
1040 static void
1041 ruxagg_locked(struct rusage_ext *rux, struct thread *td)
1042 {
1043 
1044 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1045 	PROC_SLOCK_ASSERT(td->td_proc, MA_OWNED);
1046 	rux->rux_runtime += td->td_incruntime;
1047 	rux->rux_uticks += td->td_uticks;
1048 	rux->rux_sticks += td->td_sticks;
1049 	rux->rux_iticks += td->td_iticks;
1050 }
1051 
1052 void
1053 ruxagg(struct proc *p, struct thread *td)
1054 {
1055 
1056 	thread_lock(td);
1057 	ruxagg_locked(&p->p_rux, td);
1058 	ruxagg_locked(&td->td_rux, td);
1059 	td->td_incruntime = 0;
1060 	td->td_uticks = 0;
1061 	td->td_iticks = 0;
1062 	td->td_sticks = 0;
1063 	thread_unlock(td);
1064 }
1065 
1066 /*
1067  * Update the rusage_ext structure and fetch a valid aggregate rusage
1068  * for proc p if storage for one is supplied.
1069  */
1070 void
1071 rufetch(struct proc *p, struct rusage *ru)
1072 {
1073 	struct thread *td;
1074 
1075 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1076 
1077 	*ru = p->p_ru;
1078 	if (p->p_numthreads > 0)  {
1079 		FOREACH_THREAD_IN_PROC(p, td) {
1080 			ruxagg(p, td);
1081 			rucollect(ru, &td->td_ru);
1082 		}
1083 	}
1084 }
1085 
1086 /*
1087  * Atomically perform a rufetch and a calcru together.
1088  * Consumers, can safely assume the calcru is executed only once
1089  * rufetch is completed.
1090  */
1091 void
1092 rufetchcalc(struct proc *p, struct rusage *ru, struct timeval *up,
1093     struct timeval *sp)
1094 {
1095 
1096 	PROC_SLOCK(p);
1097 	rufetch(p, ru);
1098 	calcru(p, up, sp);
1099 	PROC_SUNLOCK(p);
1100 }
1101 
1102 /*
1103  * Allocate a new resource limits structure and initialize its
1104  * reference count and mutex pointer.
1105  */
1106 struct plimit *
1107 lim_alloc()
1108 {
1109 	struct plimit *limp;
1110 
1111 	limp = malloc(sizeof(struct plimit), M_PLIMIT, M_WAITOK);
1112 	refcount_init(&limp->pl_refcnt, 1);
1113 	return (limp);
1114 }
1115 
1116 struct plimit *
1117 lim_hold(struct plimit *limp)
1118 {
1119 
1120 	refcount_acquire(&limp->pl_refcnt);
1121 	return (limp);
1122 }
1123 
1124 static __inline int
1125 lim_shared(struct plimit *limp)
1126 {
1127 
1128 	return (limp->pl_refcnt > 1);
1129 }
1130 
1131 void
1132 lim_fork(struct proc *p1, struct proc *p2)
1133 {
1134 
1135 	PROC_LOCK_ASSERT(p1, MA_OWNED);
1136 	PROC_LOCK_ASSERT(p2, MA_OWNED);
1137 
1138 	p2->p_limit = lim_hold(p1->p_limit);
1139 	callout_init_mtx(&p2->p_limco, &p2->p_mtx, 0);
1140 	if (p1->p_cpulimit != RLIM_INFINITY)
1141 		callout_reset_sbt(&p2->p_limco, SBT_1S, 0,
1142 		    lim_cb, p2, C_PREL(1));
1143 }
1144 
1145 void
1146 lim_free(struct plimit *limp)
1147 {
1148 
1149 	if (refcount_release(&limp->pl_refcnt))
1150 		free((void *)limp, M_PLIMIT);
1151 }
1152 
1153 /*
1154  * Make a copy of the plimit structure.
1155  * We share these structures copy-on-write after fork.
1156  */
1157 void
1158 lim_copy(struct plimit *dst, struct plimit *src)
1159 {
1160 
1161 	KASSERT(!lim_shared(dst), ("lim_copy to shared limit"));
1162 	bcopy(src->pl_rlimit, dst->pl_rlimit, sizeof(src->pl_rlimit));
1163 }
1164 
1165 /*
1166  * Return the hard limit for a particular system resource.  The
1167  * which parameter specifies the index into the rlimit array.
1168  */
1169 rlim_t
1170 lim_max(struct proc *p, int which)
1171 {
1172 	struct rlimit rl;
1173 
1174 	lim_rlimit(p, which, &rl);
1175 	return (rl.rlim_max);
1176 }
1177 
1178 /*
1179  * Return the current (soft) limit for a particular system resource.
1180  * The which parameter which specifies the index into the rlimit array
1181  */
1182 rlim_t
1183 lim_cur(struct proc *p, int which)
1184 {
1185 	struct rlimit rl;
1186 
1187 	lim_rlimit(p, which, &rl);
1188 	return (rl.rlim_cur);
1189 }
1190 
1191 /*
1192  * Return a copy of the entire rlimit structure for the system limit
1193  * specified by 'which' in the rlimit structure pointed to by 'rlp'.
1194  */
1195 void
1196 lim_rlimit(struct proc *p, int which, struct rlimit *rlp)
1197 {
1198 
1199 	PROC_LOCK_ASSERT(p, MA_OWNED);
1200 	KASSERT(which >= 0 && which < RLIM_NLIMITS,
1201 	    ("request for invalid resource limit"));
1202 	*rlp = p->p_limit->pl_rlimit[which];
1203 	if (p->p_sysent->sv_fixlimit != NULL)
1204 		p->p_sysent->sv_fixlimit(rlp, which);
1205 }
1206 
1207 void
1208 uihashinit()
1209 {
1210 
1211 	uihashtbl = hashinit(maxproc / 16, M_UIDINFO, &uihash);
1212 	rw_init(&uihashtbl_lock, "uidinfo hash");
1213 }
1214 
1215 /*
1216  * Look up a uidinfo struct for the parameter uid.
1217  * uihashtbl_lock must be locked.
1218  * Increase refcount on uidinfo struct returned.
1219  */
1220 static struct uidinfo *
1221 uilookup(uid_t uid)
1222 {
1223 	struct uihashhead *uipp;
1224 	struct uidinfo *uip;
1225 
1226 	rw_assert(&uihashtbl_lock, RA_LOCKED);
1227 	uipp = UIHASH(uid);
1228 	LIST_FOREACH(uip, uipp, ui_hash)
1229 		if (uip->ui_uid == uid) {
1230 			uihold(uip);
1231 			break;
1232 		}
1233 
1234 	return (uip);
1235 }
1236 
1237 /*
1238  * Find or allocate a struct uidinfo for a particular uid.
1239  * Returns with uidinfo struct referenced.
1240  * uifree() should be called on a struct uidinfo when released.
1241  */
1242 struct uidinfo *
1243 uifind(uid_t uid)
1244 {
1245 	struct uidinfo *new_uip, *uip;
1246 
1247 	rw_rlock(&uihashtbl_lock);
1248 	uip = uilookup(uid);
1249 	rw_runlock(&uihashtbl_lock);
1250 	if (uip != NULL)
1251 		return (uip);
1252 
1253 	new_uip = malloc(sizeof(*new_uip), M_UIDINFO, M_WAITOK | M_ZERO);
1254 	racct_create(&new_uip->ui_racct);
1255 	refcount_init(&new_uip->ui_ref, 1);
1256 	new_uip->ui_uid = uid;
1257 	mtx_init(&new_uip->ui_vmsize_mtx, "ui_vmsize", NULL, MTX_DEF);
1258 
1259 	rw_wlock(&uihashtbl_lock);
1260 	/*
1261 	 * There's a chance someone created our uidinfo while we
1262 	 * were in malloc and not holding the lock, so we have to
1263 	 * make sure we don't insert a duplicate uidinfo.
1264 	 */
1265 	if ((uip = uilookup(uid)) == NULL) {
1266 		LIST_INSERT_HEAD(UIHASH(uid), new_uip, ui_hash);
1267 		rw_wunlock(&uihashtbl_lock);
1268 		uip = new_uip;
1269 	} else {
1270 		rw_wunlock(&uihashtbl_lock);
1271 		racct_destroy(&new_uip->ui_racct);
1272 		mtx_destroy(&new_uip->ui_vmsize_mtx);
1273 		free(new_uip, M_UIDINFO);
1274 	}
1275 	return (uip);
1276 }
1277 
1278 /*
1279  * Place another refcount on a uidinfo struct.
1280  */
1281 void
1282 uihold(struct uidinfo *uip)
1283 {
1284 
1285 	refcount_acquire(&uip->ui_ref);
1286 }
1287 
1288 /*-
1289  * Since uidinfo structs have a long lifetime, we use an
1290  * opportunistic refcounting scheme to avoid locking the lookup hash
1291  * for each release.
1292  *
1293  * If the refcount hits 0, we need to free the structure,
1294  * which means we need to lock the hash.
1295  * Optimal case:
1296  *   After locking the struct and lowering the refcount, if we find
1297  *   that we don't need to free, simply unlock and return.
1298  * Suboptimal case:
1299  *   If refcount lowering results in need to free, bump the count
1300  *   back up, lose the lock and acquire the locks in the proper
1301  *   order to try again.
1302  */
1303 void
1304 uifree(struct uidinfo *uip)
1305 {
1306 	int old;
1307 
1308 	/* Prepare for optimal case. */
1309 	old = uip->ui_ref;
1310 	if (old > 1 && atomic_cmpset_int(&uip->ui_ref, old, old - 1))
1311 		return;
1312 
1313 	/* Prepare for suboptimal case. */
1314 	rw_wlock(&uihashtbl_lock);
1315 	if (refcount_release(&uip->ui_ref) == 0) {
1316 		rw_wunlock(&uihashtbl_lock);
1317 		return;
1318 	}
1319 
1320 	racct_destroy(&uip->ui_racct);
1321 	LIST_REMOVE(uip, ui_hash);
1322 	rw_wunlock(&uihashtbl_lock);
1323 
1324 	if (uip->ui_sbsize != 0)
1325 		printf("freeing uidinfo: uid = %d, sbsize = %ld\n",
1326 		    uip->ui_uid, uip->ui_sbsize);
1327 	if (uip->ui_proccnt != 0)
1328 		printf("freeing uidinfo: uid = %d, proccnt = %ld\n",
1329 		    uip->ui_uid, uip->ui_proccnt);
1330 	if (uip->ui_vmsize != 0)
1331 		printf("freeing uidinfo: uid = %d, swapuse = %lld\n",
1332 		    uip->ui_uid, (unsigned long long)uip->ui_vmsize);
1333 	mtx_destroy(&uip->ui_vmsize_mtx);
1334 	free(uip, M_UIDINFO);
1335 }
1336 
1337 void
1338 ui_racct_foreach(void (*callback)(struct racct *racct,
1339     void *arg2, void *arg3), void *arg2, void *arg3)
1340 {
1341 	struct uidinfo *uip;
1342 	struct uihashhead *uih;
1343 
1344 	rw_rlock(&uihashtbl_lock);
1345 	for (uih = &uihashtbl[uihash]; uih >= uihashtbl; uih--) {
1346 		LIST_FOREACH(uip, uih, ui_hash) {
1347 			(callback)(uip->ui_racct, arg2, arg3);
1348 		}
1349 	}
1350 	rw_runlock(&uihashtbl_lock);
1351 }
1352 
1353 /*
1354  * Change the count associated with number of processes
1355  * a given user is using.  When 'max' is 0, don't enforce a limit
1356  */
1357 int
1358 chgproccnt(struct uidinfo *uip, int diff, rlim_t max)
1359 {
1360 
1361 	/* Don't allow them to exceed max, but allow subtraction. */
1362 	if (diff > 0 && max != 0) {
1363 		if (atomic_fetchadd_long(&uip->ui_proccnt, (long)diff) + diff > max) {
1364 			atomic_subtract_long(&uip->ui_proccnt, (long)diff);
1365 			return (0);
1366 		}
1367 	} else {
1368 		atomic_add_long(&uip->ui_proccnt, (long)diff);
1369 		if (uip->ui_proccnt < 0)
1370 			printf("negative proccnt for uid = %d\n", uip->ui_uid);
1371 	}
1372 	return (1);
1373 }
1374 
1375 /*
1376  * Change the total socket buffer size a user has used.
1377  */
1378 int
1379 chgsbsize(struct uidinfo *uip, u_int *hiwat, u_int to, rlim_t max)
1380 {
1381 	int diff;
1382 
1383 	diff = to - *hiwat;
1384 	if (diff > 0) {
1385 		if (atomic_fetchadd_long(&uip->ui_sbsize, (long)diff) + diff > max) {
1386 			atomic_subtract_long(&uip->ui_sbsize, (long)diff);
1387 			return (0);
1388 		}
1389 	} else {
1390 		atomic_add_long(&uip->ui_sbsize, (long)diff);
1391 		if (uip->ui_sbsize < 0)
1392 			printf("negative sbsize for uid = %d\n", uip->ui_uid);
1393 	}
1394 	*hiwat = to;
1395 	return (1);
1396 }
1397 
1398 /*
1399  * Change the count associated with number of pseudo-terminals
1400  * a given user is using.  When 'max' is 0, don't enforce a limit
1401  */
1402 int
1403 chgptscnt(struct uidinfo *uip, int diff, rlim_t max)
1404 {
1405 
1406 	/* Don't allow them to exceed max, but allow subtraction. */
1407 	if (diff > 0 && max != 0) {
1408 		if (atomic_fetchadd_long(&uip->ui_ptscnt, (long)diff) + diff > max) {
1409 			atomic_subtract_long(&uip->ui_ptscnt, (long)diff);
1410 			return (0);
1411 		}
1412 	} else {
1413 		atomic_add_long(&uip->ui_ptscnt, (long)diff);
1414 		if (uip->ui_ptscnt < 0)
1415 			printf("negative ptscnt for uid = %d\n", uip->ui_uid);
1416 	}
1417 	return (1);
1418 }
1419 
1420 int
1421 chgkqcnt(struct uidinfo *uip, int diff, rlim_t max)
1422 {
1423 
1424 	if (diff > 0 && max != 0) {
1425 		if (atomic_fetchadd_long(&uip->ui_kqcnt, (long)diff) +
1426 		    diff > max) {
1427 			atomic_subtract_long(&uip->ui_kqcnt, (long)diff);
1428 			return (0);
1429 		}
1430 	} else {
1431 		atomic_add_long(&uip->ui_kqcnt, (long)diff);
1432 		if (uip->ui_kqcnt < 0)
1433 			printf("negative kqcnt for uid = %d\n", uip->ui_uid);
1434 	}
1435 	return (1);
1436 }
1437