xref: /xnu-8796.121.2/bsd/kern/kern_resource.c (revision c54f35ca767986246321eb901baf8f5ff7923f6a)
1 /*
2  * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /* Copyright (c) 1995, 1997 Apple Computer, Inc. All Rights Reserved */
29 /*-
30  * Copyright (c) 1982, 1986, 1991, 1993
31  *	The Regents of the University of California.  All rights reserved.
32  * (c) UNIX System Laboratories, Inc.
33  * All or some portions of this file are derived from material licensed
34  * to the University of California by American Telephone and Telegraph
35  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36  * the permission of UNIX System Laboratories, Inc.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *	This product includes software developed by the University of
49  *	California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)kern_resource.c	8.5 (Berkeley) 1/21/94
67  */
68 /*
69  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
70  * support for mandatory and extensible security protections.  This notice
71  * is included in support of clause 2.2 (b) of the Apple Public License,
72  * Version 2.0.
73  */
74 
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/sysctl.h>
78 #include <sys/kernel.h>
79 #include <sys/file_internal.h>
80 #include <sys/resourcevar.h>
81 #include <sys/malloc.h>
82 #include <sys/proc_internal.h>
83 #include <sys/kauth.h>
84 #include <sys/mount_internal.h>
85 #include <sys/sysproto.h>
86 
87 #include <security/audit/audit.h>
88 
89 #include <machine/vmparam.h>
90 
91 #include <mach/mach_types.h>
92 #include <mach/time_value.h>
93 #include <mach/task.h>
94 #include <mach/task_info.h>
95 #include <mach/vm_map.h>
96 #include <mach/mach_vm.h>
97 #include <mach/thread_act.h>  /* for thread_policy_set( ) */
98 #include <kern/thread.h>
99 #include <kern/policy_internal.h>
100 
101 #include <kern/task.h>
102 #include <kern/clock.h>         /* for absolutetime_to_microtime() */
103 #include <netinet/in.h>         /* for TRAFFIC_MGT_SO_* */
104 #if CONFIG_FREEZE
105 #include <sys/kern_memorystatus_freeze.h> /* for memorystatus_freeze_mark_ui_transition */
106 #endif /* CONFIG_FREEZE */
107 #include <sys/socketvar.h>      /* for struct socket */
108 #if NECP
109 #include <net/necp.h>
110 #endif /* NECP */
111 
112 #include <vm/vm_map.h>
113 
114 #include <kern/assert.h>
115 #include <sys/resource.h>
116 #include <sys/priv.h>
117 #include <IOKit/IOBSD.h>
118 
119 #if CONFIG_MACF
120 #include <security/mac_framework.h>
121 #endif
122 
123 static void proc_limitblock(proc_t p);
124 static void proc_limitunblock(proc_t p);
125 static void proc_limitupdate(proc_t p, bool unblock,
126     void (^update)(struct plimit *plim));
127 
128 static int donice(struct proc *curp, struct proc *chgp, int n);
129 static int dosetrlimit(struct proc *p, u_int which, struct rlimit *limp);
130 static void do_background_socket(struct proc *p, thread_t thread);
131 static int do_background_thread(thread_t thread, int priority);
132 static int do_background_proc(struct proc *curp, struct proc *targetp, int priority);
133 static int set_gpudeny_proc(struct proc *curp, struct proc *targetp, int priority);
134 static int proc_set_darwin_role(proc_t curp, proc_t targetp, int priority);
135 static int proc_get_darwin_role(proc_t curp, proc_t targetp, int *priority);
136 static int get_background_proc(struct proc *curp, struct proc *targetp, int *priority);
137 
138 int fill_task_rusage(task_t task, rusage_info_current *ri);
139 void fill_task_billed_usage(task_t task, rusage_info_current *ri);
140 int fill_task_io_rusage(task_t task, rusage_info_current *ri);
141 int fill_task_qos_rusage(task_t task, rusage_info_current *ri);
142 uint64_t get_task_logical_writes(task_t task, bool external);
143 
144 rlim_t maxdmap = MAXDSIZ;       /* XXX */
145 rlim_t maxsmap = MAXSSIZ - PAGE_MAX_SIZE;       /* XXX */
146 
147 /* For plimit reference count */
148 os_refgrp_decl(, rlimit_refgrp, "plimit_refcnt", NULL);
149 
150 static KALLOC_TYPE_DEFINE(plimit_zone, struct plimit, KT_DEFAULT);
151 
152 /*
153  * Limits on the number of open files per process, and the number
154  * of child processes per process.
155  *
156  * Note: would be in kern/subr_param.c in FreeBSD.
157  */
158 __private_extern__ int maxfilesperproc = OPEN_MAX;              /* per-proc open files limit */
159 
160 SYSCTL_INT(_kern, KERN_MAXPROCPERUID, maxprocperuid, CTLFLAG_RW | CTLFLAG_LOCKED,
161     &maxprocperuid, 0, "Maximum processes allowed per userid" );
162 
163 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW | CTLFLAG_LOCKED,
164     &maxfilesperproc, 0, "Maximum files allowed open per process" );
165 
166 /* Args and fn for proc_iteration callback used in setpriority */
167 struct puser_nice_args {
168 	proc_t curp;
169 	int     prio;
170 	id_t    who;
171 	int *   foundp;
172 	int *   errorp;
173 };
174 static int puser_donice_callback(proc_t p, void * arg);
175 
176 
177 /* Args and fn for proc_iteration callback used in setpriority */
178 struct ppgrp_nice_args {
179 	proc_t curp;
180 	int     prio;
181 	int *   foundp;
182 	int *   errorp;
183 };
184 static int ppgrp_donice_callback(proc_t p, void * arg);
185 
186 /*
187  * Resource controls and accounting.
188  */
189 int
getpriority(struct proc * curp,struct getpriority_args * uap,int32_t * retval)190 getpriority(struct proc *curp, struct getpriority_args *uap, int32_t *retval)
191 {
192 	struct proc *p;
193 	int low = PRIO_MAX + 1;
194 	kauth_cred_t my_cred;
195 	int refheld = 0;
196 	int error = 0;
197 
198 	/* would also test (uap->who < 0), but id_t is unsigned */
199 	if (uap->who > 0x7fffffff) {
200 		return EINVAL;
201 	}
202 
203 	switch (uap->which) {
204 	case PRIO_PROCESS:
205 		if (uap->who == 0) {
206 			p = curp;
207 			low = p->p_nice;
208 		} else {
209 			p = proc_find(uap->who);
210 			if (p == 0) {
211 				break;
212 			}
213 			low = p->p_nice;
214 			proc_rele(p);
215 		}
216 		break;
217 
218 	case PRIO_PGRP: {
219 		struct pgrp *pg = PGRP_NULL;
220 
221 		if (uap->who == 0) {
222 			/* returns the pgrp to ref */
223 			pg = proc_pgrp(curp, NULL);
224 		} else if ((pg = pgrp_find(uap->who)) == PGRP_NULL) {
225 			break;
226 		}
227 		/* No need for iteration as it is a simple scan */
228 		pgrp_lock(pg);
229 		PGMEMBERS_FOREACH(pg, p) {
230 			if (p->p_nice < low) {
231 				low = p->p_nice;
232 			}
233 		}
234 		pgrp_unlock(pg);
235 		pgrp_rele(pg);
236 		break;
237 	}
238 
239 	case PRIO_USER:
240 		if (uap->who == 0) {
241 			uap->who = kauth_cred_getuid(kauth_cred_get());
242 		}
243 
244 		proc_list_lock();
245 
246 		for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
247 			my_cred = kauth_cred_proc_ref(p);
248 			if (kauth_cred_getuid(my_cred) == uap->who &&
249 			    p->p_nice < low) {
250 				low = p->p_nice;
251 			}
252 			kauth_cred_unref(&my_cred);
253 		}
254 
255 		proc_list_unlock();
256 
257 		break;
258 
259 	case PRIO_DARWIN_THREAD:
260 		/* we currently only support the current thread */
261 		if (uap->who != 0) {
262 			return EINVAL;
263 		}
264 
265 		low = proc_get_thread_policy(current_thread(), TASK_POLICY_INTERNAL, TASK_POLICY_DARWIN_BG);
266 
267 		break;
268 
269 	case PRIO_DARWIN_PROCESS:
270 		if (uap->who == 0) {
271 			p = curp;
272 		} else {
273 			p = proc_find(uap->who);
274 			if (p == PROC_NULL) {
275 				break;
276 			}
277 			refheld = 1;
278 		}
279 
280 		error = get_background_proc(curp, p, &low);
281 
282 		if (refheld) {
283 			proc_rele(p);
284 		}
285 		if (error) {
286 			return error;
287 		}
288 		break;
289 
290 	case PRIO_DARWIN_ROLE:
291 		if (uap->who == 0) {
292 			p = curp;
293 		} else {
294 			p = proc_find(uap->who);
295 			if (p == PROC_NULL) {
296 				break;
297 			}
298 			refheld = 1;
299 		}
300 
301 		error = proc_get_darwin_role(curp, p, &low);
302 
303 		if (refheld) {
304 			proc_rele(p);
305 		}
306 		if (error) {
307 			return error;
308 		}
309 		break;
310 
311 	default:
312 		return EINVAL;
313 	}
314 	if (low == PRIO_MAX + 1) {
315 		return ESRCH;
316 	}
317 	*retval = low;
318 	return 0;
319 }
320 
321 /* call back function used for proc iteration in PRIO_USER */
322 static int
puser_donice_callback(proc_t p,void * arg)323 puser_donice_callback(proc_t p, void * arg)
324 {
325 	int error, n;
326 	struct puser_nice_args * pun = (struct puser_nice_args *)arg;
327 	kauth_cred_t my_cred;
328 
329 	my_cred = kauth_cred_proc_ref(p);
330 	if (kauth_cred_getuid(my_cred) == pun->who) {
331 		error = donice(pun->curp, p, pun->prio);
332 		if (pun->errorp != NULL) {
333 			*pun->errorp = error;
334 		}
335 		if (pun->foundp != NULL) {
336 			n = *pun->foundp;
337 			*pun->foundp = n + 1;
338 		}
339 	}
340 	kauth_cred_unref(&my_cred);
341 
342 	return PROC_RETURNED;
343 }
344 
345 /* call back function used for proc iteration in PRIO_PGRP */
346 static int
ppgrp_donice_callback(proc_t p,void * arg)347 ppgrp_donice_callback(proc_t p, void * arg)
348 {
349 	int error;
350 	struct ppgrp_nice_args * pun = (struct ppgrp_nice_args *)arg;
351 	int n;
352 
353 	error = donice(pun->curp, p, pun->prio);
354 	if (pun->errorp != NULL) {
355 		*pun->errorp = error;
356 	}
357 	if (pun->foundp != NULL) {
358 		n = *pun->foundp;
359 		*pun->foundp = n + 1;
360 	}
361 
362 	return PROC_RETURNED;
363 }
364 
365 /*
366  * Returns:	0			Success
367  *		EINVAL
368  *		ESRCH
369  *	donice:EPERM
370  *	donice:EACCES
371  */
372 /* ARGSUSED */
373 int
setpriority(struct proc * curp,struct setpriority_args * uap,int32_t * retval)374 setpriority(struct proc *curp, struct setpriority_args *uap, int32_t *retval)
375 {
376 	struct proc *p;
377 	int found = 0, error = 0;
378 	int refheld = 0;
379 
380 	AUDIT_ARG(cmd, uap->which);
381 	AUDIT_ARG(owner, uap->who, 0);
382 	AUDIT_ARG(value32, uap->prio);
383 
384 	/* would also test (uap->who < 0), but id_t is unsigned */
385 	if (uap->who > 0x7fffffff) {
386 		return EINVAL;
387 	}
388 
389 	switch (uap->which) {
390 	case PRIO_PROCESS:
391 		if (uap->who == 0) {
392 			p = curp;
393 		} else {
394 			p = proc_find(uap->who);
395 			if (p == 0) {
396 				break;
397 			}
398 			refheld = 1;
399 		}
400 		error = donice(curp, p, uap->prio);
401 		found++;
402 		if (refheld != 0) {
403 			proc_rele(p);
404 		}
405 		break;
406 
407 	case PRIO_PGRP: {
408 		struct pgrp *pg = PGRP_NULL;
409 		struct ppgrp_nice_args ppgrp;
410 
411 		if (uap->who == 0) {
412 			pg = proc_pgrp(curp, NULL);
413 		} else if ((pg = pgrp_find(uap->who)) == PGRP_NULL) {
414 			break;
415 		}
416 
417 		ppgrp.curp = curp;
418 		ppgrp.prio = uap->prio;
419 		ppgrp.foundp = &found;
420 		ppgrp.errorp = &error;
421 
422 		pgrp_iterate(pg, ppgrp_donice_callback, (void *)&ppgrp, NULL);
423 		pgrp_rele(pg);
424 
425 		break;
426 	}
427 
428 	case PRIO_USER: {
429 		struct puser_nice_args punice;
430 
431 		if (uap->who == 0) {
432 			uap->who = kauth_cred_getuid(kauth_cred_get());
433 		}
434 
435 		punice.curp = curp;
436 		punice.prio = uap->prio;
437 		punice.who = uap->who;
438 		punice.foundp = &found;
439 		error = 0;
440 		punice.errorp = &error;
441 		proc_iterate(PROC_ALLPROCLIST, puser_donice_callback, (void *)&punice, NULL, NULL);
442 
443 		break;
444 	}
445 
446 	case PRIO_DARWIN_THREAD: {
447 		/* we currently only support the current thread */
448 		if (uap->who != 0) {
449 			return EINVAL;
450 		}
451 
452 		error = do_background_thread(current_thread(), uap->prio);
453 		found++;
454 		break;
455 	}
456 
457 	case PRIO_DARWIN_PROCESS: {
458 		if (uap->who == 0) {
459 			p = curp;
460 		} else {
461 			p = proc_find(uap->who);
462 			if (p == 0) {
463 				break;
464 			}
465 			refheld = 1;
466 		}
467 
468 		error = do_background_proc(curp, p, uap->prio);
469 
470 		found++;
471 		if (refheld != 0) {
472 			proc_rele(p);
473 		}
474 		break;
475 	}
476 
477 	case PRIO_DARWIN_GPU: {
478 		if (uap->who == 0) {
479 			return EINVAL;
480 		}
481 
482 		p = proc_find(uap->who);
483 		if (p == PROC_NULL) {
484 			break;
485 		}
486 
487 		error = set_gpudeny_proc(curp, p, uap->prio);
488 
489 		found++;
490 		proc_rele(p);
491 		break;
492 	}
493 
494 	case PRIO_DARWIN_ROLE: {
495 		if (uap->who == 0) {
496 			p = curp;
497 		} else {
498 			p = proc_find(uap->who);
499 			if (p == PROC_NULL) {
500 				break;
501 			}
502 			refheld = 1;
503 		}
504 
505 		error = proc_set_darwin_role(curp, p, uap->prio);
506 
507 		found++;
508 		if (refheld != 0) {
509 			proc_rele(p);
510 		}
511 		break;
512 	}
513 
514 	default:
515 		return EINVAL;
516 	}
517 	if (found == 0) {
518 		return ESRCH;
519 	}
520 	if (error == EIDRM) {
521 		*retval = -2;
522 		error = 0;
523 	}
524 	return error;
525 }
526 
527 
528 /*
529  * Returns:	0			Success
530  *		EPERM
531  *		EACCES
532  *	mac_check_proc_sched:???
533  */
534 static int
donice(struct proc * curp,struct proc * chgp,int n)535 donice(struct proc *curp, struct proc *chgp, int n)
536 {
537 	int error = 0;
538 	kauth_cred_t ucred;
539 	kauth_cred_t my_cred;
540 
541 	ucred = kauth_cred_proc_ref(curp);
542 	my_cred = kauth_cred_proc_ref(chgp);
543 
544 	if (suser(ucred, NULL) && kauth_cred_getruid(ucred) &&
545 	    kauth_cred_getuid(ucred) != kauth_cred_getuid(my_cred) &&
546 	    kauth_cred_getruid(ucred) != kauth_cred_getuid(my_cred)) {
547 		error = EPERM;
548 		goto out;
549 	}
550 	if (n > PRIO_MAX) {
551 		n = PRIO_MAX;
552 	}
553 	if (n < PRIO_MIN) {
554 		n = PRIO_MIN;
555 	}
556 	if (n < chgp->p_nice && suser(ucred, &curp->p_acflag)) {
557 		error = EACCES;
558 		goto out;
559 	}
560 #if CONFIG_MACF
561 	error = mac_proc_check_sched(curp, chgp);
562 	if (error) {
563 		goto out;
564 	}
565 #endif
566 	proc_lock(chgp);
567 	chgp->p_nice = (char)n;
568 	proc_unlock(chgp);
569 	(void)resetpriority(chgp);
570 out:
571 	kauth_cred_unref(&ucred);
572 	kauth_cred_unref(&my_cred);
573 	return error;
574 }
575 
576 static int
set_gpudeny_proc(struct proc * curp,struct proc * targetp,int priority)577 set_gpudeny_proc(struct proc *curp, struct proc *targetp, int priority)
578 {
579 	int error = 0;
580 	kauth_cred_t ucred;
581 	kauth_cred_t target_cred;
582 
583 	ucred = kauth_cred_get();
584 	target_cred = kauth_cred_proc_ref(targetp);
585 
586 	/* TODO: Entitlement instead of uid check */
587 
588 	if (!kauth_cred_issuser(ucred) && kauth_cred_getruid(ucred) &&
589 	    kauth_cred_getuid(ucred) != kauth_cred_getuid(target_cred) &&
590 	    kauth_cred_getruid(ucred) != kauth_cred_getuid(target_cred)) {
591 		error = EPERM;
592 		goto out;
593 	}
594 
595 	if (curp == targetp) {
596 		error = EPERM;
597 		goto out;
598 	}
599 
600 #if CONFIG_MACF
601 	error = mac_proc_check_sched(curp, targetp);
602 	if (error) {
603 		goto out;
604 	}
605 #endif
606 
607 	switch (priority) {
608 	case PRIO_DARWIN_GPU_DENY:
609 		task_set_gpu_denied(proc_task(targetp), TRUE);
610 		break;
611 	case PRIO_DARWIN_GPU_ALLOW:
612 		task_set_gpu_denied(proc_task(targetp), FALSE);
613 		break;
614 	default:
615 		error = EINVAL;
616 		goto out;
617 	}
618 
619 out:
620 	kauth_cred_unref(&target_cred);
621 	return error;
622 }
623 
624 static int
proc_set_darwin_role(proc_t curp,proc_t targetp,int priority)625 proc_set_darwin_role(proc_t curp, proc_t targetp, int priority)
626 {
627 	int error = 0;
628 	uint32_t flagsp = 0;
629 
630 	kauth_cred_t ucred, target_cred;
631 
632 	ucred = kauth_cred_get();
633 	target_cred = kauth_cred_proc_ref(targetp);
634 
635 	if (!kauth_cred_issuser(ucred) && kauth_cred_getruid(ucred) &&
636 	    kauth_cred_getuid(ucred) != kauth_cred_getuid(target_cred) &&
637 	    kauth_cred_getruid(ucred) != kauth_cred_getuid(target_cred)) {
638 		if (priv_check_cred(ucred, PRIV_SETPRIORITY_DARWIN_ROLE, 0) != 0) {
639 			error = EPERM;
640 			goto out;
641 		}
642 	}
643 
644 	if (curp != targetp) {
645 #if CONFIG_MACF
646 		if ((error = mac_proc_check_sched(curp, targetp))) {
647 			goto out;
648 		}
649 #endif
650 	}
651 
652 	proc_get_darwinbgstate(proc_task(targetp), &flagsp);
653 	if ((flagsp & PROC_FLAG_APPLICATION) != PROC_FLAG_APPLICATION) {
654 		error = ENOTSUP;
655 		goto out;
656 	}
657 
658 	task_role_t role = TASK_UNSPECIFIED;
659 
660 	if ((error = proc_darwin_role_to_task_role(priority, &role))) {
661 		goto out;
662 	}
663 
664 	proc_set_task_policy(proc_task(targetp), TASK_POLICY_ATTRIBUTE,
665 	    TASK_POLICY_ROLE, role);
666 
667 #if CONFIG_FREEZE
668 	if (priority == PRIO_DARWIN_ROLE_UI_FOCAL || priority == PRIO_DARWIN_ROLE_UI || priority == PRIO_DARWIN_ROLE_UI_NON_FOCAL) {
669 		memorystatus_freezer_mark_ui_transition(targetp);
670 	}
671 #endif /* CONFIG_FREEZE */
672 
673 out:
674 	kauth_cred_unref(&target_cred);
675 	return error;
676 }
677 
678 static int
proc_get_darwin_role(proc_t curp,proc_t targetp,int * priority)679 proc_get_darwin_role(proc_t curp, proc_t targetp, int *priority)
680 {
681 	int error = 0;
682 	int role = 0;
683 
684 	kauth_cred_t ucred, target_cred;
685 
686 	ucred = kauth_cred_get();
687 	target_cred = kauth_cred_proc_ref(targetp);
688 
689 	if (!kauth_cred_issuser(ucred) && kauth_cred_getruid(ucred) &&
690 	    kauth_cred_getuid(ucred) != kauth_cred_getuid(target_cred) &&
691 	    kauth_cred_getruid(ucred) != kauth_cred_getuid(target_cred)) {
692 		error = EPERM;
693 		goto out;
694 	}
695 
696 	if (curp != targetp) {
697 #if CONFIG_MACF
698 		if ((error = mac_proc_check_sched(curp, targetp))) {
699 			goto out;
700 		}
701 #endif
702 	}
703 
704 	role = proc_get_task_policy(proc_task(targetp), TASK_POLICY_ATTRIBUTE, TASK_POLICY_ROLE);
705 
706 	*priority = proc_task_role_to_darwin_role(role);
707 
708 out:
709 	kauth_cred_unref(&target_cred);
710 	return error;
711 }
712 
713 
714 static int
get_background_proc(struct proc * curp,struct proc * targetp,int * priority)715 get_background_proc(struct proc *curp, struct proc *targetp, int *priority)
716 {
717 	int external = 0;
718 	int error = 0;
719 	kauth_cred_t ucred, target_cred;
720 
721 	ucred = kauth_cred_get();
722 	target_cred = kauth_cred_proc_ref(targetp);
723 
724 	if (!kauth_cred_issuser(ucred) && kauth_cred_getruid(ucred) &&
725 	    kauth_cred_getuid(ucred) != kauth_cred_getuid(target_cred) &&
726 	    kauth_cred_getruid(ucred) != kauth_cred_getuid(target_cred)) {
727 		error = EPERM;
728 		goto out;
729 	}
730 
731 	external = (curp == targetp) ? TASK_POLICY_INTERNAL : TASK_POLICY_EXTERNAL;
732 
733 	*priority = proc_get_task_policy(current_task(), external, TASK_POLICY_DARWIN_BG);
734 
735 out:
736 	kauth_cred_unref(&target_cred);
737 	return error;
738 }
739 
740 static int
do_background_proc(struct proc * curp,struct proc * targetp,int priority)741 do_background_proc(struct proc *curp, struct proc *targetp, int priority)
742 {
743 #if !CONFIG_MACF
744 #pragma unused(curp)
745 #endif
746 	int error = 0;
747 	kauth_cred_t ucred;
748 	kauth_cred_t target_cred;
749 	int external;
750 	int enable;
751 
752 	ucred = kauth_cred_get();
753 	target_cred = kauth_cred_proc_ref(targetp);
754 
755 	if (!kauth_cred_issuser(ucred) && kauth_cred_getruid(ucred) &&
756 	    kauth_cred_getuid(ucred) != kauth_cred_getuid(target_cred) &&
757 	    kauth_cred_getruid(ucred) != kauth_cred_getuid(target_cred)) {
758 		error = EPERM;
759 		goto out;
760 	}
761 
762 #if CONFIG_MACF
763 	error = mac_proc_check_sched(curp, targetp);
764 	if (error) {
765 		goto out;
766 	}
767 #endif
768 
769 	external = (curp == targetp) ? TASK_POLICY_INTERNAL : TASK_POLICY_EXTERNAL;
770 
771 	switch (priority) {
772 	case PRIO_DARWIN_BG:
773 		enable = TASK_POLICY_ENABLE;
774 		break;
775 	case PRIO_DARWIN_NONUI:
776 		/* ignored for compatibility */
777 		goto out;
778 	default:
779 		/* TODO: EINVAL if priority != 0 */
780 		enable = TASK_POLICY_DISABLE;
781 		break;
782 	}
783 
784 	proc_set_task_policy(proc_task(targetp), external, TASK_POLICY_DARWIN_BG, enable);
785 
786 out:
787 	kauth_cred_unref(&target_cred);
788 	return error;
789 }
790 
791 static void
do_background_socket(struct proc * p,thread_t thread)792 do_background_socket(struct proc *p, thread_t thread)
793 {
794 #if SOCKETS
795 	struct fileproc *fp;
796 	int              background = false;
797 #if NECP
798 	int              update_necp = false;
799 #endif /* NECP */
800 
801 	if (thread != THREAD_NULL &&
802 	    get_threadtask(thread) != proc_task(p)) {
803 		return;
804 	}
805 
806 	proc_fdlock(p);
807 
808 	if (thread != THREAD_NULL) {
809 		background = proc_get_effective_thread_policy(thread, TASK_POLICY_ALL_SOCKETS_BG);
810 	} else {
811 		background = proc_get_effective_task_policy(proc_task(p), TASK_POLICY_ALL_SOCKETS_BG);
812 	}
813 
814 	if (background) {
815 		/*
816 		 * For PRIO_DARWIN_PROCESS (thread is NULL), simply mark
817 		 * the sockets with the background flag.  There's nothing
818 		 * to do here for the PRIO_DARWIN_THREAD case.
819 		 */
820 		if (thread == THREAD_NULL) {
821 			fdt_foreach(fp, p) {
822 				if (FILEGLOB_DTYPE(fp->fp_glob) == DTYPE_SOCKET) {
823 					struct socket *sockp = (struct socket *)fp_get_data(fp);
824 					socket_set_traffic_mgt_flags(sockp, TRAFFIC_MGT_SO_BACKGROUND);
825 					sockp->so_background_thread = NULL;
826 				}
827 #if NECP
828 				else if (FILEGLOB_DTYPE(fp->fp_glob) == DTYPE_NETPOLICY) {
829 					if (necp_set_client_as_background(p, fp, background)) {
830 						update_necp = true;
831 					}
832 				}
833 #endif /* NECP */
834 			}
835 		}
836 	} else {
837 		/* disable networking IO throttle.
838 		 * NOTE - It is a known limitation of the current design that we
839 		 * could potentially clear TRAFFIC_MGT_SO_BACKGROUND bit for
840 		 * sockets created by other threads within this process.
841 		 */
842 		fdt_foreach(fp, p) {
843 			struct socket *sockp;
844 
845 			if (FILEGLOB_DTYPE(fp->fp_glob) == DTYPE_SOCKET) {
846 				sockp = (struct socket *)fp_get_data(fp);
847 				/* skip if only clearing this thread's sockets */
848 				if ((thread) && (sockp->so_background_thread != thread)) {
849 					continue;
850 				}
851 				socket_clear_traffic_mgt_flags(sockp, TRAFFIC_MGT_SO_BACKGROUND);
852 				sockp->so_background_thread = NULL;
853 			}
854 #if NECP
855 			else if (FILEGLOB_DTYPE(fp->fp_glob) == DTYPE_NETPOLICY) {
856 				if (necp_set_client_as_background(p, fp, background)) {
857 					update_necp = true;
858 				}
859 			}
860 #endif /* NECP */
861 		}
862 	}
863 
864 	proc_fdunlock(p);
865 
866 #if NECP
867 	if (update_necp) {
868 		necp_update_all_clients();
869 	}
870 #endif /* NECP */
871 #else
872 #pragma unused(p, thread)
873 #endif
874 }
875 
876 
877 /*
878  * do_background_thread
879  *
880  * Requires: thread reference
881  *
882  * Returns:     0                       Success
883  *              EPERM                   Tried to background while in vfork
884  * XXX - todo - does this need a MACF hook?
885  */
886 static int
do_background_thread(thread_t thread,int priority)887 do_background_thread(thread_t thread, int priority)
888 {
889 	int enable, external;
890 	int rv = 0;
891 
892 	/* Backgrounding is unsupported for workq threads */
893 	if (thread_is_static_param(thread)) {
894 		return EPERM;
895 	}
896 
897 	/* Not allowed to combine QoS and DARWIN_BG, doing so strips the QoS */
898 	if (thread_has_qos_policy(thread)) {
899 		thread_remove_qos_policy(thread);
900 		rv = EIDRM;
901 	}
902 
903 	/* TODO: Fail if someone passes something besides 0 or PRIO_DARWIN_BG */
904 	enable   = (priority == PRIO_DARWIN_BG) ? TASK_POLICY_ENABLE   : TASK_POLICY_DISABLE;
905 	external = (current_thread() == thread) ? TASK_POLICY_INTERNAL : TASK_POLICY_EXTERNAL;
906 
907 	proc_set_thread_policy(thread, external, TASK_POLICY_DARWIN_BG, enable);
908 
909 	return rv;
910 }
911 
912 
913 /*
914  * Returns:	0			Success
915  *	copyin:EFAULT
916  *	dosetrlimit:
917  */
918 /* ARGSUSED */
919 int
setrlimit(struct proc * p,struct setrlimit_args * uap,__unused int32_t * retval)920 setrlimit(struct proc *p, struct setrlimit_args *uap, __unused int32_t *retval)
921 {
922 	struct rlimit alim;
923 	int error;
924 
925 	if ((error = copyin(uap->rlp, (caddr_t)&alim,
926 	    sizeof(struct rlimit)))) {
927 		return error;
928 	}
929 
930 	return dosetrlimit(p, uap->which, &alim);
931 }
932 
933 /*
934  * Returns:	0			Success
935  *		EINVAL
936  *	suser:EPERM
937  *
938  * Notes:	EINVAL is returned both for invalid arguments, and in the
939  *		case that the current usage (e.g. RLIMIT_STACK) is already
940  *		in excess of the requested limit.
941  */
942 static int
dosetrlimit(struct proc * p,u_int which,struct rlimit * newrlim)943 dosetrlimit(struct proc *p, u_int which, struct rlimit *newrlim)
944 {
945 	struct rlimit        rlim, stack_rlim = {.rlim_cur = 0, .rlim_max = 0};
946 	int                  error;
947 	kern_return_t        kr;
948 
949 	/* Mask out POSIX flag, saved above */
950 	which &= ~_RLIMIT_POSIX_FLAG;
951 
952 	/* Unknown resource */
953 	if (which >= RLIM_NLIMITS) {
954 		return EINVAL;
955 	}
956 
957 	proc_lock(p);
958 
959 	/* Only one thread is able to change the current process's rlimit values */
960 	proc_limitblock(p);
961 
962 	/*
963 	 * Take a snapshot of the current rlimit values and read this throughout
964 	 * this routine. This minimizes the critical sections and allow other
965 	 * processes in the system to access the plimit while we are in the
966 	 * middle of this setrlimit call.
967 	 */
968 	rlim = smr_serialized_load(&p->p_limit)->pl_rlimit[which];
969 
970 	proc_unlock(p);
971 
972 	error = 0;
973 	/* Sanity check: new soft limit cannot exceed new hard limit */
974 	if (newrlim->rlim_cur > newrlim->rlim_max) {
975 		error = EINVAL;
976 	}
977 	/*
978 	 * Sanity check: only super-user may raise the hard limit.
979 	 * newrlim->rlim_cur > rlim.rlim_max implies that the call
980 	 * is increasing the hard limit as well.
981 	 */
982 	else if (newrlim->rlim_cur > rlim.rlim_max || newrlim->rlim_max > rlim.rlim_max) {
983 		/* suser() returns 0 if the calling thread is super user. */
984 		error = suser(kauth_cred_get(), &p->p_acflag);
985 	}
986 
987 	if (error) {
988 		/* Invalid setrlimit request: EINVAL or EPERM */
989 		goto out;
990 	}
991 
992 	/* We have the reader lock of the process's plimit so it's safe to read the rlimit values */
993 	switch (which) {
994 	case RLIMIT_CPU:
995 		if (newrlim->rlim_cur == RLIM_INFINITY) {
996 			task_vtimer_clear(proc_task(p), TASK_VTIMER_RLIM);
997 			timerclear(&p->p_rlim_cpu);
998 		} else {
999 			task_absolutetime_info_data_t   tinfo;
1000 			mach_msg_type_number_t          count;
1001 			struct timeval                  ttv, tv;
1002 			clock_sec_t                     tv_sec;
1003 			clock_usec_t                    tv_usec;
1004 
1005 			count = TASK_ABSOLUTETIME_INFO_COUNT;
1006 			task_info(proc_task(p), TASK_ABSOLUTETIME_INFO, (task_info_t)&tinfo, &count);
1007 			absolutetime_to_microtime(tinfo.total_user + tinfo.total_system, &tv_sec, &tv_usec);
1008 			ttv.tv_sec = tv_sec;
1009 			ttv.tv_usec = tv_usec;
1010 
1011 			tv.tv_sec = (newrlim->rlim_cur > __INT_MAX__ ? __INT_MAX__ : (__darwin_time_t)newrlim->rlim_cur);
1012 			tv.tv_usec = 0;
1013 			timersub(&tv, &ttv, &p->p_rlim_cpu);
1014 
1015 			timerclear(&tv);
1016 			if (timercmp(&p->p_rlim_cpu, &tv, >)) {
1017 				task_vtimer_set(proc_task(p), TASK_VTIMER_RLIM);
1018 			} else {
1019 				task_vtimer_clear(proc_task(p), TASK_VTIMER_RLIM);
1020 
1021 				timerclear(&p->p_rlim_cpu);
1022 
1023 				psignal(p, SIGXCPU);
1024 			}
1025 		}
1026 		break;
1027 
1028 	case RLIMIT_DATA:
1029 #if 00
1030 		if (newrlim->rlim_cur > maxdmap) {
1031 			newrlim->rlim_cur = maxdmap;
1032 		}
1033 		if (newrlim->rlim_max > maxdmap) {
1034 			newrlim->rlim_max = maxdmap;
1035 		}
1036 #endif
1037 
1038 		/* Over to Mach VM to validate the new data limit */
1039 		if (vm_map_set_data_limit(current_map(), newrlim->rlim_cur) != KERN_SUCCESS) {
1040 			/* The limit specified cannot be lowered because current usage is already higher than the limit. */
1041 			error =  EINVAL;
1042 			goto out;
1043 		}
1044 		break;
1045 
1046 	case RLIMIT_STACK:
1047 		if (p->p_lflag & P_LCUSTOM_STACK) {
1048 			/* Process has a custom stack set - rlimit cannot be used to change it */
1049 			error = EINVAL;
1050 			goto out;
1051 		}
1052 
1053 		/*
1054 		 * Note: the real stack size limit is enforced by maxsmap, not a process's RLIMIT_STACK.
1055 		 *
1056 		 * The kernel uses maxsmap to control the actual stack size limit. While we allow
1057 		 * processes to set RLIMIT_STACK to RLIM_INFINITY (UNIX 03), accessing memory
1058 		 * beyond the maxsmap will still trigger an exception.
1059 		 *
1060 		 * stack_rlim is used to store the user-defined RLIMIT_STACK values while we adjust
1061 		 * the stack size using kernel limit (i.e. maxsmap).
1062 		 */
1063 		if (newrlim->rlim_cur > maxsmap ||
1064 		    newrlim->rlim_max > maxsmap) {
1065 			if (newrlim->rlim_cur > maxsmap) {
1066 				stack_rlim.rlim_cur = newrlim->rlim_cur;
1067 				newrlim->rlim_cur = maxsmap;
1068 			}
1069 			if (newrlim->rlim_max > maxsmap) {
1070 				stack_rlim.rlim_max = newrlim->rlim_max;
1071 				newrlim->rlim_max = maxsmap;
1072 			}
1073 		}
1074 
1075 		/*
1076 		 * Stack is allocated to the max at exec time with only
1077 		 * "rlim_cur" bytes accessible.  If stack limit is going
1078 		 * up make more accessible, if going down make inaccessible.
1079 		 */
1080 		if (newrlim->rlim_cur > rlim.rlim_cur) {
1081 			mach_vm_offset_t addr;
1082 			mach_vm_size_t size;
1083 
1084 			/* grow stack */
1085 			size = newrlim->rlim_cur;
1086 			if (round_page_overflow(size, &size)) {
1087 				error = EINVAL;
1088 				goto out;
1089 			}
1090 			size -= round_page_64(rlim.rlim_cur);
1091 
1092 			addr = (mach_vm_offset_t)(p->user_stack - round_page_64(newrlim->rlim_cur));
1093 			kr = mach_vm_protect(current_map(), addr, size, FALSE, VM_PROT_DEFAULT);
1094 			if (kr != KERN_SUCCESS) {
1095 				error = EINVAL;
1096 				goto out;
1097 			}
1098 		} else if (newrlim->rlim_cur < rlim.rlim_cur) {
1099 			mach_vm_offset_t addr;
1100 			mach_vm_size_t size;
1101 			uint64_t cur_sp;
1102 
1103 			/* shrink stack */
1104 
1105 			/*
1106 			 * First check if new stack limit would agree
1107 			 * with current stack usage.
1108 			 * Get the current thread's stack pointer...
1109 			 */
1110 			cur_sp = thread_adjuserstack(current_thread(), 0);
1111 			if (cur_sp <= p->user_stack &&
1112 			    cur_sp > (p->user_stack - round_page_64(rlim.rlim_cur))) {
1113 				/* stack pointer is in main stack */
1114 				if (cur_sp <= (p->user_stack - round_page_64(newrlim->rlim_cur))) {
1115 					/*
1116 					 * New limit would cause current usage to be invalid:
1117 					 * reject new limit.
1118 					 */
1119 					error =  EINVAL;
1120 					goto out;
1121 				}
1122 			} else {
1123 				/* not on the main stack: reject */
1124 				error =  EINVAL;
1125 				goto out;
1126 			}
1127 
1128 			size = round_page_64(rlim.rlim_cur);
1129 			size -= round_page_64(rlim.rlim_cur);
1130 
1131 			addr = (mach_vm_offset_t)(p->user_stack - round_page_64(rlim.rlim_cur));
1132 
1133 			kr = mach_vm_protect(current_map(), addr, size, FALSE, VM_PROT_NONE);
1134 			if (kr != KERN_SUCCESS) {
1135 				error =  EINVAL;
1136 				goto out;
1137 			}
1138 		} else {
1139 			/* no change ... */
1140 		}
1141 
1142 		/*
1143 		 * We've adjusted the process's stack region. If the user-defined limit is greater
1144 		 * than maxsmap, we need to reflect this change in rlimit interface.
1145 		 */
1146 		if (stack_rlim.rlim_cur != 0) {
1147 			newrlim->rlim_cur = stack_rlim.rlim_cur;
1148 		}
1149 		if (stack_rlim.rlim_max != 0) {
1150 			newrlim->rlim_max = stack_rlim.rlim_max;
1151 		}
1152 		break;
1153 
1154 	case RLIMIT_NOFILE:
1155 		/*
1156 		 * Nothing to be done here as we already performed the sanity checks before entering the switch code block.
1157 		 * The real NOFILE limits enforced by the kernel is capped at MIN(RLIMIT_NOFILE, maxfilesperproc)
1158 		 */
1159 		break;
1160 
1161 	case RLIMIT_AS:
1162 		/* Over to Mach VM to validate the new address space limit */
1163 		if (vm_map_set_size_limit(current_map(), newrlim->rlim_cur) != KERN_SUCCESS) {
1164 			/* The limit specified cannot be lowered because current usage is already higher than the limit. */
1165 			error =  EINVAL;
1166 			goto out;
1167 		}
1168 		break;
1169 
1170 	case RLIMIT_NPROC:
1171 		/*
1172 		 * Only root can set to the maxproc limits, as it is
1173 		 * systemwide resource; all others are limited to
1174 		 * maxprocperuid (presumably less than maxproc).
1175 		 */
1176 		if (kauth_cred_issuser(kauth_cred_get())) {
1177 			if (newrlim->rlim_cur > (rlim_t)maxproc) {
1178 				newrlim->rlim_cur = maxproc;
1179 			}
1180 			if (newrlim->rlim_max > (rlim_t)maxproc) {
1181 				newrlim->rlim_max = maxproc;
1182 			}
1183 		} else {
1184 			if (newrlim->rlim_cur > (rlim_t)maxprocperuid) {
1185 				newrlim->rlim_cur = maxprocperuid;
1186 			}
1187 			if (newrlim->rlim_max > (rlim_t)maxprocperuid) {
1188 				newrlim->rlim_max = maxprocperuid;
1189 			}
1190 		}
1191 		break;
1192 
1193 	case RLIMIT_MEMLOCK:
1194 		/*
1195 		 * Tell the Mach VM layer about the new limit value.
1196 		 */
1197 		newrlim->rlim_cur = (vm_size_t)newrlim->rlim_cur;
1198 		vm_map_set_user_wire_limit(current_map(), (vm_size_t)newrlim->rlim_cur);
1199 		break;
1200 	} /* switch... */
1201 
1202 	/* Everything checks out and we are now ready to update the rlimit */
1203 	error = 0;
1204 
1205 out:
1206 
1207 	if (error == 0) {
1208 		/*
1209 		 * COW the current plimit if it's shared, otherwise update it in place.
1210 		 * Finally unblock other threads wishing to change plimit.
1211 		 */
1212 		proc_limitupdate(p, true, ^(struct plimit *plim) {
1213 			plim->pl_rlimit[which] = *newrlim;
1214 		});
1215 	} else {
1216 		/*
1217 		 * This setrlimit has failed, just leave the plimit as is and unblock other
1218 		 * threads wishing to change plimit.
1219 		 */
1220 		proc_lock(p);
1221 		proc_limitunblock(p);
1222 		proc_unlock(p);
1223 	}
1224 
1225 	return error;
1226 }
1227 
1228 /* ARGSUSED */
1229 int
getrlimit(struct proc * p,struct getrlimit_args * uap,__unused int32_t * retval)1230 getrlimit(struct proc *p, struct getrlimit_args *uap, __unused int32_t *retval)
1231 {
1232 	struct rlimit lim = {};
1233 
1234 	/*
1235 	 * Take out flag now in case we need to use it to trigger variant
1236 	 * behaviour later.
1237 	 */
1238 	uap->which &= ~_RLIMIT_POSIX_FLAG;
1239 
1240 	if (uap->which >= RLIM_NLIMITS) {
1241 		return EINVAL;
1242 	}
1243 	lim = proc_limitget(p, uap->which);
1244 	return copyout((caddr_t)&lim,
1245 	           uap->rlp, sizeof(struct rlimit));
1246 }
1247 
1248 /*
1249  * Transform the running time and tick information in proc p into user,
1250  * system, and interrupt time usage.
1251  */
1252 /* No lock on proc is held for this.. */
1253 void
calcru(struct proc * p,struct timeval * up,struct timeval * sp,struct timeval * ip)1254 calcru(struct proc *p, struct timeval *up, struct timeval *sp, struct timeval *ip)
1255 {
1256 	task_t                  task;
1257 
1258 	timerclear(up);
1259 	timerclear(sp);
1260 	if (ip != NULL) {
1261 		timerclear(ip);
1262 	}
1263 
1264 	task = proc_task(p);
1265 	if (task) {
1266 		mach_task_basic_info_data_t tinfo;
1267 		task_thread_times_info_data_t ttimesinfo;
1268 		task_events_info_data_t teventsinfo;
1269 		mach_msg_type_number_t task_info_count, task_ttimes_count;
1270 		mach_msg_type_number_t task_events_count;
1271 		struct timeval ut, st;
1272 
1273 		task_info_count = MACH_TASK_BASIC_INFO_COUNT;
1274 		task_info(task, MACH_TASK_BASIC_INFO,
1275 		    (task_info_t)&tinfo, &task_info_count);
1276 		ut.tv_sec = tinfo.user_time.seconds;
1277 		ut.tv_usec = tinfo.user_time.microseconds;
1278 		st.tv_sec = tinfo.system_time.seconds;
1279 		st.tv_usec = tinfo.system_time.microseconds;
1280 		timeradd(&ut, up, up);
1281 		timeradd(&st, sp, sp);
1282 
1283 		task_ttimes_count = TASK_THREAD_TIMES_INFO_COUNT;
1284 		task_info(task, TASK_THREAD_TIMES_INFO,
1285 		    (task_info_t)&ttimesinfo, &task_ttimes_count);
1286 
1287 		ut.tv_sec = ttimesinfo.user_time.seconds;
1288 		ut.tv_usec = ttimesinfo.user_time.microseconds;
1289 		st.tv_sec = ttimesinfo.system_time.seconds;
1290 		st.tv_usec = ttimesinfo.system_time.microseconds;
1291 		timeradd(&ut, up, up);
1292 		timeradd(&st, sp, sp);
1293 
1294 		task_events_count = TASK_EVENTS_INFO_COUNT;
1295 		task_info(task, TASK_EVENTS_INFO,
1296 		    (task_info_t)&teventsinfo, &task_events_count);
1297 
1298 		/*
1299 		 * No need to lock "p":  this does not need to be
1300 		 * completely consistent, right ?
1301 		 */
1302 		p->p_stats->p_ru.ru_minflt = (teventsinfo.faults -
1303 		    teventsinfo.pageins);
1304 		p->p_stats->p_ru.ru_majflt = teventsinfo.pageins;
1305 		p->p_stats->p_ru.ru_nivcsw = (teventsinfo.csw -
1306 		    p->p_stats->p_ru.ru_nvcsw);
1307 		if (p->p_stats->p_ru.ru_nivcsw < 0) {
1308 			p->p_stats->p_ru.ru_nivcsw = 0;
1309 		}
1310 
1311 		p->p_stats->p_ru.ru_maxrss = (long)tinfo.resident_size_max;
1312 	}
1313 }
1314 
1315 __private_extern__ void munge_user64_rusage(struct rusage *a_rusage_p, struct user64_rusage *a_user_rusage_p);
1316 __private_extern__ void munge_user32_rusage(struct rusage *a_rusage_p, struct user32_rusage *a_user_rusage_p);
1317 
1318 /* ARGSUSED */
1319 int
getrusage(struct proc * p,struct getrusage_args * uap,__unused int32_t * retval)1320 getrusage(struct proc *p, struct getrusage_args *uap, __unused int32_t *retval)
1321 {
1322 	struct rusage *rup, rubuf;
1323 	struct user64_rusage rubuf64 = {};
1324 	struct user32_rusage rubuf32 = {};
1325 	size_t retsize = sizeof(rubuf);                 /* default: 32 bits */
1326 	caddr_t retbuf = (caddr_t)&rubuf;               /* default: 32 bits */
1327 	struct timeval utime;
1328 	struct timeval stime;
1329 
1330 
1331 	switch (uap->who) {
1332 	case RUSAGE_SELF:
1333 		calcru(p, &utime, &stime, NULL);
1334 		proc_lock(p);
1335 		rup = &p->p_stats->p_ru;
1336 		rup->ru_utime = utime;
1337 		rup->ru_stime = stime;
1338 
1339 		rubuf = *rup;
1340 		proc_unlock(p);
1341 
1342 		break;
1343 
1344 	case RUSAGE_CHILDREN:
1345 		proc_lock(p);
1346 		rup = &p->p_stats->p_cru;
1347 		rubuf = *rup;
1348 		proc_unlock(p);
1349 		break;
1350 
1351 	default:
1352 		return EINVAL;
1353 	}
1354 	if (IS_64BIT_PROCESS(p)) {
1355 		retsize = sizeof(rubuf64);
1356 		retbuf = (caddr_t)&rubuf64;
1357 		munge_user64_rusage(&rubuf, &rubuf64);
1358 	} else {
1359 		retsize = sizeof(rubuf32);
1360 		retbuf = (caddr_t)&rubuf32;
1361 		munge_user32_rusage(&rubuf, &rubuf32);
1362 	}
1363 
1364 	return copyout(retbuf, uap->rusage, retsize);
1365 }
1366 
1367 void
ruadd(struct rusage * ru,struct rusage * ru2)1368 ruadd(struct rusage *ru, struct rusage *ru2)
1369 {
1370 	long *ip, *ip2;
1371 	long i;
1372 
1373 	timeradd(&ru->ru_utime, &ru2->ru_utime, &ru->ru_utime);
1374 	timeradd(&ru->ru_stime, &ru2->ru_stime, &ru->ru_stime);
1375 	if (ru->ru_maxrss < ru2->ru_maxrss) {
1376 		ru->ru_maxrss = ru2->ru_maxrss;
1377 	}
1378 	ip = &ru->ru_first; ip2 = &ru2->ru_first;
1379 	for (i = &ru->ru_last - &ru->ru_first; i >= 0; i--) {
1380 		*ip++ += *ip2++;
1381 	}
1382 }
1383 
1384 /*
1385  * Add the rusage stats of child in parent.
1386  *
1387  * It adds rusage statistics of child process and statistics of all its
1388  * children to its parent.
1389  *
1390  * Note: proc lock of parent should be held while calling this function.
1391  */
1392 void
update_rusage_info_child(struct rusage_info_child * ri,rusage_info_current * ri_current)1393 update_rusage_info_child(struct rusage_info_child *ri, rusage_info_current *ri_current)
1394 {
1395 	ri->ri_child_user_time += (ri_current->ri_user_time +
1396 	    ri_current->ri_child_user_time);
1397 	ri->ri_child_system_time += (ri_current->ri_system_time +
1398 	    ri_current->ri_child_system_time);
1399 	ri->ri_child_pkg_idle_wkups += (ri_current->ri_pkg_idle_wkups +
1400 	    ri_current->ri_child_pkg_idle_wkups);
1401 	ri->ri_child_interrupt_wkups += (ri_current->ri_interrupt_wkups +
1402 	    ri_current->ri_child_interrupt_wkups);
1403 	ri->ri_child_pageins += (ri_current->ri_pageins +
1404 	    ri_current->ri_child_pageins);
1405 	ri->ri_child_elapsed_abstime += ((ri_current->ri_proc_exit_abstime -
1406 	    ri_current->ri_proc_start_abstime) + ri_current->ri_child_elapsed_abstime);
1407 }
1408 
1409 static void
proc_limit_free(void * plimit)1410 proc_limit_free(void *plimit)
1411 {
1412 	zfree(plimit_zone, plimit);
1413 }
1414 
1415 static void
proc_limit_release(struct plimit * plimit)1416 proc_limit_release(struct plimit *plimit)
1417 {
1418 	if (os_ref_release(&plimit->pl_refcnt) == 0) {
1419 		smr_global_retire(plimit, sizeof(*plimit), proc_limit_free);
1420 	}
1421 }
1422 
1423 /*
1424  * Reading soft limit from specified resource.
1425  */
1426 rlim_t
proc_limitgetcur(proc_t p,int which)1427 proc_limitgetcur(proc_t p, int which)
1428 {
1429 	rlim_t rlim_cur;
1430 
1431 	assert(p);
1432 	assert(which < RLIM_NLIMITS);
1433 
1434 	smr_global_enter();
1435 	rlim_cur = smr_entered_load(&p->p_limit)->pl_rlimit[which].rlim_cur;
1436 	smr_global_leave();
1437 
1438 	return rlim_cur;
1439 }
1440 
1441 /*
1442  * Handle commonly asked limit that needs to be clamped with maxfilesperproc.
1443  */
1444 int
proc_limitgetcur_nofile(struct proc * p)1445 proc_limitgetcur_nofile(struct proc *p)
1446 {
1447 	rlim_t lim = proc_limitgetcur(p, RLIMIT_NOFILE);
1448 
1449 	return (int)MIN(lim, maxfilesperproc);
1450 }
1451 
1452 /*
1453  * Writing soft limit to specified resource. This is an internal function
1454  * used only by proc_exit to update RLIMIT_FSIZE in
1455  * place without invoking setrlimit.
1456  */
1457 void
proc_limitsetcur_fsize(proc_t p,rlim_t value)1458 proc_limitsetcur_fsize(proc_t p, rlim_t value)
1459 {
1460 	proc_limitupdate(p, false, ^(struct plimit *plimit) {
1461 		plimit->pl_rlimit[RLIMIT_FSIZE].rlim_cur = value;
1462 	});
1463 }
1464 
1465 struct rlimit
proc_limitget(proc_t p,int which)1466 proc_limitget(proc_t p, int which)
1467 {
1468 	struct rlimit lim;
1469 
1470 	assert(which < RLIM_NLIMITS);
1471 
1472 	smr_global_enter();
1473 	lim = smr_entered_load(&p->p_limit)->pl_rlimit[which];
1474 	smr_global_leave();
1475 
1476 	return lim;
1477 }
1478 
1479 void
proc_limitfork(proc_t parent,proc_t child)1480 proc_limitfork(proc_t parent, proc_t child)
1481 {
1482 	struct plimit *plim;
1483 
1484 	smr_global_enter();
1485 	plim = smr_entered_load(&parent->p_limit);
1486 	os_ref_retain(&plim->pl_refcnt);
1487 	smr_global_leave();
1488 
1489 	smr_init_store(&child->p_limit, plim);
1490 }
1491 
1492 void
proc_limitdrop(proc_t p)1493 proc_limitdrop(proc_t p)
1494 {
1495 	struct plimit *plimit = NULL;
1496 
1497 	proc_lock(p);
1498 	plimit = smr_serialized_load(&p->p_limit);
1499 	smr_clear_store(&p->p_limit);
1500 	proc_unlock(p);
1501 
1502 	proc_limit_release(plimit);
1503 }
1504 
1505 /*
1506  * proc_limitblock/unblock are used to serialize access to plimit
1507  * from concurrent threads within the same process.
1508  * Callers must be holding the proc lock to enter, return with
1509  * the proc lock locked
1510  */
1511 static void
proc_limitblock(proc_t p)1512 proc_limitblock(proc_t p)
1513 {
1514 	lck_mtx_assert(&p->p_mlock, LCK_MTX_ASSERT_OWNED);
1515 
1516 	while (p->p_lflag & P_LLIMCHANGE) {
1517 		p->p_lflag |= P_LLIMWAIT;
1518 		msleep(&p->p_limit, &p->p_mlock, 0, "proc_limitblock", NULL);
1519 	}
1520 	p->p_lflag |= P_LLIMCHANGE;
1521 }
1522 
1523 /*
1524  * Callers must be holding the proc lock to enter, return with
1525  * the proc lock locked
1526  */
1527 static void
proc_limitunblock(proc_t p)1528 proc_limitunblock(proc_t p)
1529 {
1530 	lck_mtx_assert(&p->p_mlock, LCK_MTX_ASSERT_OWNED);
1531 
1532 	p->p_lflag &= ~P_LLIMCHANGE;
1533 	if (p->p_lflag & P_LLIMWAIT) {
1534 		p->p_lflag &= ~P_LLIMWAIT;
1535 		wakeup(&p->p_limit);
1536 	}
1537 }
1538 
1539 /*
1540  * Perform an rlimit update (as defined by the arbitrary `update` function).
1541  *
1542  * Because plimits are accessed without holding any locks,
1543  * with only a hazard reference, the struct plimit is always
1544  * copied, updated, and replaced, to implement a const value type.
1545  */
1546 static void
1547 proc_limitupdate(proc_t p, bool unblock, void (^update)(struct plimit *))
1548 {
1549 	struct plimit  *cur_plim;
1550 	struct plimit  *copy_plim;
1551 
1552 	copy_plim = zalloc_flags(plimit_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL);
1553 
1554 	proc_lock(p);
1555 
1556 	cur_plim = smr_serialized_load(&p->p_limit);
1557 
1558 	os_ref_init_count(&copy_plim->pl_refcnt, &rlimit_refgrp, 1);
1559 	bcopy(cur_plim->pl_rlimit, copy_plim->pl_rlimit,
1560 	    sizeof(struct rlimit) * RLIM_NLIMITS);
1561 
1562 	update(copy_plim);
1563 
1564 	smr_serialized_store(&p->p_limit, copy_plim);
1565 
1566 	if (unblock) {
1567 		proc_limitunblock(p);
1568 	}
1569 	proc_unlock(p);
1570 
1571 	proc_limit_release(cur_plim);
1572 }
1573 
1574 static int
1575 iopolicysys_disk(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1576 static int
1577 iopolicysys_vfs_hfs_case_sensitivity(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1578 static int
1579 iopolicysys_vfs_atime_updates(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1580 static int
1581 iopolicysys_vfs_statfs_no_data_volume(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1582 static int
1583 iopolicysys_vfs_trigger_resolve(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1584 static int
1585 iopolicysys_vfs_ignore_content_protection(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1586 static int
1587 iopolicysys_vfs_ignore_node_permissions(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *ipo_param);
1588 static int
1589 iopolicysys_vfs_skip_mtime_update(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1590 static int
1591 iopolicysys_vfs_allow_lowspace_writes(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1592 static int
1593 iopolicysys_vfs_disallow_rw_for_o_evtonly(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1594 static int iopolicysys_vfs_altlink(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param);
1595 
1596 /*
1597  * iopolicysys
1598  *
1599  * Description:	System call MUX for use in manipulating I/O policy attributes of the current process or thread
1600  *
1601  * Parameters:	cmd				Policy command
1602  *		arg				Pointer to policy arguments
1603  *
1604  * Returns:	0				Success
1605  *		EINVAL				Invalid command or invalid policy arguments
1606  *
1607  */
1608 int
iopolicysys(struct proc * p,struct iopolicysys_args * uap,int32_t * retval)1609 iopolicysys(struct proc *p, struct iopolicysys_args *uap, int32_t *retval)
1610 {
1611 	int     error = 0;
1612 	struct _iopol_param_t iop_param;
1613 
1614 	if ((error = copyin(uap->arg, &iop_param, sizeof(iop_param))) != 0) {
1615 		goto out;
1616 	}
1617 
1618 	switch (iop_param.iop_iotype) {
1619 	case IOPOL_TYPE_DISK:
1620 		error = iopolicysys_disk(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1621 		if (error == EIDRM) {
1622 			*retval = -2;
1623 			error = 0;
1624 		}
1625 		if (error) {
1626 			goto out;
1627 		}
1628 		break;
1629 	case IOPOL_TYPE_VFS_HFS_CASE_SENSITIVITY:
1630 		error = iopolicysys_vfs_hfs_case_sensitivity(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1631 		if (error) {
1632 			goto out;
1633 		}
1634 		break;
1635 	case IOPOL_TYPE_VFS_ATIME_UPDATES:
1636 		error = iopolicysys_vfs_atime_updates(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1637 		if (error) {
1638 			goto out;
1639 		}
1640 		break;
1641 	case IOPOL_TYPE_VFS_MATERIALIZE_DATALESS_FILES:
1642 		error = iopolicysys_vfs_materialize_dataless_files(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1643 		if (error) {
1644 			goto out;
1645 		}
1646 		break;
1647 	case IOPOL_TYPE_VFS_STATFS_NO_DATA_VOLUME:
1648 		error = iopolicysys_vfs_statfs_no_data_volume(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1649 		if (error) {
1650 			goto out;
1651 		}
1652 		break;
1653 	case IOPOL_TYPE_VFS_TRIGGER_RESOLVE:
1654 		error = iopolicysys_vfs_trigger_resolve(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1655 		if (error) {
1656 			goto out;
1657 		}
1658 		break;
1659 	case IOPOL_TYPE_VFS_IGNORE_CONTENT_PROTECTION:
1660 		error = iopolicysys_vfs_ignore_content_protection(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1661 		if (error) {
1662 			goto out;
1663 		}
1664 		break;
1665 	case IOPOL_TYPE_VFS_IGNORE_PERMISSIONS:
1666 		error = iopolicysys_vfs_ignore_node_permissions(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1667 		if (error) {
1668 			goto out;
1669 		}
1670 		break;
1671 	case IOPOL_TYPE_VFS_SKIP_MTIME_UPDATE:
1672 		error = iopolicysys_vfs_skip_mtime_update(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1673 		if (error) {
1674 			goto out;
1675 		}
1676 		break;
1677 	case IOPOL_TYPE_VFS_ALLOW_LOW_SPACE_WRITES:
1678 		error = iopolicysys_vfs_allow_lowspace_writes(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1679 		if (error) {
1680 			goto out;
1681 		}
1682 		break;
1683 	case IOPOL_TYPE_VFS_DISALLOW_RW_FOR_O_EVTONLY:
1684 		error = iopolicysys_vfs_disallow_rw_for_o_evtonly(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1685 		if (error) {
1686 			goto out;
1687 		}
1688 		break;
1689 	case IOPOL_TYPE_VFS_ALTLINK:
1690 		error = iopolicysys_vfs_altlink(p, uap->cmd, iop_param.iop_scope, iop_param.iop_policy, &iop_param);
1691 		if (error) {
1692 			goto out;
1693 		}
1694 		break;
1695 
1696 	default:
1697 		error = EINVAL;
1698 		goto out;
1699 	}
1700 
1701 	/* Individual iotype handlers are expected to update iop_param, if requested with a GET command */
1702 	if (uap->cmd == IOPOL_CMD_GET) {
1703 		error = copyout((caddr_t)&iop_param, uap->arg, sizeof(iop_param));
1704 		if (error) {
1705 			goto out;
1706 		}
1707 	}
1708 
1709 out:
1710 	return error;
1711 }
1712 
1713 static int
iopolicysys_disk(struct proc * p __unused,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)1714 iopolicysys_disk(struct proc *p __unused, int cmd, int scope, int policy, struct _iopol_param_t *iop_param)
1715 {
1716 	int                     error = 0;
1717 	thread_t        thread;
1718 	int                     policy_flavor;
1719 
1720 	/* Validate scope */
1721 	switch (scope) {
1722 	case IOPOL_SCOPE_PROCESS:
1723 		thread = THREAD_NULL;
1724 		policy_flavor = TASK_POLICY_IOPOL;
1725 		break;
1726 
1727 	case IOPOL_SCOPE_THREAD:
1728 		thread = current_thread();
1729 		policy_flavor = TASK_POLICY_IOPOL;
1730 
1731 		/* Not allowed to combine QoS and (non-PASSIVE) IO policy, doing so strips the QoS */
1732 		if (cmd == IOPOL_CMD_SET && thread_has_qos_policy(thread)) {
1733 			switch (policy) {
1734 			case IOPOL_DEFAULT:
1735 			case IOPOL_PASSIVE:
1736 				break;
1737 			case IOPOL_UTILITY:
1738 			case IOPOL_THROTTLE:
1739 			case IOPOL_IMPORTANT:
1740 			case IOPOL_STANDARD:
1741 				if (!thread_is_static_param(thread)) {
1742 					thread_remove_qos_policy(thread);
1743 					/*
1744 					 * This is not an error case, this is to return a marker to user-space that
1745 					 * we stripped the thread of its QoS class.
1746 					 */
1747 					error = EIDRM;
1748 					break;
1749 				}
1750 				OS_FALLTHROUGH;
1751 			default:
1752 				error = EINVAL;
1753 				goto out;
1754 			}
1755 		}
1756 		break;
1757 
1758 	case IOPOL_SCOPE_DARWIN_BG:
1759 #if !defined(XNU_TARGET_OS_OSX)
1760 		/* We don't want this on platforms outside of macOS as BG is always IOPOL_THROTTLE */
1761 		error = ENOTSUP;
1762 		goto out;
1763 #else /* !defined(XNU_TARGET_OS_OSX) */
1764 		thread = THREAD_NULL;
1765 		policy_flavor = TASK_POLICY_DARWIN_BG_IOPOL;
1766 		break;
1767 #endif /* !defined(XNU_TARGET_OS_OSX) */
1768 
1769 	default:
1770 		error = EINVAL;
1771 		goto out;
1772 	}
1773 
1774 	/* Validate policy */
1775 	if (cmd == IOPOL_CMD_SET) {
1776 		switch (policy) {
1777 		case IOPOL_DEFAULT:
1778 			if (scope == IOPOL_SCOPE_DARWIN_BG) {
1779 				/* the current default BG throttle level is UTILITY */
1780 				policy = IOPOL_UTILITY;
1781 			} else {
1782 				policy = IOPOL_IMPORTANT;
1783 			}
1784 			break;
1785 		case IOPOL_UTILITY:
1786 		/* fall-through */
1787 		case IOPOL_THROTTLE:
1788 			/* These levels are OK */
1789 			break;
1790 		case IOPOL_IMPORTANT:
1791 		/* fall-through */
1792 		case IOPOL_STANDARD:
1793 		/* fall-through */
1794 		case IOPOL_PASSIVE:
1795 			if (scope == IOPOL_SCOPE_DARWIN_BG) {
1796 				/* These levels are invalid for BG */
1797 				error = EINVAL;
1798 				goto out;
1799 			} else {
1800 				/* OK for other scopes */
1801 			}
1802 			break;
1803 		default:
1804 			error = EINVAL;
1805 			goto out;
1806 		}
1807 	}
1808 
1809 	/* Perform command */
1810 	switch (cmd) {
1811 	case IOPOL_CMD_SET:
1812 		if (thread != THREAD_NULL) {
1813 			proc_set_thread_policy(thread, TASK_POLICY_INTERNAL, policy_flavor, policy);
1814 		} else {
1815 			proc_set_task_policy(current_task(), TASK_POLICY_INTERNAL, policy_flavor, policy);
1816 		}
1817 		break;
1818 	case IOPOL_CMD_GET:
1819 		if (thread != THREAD_NULL) {
1820 			policy = proc_get_thread_policy(thread, TASK_POLICY_INTERNAL, policy_flavor);
1821 		} else {
1822 			policy = proc_get_task_policy(current_task(), TASK_POLICY_INTERNAL, policy_flavor);
1823 		}
1824 		iop_param->iop_policy = policy;
1825 		break;
1826 	default:
1827 		error = EINVAL;         /* unknown command */
1828 		break;
1829 	}
1830 
1831 out:
1832 	return error;
1833 }
1834 
1835 static int
iopolicysys_vfs_hfs_case_sensitivity(struct proc * p,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)1836 iopolicysys_vfs_hfs_case_sensitivity(struct proc *p, int cmd, int scope, int policy, struct _iopol_param_t *iop_param)
1837 {
1838 	int                     error = 0;
1839 
1840 	/* Validate scope */
1841 	switch (scope) {
1842 	case IOPOL_SCOPE_PROCESS:
1843 		/* Only process OK */
1844 		break;
1845 	default:
1846 		error = EINVAL;
1847 		goto out;
1848 	}
1849 
1850 	/* Validate policy */
1851 	if (cmd == IOPOL_CMD_SET) {
1852 		switch (policy) {
1853 		case IOPOL_VFS_HFS_CASE_SENSITIVITY_DEFAULT:
1854 		/* fall-through */
1855 		case IOPOL_VFS_HFS_CASE_SENSITIVITY_FORCE_CASE_SENSITIVE:
1856 			/* These policies are OK */
1857 			break;
1858 		default:
1859 			error = EINVAL;
1860 			goto out;
1861 		}
1862 	}
1863 
1864 	/* Perform command */
1865 	switch (cmd) {
1866 	case IOPOL_CMD_SET:
1867 		if (0 == kauth_cred_issuser(kauth_cred_get())) {
1868 			/* If it's a non-root process, it needs to have the entitlement to set the policy */
1869 			boolean_t entitled = FALSE;
1870 			entitled = IOCurrentTaskHasEntitlement("com.apple.private.iopol.case_sensitivity");
1871 			if (!entitled) {
1872 				error = EPERM;
1873 				goto out;
1874 			}
1875 		}
1876 
1877 		switch (policy) {
1878 		case IOPOL_VFS_HFS_CASE_SENSITIVITY_DEFAULT:
1879 			OSBitAndAtomic16(~((uint32_t)P_VFS_IOPOLICY_FORCE_HFS_CASE_SENSITIVITY), &p->p_vfs_iopolicy);
1880 			break;
1881 		case IOPOL_VFS_HFS_CASE_SENSITIVITY_FORCE_CASE_SENSITIVE:
1882 			OSBitOrAtomic16((uint32_t)P_VFS_IOPOLICY_FORCE_HFS_CASE_SENSITIVITY, &p->p_vfs_iopolicy);
1883 			break;
1884 		default:
1885 			error = EINVAL;
1886 			goto out;
1887 		}
1888 
1889 		break;
1890 	case IOPOL_CMD_GET:
1891 		iop_param->iop_policy = (p->p_vfs_iopolicy & P_VFS_IOPOLICY_FORCE_HFS_CASE_SENSITIVITY)
1892 		    ? IOPOL_VFS_HFS_CASE_SENSITIVITY_FORCE_CASE_SENSITIVE
1893 		    : IOPOL_VFS_HFS_CASE_SENSITIVITY_DEFAULT;
1894 		break;
1895 	default:
1896 		error = EINVAL;         /* unknown command */
1897 		break;
1898 	}
1899 
1900 out:
1901 	return error;
1902 }
1903 
1904 static inline int
get_thread_atime_policy(struct uthread * ut)1905 get_thread_atime_policy(struct uthread *ut)
1906 {
1907 	return (ut->uu_flag & UT_ATIME_UPDATE) ? IOPOL_ATIME_UPDATES_OFF : IOPOL_ATIME_UPDATES_DEFAULT;
1908 }
1909 
1910 static inline void
set_thread_atime_policy(struct uthread * ut,int policy)1911 set_thread_atime_policy(struct uthread *ut, int policy)
1912 {
1913 	if (policy == IOPOL_ATIME_UPDATES_OFF) {
1914 		ut->uu_flag |= UT_ATIME_UPDATE;
1915 	} else {
1916 		ut->uu_flag &= ~UT_ATIME_UPDATE;
1917 	}
1918 }
1919 
1920 static inline void
set_task_atime_policy(struct proc * p,int policy)1921 set_task_atime_policy(struct proc *p, int policy)
1922 {
1923 	if (policy == IOPOL_ATIME_UPDATES_OFF) {
1924 		OSBitOrAtomic16((uint16_t)P_VFS_IOPOLICY_ATIME_UPDATES, &p->p_vfs_iopolicy);
1925 	} else {
1926 		OSBitAndAtomic16(~((uint16_t)P_VFS_IOPOLICY_ATIME_UPDATES), &p->p_vfs_iopolicy);
1927 	}
1928 }
1929 
1930 static inline int
get_task_atime_policy(struct proc * p)1931 get_task_atime_policy(struct proc *p)
1932 {
1933 	return (p->p_vfs_iopolicy & P_VFS_IOPOLICY_ATIME_UPDATES) ? IOPOL_ATIME_UPDATES_OFF : IOPOL_ATIME_UPDATES_DEFAULT;
1934 }
1935 
1936 static int
iopolicysys_vfs_atime_updates(struct proc * p __unused,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)1937 iopolicysys_vfs_atime_updates(struct proc *p __unused, int cmd, int scope, int policy, struct _iopol_param_t *iop_param)
1938 {
1939 	int                     error = 0;
1940 	thread_t                thread;
1941 
1942 	/* Validate scope */
1943 	switch (scope) {
1944 	case IOPOL_SCOPE_THREAD:
1945 		thread = current_thread();
1946 		break;
1947 	case IOPOL_SCOPE_PROCESS:
1948 		thread = THREAD_NULL;
1949 		break;
1950 	default:
1951 		error = EINVAL;
1952 		goto out;
1953 	}
1954 
1955 	/* Validate policy */
1956 	if (cmd == IOPOL_CMD_SET) {
1957 		switch (policy) {
1958 		case IOPOL_ATIME_UPDATES_DEFAULT:
1959 		case IOPOL_ATIME_UPDATES_OFF:
1960 			break;
1961 		default:
1962 			error = EINVAL;
1963 			goto out;
1964 		}
1965 	}
1966 
1967 	/* Perform command */
1968 	switch (cmd) {
1969 	case IOPOL_CMD_SET:
1970 		if (thread != THREAD_NULL) {
1971 			set_thread_atime_policy(get_bsdthread_info(thread), policy);
1972 		} else {
1973 			set_task_atime_policy(p, policy);
1974 		}
1975 		break;
1976 	case IOPOL_CMD_GET:
1977 		if (thread != THREAD_NULL) {
1978 			policy = get_thread_atime_policy(get_bsdthread_info(thread));
1979 		} else {
1980 			policy = get_task_atime_policy(p);
1981 		}
1982 		iop_param->iop_policy = policy;
1983 		break;
1984 	default:
1985 		error = EINVAL;         /* unknown command */
1986 		break;
1987 	}
1988 
1989 out:
1990 	return error;
1991 }
1992 
1993 static inline int
get_thread_materialize_policy(struct uthread * ut)1994 get_thread_materialize_policy(struct uthread *ut)
1995 {
1996 	if (ut->uu_flag & UT_NSPACE_NODATALESSFAULTS) {
1997 		return IOPOL_MATERIALIZE_DATALESS_FILES_OFF;
1998 	} else if (ut->uu_flag & UT_NSPACE_FORCEDATALESSFAULTS) {
1999 		return IOPOL_MATERIALIZE_DATALESS_FILES_ON;
2000 	}
2001 	/* Default thread behavior is "inherit process behavior". */
2002 	return IOPOL_MATERIALIZE_DATALESS_FILES_DEFAULT;
2003 }
2004 
2005 static inline void
set_thread_materialize_policy(struct uthread * ut,int policy)2006 set_thread_materialize_policy(struct uthread *ut, int policy)
2007 {
2008 	if (policy == IOPOL_MATERIALIZE_DATALESS_FILES_OFF) {
2009 		ut->uu_flag &= ~UT_NSPACE_FORCEDATALESSFAULTS;
2010 		ut->uu_flag |= UT_NSPACE_NODATALESSFAULTS;
2011 	} else if (policy == IOPOL_MATERIALIZE_DATALESS_FILES_ON) {
2012 		ut->uu_flag &= ~UT_NSPACE_NODATALESSFAULTS;
2013 		ut->uu_flag |= UT_NSPACE_FORCEDATALESSFAULTS;
2014 	} else {
2015 		ut->uu_flag &= ~(UT_NSPACE_NODATALESSFAULTS | UT_NSPACE_FORCEDATALESSFAULTS);
2016 	}
2017 }
2018 
2019 static inline void
set_proc_materialize_policy(struct proc * p,int policy)2020 set_proc_materialize_policy(struct proc *p, int policy)
2021 {
2022 	if (policy == IOPOL_MATERIALIZE_DATALESS_FILES_DEFAULT) {
2023 		/*
2024 		 * Caller has specified "use the default policy".
2025 		 * The default policy is to NOT materialize dataless
2026 		 * files.
2027 		 */
2028 		policy = IOPOL_MATERIALIZE_DATALESS_FILES_OFF;
2029 	}
2030 	if (policy == IOPOL_MATERIALIZE_DATALESS_FILES_ON) {
2031 		OSBitOrAtomic16((uint16_t)P_VFS_IOPOLICY_MATERIALIZE_DATALESS_FILES, &p->p_vfs_iopolicy);
2032 	} else {
2033 		OSBitAndAtomic16(~((uint16_t)P_VFS_IOPOLICY_MATERIALIZE_DATALESS_FILES), &p->p_vfs_iopolicy);
2034 	}
2035 }
2036 
2037 static int
get_proc_materialize_policy(struct proc * p)2038 get_proc_materialize_policy(struct proc *p)
2039 {
2040 	return (p->p_vfs_iopolicy & P_VFS_IOPOLICY_MATERIALIZE_DATALESS_FILES) ? IOPOL_MATERIALIZE_DATALESS_FILES_ON : IOPOL_MATERIALIZE_DATALESS_FILES_OFF;
2041 }
2042 
2043 int
iopolicysys_vfs_materialize_dataless_files(struct proc * p __unused,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)2044 iopolicysys_vfs_materialize_dataless_files(struct proc *p __unused, int cmd, int scope, int policy, struct _iopol_param_t *iop_param)
2045 {
2046 	int                     error = 0;
2047 	thread_t                thread;
2048 
2049 	/* Validate scope */
2050 	switch (scope) {
2051 	case IOPOL_SCOPE_THREAD:
2052 		thread = current_thread();
2053 		break;
2054 	case IOPOL_SCOPE_PROCESS:
2055 		thread = THREAD_NULL;
2056 		break;
2057 	default:
2058 		error = EINVAL;
2059 		goto out;
2060 	}
2061 
2062 	/* Validate policy */
2063 	if (cmd == IOPOL_CMD_SET) {
2064 		switch (policy) {
2065 		case IOPOL_MATERIALIZE_DATALESS_FILES_DEFAULT:
2066 		case IOPOL_MATERIALIZE_DATALESS_FILES_OFF:
2067 		case IOPOL_MATERIALIZE_DATALESS_FILES_ON:
2068 			break;
2069 		default:
2070 			error = EINVAL;
2071 			goto out;
2072 		}
2073 	}
2074 
2075 	/* Perform command */
2076 	switch (cmd) {
2077 	case IOPOL_CMD_SET:
2078 		if (thread != THREAD_NULL) {
2079 			set_thread_materialize_policy(get_bsdthread_info(thread), policy);
2080 		} else {
2081 			set_proc_materialize_policy(p, policy);
2082 		}
2083 		break;
2084 	case IOPOL_CMD_GET:
2085 		if (thread != THREAD_NULL) {
2086 			policy = get_thread_materialize_policy(get_bsdthread_info(thread));
2087 		} else {
2088 			policy = get_proc_materialize_policy(p);
2089 		}
2090 		iop_param->iop_policy = policy;
2091 		break;
2092 	default:
2093 		error = EINVAL;         /* unknown command */
2094 		break;
2095 	}
2096 
2097 out:
2098 	return error;
2099 }
2100 
2101 static int
iopolicysys_vfs_statfs_no_data_volume(struct proc * p __unused,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)2102 iopolicysys_vfs_statfs_no_data_volume(struct proc *p __unused, int cmd,
2103     int scope, int policy, struct _iopol_param_t *iop_param)
2104 {
2105 	int error = 0;
2106 
2107 	/* Validate scope */
2108 	switch (scope) {
2109 	case IOPOL_SCOPE_PROCESS:
2110 		/* Only process OK */
2111 		break;
2112 	default:
2113 		error = EINVAL;
2114 		goto out;
2115 	}
2116 
2117 	/* Validate policy */
2118 	if (cmd == IOPOL_CMD_SET) {
2119 		switch (policy) {
2120 		case IOPOL_VFS_STATFS_NO_DATA_VOLUME_DEFAULT:
2121 		/* fall-through */
2122 		case IOPOL_VFS_STATFS_FORCE_NO_DATA_VOLUME:
2123 			/* These policies are OK */
2124 			break;
2125 		default:
2126 			error = EINVAL;
2127 			goto out;
2128 		}
2129 	}
2130 
2131 	/* Perform command */
2132 	switch (cmd) {
2133 	case IOPOL_CMD_SET:
2134 		if (0 == kauth_cred_issuser(kauth_cred_get())) {
2135 			/* If it's a non-root process, it needs to have the entitlement to set the policy */
2136 			boolean_t entitled = FALSE;
2137 			entitled = IOCurrentTaskHasEntitlement("com.apple.private.iopol.case_sensitivity");
2138 			if (!entitled) {
2139 				error = EPERM;
2140 				goto out;
2141 			}
2142 		}
2143 
2144 		switch (policy) {
2145 		case IOPOL_VFS_STATFS_NO_DATA_VOLUME_DEFAULT:
2146 			OSBitAndAtomic16(~((uint32_t)P_VFS_IOPOLICY_STATFS_NO_DATA_VOLUME), &p->p_vfs_iopolicy);
2147 			break;
2148 		case IOPOL_VFS_STATFS_FORCE_NO_DATA_VOLUME:
2149 			OSBitOrAtomic16((uint32_t)P_VFS_IOPOLICY_STATFS_NO_DATA_VOLUME, &p->p_vfs_iopolicy);
2150 			break;
2151 		default:
2152 			error = EINVAL;
2153 			goto out;
2154 		}
2155 
2156 		break;
2157 	case IOPOL_CMD_GET:
2158 		iop_param->iop_policy = (p->p_vfs_iopolicy & P_VFS_IOPOLICY_STATFS_NO_DATA_VOLUME)
2159 		    ? IOPOL_VFS_STATFS_FORCE_NO_DATA_VOLUME
2160 		    : IOPOL_VFS_STATFS_NO_DATA_VOLUME_DEFAULT;
2161 		break;
2162 	default:
2163 		error = EINVAL;         /* unknown command */
2164 		break;
2165 	}
2166 
2167 out:
2168 	return error;
2169 }
2170 
2171 static int
iopolicysys_vfs_trigger_resolve(struct proc * p __unused,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)2172 iopolicysys_vfs_trigger_resolve(struct proc *p __unused, int cmd,
2173     int scope, int policy, struct _iopol_param_t *iop_param)
2174 {
2175 	int error = 0;
2176 
2177 	/* Validate scope */
2178 	switch (scope) {
2179 	case IOPOL_SCOPE_PROCESS:
2180 		/* Only process OK */
2181 		break;
2182 	default:
2183 		error = EINVAL;
2184 		goto out;
2185 	}
2186 
2187 	/* Validate policy */
2188 	if (cmd == IOPOL_CMD_SET) {
2189 		switch (policy) {
2190 		case IOPOL_VFS_TRIGGER_RESOLVE_DEFAULT:
2191 		/* fall-through */
2192 		case IOPOL_VFS_TRIGGER_RESOLVE_OFF:
2193 			/* These policies are OK */
2194 			break;
2195 		default:
2196 			error = EINVAL;
2197 			goto out;
2198 		}
2199 	}
2200 
2201 	/* Perform command */
2202 	switch (cmd) {
2203 	case IOPOL_CMD_SET:
2204 		switch (policy) {
2205 		case IOPOL_VFS_TRIGGER_RESOLVE_DEFAULT:
2206 			OSBitAndAtomic16(~((uint32_t)P_VFS_IOPOLICY_TRIGGER_RESOLVE_DISABLE), &p->p_vfs_iopolicy);
2207 			break;
2208 		case IOPOL_VFS_TRIGGER_RESOLVE_OFF:
2209 			OSBitOrAtomic16((uint32_t)P_VFS_IOPOLICY_TRIGGER_RESOLVE_DISABLE, &p->p_vfs_iopolicy);
2210 			break;
2211 		default:
2212 			error = EINVAL;
2213 			goto out;
2214 		}
2215 
2216 		break;
2217 	case IOPOL_CMD_GET:
2218 		iop_param->iop_policy = (p->p_vfs_iopolicy & P_VFS_IOPOLICY_TRIGGER_RESOLVE_DISABLE)
2219 		    ? IOPOL_VFS_TRIGGER_RESOLVE_OFF
2220 		    : IOPOL_VFS_TRIGGER_RESOLVE_DEFAULT;
2221 		break;
2222 	default:
2223 		error = EINVAL;         /* unknown command */
2224 		break;
2225 	}
2226 
2227 out:
2228 	return error;
2229 }
2230 
2231 static int
iopolicysys_vfs_ignore_content_protection(struct proc * p,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)2232 iopolicysys_vfs_ignore_content_protection(struct proc *p, int cmd, int scope,
2233     int policy, struct _iopol_param_t *iop_param)
2234 {
2235 	int error = 0;
2236 
2237 	/* Validate scope */
2238 	switch (scope) {
2239 	case IOPOL_SCOPE_PROCESS:
2240 		/* Only process OK */
2241 		break;
2242 	default:
2243 		error = EINVAL;
2244 		goto out;
2245 	}
2246 
2247 	/* Validate policy */
2248 	if (cmd == IOPOL_CMD_SET) {
2249 		switch (policy) {
2250 		case IOPOL_VFS_CONTENT_PROTECTION_DEFAULT:
2251 			OS_FALLTHROUGH;
2252 		case IOPOL_VFS_CONTENT_PROTECTION_IGNORE:
2253 			/* These policies are OK */
2254 			break;
2255 		default:
2256 			error = EINVAL;
2257 			goto out;
2258 		}
2259 	}
2260 
2261 	/* Perform command */
2262 	switch (cmd) {
2263 	case IOPOL_CMD_SET:
2264 		if (0 == kauth_cred_issuser(kauth_cred_get())) {
2265 			/* If it's a non-root process, it needs to have the entitlement to set the policy */
2266 			boolean_t entitled = FALSE;
2267 			entitled = IOCurrentTaskHasEntitlement("com.apple.private.iopol.case_sensitivity");
2268 			if (!entitled) {
2269 				error = EPERM;
2270 				goto out;
2271 			}
2272 		}
2273 
2274 		switch (policy) {
2275 		case IOPOL_VFS_CONTENT_PROTECTION_DEFAULT:
2276 			os_atomic_andnot(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_IGNORE_CONTENT_PROTECTION, relaxed);
2277 			break;
2278 		case IOPOL_VFS_CONTENT_PROTECTION_IGNORE:
2279 			os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_IGNORE_CONTENT_PROTECTION, relaxed);
2280 			break;
2281 		default:
2282 			error = EINVAL;
2283 			goto out;
2284 		}
2285 
2286 		break;
2287 	case IOPOL_CMD_GET:
2288 		iop_param->iop_policy = (os_atomic_load(&p->p_vfs_iopolicy, relaxed) & P_VFS_IOPOLICY_IGNORE_CONTENT_PROTECTION)
2289 		    ? IOPOL_VFS_CONTENT_PROTECTION_IGNORE
2290 		    : IOPOL_VFS_CONTENT_PROTECTION_DEFAULT;
2291 		break;
2292 	default:
2293 		error = EINVAL;         /* unknown command */
2294 		break;
2295 	}
2296 
2297 out:
2298 	return error;
2299 }
2300 
2301 #define AUTHORIZED_ACCESS_ENTITLEMENT \
2302 	"com.apple.private.vfs.authorized-access"
2303 int
iopolicysys_vfs_ignore_node_permissions(struct proc * p,int cmd,int scope,int policy,__unused struct _iopol_param_t * iop_param)2304 iopolicysys_vfs_ignore_node_permissions(struct proc *p, int cmd, int scope,
2305     int policy, __unused struct _iopol_param_t *iop_param)
2306 {
2307 	int error = EINVAL;
2308 
2309 	switch (scope) {
2310 	case IOPOL_SCOPE_PROCESS:
2311 		break;
2312 	default:
2313 		goto out;
2314 	}
2315 
2316 	switch (cmd) {
2317 	case IOPOL_CMD_GET:
2318 		policy = os_atomic_load(&p->p_vfs_iopolicy, relaxed) & P_VFS_IOPOLICY_IGNORE_NODE_PERMISSIONS ?
2319 		    IOPOL_VFS_IGNORE_PERMISSIONS_ON : IOPOL_VFS_IGNORE_PERMISSIONS_OFF;
2320 		iop_param->iop_policy = policy;
2321 		goto out_ok;
2322 	case IOPOL_CMD_SET:
2323 		/* SET is handled after the switch */
2324 		break;
2325 	default:
2326 		goto out;
2327 	}
2328 
2329 	if (!IOCurrentTaskHasEntitlement(AUTHORIZED_ACCESS_ENTITLEMENT)) {
2330 		error = EPERM;
2331 		goto out;
2332 	}
2333 
2334 	switch (policy) {
2335 	case IOPOL_VFS_IGNORE_PERMISSIONS_OFF:
2336 		os_atomic_andnot(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_IGNORE_NODE_PERMISSIONS, relaxed);
2337 		break;
2338 	case IOPOL_VFS_IGNORE_PERMISSIONS_ON:
2339 		os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_IGNORE_NODE_PERMISSIONS, relaxed);
2340 		break;
2341 	default:
2342 		break;
2343 	}
2344 
2345 out_ok:
2346 	error = 0;
2347 out:
2348 	return error;
2349 }
2350 
2351 #define SKIP_MTIME_UPDATE_ENTITLEMENT \
2352 	"com.apple.private.vfs.skip-mtime-updates"
2353 int
iopolicysys_vfs_skip_mtime_update(struct proc * p,int cmd,int scope,int policy,__unused struct _iopol_param_t * iop_param)2354 iopolicysys_vfs_skip_mtime_update(struct proc *p, int cmd, int scope,
2355     int policy, __unused struct _iopol_param_t *iop_param)
2356 {
2357 	int error = EINVAL;
2358 
2359 	switch (scope) {
2360 	case IOPOL_SCOPE_PROCESS:
2361 		break;
2362 	default:
2363 		goto out;
2364 	}
2365 
2366 	switch (cmd) {
2367 	case IOPOL_CMD_GET:
2368 		policy = os_atomic_load(&p->p_vfs_iopolicy, relaxed) & P_VFS_IOPOLICY_SKIP_MTIME_UPDATE ?
2369 		    IOPOL_VFS_SKIP_MTIME_UPDATE_ON : IOPOL_VFS_SKIP_MTIME_UPDATE_OFF;
2370 		iop_param->iop_policy = policy;
2371 		goto out_ok;
2372 	case IOPOL_CMD_SET:
2373 		break;
2374 	default:
2375 		break;
2376 	}
2377 
2378 	if (!IOCurrentTaskHasEntitlement(SKIP_MTIME_UPDATE_ENTITLEMENT)) {
2379 		error = EPERM;
2380 		goto out;
2381 	}
2382 
2383 	switch (policy) {
2384 	case IOPOL_VFS_SKIP_MTIME_UPDATE_OFF:
2385 		os_atomic_andnot(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_SKIP_MTIME_UPDATE, relaxed);
2386 		break;
2387 	case IOPOL_VFS_SKIP_MTIME_UPDATE_ON:
2388 		os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_SKIP_MTIME_UPDATE, relaxed);
2389 		break;
2390 	default:
2391 		break;
2392 	}
2393 
2394 out_ok:
2395 	error = 0;
2396 out:
2397 	return error;
2398 }
2399 
2400 #define ALLOW_LOW_SPACE_WRITES_ENTITLEMENT \
2401 	"com.apple.private.vfs.allow-low-space-writes"
2402 static int
iopolicysys_vfs_allow_lowspace_writes(struct proc * p,int cmd,int scope,int policy,__unused struct _iopol_param_t * iop_param)2403 iopolicysys_vfs_allow_lowspace_writes(struct proc *p, int cmd, int scope,
2404     int policy, __unused struct _iopol_param_t *iop_param)
2405 {
2406 	int error = EINVAL;
2407 
2408 	switch (scope) {
2409 	case IOPOL_SCOPE_PROCESS:
2410 		break;
2411 	default:
2412 		goto out;
2413 	}
2414 
2415 	switch (cmd) {
2416 	case IOPOL_CMD_GET:
2417 		policy = os_atomic_load(&p->p_vfs_iopolicy, relaxed) & P_VFS_IOPOLICY_ALLOW_LOW_SPACE_WRITES ?
2418 		    IOPOL_VFS_ALLOW_LOW_SPACE_WRITES_ON : IOPOL_VFS_ALLOW_LOW_SPACE_WRITES_OFF;
2419 		iop_param->iop_policy = policy;
2420 		goto out_ok;
2421 	case IOPOL_CMD_SET:
2422 		break;
2423 	default:
2424 		break;
2425 	}
2426 
2427 	if (!IOCurrentTaskHasEntitlement(ALLOW_LOW_SPACE_WRITES_ENTITLEMENT)) {
2428 		error = EPERM;
2429 		goto out;
2430 	}
2431 
2432 	switch (policy) {
2433 	case IOPOL_VFS_ALLOW_LOW_SPACE_WRITES_OFF:
2434 		os_atomic_andnot(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_ALLOW_LOW_SPACE_WRITES, relaxed);
2435 		break;
2436 	case IOPOL_VFS_ALLOW_LOW_SPACE_WRITES_ON:
2437 		os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_ALLOW_LOW_SPACE_WRITES, relaxed);
2438 		break;
2439 	default:
2440 		break;
2441 	}
2442 
2443 out_ok:
2444 	error = 0;
2445 out:
2446 	return error;
2447 }
2448 
2449 static int
iopolicysys_vfs_disallow_rw_for_o_evtonly(struct proc * p,int cmd,int scope,int policy,__unused struct _iopol_param_t * iop_param)2450 iopolicysys_vfs_disallow_rw_for_o_evtonly(struct proc *p, int cmd, int scope,
2451     int policy, __unused struct _iopol_param_t *iop_param)
2452 {
2453 	int error = EINVAL;
2454 
2455 	switch (scope) {
2456 	case IOPOL_SCOPE_PROCESS:
2457 		break;
2458 	default:
2459 		goto out;
2460 	}
2461 
2462 	switch (cmd) {
2463 	case IOPOL_CMD_GET:
2464 		policy = (os_atomic_load(&p->p_vfs_iopolicy, relaxed) &
2465 		    P_VFS_IOPOLICY_DISALLOW_RW_FOR_O_EVTONLY) ?
2466 		    IOPOL_VFS_DISALLOW_RW_FOR_O_EVTONLY_ON :
2467 		    IOPOL_VFS_DISALLOW_RW_FOR_O_EVTONLY_DEFAULT;
2468 		iop_param->iop_policy = policy;
2469 		goto out_ok;
2470 	case IOPOL_CMD_SET:
2471 		break;
2472 	default:
2473 		goto out;
2474 	}
2475 
2476 	/* Once set, we don't allow the process to clear it. */
2477 	switch (policy) {
2478 	case IOPOL_VFS_DISALLOW_RW_FOR_O_EVTONLY_ON:
2479 		os_atomic_or(&p->p_vfs_iopolicy,
2480 		    P_VFS_IOPOLICY_DISALLOW_RW_FOR_O_EVTONLY, relaxed);
2481 		break;
2482 	default:
2483 		goto out;
2484 	}
2485 
2486 out_ok:
2487 	error = 0;
2488 out:
2489 	return error;
2490 }
2491 
2492 static int
iopolicysys_vfs_altlink(struct proc * p,int cmd,int scope,int policy,struct _iopol_param_t * iop_param)2493 iopolicysys_vfs_altlink(struct proc *p, int cmd, int scope, int policy,
2494     struct _iopol_param_t *iop_param)
2495 {
2496 	if (scope != IOPOL_SCOPE_PROCESS) {
2497 		return EINVAL;
2498 	}
2499 
2500 	if (cmd == IOPOL_CMD_GET) {
2501 		policy = (os_atomic_load(&p->p_vfs_iopolicy, relaxed) & P_VFS_IOPOLICY_ALTLINK) ?
2502 		    IOPOL_VFS_ALTLINK_ENABLED : IOPOL_VFS_ALTLINK_DISABLED;
2503 		iop_param->iop_policy = policy;
2504 		return 0;
2505 	}
2506 
2507 	/* Once set, we don't allow the process to clear it. */
2508 	if (policy == IOPOL_VFS_ALTLINK_ENABLED) {
2509 		os_atomic_or(&p->p_vfs_iopolicy, P_VFS_IOPOLICY_ALTLINK, relaxed);
2510 		return 0;
2511 	}
2512 
2513 	return EINVAL;
2514 }
2515 
2516 void
proc_apply_task_networkbg(int pid,thread_t thread)2517 proc_apply_task_networkbg(int pid, thread_t thread)
2518 {
2519 	proc_t p = proc_find(pid);
2520 
2521 	if (p != PROC_NULL) {
2522 		do_background_socket(p, thread);
2523 		proc_rele(p);
2524 	}
2525 }
2526 
2527 void
gather_rusage_info(proc_t p,rusage_info_current * ru,int flavor)2528 gather_rusage_info(proc_t p, rusage_info_current *ru, int flavor)
2529 {
2530 	struct rusage_info_child *ri_child;
2531 
2532 	assert(p->p_stats != NULL);
2533 	memset(ru, 0, sizeof(*ru));
2534 	switch (flavor) {
2535 	case RUSAGE_INFO_V6:
2536 		/* Any P-specific resource counters are captured in fill_task_rusage. */
2537 		OS_FALLTHROUGH;
2538 
2539 	case RUSAGE_INFO_V5:
2540 #if __has_feature(ptrauth_calls)
2541 		if (vm_shared_region_is_reslide(proc_task(p))) {
2542 			ru->ri_flags |= RU_PROC_RUNS_RESLIDE;
2543 		}
2544 #endif /* __has_feature(ptrauth_calls) */
2545 		OS_FALLTHROUGH;
2546 
2547 	case RUSAGE_INFO_V4:
2548 		ru->ri_logical_writes = get_task_logical_writes(proc_task(p), false);
2549 		ru->ri_lifetime_max_phys_footprint = get_task_phys_footprint_lifetime_max(proc_task(p));
2550 #if CONFIG_LEDGER_INTERVAL_MAX
2551 		ru->ri_interval_max_phys_footprint = get_task_phys_footprint_interval_max(proc_task(p), FALSE);
2552 #endif
2553 		OS_FALLTHROUGH;
2554 
2555 	case RUSAGE_INFO_V3:
2556 		fill_task_qos_rusage(proc_task(p), ru);
2557 		fill_task_billed_usage(proc_task(p), ru);
2558 		OS_FALLTHROUGH;
2559 
2560 	case RUSAGE_INFO_V2:
2561 		fill_task_io_rusage(proc_task(p), ru);
2562 		OS_FALLTHROUGH;
2563 
2564 	case RUSAGE_INFO_V1:
2565 		/*
2566 		 * p->p_stats->ri_child statistics are protected under proc lock.
2567 		 */
2568 		proc_lock(p);
2569 
2570 		ri_child = &(p->p_stats->ri_child);
2571 		ru->ri_child_user_time = ri_child->ri_child_user_time;
2572 		ru->ri_child_system_time = ri_child->ri_child_system_time;
2573 		ru->ri_child_pkg_idle_wkups = ri_child->ri_child_pkg_idle_wkups;
2574 		ru->ri_child_interrupt_wkups = ri_child->ri_child_interrupt_wkups;
2575 		ru->ri_child_pageins = ri_child->ri_child_pageins;
2576 		ru->ri_child_elapsed_abstime = ri_child->ri_child_elapsed_abstime;
2577 
2578 		proc_unlock(p);
2579 		OS_FALLTHROUGH;
2580 
2581 	case RUSAGE_INFO_V0:
2582 		proc_getexecutableuuid(p, (unsigned char *)&ru->ri_uuid, sizeof(ru->ri_uuid));
2583 		fill_task_rusage(proc_task(p), ru);
2584 		ru->ri_proc_start_abstime = p->p_stats->ps_start;
2585 	}
2586 }
2587 
2588 int
proc_get_rusage(proc_t p,int flavor,user_addr_t buffer,__unused int is_zombie)2589 proc_get_rusage(proc_t p, int flavor, user_addr_t buffer, __unused int is_zombie)
2590 {
2591 	rusage_info_current ri_current = {};
2592 
2593 	size_t size = 0;
2594 
2595 	switch (flavor) {
2596 	case RUSAGE_INFO_V0:
2597 		size = sizeof(struct rusage_info_v0);
2598 		break;
2599 
2600 	case RUSAGE_INFO_V1:
2601 		size = sizeof(struct rusage_info_v1);
2602 		break;
2603 
2604 	case RUSAGE_INFO_V2:
2605 		size = sizeof(struct rusage_info_v2);
2606 		break;
2607 
2608 	case RUSAGE_INFO_V3:
2609 		size = sizeof(struct rusage_info_v3);
2610 		break;
2611 
2612 	case RUSAGE_INFO_V4:
2613 		size = sizeof(struct rusage_info_v4);
2614 		break;
2615 
2616 	case RUSAGE_INFO_V5:
2617 		size = sizeof(struct rusage_info_v5);
2618 		break;
2619 
2620 	case RUSAGE_INFO_V6:
2621 		size = sizeof(struct rusage_info_v6);
2622 		break;
2623 	default:
2624 		return EINVAL;
2625 	}
2626 
2627 	if (size == 0) {
2628 		return EINVAL;
2629 	}
2630 
2631 	/*
2632 	 * If task is still alive, collect info from the live task itself.
2633 	 * Otherwise, look to the cached info in the zombie proc.
2634 	 */
2635 	if (p->p_ru) {
2636 		return copyout(&p->p_ru->ri, buffer, size);
2637 	} else {
2638 		gather_rusage_info(p, &ri_current, flavor);
2639 		ri_current.ri_proc_exit_abstime = 0;
2640 		return copyout(&ri_current, buffer, size);
2641 	}
2642 }
2643 
2644 static int
mach_to_bsd_rv(int mach_rv)2645 mach_to_bsd_rv(int mach_rv)
2646 {
2647 	int bsd_rv = 0;
2648 
2649 	switch (mach_rv) {
2650 	case KERN_SUCCESS:
2651 		bsd_rv = 0;
2652 		break;
2653 	case KERN_INVALID_ARGUMENT:
2654 		bsd_rv = EINVAL;
2655 		break;
2656 	default:
2657 		panic("unknown error %#x", mach_rv);
2658 	}
2659 
2660 	return bsd_rv;
2661 }
2662 
2663 /*
2664  * Resource limit controls
2665  *
2666  * uap->flavor available flavors:
2667  *
2668  *     RLIMIT_WAKEUPS_MONITOR
2669  *     RLIMIT_CPU_USAGE_MONITOR
2670  *     RLIMIT_THREAD_CPULIMITS
2671  *     RLIMIT_FOOTPRINT_INTERVAL
2672  */
2673 int
proc_rlimit_control(__unused struct proc * p,struct proc_rlimit_control_args * uap,__unused int32_t * retval)2674 proc_rlimit_control(__unused struct proc *p, struct proc_rlimit_control_args *uap, __unused int32_t *retval)
2675 {
2676 	proc_t  targetp;
2677 	int     error = 0;
2678 	struct  proc_rlimit_control_wakeupmon wakeupmon_args;
2679 	uint32_t cpumon_flags;
2680 	uint32_t cpulimits_flags;
2681 	kauth_cred_t my_cred, target_cred;
2682 #if CONFIG_LEDGER_INTERVAL_MAX
2683 	uint32_t footprint_interval_flags;
2684 	uint64_t interval_max_footprint;
2685 #endif /* CONFIG_LEDGER_INTERVAL_MAX */
2686 
2687 	/* -1 implicitly means our own process (perhaps even the current thread for per-thread attributes) */
2688 	if (uap->pid == -1) {
2689 		targetp = proc_self();
2690 	} else {
2691 		targetp = proc_find(uap->pid);
2692 	}
2693 
2694 	/* proc_self() can return NULL for an exiting process */
2695 	if (targetp == PROC_NULL) {
2696 		return ESRCH;
2697 	}
2698 
2699 	my_cred = kauth_cred_get();
2700 	target_cred = kauth_cred_proc_ref(targetp);
2701 
2702 	if (!kauth_cred_issuser(my_cred) && kauth_cred_getruid(my_cred) &&
2703 	    kauth_cred_getuid(my_cred) != kauth_cred_getuid(target_cred) &&
2704 	    kauth_cred_getruid(my_cred) != kauth_cred_getuid(target_cred)) {
2705 		proc_rele(targetp);
2706 		kauth_cred_unref(&target_cred);
2707 		return EACCES;
2708 	}
2709 
2710 	switch (uap->flavor) {
2711 	case RLIMIT_WAKEUPS_MONITOR:
2712 		if ((error = copyin(uap->arg, &wakeupmon_args, sizeof(wakeupmon_args))) != 0) {
2713 			break;
2714 		}
2715 		if ((error = mach_to_bsd_rv(task_wakeups_monitor_ctl(proc_task(targetp), &wakeupmon_args.wm_flags,
2716 		    &wakeupmon_args.wm_rate))) != 0) {
2717 			break;
2718 		}
2719 		error = copyout(&wakeupmon_args, uap->arg, sizeof(wakeupmon_args));
2720 		break;
2721 	case RLIMIT_CPU_USAGE_MONITOR:
2722 		cpumon_flags = (uint32_t)uap->arg; // XXX temporarily stashing flags in argp (12592127)
2723 		error = mach_to_bsd_rv(task_cpu_usage_monitor_ctl(proc_task(targetp), &cpumon_flags));
2724 		break;
2725 	case RLIMIT_THREAD_CPULIMITS:
2726 		cpulimits_flags = (uint32_t)uap->arg; // only need a limited set of bits, pass in void * argument
2727 
2728 		if (uap->pid != -1) {
2729 			error = EINVAL;
2730 			break;
2731 		}
2732 
2733 		uint8_t percent = 0;
2734 		uint32_t ms_refill = 0;
2735 		uint64_t ns_refill;
2736 
2737 		percent = (uint8_t)(cpulimits_flags & 0xffU);           /* low 8 bits for percent */
2738 		ms_refill = (cpulimits_flags >> 8) & 0xffffff;          /* next 24 bits represent ms refill value */
2739 		if (percent >= 100 || percent == 0) {
2740 			error = EINVAL;
2741 			break;
2742 		}
2743 
2744 		ns_refill = ((uint64_t)ms_refill) * NSEC_PER_MSEC;
2745 
2746 		error = mach_to_bsd_rv(thread_set_cpulimit(THREAD_CPULIMIT_BLOCK, percent, ns_refill));
2747 		break;
2748 
2749 #if CONFIG_LEDGER_INTERVAL_MAX
2750 	case RLIMIT_FOOTPRINT_INTERVAL:
2751 		footprint_interval_flags = (uint32_t)uap->arg; // XXX temporarily stashing flags in argp (12592127)
2752 		/*
2753 		 * There is currently only one option for this flavor.
2754 		 */
2755 		if ((footprint_interval_flags & FOOTPRINT_INTERVAL_RESET) == 0) {
2756 			error = EINVAL;
2757 			break;
2758 		}
2759 		interval_max_footprint = get_task_phys_footprint_interval_max(proc_task(targetp), TRUE);
2760 		break;
2761 #endif /* CONFIG_LEDGER_INTERVAL_MAX */
2762 	default:
2763 		error = EINVAL;
2764 		break;
2765 	}
2766 
2767 	proc_rele(targetp);
2768 	kauth_cred_unref(&target_cred);
2769 
2770 	/*
2771 	 * Return value from this function becomes errno to userland caller.
2772 	 */
2773 	return error;
2774 }
2775 
2776 /*
2777  * Return the current amount of CPU consumed by this thread (in either user or kernel mode)
2778  */
2779 int
thread_selfusage(struct proc * p __unused,struct thread_selfusage_args * uap __unused,uint64_t * retval)2780 thread_selfusage(struct proc *p __unused, struct thread_selfusage_args *uap __unused, uint64_t *retval)
2781 {
2782 	uint64_t runtime;
2783 
2784 	runtime = thread_get_runtime_self();
2785 	*retval = runtime;
2786 
2787 	return 0;
2788 }
2789