xref: /freebsd/sys/kern/kern_resource.c (revision 836749817036b90b60af0584fa21f2d9dbd60ff7)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
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.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
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.
23  *
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
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/sysproto.h>
40 #include <sys/capsicum.h>
41 #include <sys/file.h>
42 #include <sys/filedesc.h>
43 #include <sys/kernel.h>
44 #include <sys/lock.h>
45 #include <sys/malloc.h>
46 #include <sys/mutex.h>
47 #include <sys/priv.h>
48 #include <sys/proc.h>
49 #include <sys/ptrace.h>
50 #include <sys/refcount.h>
51 #include <sys/racct.h>
52 #include <sys/resourcevar.h>
53 #include <sys/rwlock.h>
54 #include <sys/sched.h>
55 #include <sys/sx.h>
56 #include <sys/syscallsubr.h>
57 #include <sys/sysctl.h>
58 #include <sys/sysent.h>
59 #include <sys/time.h>
60 #include <sys/umtxvar.h>
61 
62 #include <vm/vm.h>
63 #include <vm/vm_param.h>
64 #include <vm/pmap.h>
65 #include <vm/vm_map.h>
66 #include <vm/vm_extern.h>
67 
68 static MALLOC_DEFINE(M_PLIMIT, "plimit", "plimit structures");
69 static MALLOC_DEFINE(M_UIDINFO, "uidinfo", "uidinfo structures");
70 #define	UIHASH(uid)	(&uihashtbl[(uid) & uihash])
71 static struct rwlock uihashtbl_lock;
72 static LIST_HEAD(uihashhead, uidinfo) *uihashtbl;
73 static u_long uihash;		/* size of hash table - 1 */
74 
75 static void	calcru1(struct proc *p, struct rusage_ext *ruxp,
76 		    struct timeval *up, struct timeval *sp);
77 static int	donice(struct thread *td, struct proc *chgp, int n);
78 static struct uidinfo *uilookup(uid_t uid);
79 static void	ruxagg_ext_locked(struct rusage_ext *rux, struct thread *td);
80 
81 /*
82  * Resource controls and accounting.
83  */
84 #ifndef _SYS_SYSPROTO_H_
85 struct getpriority_args {
86 	int	which;
87 	int	who;
88 };
89 #endif
90 int
91 sys_getpriority(struct thread *td, struct getpriority_args *uap)
92 {
93 
94 	return (kern_getpriority(td, uap->which, uap->who));
95 }
96 
97 int
98 kern_getpriority(struct thread *td, int which, int who)
99 {
100 	struct proc *p;
101 	struct pgrp *pg;
102 	int error, low;
103 
104 	if (IN_CAPABILITY_MODE(td)) {
105 		if (which != PRIO_PROCESS)
106 			return (ECAPMODE);
107 		if (who != 0 && who != td->td_proc->p_pid)
108 			return (ECAPMODE);
109 	}
110 
111 	error = 0;
112 	low = PRIO_MAX + 1;
113 	switch (which) {
114 	case PRIO_PROCESS:
115 		if (who == 0)
116 			low = td->td_proc->p_nice;
117 		else {
118 			p = pfind(who);
119 			if (p == NULL)
120 				break;
121 			if (p_cansee(td, p) == 0)
122 				low = p->p_nice;
123 			PROC_UNLOCK(p);
124 		}
125 		break;
126 
127 	case PRIO_PGRP:
128 		sx_slock(&proctree_lock);
129 		if (who == 0) {
130 			pg = td->td_proc->p_pgrp;
131 			PGRP_LOCK(pg);
132 		} else {
133 			pg = pgfind(who);
134 			if (pg == NULL) {
135 				sx_sunlock(&proctree_lock);
136 				break;
137 			}
138 		}
139 		sx_sunlock(&proctree_lock);
140 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
141 			PROC_LOCK(p);
142 			if (p->p_state == PRS_NORMAL &&
143 			    p_cansee(td, p) == 0) {
144 				if (p->p_nice < low)
145 					low = p->p_nice;
146 			}
147 			PROC_UNLOCK(p);
148 		}
149 		PGRP_UNLOCK(pg);
150 		break;
151 
152 	case PRIO_USER:
153 		if (who == 0)
154 			who = td->td_ucred->cr_uid;
155 		sx_slock(&allproc_lock);
156 		FOREACH_PROC_IN_SYSTEM(p) {
157 			PROC_LOCK(p);
158 			if (p->p_state == PRS_NORMAL &&
159 			    p_cansee(td, p) == 0 &&
160 			    p->p_ucred->cr_uid == who) {
161 				if (p->p_nice < low)
162 					low = p->p_nice;
163 			}
164 			PROC_UNLOCK(p);
165 		}
166 		sx_sunlock(&allproc_lock);
167 		break;
168 
169 	default:
170 		error = EINVAL;
171 		break;
172 	}
173 	if (low == PRIO_MAX + 1 && error == 0)
174 		error = ESRCH;
175 	td->td_retval[0] = low;
176 	return (error);
177 }
178 
179 #ifndef _SYS_SYSPROTO_H_
180 struct setpriority_args {
181 	int	which;
182 	int	who;
183 	int	prio;
184 };
185 #endif
186 int
187 sys_setpriority(struct thread *td, struct setpriority_args *uap)
188 {
189 
190 	return (kern_setpriority(td, uap->which, uap->who, uap->prio));
191 }
192 
193 int
194 kern_setpriority(struct thread *td, int which, int who, int prio)
195 {
196 	struct proc *curp, *p;
197 	struct pgrp *pg;
198 	int found = 0, error = 0;
199 
200 	curp = td->td_proc;
201 
202 	if (IN_CAPABILITY_MODE(td)) {
203 		if (which != PRIO_PROCESS)
204 			return (ECAPMODE);
205 		if (who != 0 && who != curp->p_pid)
206 			return (ECAPMODE);
207 	}
208 
209 	switch (which) {
210 	case PRIO_PROCESS:
211 		if (who == 0) {
212 			PROC_LOCK(curp);
213 			error = donice(td, curp, prio);
214 			PROC_UNLOCK(curp);
215 		} else {
216 			p = pfind(who);
217 			if (p == NULL)
218 				break;
219 			error = p_cansee(td, p);
220 			if (error == 0)
221 				error = donice(td, p, prio);
222 			PROC_UNLOCK(p);
223 		}
224 		found++;
225 		break;
226 
227 	case PRIO_PGRP:
228 		sx_slock(&proctree_lock);
229 		if (who == 0) {
230 			pg = curp->p_pgrp;
231 			PGRP_LOCK(pg);
232 		} else {
233 			pg = pgfind(who);
234 			if (pg == NULL) {
235 				sx_sunlock(&proctree_lock);
236 				break;
237 			}
238 		}
239 		sx_sunlock(&proctree_lock);
240 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
241 			PROC_LOCK(p);
242 			if (p->p_state == PRS_NORMAL &&
243 			    p_cansee(td, p) == 0) {
244 				error = donice(td, p, prio);
245 				found++;
246 			}
247 			PROC_UNLOCK(p);
248 		}
249 		PGRP_UNLOCK(pg);
250 		break;
251 
252 	case PRIO_USER:
253 		if (who == 0)
254 			who = td->td_ucred->cr_uid;
255 		sx_slock(&allproc_lock);
256 		FOREACH_PROC_IN_SYSTEM(p) {
257 			PROC_LOCK(p);
258 			if (p->p_state == PRS_NORMAL &&
259 			    p->p_ucred->cr_uid == who &&
260 			    p_cansee(td, p) == 0) {
261 				error = donice(td, p, prio);
262 				found++;
263 			}
264 			PROC_UNLOCK(p);
265 		}
266 		sx_sunlock(&allproc_lock);
267 		break;
268 
269 	default:
270 		error = EINVAL;
271 		break;
272 	}
273 	if (found == 0 && error == 0)
274 		error = ESRCH;
275 	return (error);
276 }
277 
278 /*
279  * Set "nice" for a (whole) process.
280  */
281 static int
282 donice(struct thread *td, struct proc *p, int n)
283 {
284 	int error;
285 
286 	PROC_LOCK_ASSERT(p, MA_OWNED);
287 	if ((error = p_cansched(td, p)))
288 		return (error);
289 	if (n > PRIO_MAX)
290 		n = PRIO_MAX;
291 	if (n < PRIO_MIN)
292 		n = PRIO_MIN;
293 	if (n < p->p_nice && priv_check(td, PRIV_SCHED_SETPRIORITY) != 0)
294 		return (EACCES);
295 	sched_nice(p, n);
296 	return (0);
297 }
298 
299 static int unprivileged_idprio;
300 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_idprio, CTLFLAG_RW,
301     &unprivileged_idprio, 0,
302     "Allow non-root users to set an idle priority (deprecated)");
303 
304 /*
305  * Set realtime priority for LWP.
306  */
307 #ifndef _SYS_SYSPROTO_H_
308 struct rtprio_thread_args {
309 	int		function;
310 	lwpid_t		lwpid;
311 	struct rtprio	*rtp;
312 };
313 #endif
314 int
315 sys_rtprio_thread(struct thread *td, struct rtprio_thread_args *uap)
316 {
317 	struct proc *p;
318 	struct rtprio rtp;
319 	struct thread *td1;
320 	int cierror, error;
321 
322 	/* Perform copyin before acquiring locks if needed. */
323 	if (uap->function == RTP_SET)
324 		cierror = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
325 	else
326 		cierror = 0;
327 
328 	if (uap->lwpid == 0 || uap->lwpid == td->td_tid) {
329 		p = td->td_proc;
330 		td1 = td;
331 		PROC_LOCK(p);
332 	} else {
333 		td1 = tdfind(uap->lwpid, -1);
334 		if (td1 == NULL)
335 			return (ESRCH);
336 		p = td1->td_proc;
337 	}
338 
339 	switch (uap->function) {
340 	case RTP_LOOKUP:
341 		if ((error = p_cansee(td, p)))
342 			break;
343 		pri_to_rtp(td1, &rtp);
344 		PROC_UNLOCK(p);
345 		return (copyout(&rtp, uap->rtp, sizeof(struct rtprio)));
346 	case RTP_SET:
347 		if ((error = p_cansched(td, p)) || (error = cierror))
348 			break;
349 
350 		/* Disallow setting rtprio in most cases if not superuser. */
351 
352 		/*
353 		 * Realtime priority has to be restricted for reasons which
354 		 * should be obvious.  However, for idleprio processes, there is
355 		 * a potential for system deadlock if an idleprio process gains
356 		 * a lock on a resource that other processes need (and the
357 		 * idleprio process can't run due to a CPU-bound normal
358 		 * process).  Fix me!  XXX
359 		 *
360 		 * This problem is not only related to idleprio process.
361 		 * A user level program can obtain a file lock and hold it
362 		 * indefinitely.  Additionally, without idleprio processes it is
363 		 * still conceivable that a program with low priority will never
364 		 * get to run.  In short, allowing this feature might make it
365 		 * easier to lock a resource indefinitely, but it is not the
366 		 * only thing that makes it possible.
367 		 */
368 		if (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_REALTIME &&
369 		    (error = priv_check(td, PRIV_SCHED_RTPRIO)) != 0)
370 			break;
371 		if (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_IDLE &&
372 		    unprivileged_idprio == 0 &&
373 		    (error = priv_check(td, PRIV_SCHED_IDPRIO)) != 0)
374 			break;
375 		error = rtp_to_pri(&rtp, td1);
376 		break;
377 	default:
378 		error = EINVAL;
379 		break;
380 	}
381 	PROC_UNLOCK(p);
382 	return (error);
383 }
384 
385 /*
386  * Set realtime priority.
387  */
388 #ifndef _SYS_SYSPROTO_H_
389 struct rtprio_args {
390 	int		function;
391 	pid_t		pid;
392 	struct rtprio	*rtp;
393 };
394 #endif
395 int
396 sys_rtprio(struct thread *td, struct rtprio_args *uap)
397 {
398 	struct proc *p;
399 	struct thread *tdp;
400 	struct rtprio rtp;
401 	int cierror, error;
402 
403 	/* Perform copyin before acquiring locks if needed. */
404 	if (uap->function == RTP_SET)
405 		cierror = copyin(uap->rtp, &rtp, sizeof(struct rtprio));
406 	else
407 		cierror = 0;
408 
409 	if (uap->pid == 0) {
410 		p = td->td_proc;
411 		PROC_LOCK(p);
412 	} else {
413 		p = pfind(uap->pid);
414 		if (p == NULL)
415 			return (ESRCH);
416 	}
417 
418 	switch (uap->function) {
419 	case RTP_LOOKUP:
420 		if ((error = p_cansee(td, p)))
421 			break;
422 		/*
423 		 * Return OUR priority if no pid specified,
424 		 * or if one is, report the highest priority
425 		 * in the process.  There isn't much more you can do as
426 		 * there is only room to return a single priority.
427 		 * Note: specifying our own pid is not the same
428 		 * as leaving it zero.
429 		 */
430 		if (uap->pid == 0) {
431 			pri_to_rtp(td, &rtp);
432 		} else {
433 			struct rtprio rtp2;
434 
435 			rtp.type = RTP_PRIO_IDLE;
436 			rtp.prio = RTP_PRIO_MAX;
437 			FOREACH_THREAD_IN_PROC(p, tdp) {
438 				pri_to_rtp(tdp, &rtp2);
439 				if (rtp2.type <  rtp.type ||
440 				    (rtp2.type == rtp.type &&
441 				    rtp2.prio < rtp.prio)) {
442 					rtp.type = rtp2.type;
443 					rtp.prio = rtp2.prio;
444 				}
445 			}
446 		}
447 		PROC_UNLOCK(p);
448 		return (copyout(&rtp, uap->rtp, sizeof(struct rtprio)));
449 	case RTP_SET:
450 		if ((error = p_cansched(td, p)) || (error = cierror))
451 			break;
452 
453 		/*
454 		 * Disallow setting rtprio in most cases if not superuser.
455 		 * See the comment in sys_rtprio_thread about idprio
456 		 * threads holding a lock.
457 		 */
458 		if (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_REALTIME &&
459 		    (error = priv_check(td, PRIV_SCHED_RTPRIO)) != 0)
460 			break;
461 		if (RTP_PRIO_BASE(rtp.type) == RTP_PRIO_IDLE &&
462 		    unprivileged_idprio == 0 &&
463 		    (error = priv_check(td, PRIV_SCHED_IDPRIO)) != 0)
464 			break;
465 
466 		/*
467 		 * If we are setting our own priority, set just our
468 		 * thread but if we are doing another process,
469 		 * do all the threads on that process. If we
470 		 * specify our own pid we do the latter.
471 		 */
472 		if (uap->pid == 0) {
473 			error = rtp_to_pri(&rtp, td);
474 		} else {
475 			FOREACH_THREAD_IN_PROC(p, td) {
476 				if ((error = rtp_to_pri(&rtp, td)) != 0)
477 					break;
478 			}
479 		}
480 		break;
481 	default:
482 		error = EINVAL;
483 		break;
484 	}
485 	PROC_UNLOCK(p);
486 	return (error);
487 }
488 
489 int
490 rtp_to_pri(struct rtprio *rtp, struct thread *td)
491 {
492 	u_char  newpri, oldclass, oldpri;
493 
494 	switch (RTP_PRIO_BASE(rtp->type)) {
495 	case RTP_PRIO_REALTIME:
496 		if (rtp->prio > RTP_PRIO_MAX)
497 			return (EINVAL);
498 		newpri = PRI_MIN_REALTIME + rtp->prio;
499 		break;
500 	case RTP_PRIO_NORMAL:
501 		if (rtp->prio > (PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE))
502 			return (EINVAL);
503 		newpri = PRI_MIN_TIMESHARE + rtp->prio;
504 		break;
505 	case RTP_PRIO_IDLE:
506 		if (rtp->prio > RTP_PRIO_MAX)
507 			return (EINVAL);
508 		newpri = PRI_MIN_IDLE + rtp->prio;
509 		break;
510 	default:
511 		return (EINVAL);
512 	}
513 
514 	thread_lock(td);
515 	oldclass = td->td_pri_class;
516 	sched_class(td, rtp->type);	/* XXX fix */
517 	oldpri = td->td_user_pri;
518 	sched_user_prio(td, newpri);
519 	if (td->td_user_pri != oldpri && (oldclass != RTP_PRIO_NORMAL ||
520 	    td->td_pri_class != RTP_PRIO_NORMAL))
521 		sched_prio(td, td->td_user_pri);
522 	if (TD_ON_UPILOCK(td) && oldpri != newpri) {
523 		critical_enter();
524 		thread_unlock(td);
525 		umtx_pi_adjust(td, oldpri);
526 		critical_exit();
527 	} else
528 		thread_unlock(td);
529 	return (0);
530 }
531 
532 void
533 pri_to_rtp(struct thread *td, struct rtprio *rtp)
534 {
535 
536 	thread_lock(td);
537 	switch (PRI_BASE(td->td_pri_class)) {
538 	case PRI_REALTIME:
539 		rtp->prio = td->td_base_user_pri - PRI_MIN_REALTIME;
540 		break;
541 	case PRI_TIMESHARE:
542 		rtp->prio = td->td_base_user_pri - PRI_MIN_TIMESHARE;
543 		break;
544 	case PRI_IDLE:
545 		rtp->prio = td->td_base_user_pri - PRI_MIN_IDLE;
546 		break;
547 	default:
548 		break;
549 	}
550 	rtp->type = td->td_pri_class;
551 	thread_unlock(td);
552 }
553 
554 #if defined(COMPAT_43)
555 #ifndef _SYS_SYSPROTO_H_
556 struct osetrlimit_args {
557 	u_int	which;
558 	struct	orlimit *rlp;
559 };
560 #endif
561 int
562 osetrlimit(struct thread *td, struct osetrlimit_args *uap)
563 {
564 	struct orlimit olim;
565 	struct rlimit lim;
566 	int error;
567 
568 	if ((error = copyin(uap->rlp, &olim, sizeof(struct orlimit))))
569 		return (error);
570 	lim.rlim_cur = olim.rlim_cur;
571 	lim.rlim_max = olim.rlim_max;
572 	error = kern_setrlimit(td, uap->which, &lim);
573 	return (error);
574 }
575 
576 #ifndef _SYS_SYSPROTO_H_
577 struct ogetrlimit_args {
578 	u_int	which;
579 	struct	orlimit *rlp;
580 };
581 #endif
582 int
583 ogetrlimit(struct thread *td, struct ogetrlimit_args *uap)
584 {
585 	struct orlimit olim;
586 	struct rlimit rl;
587 	int error;
588 
589 	if (uap->which >= RLIM_NLIMITS)
590 		return (EINVAL);
591 	lim_rlimit(td, uap->which, &rl);
592 
593 	/*
594 	 * XXX would be more correct to convert only RLIM_INFINITY to the
595 	 * old RLIM_INFINITY and fail with EOVERFLOW for other larger
596 	 * values.  Most 64->32 and 32->16 conversions, including not
597 	 * unimportant ones of uids are even more broken than what we
598 	 * do here (they blindly truncate).  We don't do this correctly
599 	 * here since we have little experience with EOVERFLOW yet.
600 	 * Elsewhere, getuid() can't fail...
601 	 */
602 	olim.rlim_cur = rl.rlim_cur > 0x7fffffff ? 0x7fffffff : rl.rlim_cur;
603 	olim.rlim_max = rl.rlim_max > 0x7fffffff ? 0x7fffffff : rl.rlim_max;
604 	error = copyout(&olim, uap->rlp, sizeof(olim));
605 	return (error);
606 }
607 #endif /* COMPAT_43 */
608 
609 #ifndef _SYS_SYSPROTO_H_
610 struct setrlimit_args {
611 	u_int	which;
612 	struct	rlimit *rlp;
613 };
614 #endif
615 int
616 sys_setrlimit(struct thread *td, struct setrlimit_args *uap)
617 {
618 	struct rlimit alim;
619 	int error;
620 
621 	if ((error = copyin(uap->rlp, &alim, sizeof(struct rlimit))))
622 		return (error);
623 	error = kern_setrlimit(td, uap->which, &alim);
624 	return (error);
625 }
626 
627 static void
628 lim_cb(void *arg)
629 {
630 	struct rlimit rlim;
631 	struct thread *td;
632 	struct proc *p;
633 
634 	p = arg;
635 	PROC_LOCK_ASSERT(p, MA_OWNED);
636 	/*
637 	 * Check if the process exceeds its cpu resource allocation.  If
638 	 * it reaches the max, arrange to kill the process in ast().
639 	 */
640 	if (p->p_cpulimit == RLIM_INFINITY)
641 		return;
642 	PROC_STATLOCK(p);
643 	FOREACH_THREAD_IN_PROC(p, td) {
644 		ruxagg(p, td);
645 	}
646 	PROC_STATUNLOCK(p);
647 	if (p->p_rux.rux_runtime > p->p_cpulimit * cpu_tickrate()) {
648 		lim_rlimit_proc(p, RLIMIT_CPU, &rlim);
649 		if (p->p_rux.rux_runtime >= rlim.rlim_max * cpu_tickrate()) {
650 			killproc(p, "exceeded maximum CPU limit");
651 		} else {
652 			if (p->p_cpulimit < rlim.rlim_max)
653 				p->p_cpulimit += 5;
654 			kern_psignal(p, SIGXCPU);
655 		}
656 	}
657 	if ((p->p_flag & P_WEXIT) == 0)
658 		callout_reset_sbt(&p->p_limco, SBT_1S, 0,
659 		    lim_cb, p, C_PREL(1));
660 }
661 
662 int
663 kern_setrlimit(struct thread *td, u_int which, struct rlimit *limp)
664 {
665 
666 	return (kern_proc_setrlimit(td, td->td_proc, which, limp));
667 }
668 
669 int
670 kern_proc_setrlimit(struct thread *td, struct proc *p, u_int which,
671     struct rlimit *limp)
672 {
673 	struct plimit *newlim, *oldlim, *oldlim_td;
674 	struct rlimit *alimp;
675 	struct rlimit oldssiz;
676 	int error;
677 
678 	if (which >= RLIM_NLIMITS)
679 		return (EINVAL);
680 
681 	/*
682 	 * Preserve historical bugs by treating negative limits as unsigned.
683 	 */
684 	if (limp->rlim_cur < 0)
685 		limp->rlim_cur = RLIM_INFINITY;
686 	if (limp->rlim_max < 0)
687 		limp->rlim_max = RLIM_INFINITY;
688 
689 	oldssiz.rlim_cur = 0;
690 	newlim = lim_alloc();
691 	PROC_LOCK(p);
692 	oldlim = p->p_limit;
693 	alimp = &oldlim->pl_rlimit[which];
694 	if (limp->rlim_cur > alimp->rlim_max ||
695 	    limp->rlim_max > alimp->rlim_max)
696 		if ((error = priv_check(td, PRIV_PROC_SETRLIMIT))) {
697 			PROC_UNLOCK(p);
698 			lim_free(newlim);
699 			return (error);
700 		}
701 	if (limp->rlim_cur > limp->rlim_max)
702 		limp->rlim_cur = limp->rlim_max;
703 	lim_copy(newlim, oldlim);
704 	alimp = &newlim->pl_rlimit[which];
705 
706 	switch (which) {
707 	case RLIMIT_CPU:
708 		if (limp->rlim_cur != RLIM_INFINITY &&
709 		    p->p_cpulimit == RLIM_INFINITY)
710 			callout_reset_sbt(&p->p_limco, SBT_1S, 0,
711 			    lim_cb, p, C_PREL(1));
712 		p->p_cpulimit = limp->rlim_cur;
713 		break;
714 	case RLIMIT_DATA:
715 		if (limp->rlim_cur > maxdsiz)
716 			limp->rlim_cur = maxdsiz;
717 		if (limp->rlim_max > maxdsiz)
718 			limp->rlim_max = maxdsiz;
719 		break;
720 
721 	case RLIMIT_STACK:
722 		if (limp->rlim_cur > maxssiz)
723 			limp->rlim_cur = maxssiz;
724 		if (limp->rlim_max > maxssiz)
725 			limp->rlim_max = maxssiz;
726 		oldssiz = *alimp;
727 		if (p->p_sysent->sv_fixlimit != NULL)
728 			p->p_sysent->sv_fixlimit(&oldssiz,
729 			    RLIMIT_STACK);
730 		break;
731 
732 	case RLIMIT_NOFILE:
733 		if (limp->rlim_cur > maxfilesperproc)
734 			limp->rlim_cur = maxfilesperproc;
735 		if (limp->rlim_max > maxfilesperproc)
736 			limp->rlim_max = maxfilesperproc;
737 		break;
738 
739 	case RLIMIT_NPROC:
740 		if (limp->rlim_cur > maxprocperuid)
741 			limp->rlim_cur = maxprocperuid;
742 		if (limp->rlim_max > maxprocperuid)
743 			limp->rlim_max = maxprocperuid;
744 		if (limp->rlim_cur < 1)
745 			limp->rlim_cur = 1;
746 		if (limp->rlim_max < 1)
747 			limp->rlim_max = 1;
748 		break;
749 	}
750 	if (p->p_sysent->sv_fixlimit != NULL)
751 		p->p_sysent->sv_fixlimit(limp, which);
752 	*alimp = *limp;
753 	p->p_limit = newlim;
754 	PROC_UPDATE_COW(p);
755 	oldlim_td = NULL;
756 	if (td == curthread && PROC_COW_CHANGECOUNT(td, p) == 1) {
757 		oldlim_td = lim_cowsync();
758 		thread_cow_synced(td);
759 	}
760 	PROC_UNLOCK(p);
761 	if (oldlim_td != NULL) {
762 		MPASS(oldlim_td == oldlim);
763 		lim_freen(oldlim, 2);
764 	} else {
765 		lim_free(oldlim);
766 	}
767 
768 	if (which == RLIMIT_STACK &&
769 	    /*
770 	     * Skip calls from exec_new_vmspace(), done when stack is
771 	     * not mapped yet.
772 	     */
773 	    (td != curthread || (p->p_flag & P_INEXEC) == 0)) {
774 		/*
775 		 * Stack is allocated to the max at exec time with only
776 		 * "rlim_cur" bytes accessible.  If stack limit is going
777 		 * up make more accessible, if going down make inaccessible.
778 		 */
779 		if (limp->rlim_cur != oldssiz.rlim_cur) {
780 			vm_offset_t addr;
781 			vm_size_t size;
782 			vm_prot_t prot;
783 
784 			if (limp->rlim_cur > oldssiz.rlim_cur) {
785 				prot = p->p_sysent->sv_stackprot;
786 				size = limp->rlim_cur - oldssiz.rlim_cur;
787 				addr = round_page(p->p_vmspace->vm_stacktop) -
788 				    limp->rlim_cur;
789 			} else {
790 				prot = VM_PROT_NONE;
791 				size = oldssiz.rlim_cur - limp->rlim_cur;
792 				addr = round_page(p->p_vmspace->vm_stacktop) -
793 				    oldssiz.rlim_cur;
794 			}
795 			addr = trunc_page(addr);
796 			size = round_page(size);
797 			(void)vm_map_protect(&p->p_vmspace->vm_map,
798 			    addr, addr + size, prot, 0,
799 			    VM_MAP_PROTECT_SET_PROT);
800 		}
801 	}
802 
803 	return (0);
804 }
805 
806 #ifndef _SYS_SYSPROTO_H_
807 struct getrlimit_args {
808 	u_int	which;
809 	struct	rlimit *rlp;
810 };
811 #endif
812 /* ARGSUSED */
813 int
814 sys_getrlimit(struct thread *td, struct getrlimit_args *uap)
815 {
816 	struct rlimit rlim;
817 	int error;
818 
819 	if (uap->which >= RLIM_NLIMITS)
820 		return (EINVAL);
821 	lim_rlimit(td, uap->which, &rlim);
822 	error = copyout(&rlim, uap->rlp, sizeof(struct rlimit));
823 	return (error);
824 }
825 
826 static int
827 getrlimitusage_one(struct proc *p, struct vmspace *vm, u_int which, int flags,
828     rlim_t *res)
829 {
830 	struct thread *td;
831 	struct uidinfo *ui;
832 	uid_t uid;
833 	int error;
834 
835 	error = 0;
836 	PROC_LOCK(p);
837 	uid = (flags & GETRLIMITUSAGE_EUID) == 0 ? p->p_ucred->cr_ruid :
838 	    p->p_ucred->cr_uid;
839 	PROC_UNLOCK(p);
840 
841 	ui = uifind(uid);
842 
843 	switch (which) {
844 	case RLIMIT_CPU:
845 		PROC_LOCK(p);
846 		PROC_STATLOCK(p);
847 		FOREACH_THREAD_IN_PROC(p, td)
848 			ruxagg(p, td);
849 		*res = p->p_rux.rux_runtime;
850 		PROC_STATUNLOCK(p);
851 		PROC_UNLOCK(p);
852 		*res /= cpu_tickrate();
853 		break;
854 	case RLIMIT_FSIZE:
855 		error = ENXIO;
856 		break;
857 	case RLIMIT_DATA:
858 		if (vm == NULL)
859 			error = ENXIO;
860 		else
861 			*res = vm->vm_dsize * PAGE_SIZE;
862 		break;
863 	case RLIMIT_STACK:
864 		if (vm == NULL)
865 			error = ENXIO;
866 		else
867 			*res = vm->vm_ssize * PAGE_SIZE;
868 		break;
869 	case RLIMIT_CORE:
870 		error = ENXIO;
871 		break;
872 	case RLIMIT_RSS:
873 		if (vm == NULL)
874 			error = ENXIO;
875 		else
876 			*res = vmspace_resident_count(vm) * PAGE_SIZE;
877 		break;
878 	case RLIMIT_MEMLOCK:
879 		if (vm == NULL)
880 			error = ENXIO;
881 		else
882 			*res = pmap_wired_count(vmspace_pmap(vm)) * PAGE_SIZE;
883 		break;
884 	case RLIMIT_NPROC:
885 		*res = ui->ui_proccnt;
886 		break;
887 	case RLIMIT_NOFILE:
888 		*res = proc_nfiles(p);
889 		break;
890 	case RLIMIT_SBSIZE:
891 		*res = ui->ui_sbsize;
892 		break;
893 	case RLIMIT_VMEM:
894 		if (vm == NULL)
895 			error = ENXIO;
896 		else
897 			*res = vm->vm_map.size;
898 		break;
899 	case RLIMIT_NPTS:
900 		*res = ui->ui_ptscnt;
901 		break;
902 	case RLIMIT_SWAP:
903 		*res = ui->ui_vmsize;
904 		break;
905 	case RLIMIT_KQUEUES:
906 		*res = ui->ui_kqcnt;
907 		break;
908 	case RLIMIT_UMTXP:
909 		*res = ui->ui_umtxcnt;
910 		break;
911 	case RLIMIT_PIPEBUF:
912 		*res = ui->ui_pipecnt;
913 		break;
914 	case RLIMIT_VMM:
915 		*res = ui->ui_vmmcnt;
916 		break;
917 	default:
918 		error = EINVAL;
919 		break;
920 	}
921 
922 	uifree(ui);
923 	return (error);
924 }
925 
926 int
927 sys_getrlimitusage(struct thread *td, struct getrlimitusage_args *uap)
928 {
929 	struct proc *p;
930 	rlim_t res;
931 	int error;
932 
933 	if ((uap->flags & ~(GETRLIMITUSAGE_EUID)) != 0)
934 		return (EINVAL);
935 	p = curproc;
936 	error = getrlimitusage_one(p, p->p_vmspace, uap->which, uap->flags,
937 	    &res);
938 	if (error == 0)
939 		error = copyout(&res, uap->res, sizeof(res));
940 	return (error);
941 }
942 
943 /*
944  * Transform the running time and tick information for children of proc p
945  * into user and system time usage.
946  */
947 void
948 calccru(struct proc *p, struct timeval *up, struct timeval *sp)
949 {
950 
951 	PROC_LOCK_ASSERT(p, MA_OWNED);
952 	calcru1(p, &p->p_crux, up, sp);
953 }
954 
955 /*
956  * Transform the running time and tick information in proc p into user
957  * and system time usage.  If appropriate, include the current time slice
958  * on this CPU.
959  */
960 void
961 calcru(struct proc *p, struct timeval *up, struct timeval *sp)
962 {
963 	struct thread *td;
964 	uint64_t runtime, u;
965 
966 	PROC_LOCK_ASSERT(p, MA_OWNED);
967 	PROC_STATLOCK_ASSERT(p, MA_OWNED);
968 	/*
969 	 * If we are getting stats for the current process, then add in the
970 	 * stats that this thread has accumulated in its current time slice.
971 	 * We reset the thread and CPU state as if we had performed a context
972 	 * switch right here.
973 	 */
974 	td = curthread;
975 	if (td->td_proc == p) {
976 		u = cpu_ticks();
977 		runtime = u - PCPU_GET(switchtime);
978 		td->td_runtime += runtime;
979 		td->td_incruntime += runtime;
980 		PCPU_SET(switchtime, u);
981 	}
982 	/* Make sure the per-thread stats are current. */
983 	FOREACH_THREAD_IN_PROC(p, td) {
984 		if (td->td_incruntime == 0)
985 			continue;
986 		ruxagg(p, td);
987 	}
988 	calcru1(p, &p->p_rux, up, sp);
989 }
990 
991 /* Collect resource usage for a single thread. */
992 void
993 rufetchtd(struct thread *td, struct rusage *ru)
994 {
995 	struct proc *p;
996 	uint64_t runtime, u;
997 
998 	p = td->td_proc;
999 	PROC_STATLOCK_ASSERT(p, MA_OWNED);
1000 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1001 	/*
1002 	 * If we are getting stats for the current thread, then add in the
1003 	 * stats that this thread has accumulated in its current time slice.
1004 	 * We reset the thread and CPU state as if we had performed a context
1005 	 * switch right here.
1006 	 */
1007 	if (td == curthread) {
1008 		u = cpu_ticks();
1009 		runtime = u - PCPU_GET(switchtime);
1010 		td->td_runtime += runtime;
1011 		td->td_incruntime += runtime;
1012 		PCPU_SET(switchtime, u);
1013 	}
1014 	ruxagg_locked(p, td);
1015 	*ru = td->td_ru;
1016 	calcru1(p, &td->td_rux, &ru->ru_utime, &ru->ru_stime);
1017 }
1018 
1019 static uint64_t
1020 mul64_by_fraction(uint64_t a, uint64_t b, uint64_t c)
1021 {
1022 	uint64_t acc, bh, bl;
1023 	int i, s, sa, sb;
1024 
1025 	/*
1026 	 * Calculate (a * b) / c accurately enough without overflowing.  c
1027 	 * must be nonzero, and its top bit must be 0.  a or b must be
1028 	 * <= c, and the implementation is tuned for b <= c.
1029 	 *
1030 	 * The comments about times are for use in calcru1() with units of
1031 	 * microseconds for 'a' and stathz ticks at 128 Hz for b and c.
1032 	 *
1033 	 * Let n be the number of top zero bits in c.  Each iteration
1034 	 * either returns, or reduces b by right shifting it by at least n.
1035 	 * The number of iterations is at most 1 + 64 / n, and the error is
1036 	 * at most the number of iterations.
1037 	 *
1038 	 * It is very unusual to need even 2 iterations.  Previous
1039 	 * implementations overflowed essentially by returning early in the
1040 	 * first iteration, with n = 38 giving overflow at 105+ hours and
1041 	 * n = 32 giving overlow at at 388+ days despite a more careful
1042 	 * calculation.  388 days is a reasonable uptime, and the calculation
1043 	 * needs to work for the uptime times the number of CPUs since 'a'
1044 	 * is per-process.
1045 	 */
1046 	if (a >= (uint64_t)1 << 63)
1047 		return (0);		/* Unsupported arg -- can't happen. */
1048 	acc = 0;
1049 	for (i = 0; i < 128; i++) {
1050 		sa = flsll(a);
1051 		sb = flsll(b);
1052 		if (sa + sb <= 64)
1053 			/* Up to 105 hours on first iteration. */
1054 			return (acc + (a * b) / c);
1055 		if (a >= c) {
1056 			/*
1057 			 * This reduction is based on a = q * c + r, with the
1058 			 * remainder r < c.  'a' may be large to start, and
1059 			 * moving bits from b into 'a' at the end of the loop
1060 			 * sets the top bit of 'a', so the reduction makes
1061 			 * significant progress.
1062 			 */
1063 			acc += (a / c) * b;
1064 			a %= c;
1065 			sa = flsll(a);
1066 			if (sa + sb <= 64)
1067 				/* Up to 388 days on first iteration. */
1068 				return (acc + (a * b) / c);
1069 		}
1070 
1071 		/*
1072 		 * This step writes a * b as a * ((bh << s) + bl) =
1073 		 * a * (bh << s) + a * bl = (a << s) * bh + a * bl.  The 2
1074 		 * additive terms are handled separately.  Splitting in
1075 		 * this way is linear except for rounding errors.
1076 		 *
1077 		 * s = 64 - sa is the maximum such that a << s fits in 64
1078 		 * bits.  Since a < c and c has at least 1 zero top bit,
1079 		 * sa < 64 and s > 0.  Thus this step makes progress by
1080 		 * reducing b (it increases 'a', but taking remainders on
1081 		 * the next iteration completes the reduction).
1082 		 *
1083 		 * Finally, the choice for s is just what is needed to keep
1084 		 * a * bl from overflowing, so we don't need complications
1085 		 * like a recursive call mul64_by_fraction(a, bl, c) to
1086 		 * handle the second additive term.
1087 		 */
1088 		s = 64 - sa;
1089 		bh = b >> s;
1090 		bl = b - (bh << s);
1091 		acc += (a * bl) / c;
1092 		a <<= s;
1093 		b = bh;
1094 	}
1095 	return (0);		/* Algorithm failure -- can't happen. */
1096 }
1097 
1098 static void
1099 calcru1(struct proc *p, struct rusage_ext *ruxp, struct timeval *up,
1100     struct timeval *sp)
1101 {
1102 	/* {user, system, interrupt, total} {ticks, usec}: */
1103 	uint64_t ut, uu, st, su, it, tt, tu;
1104 
1105 	ut = ruxp->rux_uticks;
1106 	st = ruxp->rux_sticks;
1107 	it = ruxp->rux_iticks;
1108 	tt = ut + st + it;
1109 	if (tt == 0) {
1110 		/* Avoid divide by zero */
1111 		st = 1;
1112 		tt = 1;
1113 	}
1114 	tu = cputick2usec(ruxp->rux_runtime);
1115 	if ((int64_t)tu < 0) {
1116 		/* XXX: this should be an assert /phk */
1117 		printf("calcru: negative runtime of %jd usec for pid %d (%s)\n",
1118 		    (intmax_t)tu, p->p_pid, p->p_comm);
1119 		tu = ruxp->rux_tu;
1120 	}
1121 
1122 	/* Subdivide tu.  Avoid overflow in the multiplications. */
1123 	if (__predict_true(tu <= ((uint64_t)1 << 38) && tt <= (1 << 26))) {
1124 		/* Up to 76 hours when stathz is 128. */
1125 		uu = (tu * ut) / tt;
1126 		su = (tu * st) / tt;
1127 	} else {
1128 		uu = mul64_by_fraction(tu, ut, tt);
1129 		su = mul64_by_fraction(tu, st, tt);
1130 	}
1131 
1132 	if (tu >= ruxp->rux_tu) {
1133 		/*
1134 		 * The normal case, time increased.
1135 		 * Enforce monotonicity of bucketed numbers.
1136 		 */
1137 		if (uu < ruxp->rux_uu)
1138 			uu = ruxp->rux_uu;
1139 		if (su < ruxp->rux_su)
1140 			su = ruxp->rux_su;
1141 	} else if (tu + 3 > ruxp->rux_tu || 101 * tu > 100 * ruxp->rux_tu) {
1142 		/*
1143 		 * When we calibrate the cputicker, it is not uncommon to
1144 		 * see the presumably fixed frequency increase slightly over
1145 		 * time as a result of thermal stabilization and NTP
1146 		 * discipline (of the reference clock).  We therefore ignore
1147 		 * a bit of backwards slop because we  expect to catch up
1148 		 * shortly.  We use a 3 microsecond limit to catch low
1149 		 * counts and a 1% limit for high counts.
1150 		 */
1151 		uu = ruxp->rux_uu;
1152 		su = ruxp->rux_su;
1153 		tu = ruxp->rux_tu;
1154 	} else if (vm_guest == VM_GUEST_NO) {  /* tu < ruxp->rux_tu */
1155 		/*
1156 		 * What happened here was likely that a laptop, which ran at
1157 		 * a reduced clock frequency at boot, kicked into high gear.
1158 		 * The wisdom of spamming this message in that case is
1159 		 * dubious, but it might also be indicative of something
1160 		 * serious, so lets keep it and hope laptops can be made
1161 		 * more truthful about their CPU speed via ACPI.
1162 		 */
1163 		printf("calcru: runtime went backwards from %ju usec "
1164 		    "to %ju usec for pid %d (%s)\n",
1165 		    (uintmax_t)ruxp->rux_tu, (uintmax_t)tu,
1166 		    p->p_pid, p->p_comm);
1167 	}
1168 
1169 	ruxp->rux_uu = uu;
1170 	ruxp->rux_su = su;
1171 	ruxp->rux_tu = tu;
1172 
1173 	up->tv_sec = uu / 1000000;
1174 	up->tv_usec = uu % 1000000;
1175 	sp->tv_sec = su / 1000000;
1176 	sp->tv_usec = su % 1000000;
1177 }
1178 
1179 #ifndef _SYS_SYSPROTO_H_
1180 struct getrusage_args {
1181 	int	who;
1182 	struct	rusage *rusage;
1183 };
1184 #endif
1185 int
1186 sys_getrusage(struct thread *td, struct getrusage_args *uap)
1187 {
1188 	struct rusage ru;
1189 	int error;
1190 
1191 	error = kern_getrusage(td, uap->who, &ru);
1192 	if (error == 0)
1193 		error = copyout(&ru, uap->rusage, sizeof(struct rusage));
1194 	return (error);
1195 }
1196 
1197 int
1198 kern_getrusage(struct thread *td, int who, struct rusage *rup)
1199 {
1200 	struct proc *p;
1201 	int error;
1202 
1203 	error = 0;
1204 	p = td->td_proc;
1205 	PROC_LOCK(p);
1206 	switch (who) {
1207 	case RUSAGE_SELF:
1208 		rufetchcalc(p, rup, &rup->ru_utime,
1209 		    &rup->ru_stime);
1210 		break;
1211 
1212 	case RUSAGE_CHILDREN:
1213 		*rup = p->p_stats->p_cru;
1214 		calccru(p, &rup->ru_utime, &rup->ru_stime);
1215 		break;
1216 
1217 	case RUSAGE_THREAD:
1218 		PROC_STATLOCK(p);
1219 		thread_lock(td);
1220 		rufetchtd(td, rup);
1221 		thread_unlock(td);
1222 		PROC_STATUNLOCK(p);
1223 		break;
1224 
1225 	default:
1226 		error = EINVAL;
1227 	}
1228 	PROC_UNLOCK(p);
1229 	return (error);
1230 }
1231 
1232 void
1233 rucollect(struct rusage *ru, struct rusage *ru2)
1234 {
1235 	long *ip, *ip2;
1236 	int i;
1237 
1238 	if (ru->ru_maxrss < ru2->ru_maxrss)
1239 		ru->ru_maxrss = ru2->ru_maxrss;
1240 	ip = &ru->ru_first;
1241 	ip2 = &ru2->ru_first;
1242 	for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--)
1243 		*ip++ += *ip2++;
1244 }
1245 
1246 void
1247 ruadd(struct rusage *ru, struct rusage_ext *rux, struct rusage *ru2,
1248     struct rusage_ext *rux2)
1249 {
1250 
1251 	rux->rux_runtime += rux2->rux_runtime;
1252 	rux->rux_uticks += rux2->rux_uticks;
1253 	rux->rux_sticks += rux2->rux_sticks;
1254 	rux->rux_iticks += rux2->rux_iticks;
1255 	rux->rux_uu += rux2->rux_uu;
1256 	rux->rux_su += rux2->rux_su;
1257 	rux->rux_tu += rux2->rux_tu;
1258 	rucollect(ru, ru2);
1259 }
1260 
1261 /*
1262  * Aggregate tick counts into the proc's rusage_ext.
1263  */
1264 static void
1265 ruxagg_ext_locked(struct rusage_ext *rux, struct thread *td)
1266 {
1267 
1268 	rux->rux_runtime += td->td_incruntime;
1269 	rux->rux_uticks += td->td_uticks;
1270 	rux->rux_sticks += td->td_sticks;
1271 	rux->rux_iticks += td->td_iticks;
1272 }
1273 
1274 void
1275 ruxagg_locked(struct proc *p, struct thread *td)
1276 {
1277 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1278 	PROC_STATLOCK_ASSERT(td->td_proc, MA_OWNED);
1279 
1280 	ruxagg_ext_locked(&p->p_rux, td);
1281 	ruxagg_ext_locked(&td->td_rux, td);
1282 	td->td_incruntime = 0;
1283 	td->td_uticks = 0;
1284 	td->td_iticks = 0;
1285 	td->td_sticks = 0;
1286 }
1287 
1288 void
1289 ruxagg(struct proc *p, struct thread *td)
1290 {
1291 
1292 	thread_lock(td);
1293 	ruxagg_locked(p, td);
1294 	thread_unlock(td);
1295 }
1296 
1297 /*
1298  * Update the rusage_ext structure and fetch a valid aggregate rusage
1299  * for proc p if storage for one is supplied.
1300  */
1301 void
1302 rufetch(struct proc *p, struct rusage *ru)
1303 {
1304 	struct thread *td;
1305 
1306 	PROC_STATLOCK_ASSERT(p, MA_OWNED);
1307 
1308 	*ru = p->p_ru;
1309 	if (p->p_numthreads > 0)  {
1310 		FOREACH_THREAD_IN_PROC(p, td) {
1311 			ruxagg(p, td);
1312 			rucollect(ru, &td->td_ru);
1313 		}
1314 	}
1315 }
1316 
1317 /*
1318  * Atomically perform a rufetch and a calcru together.
1319  * Consumers, can safely assume the calcru is executed only once
1320  * rufetch is completed.
1321  */
1322 void
1323 rufetchcalc(struct proc *p, struct rusage *ru, struct timeval *up,
1324     struct timeval *sp)
1325 {
1326 
1327 	PROC_STATLOCK(p);
1328 	rufetch(p, ru);
1329 	calcru(p, up, sp);
1330 	PROC_STATUNLOCK(p);
1331 }
1332 
1333 /*
1334  * Allocate a new resource limits structure and initialize its
1335  * reference count and mutex pointer.
1336  */
1337 struct plimit *
1338 lim_alloc(void)
1339 {
1340 	struct plimit *limp;
1341 
1342 	limp = malloc(sizeof(struct plimit), M_PLIMIT, M_WAITOK);
1343 	refcount_init(&limp->pl_refcnt, 1);
1344 	return (limp);
1345 }
1346 
1347 struct plimit *
1348 lim_hold(struct plimit *limp)
1349 {
1350 
1351 	refcount_acquire(&limp->pl_refcnt);
1352 	return (limp);
1353 }
1354 
1355 struct plimit *
1356 lim_cowsync(void)
1357 {
1358 	struct thread *td;
1359 	struct proc *p;
1360 	struct plimit *oldlimit;
1361 
1362 	td = curthread;
1363 	p = td->td_proc;
1364 	PROC_LOCK_ASSERT(p, MA_OWNED);
1365 
1366 	if (td->td_limit == p->p_limit)
1367 		return (NULL);
1368 
1369 	oldlimit = td->td_limit;
1370 	td->td_limit = lim_hold(p->p_limit);
1371 
1372 	return (oldlimit);
1373 }
1374 
1375 void
1376 lim_fork(struct proc *p1, struct proc *p2)
1377 {
1378 
1379 	PROC_LOCK_ASSERT(p1, MA_OWNED);
1380 	PROC_LOCK_ASSERT(p2, MA_OWNED);
1381 
1382 	p2->p_limit = lim_hold(p1->p_limit);
1383 	callout_init_mtx(&p2->p_limco, &p2->p_mtx, 0);
1384 	if (p1->p_cpulimit != RLIM_INFINITY)
1385 		callout_reset_sbt(&p2->p_limco, SBT_1S, 0,
1386 		    lim_cb, p2, C_PREL(1));
1387 }
1388 
1389 void
1390 lim_free(struct plimit *limp)
1391 {
1392 
1393 	if (refcount_release(&limp->pl_refcnt))
1394 		free((void *)limp, M_PLIMIT);
1395 }
1396 
1397 void
1398 lim_freen(struct plimit *limp, int n)
1399 {
1400 
1401 	if (refcount_releasen(&limp->pl_refcnt, n))
1402 		free((void *)limp, M_PLIMIT);
1403 }
1404 
1405 void
1406 limbatch_add(struct limbatch *lb, struct thread *td)
1407 {
1408 	struct plimit *limp;
1409 
1410 	MPASS(td->td_limit != NULL);
1411 	limp = td->td_limit;
1412 
1413 	if (lb->limp != limp) {
1414 		if (lb->count != 0) {
1415 			lim_freen(lb->limp, lb->count);
1416 			lb->count = 0;
1417 		}
1418 		lb->limp = limp;
1419 	}
1420 
1421 	lb->count++;
1422 }
1423 
1424 void
1425 limbatch_final(struct limbatch *lb)
1426 {
1427 
1428 	MPASS(lb->count != 0);
1429 	lim_freen(lb->limp, lb->count);
1430 }
1431 
1432 /*
1433  * Make a copy of the plimit structure.
1434  * We share these structures copy-on-write after fork.
1435  */
1436 void
1437 lim_copy(struct plimit *dst, struct plimit *src)
1438 {
1439 
1440 	KASSERT(dst->pl_refcnt <= 1, ("lim_copy to shared limit"));
1441 	bcopy(src->pl_rlimit, dst->pl_rlimit, sizeof(src->pl_rlimit));
1442 }
1443 
1444 /*
1445  * Return the hard limit for a particular system resource.  The
1446  * which parameter specifies the index into the rlimit array.
1447  */
1448 rlim_t
1449 lim_max(struct thread *td, int which)
1450 {
1451 	struct rlimit rl;
1452 
1453 	lim_rlimit(td, which, &rl);
1454 	return (rl.rlim_max);
1455 }
1456 
1457 rlim_t
1458 lim_max_proc(struct proc *p, int which)
1459 {
1460 	struct rlimit rl;
1461 
1462 	lim_rlimit_proc(p, which, &rl);
1463 	return (rl.rlim_max);
1464 }
1465 
1466 /*
1467  * Return the current (soft) limit for a particular system resource.
1468  * The which parameter which specifies the index into the rlimit array
1469  */
1470 rlim_t
1471 (lim_cur)(struct thread *td, int which)
1472 {
1473 	struct rlimit rl;
1474 
1475 	lim_rlimit(td, which, &rl);
1476 	return (rl.rlim_cur);
1477 }
1478 
1479 rlim_t
1480 lim_cur_proc(struct proc *p, int which)
1481 {
1482 	struct rlimit rl;
1483 
1484 	lim_rlimit_proc(p, which, &rl);
1485 	return (rl.rlim_cur);
1486 }
1487 
1488 /*
1489  * Return a copy of the entire rlimit structure for the system limit
1490  * specified by 'which' in the rlimit structure pointed to by 'rlp'.
1491  */
1492 void
1493 lim_rlimit(struct thread *td, int which, struct rlimit *rlp)
1494 {
1495 	struct proc *p = td->td_proc;
1496 
1497 	MPASS(td == curthread);
1498 	KASSERT(which >= 0 && which < RLIM_NLIMITS,
1499 	    ("request for invalid resource limit"));
1500 	*rlp = td->td_limit->pl_rlimit[which];
1501 	if (p->p_sysent->sv_fixlimit != NULL)
1502 		p->p_sysent->sv_fixlimit(rlp, which);
1503 }
1504 
1505 void
1506 lim_rlimit_proc(struct proc *p, int which, struct rlimit *rlp)
1507 {
1508 
1509 	PROC_LOCK_ASSERT(p, MA_OWNED);
1510 	KASSERT(which >= 0 && which < RLIM_NLIMITS,
1511 	    ("request for invalid resource limit"));
1512 	*rlp = p->p_limit->pl_rlimit[which];
1513 	if (p->p_sysent->sv_fixlimit != NULL)
1514 		p->p_sysent->sv_fixlimit(rlp, which);
1515 }
1516 
1517 void
1518 uihashinit(void)
1519 {
1520 
1521 	uihashtbl = hashinit(maxproc / 16, M_UIDINFO, &uihash);
1522 	rw_init(&uihashtbl_lock, "uidinfo hash");
1523 }
1524 
1525 /*
1526  * Look up a uidinfo struct for the parameter uid.
1527  * uihashtbl_lock must be locked.
1528  * Increase refcount on uidinfo struct returned.
1529  */
1530 static struct uidinfo *
1531 uilookup(uid_t uid)
1532 {
1533 	struct uihashhead *uipp;
1534 	struct uidinfo *uip;
1535 
1536 	rw_assert(&uihashtbl_lock, RA_LOCKED);
1537 	uipp = UIHASH(uid);
1538 	LIST_FOREACH(uip, uipp, ui_hash)
1539 		if (uip->ui_uid == uid) {
1540 			uihold(uip);
1541 			break;
1542 		}
1543 
1544 	return (uip);
1545 }
1546 
1547 /*
1548  * Find or allocate a struct uidinfo for a particular uid.
1549  * Returns with uidinfo struct referenced.
1550  * uifree() should be called on a struct uidinfo when released.
1551  */
1552 struct uidinfo *
1553 uifind(uid_t uid)
1554 {
1555 	struct uidinfo *new_uip, *uip;
1556 	struct ucred *cred;
1557 
1558 	cred = curthread->td_ucred;
1559 	if (cred->cr_uidinfo->ui_uid == uid) {
1560 		uip = cred->cr_uidinfo;
1561 		uihold(uip);
1562 		return (uip);
1563 	} else if (cred->cr_ruidinfo->ui_uid == uid) {
1564 		uip = cred->cr_ruidinfo;
1565 		uihold(uip);
1566 		return (uip);
1567 	}
1568 
1569 	rw_rlock(&uihashtbl_lock);
1570 	uip = uilookup(uid);
1571 	rw_runlock(&uihashtbl_lock);
1572 	if (uip != NULL)
1573 		return (uip);
1574 
1575 	new_uip = malloc(sizeof(*new_uip), M_UIDINFO, M_WAITOK | M_ZERO);
1576 	racct_create(&new_uip->ui_racct);
1577 	refcount_init(&new_uip->ui_ref, 1);
1578 	new_uip->ui_uid = uid;
1579 
1580 	rw_wlock(&uihashtbl_lock);
1581 	/*
1582 	 * There's a chance someone created our uidinfo while we
1583 	 * were in malloc and not holding the lock, so we have to
1584 	 * make sure we don't insert a duplicate uidinfo.
1585 	 */
1586 	if ((uip = uilookup(uid)) == NULL) {
1587 		LIST_INSERT_HEAD(UIHASH(uid), new_uip, ui_hash);
1588 		rw_wunlock(&uihashtbl_lock);
1589 		uip = new_uip;
1590 	} else {
1591 		rw_wunlock(&uihashtbl_lock);
1592 		racct_destroy(&new_uip->ui_racct);
1593 		free(new_uip, M_UIDINFO);
1594 	}
1595 	return (uip);
1596 }
1597 
1598 /*
1599  * Place another refcount on a uidinfo struct.
1600  */
1601 void
1602 uihold(struct uidinfo *uip)
1603 {
1604 
1605 	refcount_acquire(&uip->ui_ref);
1606 }
1607 
1608 /*-
1609  * Since uidinfo structs have a long lifetime, we use an
1610  * opportunistic refcounting scheme to avoid locking the lookup hash
1611  * for each release.
1612  *
1613  * If the refcount hits 0, we need to free the structure,
1614  * which means we need to lock the hash.
1615  * Optimal case:
1616  *   After locking the struct and lowering the refcount, if we find
1617  *   that we don't need to free, simply unlock and return.
1618  * Suboptimal case:
1619  *   If refcount lowering results in need to free, bump the count
1620  *   back up, lose the lock and acquire the locks in the proper
1621  *   order to try again.
1622  */
1623 void
1624 uifree(struct uidinfo *uip)
1625 {
1626 
1627 	if (refcount_release_if_not_last(&uip->ui_ref))
1628 		return;
1629 
1630 	rw_wlock(&uihashtbl_lock);
1631 	if (refcount_release(&uip->ui_ref) == 0) {
1632 		rw_wunlock(&uihashtbl_lock);
1633 		return;
1634 	}
1635 
1636 	racct_destroy(&uip->ui_racct);
1637 	LIST_REMOVE(uip, ui_hash);
1638 	rw_wunlock(&uihashtbl_lock);
1639 
1640 	if (uip->ui_sbsize != 0)
1641 		printf("freeing uidinfo: uid = %d, sbsize = %ld\n",
1642 		    uip->ui_uid, uip->ui_sbsize);
1643 	if (uip->ui_proccnt != 0)
1644 		printf("freeing uidinfo: uid = %d, proccnt = %ld\n",
1645 		    uip->ui_uid, uip->ui_proccnt);
1646 	if (uip->ui_vmsize != 0)
1647 		printf("freeing uidinfo: uid = %d, swapuse = %lld\n",
1648 		    uip->ui_uid, (unsigned long long)uip->ui_vmsize);
1649 	if (uip->ui_ptscnt != 0)
1650 		printf("freeing uidinfo: uid = %d, ptscnt = %ld\n",
1651 		    uip->ui_uid, uip->ui_ptscnt);
1652 	if (uip->ui_kqcnt != 0)
1653 		printf("freeing uidinfo: uid = %d, kqcnt = %ld\n",
1654 		    uip->ui_uid, uip->ui_kqcnt);
1655 	if (uip->ui_umtxcnt != 0)
1656 		printf("freeing uidinfo: uid = %d, umtxcnt = %ld\n",
1657 		    uip->ui_uid, uip->ui_umtxcnt);
1658 	if (uip->ui_pipecnt != 0)
1659 		printf("freeing uidinfo: uid = %d, pipecnt = %ld\n",
1660 		    uip->ui_uid, uip->ui_pipecnt);
1661 	if (uip->ui_inotifycnt != 0)
1662 		printf("freeing uidinfo: uid = %d, inotifycnt = %ld\n",
1663 		    uip->ui_uid, uip->ui_inotifycnt);
1664 	if (uip->ui_inotifywatchcnt != 0)
1665 		printf("freeing uidinfo: uid = %d, inotifywatchcnt = %ld\n",
1666 		    uip->ui_uid, uip->ui_inotifywatchcnt);
1667 	if (uip->ui_vmmcnt != 0)
1668 		printf("freeing vmmcnt: uid = %d, vmmcnt = %ld\n",
1669 		    uip->ui_uid, uip->ui_vmmcnt);
1670 	free(uip, M_UIDINFO);
1671 }
1672 
1673 #ifdef RACCT
1674 void
1675 ui_racct_foreach(void (*callback)(struct racct *racct,
1676     void *arg2, void *arg3), void (*pre)(void), void (*post)(void),
1677     void *arg2, void *arg3)
1678 {
1679 	struct uidinfo *uip;
1680 	struct uihashhead *uih;
1681 
1682 	rw_rlock(&uihashtbl_lock);
1683 	if (pre != NULL)
1684 		(pre)();
1685 	for (uih = &uihashtbl[uihash]; uih >= uihashtbl; uih--) {
1686 		LIST_FOREACH(uip, uih, ui_hash) {
1687 			(callback)(uip->ui_racct, arg2, arg3);
1688 		}
1689 	}
1690 	if (post != NULL)
1691 		(post)();
1692 	rw_runlock(&uihashtbl_lock);
1693 }
1694 #endif
1695 
1696 static inline int
1697 chglimit(struct uidinfo *uip, long *limit, int diff, rlim_t max, const char *name)
1698 {
1699 	long new;
1700 
1701 	/* Don't allow them to exceed max, but allow subtraction. */
1702 	new = atomic_fetchadd_long(limit, (long)diff) + diff;
1703 	if (diff > 0 && max != 0) {
1704 		if (new < 0 || new > max) {
1705 			atomic_subtract_long(limit, (long)diff);
1706 			return (0);
1707 		}
1708 	} else if (new < 0)
1709 		printf("negative %s for uid = %d\n", name, uip->ui_uid);
1710 	return (1);
1711 }
1712 
1713 /*
1714  * Change the count associated with number of processes
1715  * a given user is using.  When 'max' is 0, don't enforce a limit
1716  */
1717 int
1718 chgproccnt(struct uidinfo *uip, int diff, rlim_t max)
1719 {
1720 
1721 	return (chglimit(uip, &uip->ui_proccnt, diff, max, "proccnt"));
1722 }
1723 
1724 /*
1725  * Change the total socket buffer size a user has used.
1726  */
1727 int
1728 chgsbsize(struct uidinfo *uip, u_int *hiwat, u_int to, rlim_t max)
1729 {
1730 	int diff, rv;
1731 
1732 	diff = to - *hiwat;
1733 	if (diff > 0 && max == 0) {
1734 		rv = 0;
1735 	} else {
1736 		rv = chglimit(uip, &uip->ui_sbsize, diff, max, "sbsize");
1737 		if (rv != 0)
1738 			*hiwat = to;
1739 	}
1740 	return (rv);
1741 }
1742 
1743 /*
1744  * Change the count associated with number of pseudo-terminals
1745  * a given user is using.  When 'max' is 0, don't enforce a limit
1746  */
1747 int
1748 chgptscnt(struct uidinfo *uip, int diff, rlim_t max)
1749 {
1750 
1751 	return (chglimit(uip, &uip->ui_ptscnt, diff, max, "ptscnt"));
1752 }
1753 
1754 int
1755 chgkqcnt(struct uidinfo *uip, int diff, rlim_t max)
1756 {
1757 
1758 	return (chglimit(uip, &uip->ui_kqcnt, diff, max, "kqcnt"));
1759 }
1760 
1761 int
1762 chgumtxcnt(struct uidinfo *uip, int diff, rlim_t max)
1763 {
1764 
1765 	return (chglimit(uip, &uip->ui_umtxcnt, diff, max, "umtxcnt"));
1766 }
1767 
1768 int
1769 chgpipecnt(struct uidinfo *uip, int diff, rlim_t max)
1770 {
1771 
1772 	return (chglimit(uip, &uip->ui_pipecnt, diff, max, "pipecnt"));
1773 }
1774 
1775 int
1776 chginotifycnt(struct uidinfo *uip, int diff, rlim_t max)
1777 {
1778 
1779 	return (chglimit(uip, &uip->ui_inotifycnt, diff, max, "inotifycnt"));
1780 }
1781 
1782 int
1783 chginotifywatchcnt(struct uidinfo *uip, int diff, rlim_t max)
1784 {
1785 
1786 	return (chglimit(uip, &uip->ui_inotifywatchcnt, diff, max,
1787 	    "inotifywatchcnt"));
1788 }
1789 
1790 int
1791 chgvmmcnt(struct uidinfo *uip, int diff, rlim_t max)
1792 {
1793 
1794 	return (chglimit(uip, &uip->ui_vmmcnt, diff, max, "vmmcnt"));
1795 }
1796 
1797 static int
1798 sysctl_kern_proc_rlimit_usage(SYSCTL_HANDLER_ARGS)
1799 {
1800 	rlim_t resval[RLIM_NLIMITS];
1801 	struct proc *p;
1802 	struct thread *td;
1803 	struct vmspace *vm;
1804 	size_t len;
1805 	int error, *name, i;
1806 
1807 	name = (int *)arg1;
1808 	if ((u_int)arg2 != 1 && (u_int)arg2 != 2)
1809 		return (EINVAL);
1810 	if (req->newptr != NULL)
1811 		return (EINVAL);
1812 
1813 	td = curthread;
1814 	error = pget((pid_t)name[0], PGET_HOLD | PGET_NOTWEXIT, &p);
1815 	if (error != 0)
1816 		return (error);
1817 	error = proc_vmspace_ref(td, p, PRVM_BLOCK_EXEC |
1818 	    PRVM_CHECK_VISIBILITY, &vm);
1819 	if (error != 0)
1820 		goto out;
1821 
1822 	if ((u_int)arg2 == 1) {
1823 		len = sizeof(resval);
1824 		memset(resval, 0, sizeof(resval));
1825 		for (i = 0; i < RLIM_NLIMITS; i++) {
1826 			error = getrlimitusage_one(p, vm, (unsigned)i, 0,
1827 			    &resval[i]);
1828 			if (error == ENXIO) {
1829 				resval[i] = -1;
1830 				error = 0;
1831 			} else if (error != 0) {
1832 				break;
1833 			}
1834 		}
1835 	} else {
1836 		len = sizeof(resval[0]);
1837 		error = getrlimitusage_one(p, vm, (unsigned)name[1], 0,
1838 		    &resval[0]);
1839 		if (error == ENXIO) {
1840 			resval[0] = -1;
1841 			error = 0;
1842 		}
1843 	}
1844 	if (error == 0)
1845 		error = SYSCTL_OUT(req, resval, len);
1846 	proc_vmspace_unref(td, p, PRVM_BLOCK_EXEC | PRVM_CHECK_VISIBILITY, vm);
1847 out:
1848 	PRELE(p);
1849 	return (error);
1850 }
1851 static SYSCTL_NODE(_kern_proc, KERN_PROC_RLIMIT_USAGE, rlimit_usage,
1852     CTLFLAG_RD | CTLFLAG_ANYBODY | CTLFLAG_MPSAFE,
1853     sysctl_kern_proc_rlimit_usage,
1854     "Process limited resources usage info");
1855