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