xref: /freebsd/sys/kern/kern_resource.c (revision 9a14aa017b21c292740c00ee098195cd46642730)
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 /*
84  * Resource controls and accounting.
85  */
86 #ifndef _SYS_SYSPROTO_H_
87 struct getpriority_args {
88 	int	which;
89 	int	who;
90 };
91 #endif
92 int
93 sys_getpriority(td, uap)
94 	struct thread *td;
95 	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(td, uap)
179 	struct thread *td;
180 	struct setpriority_args *uap;
181 {
182 	struct proc *curp, *p;
183 	struct pgrp *pg;
184 	int found = 0, error = 0;
185 
186 	curp = td->td_proc;
187 	switch (uap->which) {
188 	case PRIO_PROCESS:
189 		if (uap->who == 0) {
190 			PROC_LOCK(curp);
191 			error = donice(td, curp, uap->prio);
192 			PROC_UNLOCK(curp);
193 		} else {
194 			p = pfind(uap->who);
195 			if (p == NULL)
196 				break;
197 			error = p_cansee(td, p);
198 			if (error == 0)
199 				error = donice(td, p, uap->prio);
200 			PROC_UNLOCK(p);
201 		}
202 		found++;
203 		break;
204 
205 	case PRIO_PGRP:
206 		sx_slock(&proctree_lock);
207 		if (uap->who == 0) {
208 			pg = curp->p_pgrp;
209 			PGRP_LOCK(pg);
210 		} else {
211 			pg = pgfind(uap->who);
212 			if (pg == NULL) {
213 				sx_sunlock(&proctree_lock);
214 				break;
215 			}
216 		}
217 		sx_sunlock(&proctree_lock);
218 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
219 			PROC_LOCK(p);
220 			if (p->p_state == PRS_NORMAL &&
221 			    p_cansee(td, p) == 0) {
222 				error = donice(td, p, uap->prio);
223 				found++;
224 			}
225 			PROC_UNLOCK(p);
226 		}
227 		PGRP_UNLOCK(pg);
228 		break;
229 
230 	case PRIO_USER:
231 		if (uap->who == 0)
232 			uap->who = td->td_ucred->cr_uid;
233 		sx_slock(&allproc_lock);
234 		FOREACH_PROC_IN_SYSTEM(p) {
235 			PROC_LOCK(p);
236 			if (p->p_state == PRS_NORMAL &&
237 			    p->p_ucred->cr_uid == uap->who &&
238 			    p_cansee(td, p) == 0) {
239 				error = donice(td, p, uap->prio);
240 				found++;
241 			}
242 			PROC_UNLOCK(p);
243 		}
244 		sx_sunlock(&allproc_lock);
245 		break;
246 
247 	default:
248 		error = EINVAL;
249 		break;
250 	}
251 	if (found == 0 && error == 0)
252 		error = ESRCH;
253 	return (error);
254 }
255 
256 /*
257  * Set "nice" for a (whole) process.
258  */
259 static int
260 donice(struct thread *td, struct proc *p, int n)
261 {
262 	int error;
263 
264 	PROC_LOCK_ASSERT(p, MA_OWNED);
265 	if ((error = p_cansched(td, p)))
266 		return (error);
267 	if (n > PRIO_MAX)
268 		n = PRIO_MAX;
269 	if (n < PRIO_MIN)
270 		n = PRIO_MIN;
271 	if (n < p->p_nice && priv_check(td, PRIV_SCHED_SETPRIORITY) != 0)
272 		return (EACCES);
273 	sched_nice(p, n);
274 	return (0);
275 }
276 
277 static int unprivileged_idprio;
278 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_idprio, CTLFLAG_RW,
279     &unprivileged_idprio, 0, "Allow non-root users to set an idle priority");
280 
281 /*
282  * Set realtime priority for LWP.
283  */
284 #ifndef _SYS_SYSPROTO_H_
285 struct rtprio_thread_args {
286 	int		function;
287 	lwpid_t		lwpid;
288 	struct rtprio	*rtp;
289 };
290 #endif
291 int
292 sys_rtprio_thread(struct thread *td, struct rtprio_thread_args *uap)
293 {
294 	struct proc *p;
295 	struct rtprio rtp;
296 	struct thread *td1;
297 	int cierror, error;
298 
299 	/* Perform copyin before acquiring locks if needed. */
300 	if (uap->function == RTP_SET)
301 		cierror = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
302 	else
303 		cierror = 0;
304 
305 	if (uap->lwpid == 0 || uap->lwpid == td->td_tid) {
306 		p = td->td_proc;
307 		td1 = td;
308 		PROC_LOCK(p);
309 	} else {
310 		/* Only look up thread in current process */
311 		td1 = tdfind(uap->lwpid, curproc->p_pid);
312 		if (td1 == NULL)
313 			return (ESRCH);
314 		p = td1->td_proc;
315 	}
316 
317 	switch (uap->function) {
318 	case RTP_LOOKUP:
319 		if ((error = p_cansee(td, p)))
320 			break;
321 		pri_to_rtp(td1, &rtp);
322 		PROC_UNLOCK(p);
323 		return (copyout(&rtp, uap->rtp, sizeof(struct rtprio)));
324 	case RTP_SET:
325 		if ((error = p_cansched(td, p)) || (error = cierror))
326 			break;
327 
328 		/* Disallow setting rtprio in most cases if not superuser. */
329 
330 		/*
331 		 * Realtime priority has to be restricted for reasons which
332 		 * should be obvious.  However, for idleprio processes, there is
333 		 * a potential for system deadlock if an idleprio process gains
334 		 * a lock on a resource that other processes need (and the
335 		 * idleprio process can't run due to a CPU-bound normal
336 		 * process).  Fix me!  XXX
337 		 *
338 		 * This problem is not only related to idleprio process.
339 		 * A user level program can obtain a file lock and hold it
340 		 * indefinitely.  Additionally, without idleprio processes it is
341 		 * still conceivable that a program with low priority will never
342 		 * get to run.  In short, allowing this feature might make it
343 		 * easier to lock a resource indefinitely, but it is not the
344 		 * only thing that makes it possible.
345 		 */
346 		if (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_REALTIME ||
347 		    (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_IDLE &&
348 		    unprivileged_idprio == 0)) {
349 			error = priv_check(td, PRIV_SCHED_RTPRIO);
350 			if (error)
351 				break;
352 		}
353 		error = rtp_to_pri(&rtp, td1);
354 		break;
355 	default:
356 		error = EINVAL;
357 		break;
358 	}
359 	PROC_UNLOCK(p);
360 	return (error);
361 }
362 
363 /*
364  * Set realtime priority.
365  */
366 #ifndef _SYS_SYSPROTO_H_
367 struct rtprio_args {
368 	int		function;
369 	pid_t		pid;
370 	struct rtprio	*rtp;
371 };
372 #endif
373 int
374 sys_rtprio(td, uap)
375 	struct thread *td;		/* curthread */
376 	register struct rtprio_args *uap;
377 {
378 	struct proc *p;
379 	struct thread *tdp;
380 	struct rtprio rtp;
381 	int cierror, error;
382 
383 	/* Perform copyin before acquiring locks if needed. */
384 	if (uap->function == RTP_SET)
385 		cierror = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
386 	else
387 		cierror = 0;
388 
389 	if (uap->pid == 0) {
390 		p = td->td_proc;
391 		PROC_LOCK(p);
392 	} else {
393 		p = pfind(uap->pid);
394 		if (p == NULL)
395 			return (ESRCH);
396 	}
397 
398 	switch (uap->function) {
399 	case RTP_LOOKUP:
400 		if ((error = p_cansee(td, p)))
401 			break;
402 		/*
403 		 * Return OUR priority if no pid specified,
404 		 * or if one is, report the highest priority
405 		 * in the process.  There isn't much more you can do as
406 		 * there is only room to return a single priority.
407 		 * Note: specifying our own pid is not the same
408 		 * as leaving it zero.
409 		 */
410 		if (uap->pid == 0) {
411 			pri_to_rtp(td, &rtp);
412 		} else {
413 			struct rtprio rtp2;
414 
415 			rtp.type = RTP_PRIO_IDLE;
416 			rtp.prio = RTP_PRIO_MAX;
417 			FOREACH_THREAD_IN_PROC(p, tdp) {
418 				pri_to_rtp(tdp, &rtp2);
419 				if (rtp2.type <  rtp.type ||
420 				    (rtp2.type == rtp.type &&
421 				    rtp2.prio < rtp.prio)) {
422 					rtp.type = rtp2.type;
423 					rtp.prio = rtp2.prio;
424 				}
425 			}
426 		}
427 		PROC_UNLOCK(p);
428 		return (copyout(&rtp, uap->rtp, sizeof(struct rtprio)));
429 	case RTP_SET:
430 		if ((error = p_cansched(td, p)) || (error = cierror))
431 			break;
432 
433 		/*
434 		 * Disallow setting rtprio in most cases if not superuser.
435 		 * See the comment in sys_rtprio_thread about idprio
436 		 * threads holding a lock.
437 		 */
438 		if (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_REALTIME ||
439 		    (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_IDLE &&
440 		    !unprivileged_idprio)) {
441 			error = priv_check(td, PRIV_SCHED_RTPRIO);
442 			if (error)
443 				break;
444 		}
445 
446 		/*
447 		 * If we are setting our own priority, set just our
448 		 * thread but if we are doing another process,
449 		 * do all the threads on that process. If we
450 		 * specify our own pid we do the latter.
451 		 */
452 		if (uap->pid == 0) {
453 			error = rtp_to_pri(&rtp, td);
454 		} else {
455 			FOREACH_THREAD_IN_PROC(p, td) {
456 				if ((error = rtp_to_pri(&rtp, td)) != 0)
457 					break;
458 			}
459 		}
460 		break;
461 	default:
462 		error = EINVAL;
463 		break;
464 	}
465 	PROC_UNLOCK(p);
466 	return (error);
467 }
468 
469 int
470 rtp_to_pri(struct rtprio *rtp, struct thread *td)
471 {
472 	u_char	newpri;
473 	u_char	oldpri;
474 
475 	switch (RTP_PRIO_BASE(rtp->type)) {
476 	case RTP_PRIO_REALTIME:
477 		if (rtp->prio > RTP_PRIO_MAX)
478 			return (EINVAL);
479 		newpri = PRI_MIN_REALTIME + rtp->prio;
480 		break;
481 	case RTP_PRIO_NORMAL:
482 		if (rtp->prio > (PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE))
483 			return (EINVAL);
484 		newpri = PRI_MIN_TIMESHARE + rtp->prio;
485 		break;
486 	case RTP_PRIO_IDLE:
487 		if (rtp->prio > RTP_PRIO_MAX)
488 			return (EINVAL);
489 		newpri = PRI_MIN_IDLE + rtp->prio;
490 		break;
491 	default:
492 		return (EINVAL);
493 	}
494 
495 	thread_lock(td);
496 	sched_class(td, rtp->type);	/* XXX fix */
497 	oldpri = td->td_user_pri;
498 	sched_user_prio(td, newpri);
499 	if (td->td_user_pri != oldpri && (td == curthread ||
500 	    td->td_priority == oldpri || td->td_user_pri <= PRI_MAX_REALTIME))
501 		sched_prio(td, td->td_user_pri);
502 	if (TD_ON_UPILOCK(td) && oldpri != newpri) {
503 		critical_enter();
504 		thread_unlock(td);
505 		umtx_pi_adjust(td, oldpri);
506 		critical_exit();
507 	} else
508 		thread_unlock(td);
509 	return (0);
510 }
511 
512 void
513 pri_to_rtp(struct thread *td, struct rtprio *rtp)
514 {
515 
516 	thread_lock(td);
517 	switch (PRI_BASE(td->td_pri_class)) {
518 	case PRI_REALTIME:
519 		rtp->prio = td->td_base_user_pri - PRI_MIN_REALTIME;
520 		break;
521 	case PRI_TIMESHARE:
522 		rtp->prio = td->td_base_user_pri - PRI_MIN_TIMESHARE;
523 		break;
524 	case PRI_IDLE:
525 		rtp->prio = td->td_base_user_pri - PRI_MIN_IDLE;
526 		break;
527 	default:
528 		break;
529 	}
530 	rtp->type = td->td_pri_class;
531 	thread_unlock(td);
532 }
533 
534 #if defined(COMPAT_43)
535 #ifndef _SYS_SYSPROTO_H_
536 struct osetrlimit_args {
537 	u_int	which;
538 	struct	orlimit *rlp;
539 };
540 #endif
541 int
542 osetrlimit(td, uap)
543 	struct thread *td;
544 	register struct osetrlimit_args *uap;
545 {
546 	struct orlimit olim;
547 	struct rlimit lim;
548 	int error;
549 
550 	if ((error = copyin(uap->rlp, &olim, sizeof(struct orlimit))))
551 		return (error);
552 	lim.rlim_cur = olim.rlim_cur;
553 	lim.rlim_max = olim.rlim_max;
554 	error = kern_setrlimit(td, uap->which, &lim);
555 	return (error);
556 }
557 
558 #ifndef _SYS_SYSPROTO_H_
559 struct ogetrlimit_args {
560 	u_int	which;
561 	struct	orlimit *rlp;
562 };
563 #endif
564 int
565 ogetrlimit(td, uap)
566 	struct thread *td;
567 	register struct ogetrlimit_args *uap;
568 {
569 	struct orlimit olim;
570 	struct rlimit rl;
571 	struct proc *p;
572 	int error;
573 
574 	if (uap->which >= RLIM_NLIMITS)
575 		return (EINVAL);
576 	p = td->td_proc;
577 	PROC_LOCK(p);
578 	lim_rlimit(p, uap->which, &rl);
579 	PROC_UNLOCK(p);
580 
581 	/*
582 	 * XXX would be more correct to convert only RLIM_INFINITY to the
583 	 * old RLIM_INFINITY and fail with EOVERFLOW for other larger
584 	 * values.  Most 64->32 and 32->16 conversions, including not
585 	 * unimportant ones of uids are even more broken than what we
586 	 * do here (they blindly truncate).  We don't do this correctly
587 	 * here since we have little experience with EOVERFLOW yet.
588 	 * Elsewhere, getuid() can't fail...
589 	 */
590 	olim.rlim_cur = rl.rlim_cur > 0x7fffffff ? 0x7fffffff : rl.rlim_cur;
591 	olim.rlim_max = rl.rlim_max > 0x7fffffff ? 0x7fffffff : rl.rlim_max;
592 	error = copyout(&olim, uap->rlp, sizeof(olim));
593 	return (error);
594 }
595 #endif /* COMPAT_43 */
596 
597 #ifndef _SYS_SYSPROTO_H_
598 struct __setrlimit_args {
599 	u_int	which;
600 	struct	rlimit *rlp;
601 };
602 #endif
603 int
604 sys_setrlimit(td, uap)
605 	struct thread *td;
606 	register struct __setrlimit_args *uap;
607 {
608 	struct rlimit alim;
609 	int error;
610 
611 	if ((error = copyin(uap->rlp, &alim, sizeof(struct rlimit))))
612 		return (error);
613 	error = kern_setrlimit(td, uap->which, &alim);
614 	return (error);
615 }
616 
617 static void
618 lim_cb(void *arg)
619 {
620 	struct rlimit rlim;
621 	struct thread *td;
622 	struct proc *p;
623 
624 	p = arg;
625 	PROC_LOCK_ASSERT(p, MA_OWNED);
626 	/*
627 	 * Check if the process exceeds its cpu resource allocation.  If
628 	 * it reaches the max, arrange to kill the process in ast().
629 	 */
630 	if (p->p_cpulimit == RLIM_INFINITY)
631 		return;
632 	PROC_SLOCK(p);
633 	FOREACH_THREAD_IN_PROC(p, td) {
634 		ruxagg(p, td);
635 	}
636 	PROC_SUNLOCK(p);
637 	if (p->p_rux.rux_runtime > p->p_cpulimit * cpu_tickrate()) {
638 		lim_rlimit(p, RLIMIT_CPU, &rlim);
639 		if (p->p_rux.rux_runtime >= rlim.rlim_max * cpu_tickrate()) {
640 			killproc(p, "exceeded maximum CPU limit");
641 		} else {
642 			if (p->p_cpulimit < rlim.rlim_max)
643 				p->p_cpulimit += 5;
644 			kern_psignal(p, SIGXCPU);
645 		}
646 	}
647 	if ((p->p_flag & P_WEXIT) == 0)
648 		callout_reset(&p->p_limco, hz, lim_cb, p);
649 }
650 
651 int
652 kern_setrlimit(td, which, limp)
653 	struct thread *td;
654 	u_int which;
655 	struct rlimit *limp;
656 {
657 	struct plimit *newlim, *oldlim;
658 	struct proc *p;
659 	register struct rlimit *alimp;
660 	struct rlimit oldssiz;
661 	int error;
662 
663 	if (which >= RLIM_NLIMITS)
664 		return (EINVAL);
665 
666 	/*
667 	 * Preserve historical bugs by treating negative limits as unsigned.
668 	 */
669 	if (limp->rlim_cur < 0)
670 		limp->rlim_cur = RLIM_INFINITY;
671 	if (limp->rlim_max < 0)
672 		limp->rlim_max = RLIM_INFINITY;
673 
674 	oldssiz.rlim_cur = 0;
675 	p = td->td_proc;
676 	newlim = lim_alloc();
677 	PROC_LOCK(p);
678 	oldlim = p->p_limit;
679 	alimp = &oldlim->pl_rlimit[which];
680 	if (limp->rlim_cur > alimp->rlim_max ||
681 	    limp->rlim_max > alimp->rlim_max)
682 		if ((error = priv_check(td, PRIV_PROC_SETRLIMIT))) {
683 			PROC_UNLOCK(p);
684 			lim_free(newlim);
685 			return (error);
686 		}
687 	if (limp->rlim_cur > limp->rlim_max)
688 		limp->rlim_cur = limp->rlim_max;
689 	lim_copy(newlim, oldlim);
690 	alimp = &newlim->pl_rlimit[which];
691 
692 	switch (which) {
693 
694 	case RLIMIT_CPU:
695 		if (limp->rlim_cur != RLIM_INFINITY &&
696 		    p->p_cpulimit == RLIM_INFINITY)
697 			callout_reset(&p->p_limco, hz, lim_cb, p);
698 		p->p_cpulimit = limp->rlim_cur;
699 		break;
700 	case RLIMIT_DATA:
701 		if (limp->rlim_cur > maxdsiz)
702 			limp->rlim_cur = maxdsiz;
703 		if (limp->rlim_max > maxdsiz)
704 			limp->rlim_max = maxdsiz;
705 		break;
706 
707 	case RLIMIT_STACK:
708 		if (limp->rlim_cur > maxssiz)
709 			limp->rlim_cur = maxssiz;
710 		if (limp->rlim_max > maxssiz)
711 			limp->rlim_max = maxssiz;
712 		oldssiz = *alimp;
713 		if (p->p_sysent->sv_fixlimit != NULL)
714 			p->p_sysent->sv_fixlimit(&oldssiz,
715 			    RLIMIT_STACK);
716 		break;
717 
718 	case RLIMIT_NOFILE:
719 		if (limp->rlim_cur > maxfilesperproc)
720 			limp->rlim_cur = maxfilesperproc;
721 		if (limp->rlim_max > maxfilesperproc)
722 			limp->rlim_max = maxfilesperproc;
723 		break;
724 
725 	case RLIMIT_NPROC:
726 		if (limp->rlim_cur > maxprocperuid)
727 			limp->rlim_cur = maxprocperuid;
728 		if (limp->rlim_max > maxprocperuid)
729 			limp->rlim_max = maxprocperuid;
730 		if (limp->rlim_cur < 1)
731 			limp->rlim_cur = 1;
732 		if (limp->rlim_max < 1)
733 			limp->rlim_max = 1;
734 		break;
735 	}
736 	if (p->p_sysent->sv_fixlimit != NULL)
737 		p->p_sysent->sv_fixlimit(limp, which);
738 	*alimp = *limp;
739 	p->p_limit = newlim;
740 	PROC_UNLOCK(p);
741 	lim_free(oldlim);
742 
743 	if (which == RLIMIT_STACK) {
744 		/*
745 		 * Stack is allocated to the max at exec time with only
746 		 * "rlim_cur" bytes accessible.  If stack limit is going
747 		 * up make more accessible, if going down make inaccessible.
748 		 */
749 		if (limp->rlim_cur != oldssiz.rlim_cur) {
750 			vm_offset_t addr;
751 			vm_size_t size;
752 			vm_prot_t prot;
753 
754 			if (limp->rlim_cur > oldssiz.rlim_cur) {
755 				prot = p->p_sysent->sv_stackprot;
756 				size = limp->rlim_cur - oldssiz.rlim_cur;
757 				addr = p->p_sysent->sv_usrstack -
758 				    limp->rlim_cur;
759 			} else {
760 				prot = VM_PROT_NONE;
761 				size = oldssiz.rlim_cur - limp->rlim_cur;
762 				addr = p->p_sysent->sv_usrstack -
763 				    oldssiz.rlim_cur;
764 			}
765 			addr = trunc_page(addr);
766 			size = round_page(size);
767 			(void)vm_map_protect(&p->p_vmspace->vm_map,
768 			    addr, addr + size, prot, FALSE);
769 		}
770 	}
771 
772 	return (0);
773 }
774 
775 #ifndef _SYS_SYSPROTO_H_
776 struct __getrlimit_args {
777 	u_int	which;
778 	struct	rlimit *rlp;
779 };
780 #endif
781 /* ARGSUSED */
782 int
783 sys_getrlimit(td, uap)
784 	struct thread *td;
785 	register struct __getrlimit_args *uap;
786 {
787 	struct rlimit rlim;
788 	struct proc *p;
789 	int error;
790 
791 	if (uap->which >= RLIM_NLIMITS)
792 		return (EINVAL);
793 	p = td->td_proc;
794 	PROC_LOCK(p);
795 	lim_rlimit(p, uap->which, &rlim);
796 	PROC_UNLOCK(p);
797 	error = copyout(&rlim, uap->rlp, sizeof(struct rlimit));
798 	return (error);
799 }
800 
801 /*
802  * Transform the running time and tick information for children of proc p
803  * into user and system time usage.
804  */
805 void
806 calccru(p, up, sp)
807 	struct proc *p;
808 	struct timeval *up;
809 	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(td, uap)
963 	register struct thread *td;
964 	register struct getrusage_args *uap;
965 {
966 	struct rusage ru;
967 	int error;
968 
969 	error = kern_getrusage(td, uap->who, &ru);
970 	if (error == 0)
971 		error = copyout(&ru, uap->rusage, sizeof(struct rusage));
972 	return (error);
973 }
974 
975 int
976 kern_getrusage(struct thread *td, int who, struct rusage *rup)
977 {
978 	struct proc *p;
979 	int error;
980 
981 	error = 0;
982 	p = td->td_proc;
983 	PROC_LOCK(p);
984 	switch (who) {
985 	case RUSAGE_SELF:
986 		rufetchcalc(p, rup, &rup->ru_utime,
987 		    &rup->ru_stime);
988 		break;
989 
990 	case RUSAGE_CHILDREN:
991 		*rup = p->p_stats->p_cru;
992 		calccru(p, &rup->ru_utime, &rup->ru_stime);
993 		break;
994 
995 	case RUSAGE_THREAD:
996 		PROC_SLOCK(p);
997 		thread_lock(td);
998 		rufetchtd(td, rup);
999 		thread_unlock(td);
1000 		PROC_SUNLOCK(p);
1001 		break;
1002 
1003 	default:
1004 		error = EINVAL;
1005 	}
1006 	PROC_UNLOCK(p);
1007 	return (error);
1008 }
1009 
1010 void
1011 rucollect(struct rusage *ru, struct rusage *ru2)
1012 {
1013 	long *ip, *ip2;
1014 	int i;
1015 
1016 	if (ru->ru_maxrss < ru2->ru_maxrss)
1017 		ru->ru_maxrss = ru2->ru_maxrss;
1018 	ip = &ru->ru_first;
1019 	ip2 = &ru2->ru_first;
1020 	for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--)
1021 		*ip++ += *ip2++;
1022 }
1023 
1024 void
1025 ruadd(struct rusage *ru, struct rusage_ext *rux, struct rusage *ru2,
1026     struct rusage_ext *rux2)
1027 {
1028 
1029 	rux->rux_runtime += rux2->rux_runtime;
1030 	rux->rux_uticks += rux2->rux_uticks;
1031 	rux->rux_sticks += rux2->rux_sticks;
1032 	rux->rux_iticks += rux2->rux_iticks;
1033 	rux->rux_uu += rux2->rux_uu;
1034 	rux->rux_su += rux2->rux_su;
1035 	rux->rux_tu += rux2->rux_tu;
1036 	rucollect(ru, ru2);
1037 }
1038 
1039 /*
1040  * Aggregate tick counts into the proc's rusage_ext.
1041  */
1042 static void
1043 ruxagg_locked(struct rusage_ext *rux, struct thread *td)
1044 {
1045 
1046 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1047 	PROC_SLOCK_ASSERT(td->td_proc, MA_OWNED);
1048 	rux->rux_runtime += td->td_incruntime;
1049 	rux->rux_uticks += td->td_uticks;
1050 	rux->rux_sticks += td->td_sticks;
1051 	rux->rux_iticks += td->td_iticks;
1052 }
1053 
1054 void
1055 ruxagg(struct proc *p, struct thread *td)
1056 {
1057 
1058 	thread_lock(td);
1059 	ruxagg_locked(&p->p_rux, td);
1060 	ruxagg_locked(&td->td_rux, td);
1061 	td->td_incruntime = 0;
1062 	td->td_uticks = 0;
1063 	td->td_iticks = 0;
1064 	td->td_sticks = 0;
1065 	thread_unlock(td);
1066 }
1067 
1068 /*
1069  * Update the rusage_ext structure and fetch a valid aggregate rusage
1070  * for proc p if storage for one is supplied.
1071  */
1072 void
1073 rufetch(struct proc *p, struct rusage *ru)
1074 {
1075 	struct thread *td;
1076 
1077 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1078 
1079 	*ru = p->p_ru;
1080 	if (p->p_numthreads > 0)  {
1081 		FOREACH_THREAD_IN_PROC(p, td) {
1082 			ruxagg(p, td);
1083 			rucollect(ru, &td->td_ru);
1084 		}
1085 	}
1086 }
1087 
1088 /*
1089  * Atomically perform a rufetch and a calcru together.
1090  * Consumers, can safely assume the calcru is executed only once
1091  * rufetch is completed.
1092  */
1093 void
1094 rufetchcalc(struct proc *p, struct rusage *ru, struct timeval *up,
1095     struct timeval *sp)
1096 {
1097 
1098 	PROC_SLOCK(p);
1099 	rufetch(p, ru);
1100 	calcru(p, up, sp);
1101 	PROC_SUNLOCK(p);
1102 }
1103 
1104 /*
1105  * Allocate a new resource limits structure and initialize its
1106  * reference count and mutex pointer.
1107  */
1108 struct plimit *
1109 lim_alloc()
1110 {
1111 	struct plimit *limp;
1112 
1113 	limp = malloc(sizeof(struct plimit), M_PLIMIT, M_WAITOK);
1114 	refcount_init(&limp->pl_refcnt, 1);
1115 	return (limp);
1116 }
1117 
1118 struct plimit *
1119 lim_hold(limp)
1120 	struct plimit *limp;
1121 {
1122 
1123 	refcount_acquire(&limp->pl_refcnt);
1124 	return (limp);
1125 }
1126 
1127 void
1128 lim_fork(struct proc *p1, struct proc *p2)
1129 {
1130 
1131 	PROC_LOCK_ASSERT(p1, MA_OWNED);
1132 	PROC_LOCK_ASSERT(p2, MA_OWNED);
1133 
1134 	p2->p_limit = lim_hold(p1->p_limit);
1135 	callout_init_mtx(&p2->p_limco, &p2->p_mtx, 0);
1136 	if (p1->p_cpulimit != RLIM_INFINITY)
1137 		callout_reset(&p2->p_limco, hz, lim_cb, p2);
1138 }
1139 
1140 void
1141 lim_free(limp)
1142 	struct plimit *limp;
1143 {
1144 
1145 	KASSERT(limp->pl_refcnt > 0, ("plimit refcnt underflow"));
1146 	if (refcount_release(&limp->pl_refcnt))
1147 		free((void *)limp, M_PLIMIT);
1148 }
1149 
1150 /*
1151  * Make a copy of the plimit structure.
1152  * We share these structures copy-on-write after fork.
1153  */
1154 void
1155 lim_copy(dst, src)
1156 	struct plimit *dst, *src;
1157 {
1158 
1159 	KASSERT(dst->pl_refcnt == 1, ("lim_copy to shared limit"));
1160 	bcopy(src->pl_rlimit, dst->pl_rlimit, sizeof(src->pl_rlimit));
1161 }
1162 
1163 /*
1164  * Return the hard limit for a particular system resource.  The
1165  * which parameter specifies the index into the rlimit array.
1166  */
1167 rlim_t
1168 lim_max(struct proc *p, int which)
1169 {
1170 	struct rlimit rl;
1171 
1172 	lim_rlimit(p, which, &rl);
1173 	return (rl.rlim_max);
1174 }
1175 
1176 /*
1177  * Return the current (soft) limit for a particular system resource.
1178  * The which parameter which specifies the index into the rlimit array
1179  */
1180 rlim_t
1181 lim_cur(struct proc *p, int which)
1182 {
1183 	struct rlimit rl;
1184 
1185 	lim_rlimit(p, which, &rl);
1186 	return (rl.rlim_cur);
1187 }
1188 
1189 /*
1190  * Return a copy of the entire rlimit structure for the system limit
1191  * specified by 'which' in the rlimit structure pointed to by 'rlp'.
1192  */
1193 void
1194 lim_rlimit(struct proc *p, int which, struct rlimit *rlp)
1195 {
1196 
1197 	PROC_LOCK_ASSERT(p, MA_OWNED);
1198 	KASSERT(which >= 0 && which < RLIM_NLIMITS,
1199 	    ("request for invalid resource limit"));
1200 	*rlp = p->p_limit->pl_rlimit[which];
1201 	if (p->p_sysent->sv_fixlimit != NULL)
1202 		p->p_sysent->sv_fixlimit(rlp, which);
1203 }
1204 
1205 void
1206 uihashinit()
1207 {
1208 
1209 	uihashtbl = hashinit(maxproc / 16, M_UIDINFO, &uihash);
1210 	rw_init(&uihashtbl_lock, "uidinfo hash");
1211 }
1212 
1213 /*
1214  * Look up a uidinfo struct for the parameter uid.
1215  * uihashtbl_lock must be locked.
1216  */
1217 static struct uidinfo *
1218 uilookup(uid)
1219 	uid_t uid;
1220 {
1221 	struct uihashhead *uipp;
1222 	struct uidinfo *uip;
1223 
1224 	rw_assert(&uihashtbl_lock, RA_LOCKED);
1225 	uipp = UIHASH(uid);
1226 	LIST_FOREACH(uip, uipp, ui_hash)
1227 		if (uip->ui_uid == uid)
1228 			break;
1229 
1230 	return (uip);
1231 }
1232 
1233 /*
1234  * Find or allocate a struct uidinfo for a particular uid.
1235  * Increase refcount on uidinfo struct returned.
1236  * uifree() should be called on a struct uidinfo when released.
1237  */
1238 struct uidinfo *
1239 uifind(uid)
1240 	uid_t uid;
1241 {
1242 	struct uidinfo *old_uip, *uip;
1243 
1244 	rw_rlock(&uihashtbl_lock);
1245 	uip = uilookup(uid);
1246 	if (uip == NULL) {
1247 		rw_runlock(&uihashtbl_lock);
1248 		uip = malloc(sizeof(*uip), M_UIDINFO, M_WAITOK | M_ZERO);
1249 		racct_create(&uip->ui_racct);
1250 		rw_wlock(&uihashtbl_lock);
1251 		/*
1252 		 * There's a chance someone created our uidinfo while we
1253 		 * were in malloc and not holding the lock, so we have to
1254 		 * make sure we don't insert a duplicate uidinfo.
1255 		 */
1256 		if ((old_uip = uilookup(uid)) != NULL) {
1257 			/* Someone else beat us to it. */
1258 			racct_destroy(&uip->ui_racct);
1259 			free(uip, M_UIDINFO);
1260 			uip = old_uip;
1261 		} else {
1262 			refcount_init(&uip->ui_ref, 0);
1263 			uip->ui_uid = uid;
1264 			mtx_init(&uip->ui_vmsize_mtx, "ui_vmsize", NULL,
1265 			    MTX_DEF);
1266 			LIST_INSERT_HEAD(UIHASH(uid), uip, ui_hash);
1267 		}
1268 	}
1269 	uihold(uip);
1270 	rw_unlock(&uihashtbl_lock);
1271 	return (uip);
1272 }
1273 
1274 /*
1275  * Place another refcount on a uidinfo struct.
1276  */
1277 void
1278 uihold(uip)
1279 	struct uidinfo *uip;
1280 {
1281 
1282 	refcount_acquire(&uip->ui_ref);
1283 }
1284 
1285 /*-
1286  * Since uidinfo structs have a long lifetime, we use an
1287  * opportunistic refcounting scheme to avoid locking the lookup hash
1288  * for each release.
1289  *
1290  * If the refcount hits 0, we need to free the structure,
1291  * which means we need to lock the hash.
1292  * Optimal case:
1293  *   After locking the struct and lowering the refcount, if we find
1294  *   that we don't need to free, simply unlock and return.
1295  * Suboptimal case:
1296  *   If refcount lowering results in need to free, bump the count
1297  *   back up, lose the lock and acquire the locks in the proper
1298  *   order to try again.
1299  */
1300 void
1301 uifree(uip)
1302 	struct uidinfo *uip;
1303 {
1304 	int old;
1305 
1306 	/* Prepare for optimal case. */
1307 	old = uip->ui_ref;
1308 	if (old > 1 && atomic_cmpset_int(&uip->ui_ref, old, old - 1))
1309 		return;
1310 
1311 	/* Prepare for suboptimal case. */
1312 	rw_wlock(&uihashtbl_lock);
1313 	if (refcount_release(&uip->ui_ref)) {
1314 		racct_destroy(&uip->ui_racct);
1315 		LIST_REMOVE(uip, ui_hash);
1316 		rw_wunlock(&uihashtbl_lock);
1317 		if (uip->ui_sbsize != 0)
1318 			printf("freeing uidinfo: uid = %d, sbsize = %ld\n",
1319 			    uip->ui_uid, uip->ui_sbsize);
1320 		if (uip->ui_proccnt != 0)
1321 			printf("freeing uidinfo: uid = %d, proccnt = %ld\n",
1322 			    uip->ui_uid, uip->ui_proccnt);
1323 		if (uip->ui_vmsize != 0)
1324 			printf("freeing uidinfo: uid = %d, swapuse = %lld\n",
1325 			    uip->ui_uid, (unsigned long long)uip->ui_vmsize);
1326 		mtx_destroy(&uip->ui_vmsize_mtx);
1327 		free(uip, M_UIDINFO);
1328 		return;
1329 	}
1330 	/*
1331 	 * Someone added a reference between atomic_cmpset_int() and
1332 	 * rw_wlock(&uihashtbl_lock).
1333 	 */
1334 	rw_wunlock(&uihashtbl_lock);
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(uip, diff, max)
1359 	struct	uidinfo	*uip;
1360 	int	diff;
1361 	rlim_t	max;
1362 {
1363 
1364 	/* Don't allow them to exceed max, but allow subtraction. */
1365 	if (diff > 0 && max != 0) {
1366 		if (atomic_fetchadd_long(&uip->ui_proccnt, (long)diff) + diff > max) {
1367 			atomic_subtract_long(&uip->ui_proccnt, (long)diff);
1368 			return (0);
1369 		}
1370 	} else {
1371 		atomic_add_long(&uip->ui_proccnt, (long)diff);
1372 		if (uip->ui_proccnt < 0)
1373 			printf("negative proccnt for uid = %d\n", uip->ui_uid);
1374 	}
1375 	return (1);
1376 }
1377 
1378 /*
1379  * Change the total socket buffer size a user has used.
1380  */
1381 int
1382 chgsbsize(uip, hiwat, to, max)
1383 	struct	uidinfo	*uip;
1384 	u_int  *hiwat;
1385 	u_int	to;
1386 	rlim_t	max;
1387 {
1388 	int diff;
1389 
1390 	diff = to - *hiwat;
1391 	if (diff > 0) {
1392 		if (atomic_fetchadd_long(&uip->ui_sbsize, (long)diff) + diff > max) {
1393 			atomic_subtract_long(&uip->ui_sbsize, (long)diff);
1394 			return (0);
1395 		}
1396 	} else {
1397 		atomic_add_long(&uip->ui_sbsize, (long)diff);
1398 		if (uip->ui_sbsize < 0)
1399 			printf("negative sbsize for uid = %d\n", uip->ui_uid);
1400 	}
1401 	*hiwat = to;
1402 	return (1);
1403 }
1404 
1405 /*
1406  * Change the count associated with number of pseudo-terminals
1407  * a given user is using.  When 'max' is 0, don't enforce a limit
1408  */
1409 int
1410 chgptscnt(uip, diff, max)
1411 	struct	uidinfo	*uip;
1412 	int	diff;
1413 	rlim_t	max;
1414 {
1415 
1416 	/* Don't allow them to exceed max, but allow subtraction. */
1417 	if (diff > 0 && max != 0) {
1418 		if (atomic_fetchadd_long(&uip->ui_ptscnt, (long)diff) + diff > max) {
1419 			atomic_subtract_long(&uip->ui_ptscnt, (long)diff);
1420 			return (0);
1421 		}
1422 	} else {
1423 		atomic_add_long(&uip->ui_ptscnt, (long)diff);
1424 		if (uip->ui_ptscnt < 0)
1425 			printf("negative ptscnt for uid = %d\n", uip->ui_uid);
1426 	}
1427 	return (1);
1428 }
1429