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