xref: /xnu-12377.1.9/osfmk/vm/vm_apple_protect.c (revision f6217f891ac0bb64f3d375211650a4c1ff8ca1ea)
1 /*
2  * Copyright (c) 2006-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 
29 #include <sys/errno.h>
30 
31 #include <mach/mach_types.h>
32 #include <mach/mach_traps.h>
33 #include <mach/host_priv.h>
34 #include <mach/kern_return.h>
35 #include <mach/memory_object_control.h>
36 #include <mach/memory_object_types.h>
37 #include <mach/port.h>
38 #include <mach/policy.h>
39 #include <mach/upl.h>
40 #include <mach/thread_act.h>
41 #include <mach/mach_vm.h>
42 
43 #include <kern/host.h>
44 #include <kern/kalloc.h>
45 #include <kern/page_decrypt.h>
46 #include <kern/queue.h>
47 #include <kern/thread.h>
48 #include <kern/ipc_kobject.h>
49 #include <os/refcnt.h>
50 
51 #include <sys/kdebug_triage.h>
52 
53 #include <vm/vm_fault_internal.h>
54 #include <vm/vm_map.h>
55 #include <vm/memory_object_internal.h>
56 #include <vm/vm_pageout_xnu.h>
57 #include <vm/vm_protos_internal.h>
58 #include <vm/vm_kern.h>
59 #include <vm/vm_ubc.h>
60 #include <vm/vm_page_internal.h>
61 #include <vm/vm_object_internal.h>
62 
63 /*
64  * APPLE PROTECT MEMORY PAGER
65  *
66  * This external memory manager (EMM) handles memory from the encrypted
67  * sections of some executables protected by the DSMOS kernel extension.
68  *
69  * It mostly handles page-in requests (from memory_object_data_request()) by
70  * getting the encrypted data from its backing VM object, itself backed by
71  * the encrypted file, decrypting it and providing it to VM.
72  *
73  * The decrypted pages will never be dirtied, so the memory manager doesn't
74  * need to handle page-out requests (from memory_object_data_return()).  The
75  * pages need to be mapped copy-on-write, so that the originals stay clean.
76  *
77  * We don't expect to have to handle a large number of apple-protected
78  * binaries, so the data structures are very simple (simple linked list)
79  * for now.
80  */
81 
82 /* forward declarations */
83 void apple_protect_pager_reference(memory_object_t mem_obj);
84 void apple_protect_pager_deallocate(memory_object_t mem_obj);
85 kern_return_t apple_protect_pager_init(memory_object_t mem_obj,
86     memory_object_control_t control,
87     memory_object_cluster_size_t pg_size);
88 kern_return_t apple_protect_pager_terminate(memory_object_t mem_obj);
89 kern_return_t apple_protect_pager_data_request(memory_object_t mem_obj,
90     memory_object_offset_t offset,
91     memory_object_cluster_size_t length,
92     vm_prot_t protection_required,
93     memory_object_fault_info_t fault_info);
94 kern_return_t apple_protect_pager_data_return(memory_object_t mem_obj,
95     memory_object_offset_t offset,
96     memory_object_cluster_size_t      data_cnt,
97     memory_object_offset_t *resid_offset,
98     int *io_error,
99     boolean_t dirty,
100     boolean_t kernel_copy,
101     int upl_flags);
102 kern_return_t apple_protect_pager_data_initialize(memory_object_t mem_obj,
103     memory_object_offset_t offset,
104     memory_object_cluster_size_t data_cnt);
105 kern_return_t apple_protect_pager_map(memory_object_t mem_obj,
106     vm_prot_t prot);
107 kern_return_t apple_protect_pager_last_unmap(memory_object_t mem_obj);
108 boolean_t apple_protect_pager_backing_object(
109 	memory_object_t mem_obj,
110 	memory_object_offset_t mem_obj_offset,
111 	vm_object_t *backing_object,
112 	vm_object_offset_t *backing_offset);
113 
114 #define CRYPT_INFO_DEBUG 0
115 void crypt_info_reference(struct pager_crypt_info *crypt_info);
116 void crypt_info_deallocate(struct pager_crypt_info *crypt_info);
117 
118 /*
119  * Vector of VM operations for this EMM.
120  * These routines are invoked by VM via the memory_object_*() interfaces.
121  */
122 const struct memory_object_pager_ops apple_protect_pager_ops = {
123 	.memory_object_reference = apple_protect_pager_reference,
124 	.memory_object_deallocate = apple_protect_pager_deallocate,
125 	.memory_object_init = apple_protect_pager_init,
126 	.memory_object_terminate = apple_protect_pager_terminate,
127 	.memory_object_data_request = apple_protect_pager_data_request,
128 	.memory_object_data_return = apple_protect_pager_data_return,
129 	.memory_object_data_initialize = apple_protect_pager_data_initialize,
130 	.memory_object_map = apple_protect_pager_map,
131 	.memory_object_last_unmap = apple_protect_pager_last_unmap,
132 	.memory_object_backing_object = apple_protect_pager_backing_object,
133 	.memory_object_pager_name = "apple_protect"
134 };
135 
136 /*
137  * The "apple_protect_pager" describes a memory object backed by
138  * the "apple protect" EMM.
139  */
140 typedef struct apple_protect_pager {
141 	/* mandatory generic header */
142 	struct memory_object    ap_pgr_hdr;
143 
144 	/* pager-specific data */
145 	queue_chain_t           pager_queue;    /* next & prev pagers */
146 #if MEMORY_OBJECT_HAS_REFCOUNT
147 #define ap_pgr_hdr_ref          ap_pgr_hdr.mo_ref
148 #else
149 	os_ref_atomic_t         ap_pgr_hdr_ref;      /* reference count */
150 #endif
151 	bool                    is_ready;       /* is this pager ready ? */
152 	bool                    is_mapped;      /* is this mem_obj mapped ? */
153 	bool                    is_cached;      /* is this pager cached ? */
154 	vm_object_t             backing_object; /* VM obj w/ encrypted data */
155 	vm_object_offset_t      backing_offset;
156 	vm_object_offset_t      crypto_backing_offset; /* for key... */
157 	vm_object_offset_t      crypto_start;
158 	vm_object_offset_t      crypto_end;
159 	struct pager_crypt_info *crypt_info;
160 } *apple_protect_pager_t;
161 #define APPLE_PROTECT_PAGER_NULL        ((apple_protect_pager_t) NULL)
162 
163 /*
164  * List of memory objects managed by this EMM.
165  * The list is protected by the "apple_protect_pager_lock" lock.
166  */
167 unsigned int apple_protect_pager_count = 0;        /* number of pagers */
168 unsigned int apple_protect_pager_count_mapped = 0; /* number of unmapped pagers */
169 queue_head_t apple_protect_pager_queue = QUEUE_HEAD_INITIALIZER(apple_protect_pager_queue);
170 LCK_GRP_DECLARE(apple_protect_pager_lck_grp, "apple_protect");
171 LCK_MTX_DECLARE(apple_protect_pager_lock, &apple_protect_pager_lck_grp);
172 
173 /*
174  * Maximum number of unmapped pagers we're willing to keep around.
175  */
176 unsigned int apple_protect_pager_cache_limit = 20;
177 
178 /*
179  * Statistics & counters.
180  */
181 unsigned int apple_protect_pager_count_max = 0;
182 unsigned int apple_protect_pager_count_unmapped_max = 0;
183 unsigned int apple_protect_pager_num_trim_max = 0;
184 unsigned int apple_protect_pager_num_trim_total = 0;
185 
186 
187 
188 /* internal prototypes */
189 apple_protect_pager_t apple_protect_pager_create(
190 	vm_object_t backing_object,
191 	vm_object_offset_t backing_offset,
192 	vm_object_offset_t crypto_backing_offset,
193 	struct pager_crypt_info *crypt_info,
194 	vm_object_offset_t crypto_start,
195 	vm_object_offset_t crypto_end,
196 	boolean_t cache_pager);
197 apple_protect_pager_t apple_protect_pager_lookup(memory_object_t mem_obj);
198 void apple_protect_pager_dequeue(apple_protect_pager_t pager);
199 void apple_protect_pager_deallocate_internal(apple_protect_pager_t pager,
200     boolean_t locked);
201 void apple_protect_pager_terminate_internal(apple_protect_pager_t pager);
202 void apple_protect_pager_trim(void);
203 
204 
205 #if DEBUG
206 int apple_protect_pagerdebug = 0;
207 #define PAGER_ALL               0xffffffff
208 #define PAGER_INIT              0x00000001
209 #define PAGER_PAGEIN            0x00000002
210 
211 #define PAGER_DEBUG(LEVEL, A)                                           \
212 	MACRO_BEGIN                                                     \
213 	if ((apple_protect_pagerdebug & LEVEL)==LEVEL) {                \
214 	        printf A;                                               \
215 	}                                                               \
216 	MACRO_END
217 #else
218 #define PAGER_DEBUG(LEVEL, A)
219 #endif
220 
221 /*
222  * apple_protect_pager_init()
223  *
224  * Initialize the memory object and makes it ready to be used and mapped.
225  */
226 kern_return_t
apple_protect_pager_init(memory_object_t mem_obj,memory_object_control_t control,__unused memory_object_cluster_size_t pg_size)227 apple_protect_pager_init(
228 	memory_object_t         mem_obj,
229 	memory_object_control_t control,
230 #if !DEBUG
231 	__unused
232 #endif
233 	memory_object_cluster_size_t pg_size)
234 {
235 	apple_protect_pager_t   pager;
236 	kern_return_t           kr;
237 	memory_object_attr_info_data_t  attributes;
238 
239 	PAGER_DEBUG(PAGER_ALL,
240 	    ("apple_protect_pager_init: %p, %p, %x\n",
241 	    mem_obj, control, pg_size));
242 
243 	if (control == MEMORY_OBJECT_CONTROL_NULL) {
244 		return KERN_INVALID_ARGUMENT;
245 	}
246 
247 	pager = apple_protect_pager_lookup(mem_obj);
248 
249 	memory_object_control_reference(control);
250 
251 	pager->ap_pgr_hdr.mo_control = control;
252 
253 	attributes.copy_strategy = MEMORY_OBJECT_COPY_DELAY;
254 	/* attributes.cluster_size = (1 << (CLUSTER_SHIFT + PAGE_SHIFT));*/
255 	attributes.cluster_size = (1 << (PAGE_SHIFT));
256 	attributes.may_cache_object = FALSE;
257 	attributes.temporary = TRUE;
258 
259 	kr = memory_object_change_attributes(
260 		control,
261 		MEMORY_OBJECT_ATTRIBUTE_INFO,
262 		(memory_object_info_t) &attributes,
263 		MEMORY_OBJECT_ATTR_INFO_COUNT);
264 	if (kr != KERN_SUCCESS) {
265 		panic("apple_protect_pager_init: "
266 		    "memory_object_change_attributes() failed");
267 	}
268 
269 #if CONFIG_SECLUDED_MEMORY
270 	if (secluded_for_filecache) {
271 		memory_object_mark_eligible_for_secluded(control, TRUE);
272 	}
273 #endif /* CONFIG_SECLUDED_MEMORY */
274 
275 	return KERN_SUCCESS;
276 }
277 
278 /*
279  * apple_protect_data_return()
280  *
281  * Handles page-out requests from VM.  This should never happen since
282  * the pages provided by this EMM are not supposed to be dirty or dirtied
283  * and VM should simply discard the contents and reclaim the pages if it
284  * needs to.
285  */
286 kern_return_t
apple_protect_pager_data_return(__unused memory_object_t mem_obj,__unused memory_object_offset_t offset,__unused memory_object_cluster_size_t data_cnt,__unused memory_object_offset_t * resid_offset,__unused int * io_error,__unused boolean_t dirty,__unused boolean_t kernel_copy,__unused int upl_flags)287 apple_protect_pager_data_return(
288 	__unused memory_object_t        mem_obj,
289 	__unused memory_object_offset_t offset,
290 	__unused memory_object_cluster_size_t           data_cnt,
291 	__unused memory_object_offset_t *resid_offset,
292 	__unused int                    *io_error,
293 	__unused boolean_t              dirty,
294 	__unused boolean_t              kernel_copy,
295 	__unused int                    upl_flags)
296 {
297 	panic("apple_protect_pager_data_return: should never get called");
298 	return KERN_FAILURE;
299 }
300 
301 kern_return_t
apple_protect_pager_data_initialize(__unused memory_object_t mem_obj,__unused memory_object_offset_t offset,__unused memory_object_cluster_size_t data_cnt)302 apple_protect_pager_data_initialize(
303 	__unused memory_object_t        mem_obj,
304 	__unused memory_object_offset_t offset,
305 	__unused memory_object_cluster_size_t           data_cnt)
306 {
307 	panic("apple_protect_pager_data_initialize: should never get called");
308 	return KERN_FAILURE;
309 }
310 
311 /*
312  * apple_protect_pager_data_request()
313  *
314  * Handles page-in requests from VM.
315  */
316 int apple_protect_pager_data_request_debug = 0;
317 kern_return_t
apple_protect_pager_data_request(memory_object_t mem_obj,memory_object_offset_t offset,memory_object_cluster_size_t length,__unused vm_prot_t protection_required,memory_object_fault_info_t mo_fault_info)318 apple_protect_pager_data_request(
319 	memory_object_t         mem_obj,
320 	memory_object_offset_t  offset,
321 	memory_object_cluster_size_t            length,
322 #if !DEBUG
323 	__unused
324 #endif
325 	vm_prot_t               protection_required,
326 	memory_object_fault_info_t mo_fault_info)
327 {
328 	apple_protect_pager_t   pager;
329 	memory_object_control_t mo_control;
330 	upl_t                   upl;
331 	int                     upl_flags;
332 	upl_size_t              upl_size;
333 	upl_page_info_t         *upl_pl;
334 	unsigned int            pl_count;
335 	vm_object_t             src_top_object, src_page_object, dst_object;
336 	kern_return_t           kr, retval;
337 	vm_offset_t             src_vaddr, dst_vaddr;
338 	vm_offset_t             cur_offset;
339 	vm_offset_t             offset_in_page;
340 	kern_return_t           error_code;
341 	vm_prot_t               prot;
342 	vm_page_t               src_page, top_page;
343 	int                     interruptible;
344 	struct vm_object_fault_info     fault_info;
345 	vm_fault_return_t       vmfr;
346 	int                     ret;
347 
348 	PAGER_DEBUG(PAGER_ALL, ("apple_protect_pager_data_request: %p, %llx, %x, %x\n", mem_obj, offset, length, protection_required));
349 
350 	retval = KERN_SUCCESS;
351 	src_top_object = VM_OBJECT_NULL;
352 	src_page_object = VM_OBJECT_NULL;
353 	upl = NULL;
354 	upl_pl = NULL;
355 	fault_info = *((struct vm_object_fault_info *)(uintptr_t)mo_fault_info);
356 	fault_info.stealth = TRUE;
357 	fault_info.io_sync = FALSE;
358 	fault_info.mark_zf_absent = FALSE;
359 	fault_info.batch_pmap_op = FALSE;
360 	interruptible = fault_info.interruptible;
361 
362 	pager = apple_protect_pager_lookup(mem_obj);
363 	assert(pager->is_ready);
364 	assert(os_ref_get_count_raw(&pager->ap_pgr_hdr_ref) > 1); /* pager is alive and mapped */
365 
366 	PAGER_DEBUG(PAGER_PAGEIN, ("apple_protect_pager_data_request: %p, %llx, %x, %x, pager %p\n", mem_obj, offset, length, protection_required, pager));
367 
368 	fault_info.lo_offset += pager->backing_offset;
369 	fault_info.hi_offset += pager->backing_offset;
370 
371 	/*
372 	 * Gather in a UPL all the VM pages requested by VM.
373 	 */
374 	mo_control = pager->ap_pgr_hdr.mo_control;
375 
376 	upl_size = length;
377 	upl_flags =
378 	    UPL_RET_ONLY_ABSENT |
379 	    UPL_SET_LITE |
380 	    UPL_NO_SYNC |
381 	    UPL_CLEAN_IN_PLACE |        /* triggers UPL_CLEAR_DIRTY */
382 	    UPL_SET_INTERNAL;
383 	pl_count = 0;
384 	kr = memory_object_upl_request(mo_control,
385 	    offset, upl_size,
386 	    &upl, NULL, NULL, upl_flags, VM_KERN_MEMORY_SECURITY);
387 	if (kr != KERN_SUCCESS) {
388 		retval = kr;
389 		goto done;
390 	}
391 	dst_object = memory_object_control_to_vm_object(mo_control);
392 	assert(dst_object != VM_OBJECT_NULL);
393 
394 	/*
395 	 * We'll map the encrypted data in the kernel address space from the
396 	 * backing VM object (itself backed by the encrypted file via
397 	 * the vnode pager).
398 	 */
399 	src_top_object = pager->backing_object;
400 	assert(src_top_object != VM_OBJECT_NULL);
401 	vm_object_reference(src_top_object); /* keep the source object alive */
402 
403 	/*
404 	 * Fill in the contents of the pages requested by VM.
405 	 */
406 	upl_pl = UPL_GET_INTERNAL_PAGE_LIST(upl);
407 	pl_count = length / PAGE_SIZE;
408 	for (cur_offset = 0;
409 	    retval == KERN_SUCCESS && cur_offset < length;
410 	    cur_offset += PAGE_SIZE) {
411 		ppnum_t dst_pnum;
412 
413 		if (!upl_page_present(upl_pl, (int)(cur_offset / PAGE_SIZE))) {
414 			/* this page is not in the UPL: skip it */
415 			continue;
416 		}
417 
418 		/*
419 		 * Map the source (encrypted) page in the kernel's
420 		 * virtual address space.
421 		 * We already hold a reference on the src_top_object.
422 		 */
423 retry_src_fault:
424 		vm_object_lock(src_top_object);
425 		vm_object_paging_begin(src_top_object);
426 		error_code = 0;
427 		prot = VM_PROT_READ;
428 		src_page = VM_PAGE_NULL;
429 		vmfr = vm_fault_page(src_top_object,
430 		    pager->backing_offset + offset + cur_offset,
431 		    VM_PROT_READ,
432 		    FALSE,
433 		    FALSE,                /* src_page not looked up */
434 		    &prot,
435 		    &src_page,
436 		    &top_page,
437 		    NULL,
438 		    &error_code,
439 		    FALSE,
440 		    &fault_info);
441 		switch (vmfr) {
442 		case VM_FAULT_SUCCESS:
443 			break;
444 		case VM_FAULT_RETRY:
445 			goto retry_src_fault;
446 		case VM_FAULT_MEMORY_SHORTAGE:
447 			if (vm_page_wait(interruptible)) {
448 				goto retry_src_fault;
449 			}
450 			ktriage_record(thread_tid(current_thread()),
451 			    KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_APPLE_PROTECT_PAGER,
452 			    KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_APPLE_PROTECT_PAGER_MEMORY_SHORTAGE),
453 			    0 /* arg */);
454 			OS_FALLTHROUGH;
455 		case VM_FAULT_INTERRUPTED:
456 			retval = MACH_SEND_INTERRUPTED;
457 			goto done;
458 		case VM_FAULT_SUCCESS_NO_VM_PAGE:
459 			/* success but no VM page: fail */
460 			vm_object_paging_end(src_top_object);
461 			vm_object_unlock(src_top_object);
462 			OS_FALLTHROUGH;
463 		case VM_FAULT_MEMORY_ERROR:
464 			/* the page is not there ! */
465 			if (error_code) {
466 				retval = error_code;
467 			} else {
468 				retval = KERN_MEMORY_ERROR;
469 			}
470 			goto done;
471 		case VM_FAULT_BUSY:
472 			retval = KERN_ALREADY_WAITING;
473 			goto done;
474 		default:
475 			panic("%s: "
476 			    "vm_fault_page() return unexpected error 0x%x\n",
477 			    __func__, vmfr);
478 		}
479 		assert(src_page != VM_PAGE_NULL);
480 		assert(src_page->vmp_busy);
481 
482 		if (src_page->vmp_q_state != VM_PAGE_ON_SPECULATIVE_Q) {
483 			vm_page_lockspin_queues();
484 
485 			if (src_page->vmp_q_state != VM_PAGE_ON_SPECULATIVE_Q) {
486 				vm_page_speculate(src_page, FALSE);
487 			}
488 			vm_page_unlock_queues();
489 		}
490 
491 		/*
492 		 * Establish pointers to the source
493 		 * and destination physical pages.
494 		 */
495 		dst_pnum = (ppnum_t)
496 		    upl_phys_page(upl_pl, (int)(cur_offset / PAGE_SIZE));
497 		assert(dst_pnum != 0);
498 
499 		src_vaddr = (vm_map_offset_t)
500 		    phystokv((pmap_paddr_t)VM_PAGE_GET_PHYS_PAGE(src_page)
501 		        << PAGE_SHIFT);
502 		dst_vaddr = (vm_map_offset_t)
503 		    phystokv((pmap_paddr_t)dst_pnum << PAGE_SHIFT);
504 
505 		src_page_object = VM_PAGE_OBJECT(src_page);
506 
507 		/*
508 		 * Validate the original page...
509 		 */
510 		if (src_page_object->code_signed) {
511 			vm_page_validate_cs_mapped(
512 				src_page, PAGE_SIZE, 0,
513 				(const void *) src_vaddr);
514 		}
515 		/*
516 		 * ... and transfer the results to the destination page.
517 		 */
518 		UPL_SET_CS_VALIDATED(upl_pl, cur_offset / PAGE_SIZE,
519 		    src_page->vmp_cs_validated);
520 		UPL_SET_CS_TAINTED(upl_pl, cur_offset / PAGE_SIZE,
521 		    src_page->vmp_cs_tainted);
522 		UPL_SET_CS_NX(upl_pl, cur_offset / PAGE_SIZE,
523 		    src_page->vmp_cs_nx);
524 
525 		/*
526 		 * page_decrypt() might access a mapped file, so let's release
527 		 * the object lock for the source page to avoid a potential
528 		 * deadlock.  The source page is kept busy and we have a
529 		 * "paging_in_progress" reference on its object, so it's safe
530 		 * to unlock the object here.
531 		 */
532 		assert(src_page->vmp_busy);
533 		assert(src_page_object->paging_in_progress > 0);
534 		vm_object_unlock(src_page_object);
535 
536 		/*
537 		 * Decrypt the encrypted contents of the source page
538 		 * into the destination page.
539 		 */
540 		for (offset_in_page = 0;
541 		    offset_in_page < PAGE_SIZE;
542 		    offset_in_page += 4096) {
543 			if (offset + cur_offset + offset_in_page <
544 			    pager->crypto_start ||
545 			    offset + cur_offset + offset_in_page >=
546 			    pager->crypto_end) {
547 				/* not encrypted: just copy */
548 				bcopy((const char *)(src_vaddr +
549 				    offset_in_page),
550 				    (char *)(dst_vaddr + offset_in_page),
551 				    4096);
552 
553 				if (apple_protect_pager_data_request_debug) {
554 					printf("apple_protect_data_request"
555 					    "(%p,0x%llx+0x%llx+0x%04llx): "
556 					    "out of crypto range "
557 					    "[0x%llx:0x%llx]: "
558 					    "COPY [0x%016llx 0x%016llx] "
559 					    "code_signed=%d "
560 					    "cs_validated=%d "
561 					    "cs_tainted=%d "
562 					    "cs_nx=%d\n",
563 					    pager,
564 					    offset,
565 					    (uint64_t) cur_offset,
566 					    (uint64_t) offset_in_page,
567 					    pager->crypto_start,
568 					    pager->crypto_end,
569 					    *(uint64_t *)(dst_vaddr +
570 					    offset_in_page),
571 					    *(uint64_t *)(dst_vaddr +
572 					    offset_in_page + 8),
573 					    src_page_object->code_signed,
574 					    src_page->vmp_cs_validated,
575 					    src_page->vmp_cs_tainted,
576 					    src_page->vmp_cs_nx);
577 				}
578 				ret = 0;
579 				continue;
580 			}
581 			ret = pager->crypt_info->page_decrypt(
582 				(const void *)(src_vaddr + offset_in_page),
583 				(void *)(dst_vaddr + offset_in_page),
584 				((pager->crypto_backing_offset -
585 				pager->crypto_start) +   /* XXX ? */
586 				offset +
587 				cur_offset +
588 				offset_in_page),
589 				pager->crypt_info->crypt_ops);
590 
591 			if (apple_protect_pager_data_request_debug) {
592 				printf("apple_protect_data_request"
593 				    "(%p,0x%llx+0x%llx+0x%04llx): "
594 				    "in crypto range [0x%llx:0x%llx]: "
595 				    "DECRYPT offset 0x%llx="
596 				    "(0x%llx-0x%llx+0x%llx+0x%llx+0x%04llx)"
597 				    "[0x%016llx 0x%016llx] "
598 				    "code_signed=%d "
599 				    "cs_validated=%d "
600 				    "cs_tainted=%d "
601 				    "cs_nx=%d "
602 				    "ret=0x%x\n",
603 				    pager,
604 				    offset,
605 				    (uint64_t) cur_offset,
606 				    (uint64_t) offset_in_page,
607 				    pager->crypto_start, pager->crypto_end,
608 				    ((pager->crypto_backing_offset -
609 				    pager->crypto_start) +
610 				    offset +
611 				    cur_offset +
612 				    offset_in_page),
613 				    pager->crypto_backing_offset,
614 				    pager->crypto_start,
615 				    offset,
616 				    (uint64_t) cur_offset,
617 				    (uint64_t) offset_in_page,
618 				    *(uint64_t *)(dst_vaddr + offset_in_page),
619 				    *(uint64_t *)(dst_vaddr + offset_in_page + 8),
620 				    src_page_object->code_signed,
621 				    src_page->vmp_cs_validated,
622 				    src_page->vmp_cs_tainted,
623 				    src_page->vmp_cs_nx,
624 				    ret);
625 			}
626 			if (ret) {
627 				break;
628 			}
629 		}
630 		if (ret) {
631 			/*
632 			 * Decryption failed.  Abort the fault.
633 			 */
634 			retval = KERN_ABORTED;
635 		}
636 
637 		assert(VM_PAGE_OBJECT(src_page) == src_page_object);
638 		assert(src_page->vmp_busy);
639 		assert(src_page_object->paging_in_progress > 0);
640 		vm_object_lock(src_page_object);
641 
642 		/*
643 		 * Cleanup the result of vm_fault_page() of the source page.
644 		 */
645 		vm_page_wakeup_done(src_page_object, src_page);
646 		src_page = VM_PAGE_NULL;
647 		vm_object_paging_end(src_page_object);
648 		vm_object_unlock(src_page_object);
649 
650 		if (top_page != VM_PAGE_NULL) {
651 			assert(VM_PAGE_OBJECT(top_page) == src_top_object);
652 			vm_object_lock(src_top_object);
653 			VM_PAGE_FREE(top_page);
654 			vm_object_paging_end(src_top_object);
655 			vm_object_unlock(src_top_object);
656 		}
657 	}
658 
659 done:
660 	if (upl != NULL) {
661 		/* clean up the UPL */
662 
663 		/*
664 		 * The pages are currently dirty because we've just been
665 		 * writing on them, but as far as we're concerned, they're
666 		 * clean since they contain their "original" contents as
667 		 * provided by us, the pager.
668 		 * Tell the UPL to mark them "clean".
669 		 */
670 		upl_clear_dirty(upl, TRUE);
671 
672 		/* abort or commit the UPL */
673 		if (retval != KERN_SUCCESS) {
674 			upl_abort(upl, 0);
675 			if (retval == KERN_ABORTED) {
676 				wait_result_t   wait_result;
677 
678 				/*
679 				 * We aborted the fault and did not provide
680 				 * any contents for the requested pages but
681 				 * the pages themselves are not invalid, so
682 				 * let's return success and let the caller
683 				 * retry the fault, in case it might succeed
684 				 * later (when the decryption code is up and
685 				 * running in the kernel, for example).
686 				 */
687 				retval = KERN_SUCCESS;
688 				/*
689 				 * Wait a little bit first to avoid using
690 				 * too much CPU time retrying and failing
691 				 * the same fault over and over again.
692 				 */
693 				wait_result = assert_wait_timeout(
694 					(event_t) apple_protect_pager_data_request,
695 					THREAD_UNINT,
696 					10000,  /* 10ms */
697 					NSEC_PER_USEC);
698 				assert(wait_result == THREAD_WAITING);
699 				wait_result = thread_block(THREAD_CONTINUE_NULL);
700 				assert(wait_result == THREAD_TIMED_OUT);
701 			}
702 		} else {
703 			boolean_t empty;
704 			assertf(page_aligned(upl->u_offset) && page_aligned(upl->u_size),
705 			    "upl %p offset 0x%llx size 0x%x",
706 			    upl, upl->u_offset, upl->u_size);
707 			upl_commit_range(upl, 0, upl->u_size,
708 			    UPL_COMMIT_CS_VALIDATED | UPL_COMMIT_WRITTEN_BY_KERNEL,
709 			    upl_pl, pl_count, &empty);
710 		}
711 
712 		/* and deallocate the UPL */
713 		upl_deallocate(upl);
714 		upl = NULL;
715 	}
716 	if (src_top_object != VM_OBJECT_NULL) {
717 		vm_object_deallocate(src_top_object);
718 	}
719 	return retval;
720 }
721 
722 /*
723  * apple_protect_pager_reference()
724  *
725  * Get a reference on this memory object.
726  * For external usage only.  Assumes that the initial reference count is not 0,
727  * i.e one should not "revive" a dead pager this way.
728  */
729 void
apple_protect_pager_reference(memory_object_t mem_obj)730 apple_protect_pager_reference(
731 	memory_object_t         mem_obj)
732 {
733 	apple_protect_pager_t   pager;
734 
735 	pager = apple_protect_pager_lookup(mem_obj);
736 
737 	lck_mtx_lock(&apple_protect_pager_lock);
738 	os_ref_retain_locked_raw(&pager->ap_pgr_hdr_ref, NULL);
739 	lck_mtx_unlock(&apple_protect_pager_lock);
740 }
741 
742 
743 /*
744  * apple_protect_pager_dequeue:
745  *
746  * Removes a pager from the list of pagers.
747  *
748  * The caller must hold "apple_protect_pager_lock".
749  */
750 void
apple_protect_pager_dequeue(apple_protect_pager_t pager)751 apple_protect_pager_dequeue(
752 	apple_protect_pager_t pager)
753 {
754 	assert(!pager->is_mapped);
755 
756 	queue_remove(&apple_protect_pager_queue,
757 	    pager,
758 	    apple_protect_pager_t,
759 	    pager_queue);
760 	pager->pager_queue.next = NULL;
761 	pager->pager_queue.prev = NULL;
762 
763 	apple_protect_pager_count--;
764 }
765 
766 /*
767  * apple_protect_pager_terminate_internal:
768  *
769  * Trigger the asynchronous termination of the memory object associated
770  * with this pager.
771  * When the memory object is terminated, there will be one more call
772  * to memory_object_deallocate() (i.e. apple_protect_pager_deallocate())
773  * to finish the clean up.
774  *
775  * "apple_protect_pager_lock" should not be held by the caller.
776  * We don't need the lock because the pager has already been removed from
777  * the pagers' list and is now ours exclusively.
778  */
779 void
apple_protect_pager_terminate_internal(apple_protect_pager_t pager)780 apple_protect_pager_terminate_internal(
781 	apple_protect_pager_t pager)
782 {
783 	assert(pager->is_ready);
784 	assert(!pager->is_mapped);
785 
786 	if (pager->backing_object != VM_OBJECT_NULL) {
787 		vm_object_deallocate(pager->backing_object);
788 		pager->backing_object = VM_OBJECT_NULL;
789 	}
790 
791 	/* one less pager using this "pager_crypt_info" */
792 #if CRYPT_INFO_DEBUG
793 	printf("CRYPT_INFO %s: deallocate %p ref %d\n",
794 	    __FUNCTION__,
795 	    pager->crypt_info,
796 	    pager->crypt_info->crypt_refcnt);
797 #endif /* CRYPT_INFO_DEBUG */
798 	crypt_info_deallocate(pager->crypt_info);
799 	pager->crypt_info = NULL;
800 
801 	/* trigger the destruction of the memory object */
802 	memory_object_destroy(pager->ap_pgr_hdr.mo_control, VM_OBJECT_DESTROY_PAGER);
803 }
804 
805 /*
806  * apple_protect_pager_deallocate_internal()
807  *
808  * Release a reference on this pager and free it when the last
809  * reference goes away.
810  * Can be called with apple_protect_pager_lock held or not but always returns
811  * with it unlocked.
812  */
813 void
apple_protect_pager_deallocate_internal(apple_protect_pager_t pager,boolean_t locked)814 apple_protect_pager_deallocate_internal(
815 	apple_protect_pager_t   pager,
816 	boolean_t               locked)
817 {
818 	boolean_t       needs_trimming;
819 	unsigned int    count_unmapped;
820 	os_ref_count_t  ref_count;
821 
822 	if (!locked) {
823 		lck_mtx_lock(&apple_protect_pager_lock);
824 	}
825 
826 	count_unmapped = (apple_protect_pager_count -
827 	    apple_protect_pager_count_mapped);
828 	if (count_unmapped > apple_protect_pager_cache_limit) {
829 		/* we have too many unmapped pagers:  trim some */
830 		needs_trimming = TRUE;
831 	} else {
832 		needs_trimming = FALSE;
833 	}
834 
835 	/* drop a reference on this pager */
836 	ref_count = os_ref_release_locked_raw(&pager->ap_pgr_hdr_ref, NULL);
837 
838 	if (ref_count == 1) {
839 		/*
840 		 * Only the "named" reference is left, which means that
841 		 * no one is really holding on to this pager anymore.
842 		 * Terminate it.
843 		 */
844 		apple_protect_pager_dequeue(pager);
845 		/* the pager is all ours: no need for the lock now */
846 		lck_mtx_unlock(&apple_protect_pager_lock);
847 		apple_protect_pager_terminate_internal(pager);
848 	} else if (ref_count == 0) {
849 		/*
850 		 * Dropped the existence reference;  the memory object has
851 		 * been terminated.  Do some final cleanup and release the
852 		 * pager structure.
853 		 */
854 		lck_mtx_unlock(&apple_protect_pager_lock);
855 		if (pager->ap_pgr_hdr.mo_control != MEMORY_OBJECT_CONTROL_NULL) {
856 			memory_object_control_deallocate(pager->ap_pgr_hdr.mo_control);
857 			pager->ap_pgr_hdr.mo_control = MEMORY_OBJECT_CONTROL_NULL;
858 		}
859 		kfree_type(struct apple_protect_pager, pager);
860 		pager = APPLE_PROTECT_PAGER_NULL;
861 	} else {
862 		/* there are still plenty of references:  keep going... */
863 		lck_mtx_unlock(&apple_protect_pager_lock);
864 	}
865 
866 	if (needs_trimming) {
867 		apple_protect_pager_trim();
868 	}
869 	/* caution: lock is not held on return... */
870 }
871 
872 /*
873  * apple_protect_pager_deallocate()
874  *
875  * Release a reference on this pager and free it when the last
876  * reference goes away.
877  */
878 void
apple_protect_pager_deallocate(memory_object_t mem_obj)879 apple_protect_pager_deallocate(
880 	memory_object_t         mem_obj)
881 {
882 	apple_protect_pager_t   pager;
883 
884 	PAGER_DEBUG(PAGER_ALL, ("apple_protect_pager_deallocate: %p\n", mem_obj));
885 	pager = apple_protect_pager_lookup(mem_obj);
886 	apple_protect_pager_deallocate_internal(pager, FALSE);
887 }
888 
889 /*
890  *
891  */
892 kern_return_t
apple_protect_pager_terminate(__unused memory_object_t mem_obj)893 apple_protect_pager_terminate(
894 #if !DEBUG
895 	__unused
896 #endif
897 	memory_object_t mem_obj)
898 {
899 	PAGER_DEBUG(PAGER_ALL, ("apple_protect_pager_terminate: %p\n", mem_obj));
900 
901 	return KERN_SUCCESS;
902 }
903 
904 /*
905  * apple_protect_pager_map()
906  *
907  * This allows VM to let us, the EMM, know that this memory object
908  * is currently mapped one or more times.  This is called by VM each time
909  * the memory object gets mapped and we take one extra reference on the
910  * memory object to account for all its mappings.
911  */
912 kern_return_t
apple_protect_pager_map(memory_object_t mem_obj,__unused vm_prot_t prot)913 apple_protect_pager_map(
914 	memory_object_t         mem_obj,
915 	__unused vm_prot_t      prot)
916 {
917 	apple_protect_pager_t   pager;
918 
919 	PAGER_DEBUG(PAGER_ALL, ("apple_protect_pager_map: %p\n", mem_obj));
920 
921 	pager = apple_protect_pager_lookup(mem_obj);
922 
923 	lck_mtx_lock(&apple_protect_pager_lock);
924 	assert(pager->is_ready);
925 	assert(os_ref_get_count_raw(&pager->ap_pgr_hdr_ref) > 0); /* pager is alive */
926 	if (pager->is_mapped == FALSE) {
927 		/*
928 		 * First mapping of this pager:  take an extra reference
929 		 * that will remain until all the mappings of this pager
930 		 * are removed.
931 		 */
932 		pager->is_mapped = TRUE;
933 		os_ref_retain_locked_raw(&pager->ap_pgr_hdr_ref, NULL);
934 		apple_protect_pager_count_mapped++;
935 	}
936 	lck_mtx_unlock(&apple_protect_pager_lock);
937 
938 	return KERN_SUCCESS;
939 }
940 
941 /*
942  * apple_protect_pager_last_unmap()
943  *
944  * This is called by VM when this memory object is no longer mapped anywhere.
945  */
946 kern_return_t
apple_protect_pager_last_unmap(memory_object_t mem_obj)947 apple_protect_pager_last_unmap(
948 	memory_object_t         mem_obj)
949 {
950 	apple_protect_pager_t   pager;
951 	unsigned int            count_unmapped;
952 
953 	PAGER_DEBUG(PAGER_ALL,
954 	    ("apple_protect_pager_last_unmap: %p\n", mem_obj));
955 
956 	pager = apple_protect_pager_lookup(mem_obj);
957 
958 	lck_mtx_lock(&apple_protect_pager_lock);
959 	if (pager->is_mapped) {
960 		/*
961 		 * All the mappings are gone, so let go of the one extra
962 		 * reference that represents all the mappings of this pager.
963 		 */
964 		apple_protect_pager_count_mapped--;
965 		count_unmapped = (apple_protect_pager_count -
966 		    apple_protect_pager_count_mapped);
967 		if (count_unmapped > apple_protect_pager_count_unmapped_max) {
968 			apple_protect_pager_count_unmapped_max = count_unmapped;
969 		}
970 		pager->is_mapped = FALSE;
971 		apple_protect_pager_deallocate_internal(pager, TRUE);
972 		/* caution: deallocate_internal() released the lock ! */
973 	} else {
974 		lck_mtx_unlock(&apple_protect_pager_lock);
975 	}
976 
977 	return KERN_SUCCESS;
978 }
979 
980 boolean_t
apple_protect_pager_backing_object(memory_object_t mem_obj,memory_object_offset_t offset,vm_object_t * backing_object,vm_object_offset_t * backing_offset)981 apple_protect_pager_backing_object(
982 	memory_object_t mem_obj,
983 	memory_object_offset_t offset,
984 	vm_object_t *backing_object,
985 	vm_object_offset_t *backing_offset)
986 {
987 	apple_protect_pager_t   pager;
988 
989 	PAGER_DEBUG(PAGER_ALL,
990 	    ("apple_protect_pager_backing_object: %p\n", mem_obj));
991 
992 	pager = apple_protect_pager_lookup(mem_obj);
993 
994 	*backing_object = pager->backing_object;
995 	*backing_offset = pager->backing_offset + offset;
996 
997 	return TRUE;
998 }
999 
1000 /*
1001  *
1002  */
1003 apple_protect_pager_t
apple_protect_pager_lookup(memory_object_t mem_obj)1004 apple_protect_pager_lookup(
1005 	memory_object_t  mem_obj)
1006 {
1007 	apple_protect_pager_t   pager;
1008 
1009 	assert(mem_obj->mo_pager_ops == &apple_protect_pager_ops);
1010 	pager = (apple_protect_pager_t)(uintptr_t) mem_obj;
1011 	assert(os_ref_get_count_raw(&pager->ap_pgr_hdr_ref) > 0);
1012 	return pager;
1013 }
1014 
1015 apple_protect_pager_t
apple_protect_pager_create(vm_object_t backing_object,vm_object_offset_t backing_offset,vm_object_offset_t crypto_backing_offset,struct pager_crypt_info * crypt_info,vm_object_offset_t crypto_start,vm_object_offset_t crypto_end,boolean_t cache_pager)1016 apple_protect_pager_create(
1017 	vm_object_t             backing_object,
1018 	vm_object_offset_t      backing_offset,
1019 	vm_object_offset_t      crypto_backing_offset,
1020 	struct pager_crypt_info *crypt_info,
1021 	vm_object_offset_t      crypto_start,
1022 	vm_object_offset_t      crypto_end,
1023 	boolean_t               cache_pager)
1024 {
1025 	apple_protect_pager_t   pager, pager2;
1026 	memory_object_control_t control;
1027 	kern_return_t           kr;
1028 	struct pager_crypt_info *old_crypt_info;
1029 
1030 	pager = kalloc_type(struct apple_protect_pager, Z_WAITOK | Z_NOFAIL);
1031 
1032 	/*
1033 	 * The vm_map call takes both named entry ports and raw memory
1034 	 * objects in the same parameter.  We need to make sure that
1035 	 * vm_map does not see this object as a named entry port.  So,
1036 	 * we reserve the first word in the object for a fake object type
1037 	 * setting - that will tell vm_map to use it as a memory object.
1038 	 */
1039 	pager->ap_pgr_hdr.mo_ikot = IKOT_MEMORY_OBJECT;
1040 	pager->ap_pgr_hdr.mo_pager_ops = &apple_protect_pager_ops;
1041 	pager->ap_pgr_hdr.mo_control = MEMORY_OBJECT_CONTROL_NULL;
1042 
1043 	pager->is_ready = FALSE;/* not ready until it has a "name" */
1044 	/* one reference for the caller */
1045 	os_ref_init_count_raw(&pager->ap_pgr_hdr_ref, NULL, 1);
1046 	pager->is_mapped = FALSE;
1047 	if (cache_pager) {
1048 		/* extra reference for the cache */
1049 		os_ref_retain_locked_raw(&pager->ap_pgr_hdr_ref, NULL);
1050 		pager->is_cached = true;
1051 	} else {
1052 		pager->is_cached = false;
1053 	}
1054 	pager->backing_object = backing_object;
1055 	pager->backing_offset = backing_offset;
1056 	pager->crypto_backing_offset = crypto_backing_offset;
1057 	pager->crypto_start = crypto_start;
1058 	pager->crypto_end = crypto_end;
1059 	pager->crypt_info = crypt_info; /* allocated by caller */
1060 
1061 #if CRYPT_INFO_DEBUG
1062 	printf("CRYPT_INFO %s: crypt_info %p [%p,%p,%p,%d]\n",
1063 	    __FUNCTION__,
1064 	    crypt_info,
1065 	    crypt_info->page_decrypt,
1066 	    crypt_info->crypt_end,
1067 	    crypt_info->crypt_ops,
1068 	    crypt_info->crypt_refcnt);
1069 #endif /* CRYPT_INFO_DEBUG */
1070 
1071 	vm_object_reference(backing_object);
1072 
1073 	old_crypt_info = NULL;
1074 
1075 	lck_mtx_lock(&apple_protect_pager_lock);
1076 	/* see if anyone raced us to create a pager for the same object */
1077 	queue_iterate(&apple_protect_pager_queue,
1078 	    pager2,
1079 	    apple_protect_pager_t,
1080 	    pager_queue) {
1081 		if ((pager2->crypt_info->page_decrypt !=
1082 		    crypt_info->page_decrypt) ||
1083 		    (pager2->crypt_info->crypt_end !=
1084 		    crypt_info->crypt_end) ||
1085 		    (pager2->crypt_info->crypt_ops !=
1086 		    crypt_info->crypt_ops)) {
1087 			/* crypt_info contents do not match: next pager */
1088 			continue;
1089 		}
1090 
1091 		/* found a match for crypt_info ... */
1092 		if (old_crypt_info) {
1093 			/* ... already switched to that crypt_info */
1094 			assert(old_crypt_info == pager2->crypt_info);
1095 		} else if (pager2->crypt_info != crypt_info) {
1096 			/* ... switch to that pager's crypt_info */
1097 #if CRYPT_INFO_DEBUG
1098 			printf("CRYPT_INFO %s: reference %p ref %d "
1099 			    "(create match)\n",
1100 			    __FUNCTION__,
1101 			    pager2->crypt_info,
1102 			    pager2->crypt_info->crypt_refcnt);
1103 #endif /* CRYPT_INFO_DEBUG */
1104 			old_crypt_info = pager2->crypt_info;
1105 			crypt_info_reference(old_crypt_info);
1106 			pager->crypt_info = old_crypt_info;
1107 		}
1108 
1109 		if (pager2->backing_object == backing_object &&
1110 		    pager2->backing_offset == backing_offset &&
1111 		    pager2->crypto_backing_offset == crypto_backing_offset &&
1112 		    pager2->crypto_start == crypto_start &&
1113 		    pager2->crypto_end == crypto_end) {
1114 			/* full match: use that pager */
1115 			break;
1116 		}
1117 	}
1118 	if (!queue_end(&apple_protect_pager_queue,
1119 	    (queue_entry_t) pager2)) {
1120 		/* we lost the race, down with the loser... */
1121 		lck_mtx_unlock(&apple_protect_pager_lock);
1122 		vm_object_deallocate(pager->backing_object);
1123 		pager->backing_object = VM_OBJECT_NULL;
1124 #if CRYPT_INFO_DEBUG
1125 		printf("CRYPT_INFO %s: %p ref %d (create pager match)\n",
1126 		    __FUNCTION__,
1127 		    pager->crypt_info,
1128 		    pager->crypt_info->crypt_refcnt);
1129 #endif /* CRYPT_INFO_DEBUG */
1130 		crypt_info_deallocate(pager->crypt_info);
1131 		pager->crypt_info = NULL;
1132 		kfree_type(struct apple_protect_pager, pager);
1133 		/* ... and go with the winner */
1134 		pager = pager2;
1135 		/* let the winner make sure the pager gets ready */
1136 		return pager;
1137 	}
1138 
1139 	/* enter new pager at the head of our list of pagers */
1140 	queue_enter_first(&apple_protect_pager_queue,
1141 	    pager,
1142 	    apple_protect_pager_t,
1143 	    pager_queue);
1144 	apple_protect_pager_count++;
1145 	if (apple_protect_pager_count > apple_protect_pager_count_max) {
1146 		apple_protect_pager_count_max = apple_protect_pager_count;
1147 	}
1148 	lck_mtx_unlock(&apple_protect_pager_lock);
1149 
1150 	kr = memory_object_create_named((memory_object_t) pager,
1151 	    0,
1152 	    &control);
1153 	assert(kr == KERN_SUCCESS);
1154 
1155 	memory_object_mark_trusted(control);
1156 
1157 	lck_mtx_lock(&apple_protect_pager_lock);
1158 	/* the new pager is now ready to be used */
1159 	pager->is_ready = TRUE;
1160 	lck_mtx_unlock(&apple_protect_pager_lock);
1161 
1162 	/* wakeup anyone waiting for this pager to be ready */
1163 	thread_wakeup(&pager->is_ready);
1164 
1165 	if (old_crypt_info != NULL &&
1166 	    old_crypt_info != crypt_info) {
1167 		/* we re-used an old crypt_info instead of using our new one */
1168 #if CRYPT_INFO_DEBUG
1169 		printf("CRYPT_INFO %s: deallocate %p ref %d "
1170 		    "(create used old)\n",
1171 		    __FUNCTION__,
1172 		    crypt_info,
1173 		    crypt_info->crypt_refcnt);
1174 #endif /* CRYPT_INFO_DEBUG */
1175 		crypt_info_deallocate(crypt_info);
1176 		crypt_info = NULL;
1177 	}
1178 
1179 	return pager;
1180 }
1181 
1182 /*
1183  * apple_protect_pager_setup()
1184  *
1185  * Provide the caller with a memory object backed by the provided
1186  * "backing_object" VM object.  If such a memory object already exists,
1187  * re-use it, otherwise create a new memory object.
1188  */
1189 memory_object_t
apple_protect_pager_setup(vm_object_t backing_object,vm_object_offset_t backing_offset,vm_object_offset_t crypto_backing_offset,struct pager_crypt_info * crypt_info,vm_object_offset_t crypto_start,vm_object_offset_t crypto_end,boolean_t cache_pager)1190 apple_protect_pager_setup(
1191 	vm_object_t             backing_object,
1192 	vm_object_offset_t      backing_offset,
1193 	vm_object_offset_t      crypto_backing_offset,
1194 	struct pager_crypt_info *crypt_info,
1195 	vm_object_offset_t      crypto_start,
1196 	vm_object_offset_t      crypto_end,
1197 	boolean_t               cache_pager)
1198 {
1199 	apple_protect_pager_t   pager;
1200 	struct pager_crypt_info *old_crypt_info, *new_crypt_info;
1201 
1202 #if CRYPT_INFO_DEBUG
1203 	printf("CRYPT_INFO %s: crypt_info=%p [%p,%p,%p,%d]\n",
1204 	    __FUNCTION__,
1205 	    crypt_info,
1206 	    crypt_info->page_decrypt,
1207 	    crypt_info->crypt_end,
1208 	    crypt_info->crypt_ops,
1209 	    crypt_info->crypt_refcnt);
1210 #endif /* CRYPT_INFO_DEBUG */
1211 
1212 	old_crypt_info = NULL;
1213 
1214 	lck_mtx_lock(&apple_protect_pager_lock);
1215 
1216 	queue_iterate(&apple_protect_pager_queue,
1217 	    pager,
1218 	    apple_protect_pager_t,
1219 	    pager_queue) {
1220 		if ((pager->crypt_info->page_decrypt !=
1221 		    crypt_info->page_decrypt) ||
1222 		    (pager->crypt_info->crypt_end !=
1223 		    crypt_info->crypt_end) ||
1224 		    (pager->crypt_info->crypt_ops !=
1225 		    crypt_info->crypt_ops)) {
1226 			/* no match for "crypt_info": next pager */
1227 			continue;
1228 		}
1229 		/* found a match for crypt_info ... */
1230 		if (old_crypt_info) {
1231 			/* ... already switched to that crypt_info */
1232 			assert(old_crypt_info == pager->crypt_info);
1233 		} else {
1234 			/* ... switch to that pager's crypt_info */
1235 			old_crypt_info = pager->crypt_info;
1236 #if CRYPT_INFO_DEBUG
1237 			printf("CRYPT_INFO %s: "
1238 			    "switching crypt_info from %p [%p,%p,%p,%d] "
1239 			    "to %p [%p,%p,%p,%d] from pager %p\n",
1240 			    __FUNCTION__,
1241 			    crypt_info,
1242 			    crypt_info->page_decrypt,
1243 			    crypt_info->crypt_end,
1244 			    crypt_info->crypt_ops,
1245 			    crypt_info->crypt_refcnt,
1246 			    old_crypt_info,
1247 			    old_crypt_info->page_decrypt,
1248 			    old_crypt_info->crypt_end,
1249 			    old_crypt_info->crypt_ops,
1250 			    old_crypt_info->crypt_refcnt,
1251 			    pager);
1252 			printf("CRYPT_INFO %s: %p ref %d (setup match)\n",
1253 			    __FUNCTION__,
1254 			    pager->crypt_info,
1255 			    pager->crypt_info->crypt_refcnt);
1256 #endif /* CRYPT_INFO_DEBUG */
1257 			crypt_info_reference(pager->crypt_info);
1258 		}
1259 
1260 		if (pager->backing_object == backing_object &&
1261 		    pager->backing_offset == backing_offset &&
1262 		    pager->crypto_backing_offset == crypto_backing_offset &&
1263 		    pager->crypto_start == crypto_start &&
1264 		    pager->crypto_end == crypto_end) {
1265 			/* full match: use that pager! */
1266 			assert(old_crypt_info == pager->crypt_info);
1267 			assert(old_crypt_info->crypt_refcnt > 1);
1268 #if CRYPT_INFO_DEBUG
1269 			printf("CRYPT_INFO %s: "
1270 			    "pager match with %p crypt_info %p\n",
1271 			    __FUNCTION__,
1272 			    pager,
1273 			    pager->crypt_info);
1274 			printf("CRYPT_INFO %s: deallocate %p ref %d "
1275 			    "(pager match)\n",
1276 			    __FUNCTION__,
1277 			    old_crypt_info,
1278 			    old_crypt_info->crypt_refcnt);
1279 #endif /* CRYPT_INFO_DEBUG */
1280 			/* release the extra ref on crypt_info we got above */
1281 			crypt_info_deallocate(old_crypt_info);
1282 			assert(old_crypt_info->crypt_refcnt > 0);
1283 			/* give extra reference on pager to the caller */
1284 			os_ref_retain_locked_raw(&pager->ap_pgr_hdr_ref, NULL);
1285 			break;
1286 		}
1287 	}
1288 	if (queue_end(&apple_protect_pager_queue,
1289 	    (queue_entry_t) pager)) {
1290 		lck_mtx_unlock(&apple_protect_pager_lock);
1291 		/* no existing pager for this backing object */
1292 		pager = APPLE_PROTECT_PAGER_NULL;
1293 		if (old_crypt_info) {
1294 			/* use this old crypt_info for new pager */
1295 			new_crypt_info = old_crypt_info;
1296 #if CRYPT_INFO_DEBUG
1297 			printf("CRYPT_INFO %s: "
1298 			    "will use old_crypt_info %p for new pager\n",
1299 			    __FUNCTION__,
1300 			    old_crypt_info);
1301 #endif /* CRYPT_INFO_DEBUG */
1302 		} else {
1303 			/* allocate a new crypt_info for new pager */
1304 			new_crypt_info = kalloc_type(struct pager_crypt_info, Z_WAITOK);
1305 			*new_crypt_info = *crypt_info;
1306 			new_crypt_info->crypt_refcnt = 1;
1307 #if CRYPT_INFO_DEBUG
1308 			printf("CRYPT_INFO %s: "
1309 			    "will use new_crypt_info %p for new pager\n",
1310 			    __FUNCTION__,
1311 			    new_crypt_info);
1312 #endif /* CRYPT_INFO_DEBUG */
1313 		}
1314 		if (new_crypt_info == NULL) {
1315 			/* can't create new pager without a crypt_info */
1316 		} else {
1317 			/* create new pager */
1318 			pager = apple_protect_pager_create(
1319 				backing_object,
1320 				backing_offset,
1321 				crypto_backing_offset,
1322 				new_crypt_info,
1323 				crypto_start,
1324 				crypto_end,
1325 				cache_pager);
1326 		}
1327 		if (pager == APPLE_PROTECT_PAGER_NULL) {
1328 			/* could not create a new pager */
1329 			if (new_crypt_info == old_crypt_info) {
1330 				/* release extra reference on old_crypt_info */
1331 #if CRYPT_INFO_DEBUG
1332 				printf("CRYPT_INFO %s: deallocate %p ref %d "
1333 				    "(create fail old_crypt_info)\n",
1334 				    __FUNCTION__,
1335 				    old_crypt_info,
1336 				    old_crypt_info->crypt_refcnt);
1337 #endif /* CRYPT_INFO_DEBUG */
1338 				crypt_info_deallocate(old_crypt_info);
1339 				old_crypt_info = NULL;
1340 			} else {
1341 				/* release unused new_crypt_info */
1342 				assert(new_crypt_info->crypt_refcnt == 1);
1343 #if CRYPT_INFO_DEBUG
1344 				printf("CRYPT_INFO %s: deallocate %p ref %d "
1345 				    "(create fail new_crypt_info)\n",
1346 				    __FUNCTION__,
1347 				    new_crypt_info,
1348 				    new_crypt_info->crypt_refcnt);
1349 #endif /* CRYPT_INFO_DEBUG */
1350 				crypt_info_deallocate(new_crypt_info);
1351 				new_crypt_info = NULL;
1352 			}
1353 			return MEMORY_OBJECT_NULL;
1354 		}
1355 		lck_mtx_lock(&apple_protect_pager_lock);
1356 	} else {
1357 		assert(old_crypt_info == pager->crypt_info);
1358 	}
1359 
1360 	while (!pager->is_ready) {
1361 		lck_mtx_sleep(&apple_protect_pager_lock,
1362 		    LCK_SLEEP_DEFAULT,
1363 		    &pager->is_ready,
1364 		    THREAD_UNINT);
1365 	}
1366 	lck_mtx_unlock(&apple_protect_pager_lock);
1367 
1368 	return (memory_object_t) pager;
1369 }
1370 
1371 void
apple_protect_pager_trim(void)1372 apple_protect_pager_trim(void)
1373 {
1374 	apple_protect_pager_t   pager, prev_pager;
1375 	queue_head_t            trim_queue;
1376 	unsigned int            num_trim;
1377 	unsigned int            count_unmapped;
1378 
1379 	lck_mtx_lock(&apple_protect_pager_lock);
1380 
1381 	/*
1382 	 * We have too many pagers, try and trim some unused ones,
1383 	 * starting with the oldest pager at the end of the queue.
1384 	 */
1385 	queue_init(&trim_queue);
1386 	num_trim = 0;
1387 
1388 	for (pager = (apple_protect_pager_t)
1389 	    queue_last(&apple_protect_pager_queue);
1390 	    !queue_end(&apple_protect_pager_queue,
1391 	    (queue_entry_t) pager);
1392 	    pager = prev_pager) {
1393 		/* get prev elt before we dequeue */
1394 		prev_pager = (apple_protect_pager_t)
1395 		    queue_prev(&pager->pager_queue);
1396 
1397 		if (pager->is_cached &&
1398 		    os_ref_get_count_raw(&pager->ap_pgr_hdr_ref) == 2 &&
1399 		    pager->is_ready &&
1400 		    !pager->is_mapped) {
1401 			/* this pager can be trimmed */
1402 			num_trim++;
1403 			/* remove this pager from the main list ... */
1404 			apple_protect_pager_dequeue(pager);
1405 			/* ... and add it to our trim queue */
1406 			queue_enter_first(&trim_queue,
1407 			    pager,
1408 			    apple_protect_pager_t,
1409 			    pager_queue);
1410 
1411 			count_unmapped = (apple_protect_pager_count -
1412 			    apple_protect_pager_count_mapped);
1413 			if (count_unmapped <= apple_protect_pager_cache_limit) {
1414 				/* we have enough pagers to trim */
1415 				break;
1416 			}
1417 		}
1418 	}
1419 	if (num_trim > apple_protect_pager_num_trim_max) {
1420 		apple_protect_pager_num_trim_max = num_trim;
1421 	}
1422 	apple_protect_pager_num_trim_total += num_trim;
1423 
1424 	lck_mtx_unlock(&apple_protect_pager_lock);
1425 
1426 	/* terminate the trimmed pagers */
1427 	while (!queue_empty(&trim_queue)) {
1428 		queue_remove_first(&trim_queue,
1429 		    pager,
1430 		    apple_protect_pager_t,
1431 		    pager_queue);
1432 		assert(pager->is_cached);
1433 		pager->is_cached = false;
1434 		pager->pager_queue.next = NULL;
1435 		pager->pager_queue.prev = NULL;
1436 		/*
1437 		 * We can't call deallocate_internal() because the pager
1438 		 * has already been dequeued, but we still need to remove
1439 		 * a reference.
1440 		 */
1441 		os_ref_count_t __assert_only count;
1442 		count = os_ref_release_locked_raw(&pager->ap_pgr_hdr_ref, NULL);
1443 		assert(count == 1);
1444 		apple_protect_pager_terminate_internal(pager);
1445 	}
1446 }
1447 
1448 
1449 void
crypt_info_reference(struct pager_crypt_info * crypt_info)1450 crypt_info_reference(
1451 	struct pager_crypt_info *crypt_info)
1452 {
1453 	assert(crypt_info->crypt_refcnt != 0);
1454 #if CRYPT_INFO_DEBUG
1455 	printf("CRYPT_INFO %s: %p ref %d -> %d\n",
1456 	    __FUNCTION__,
1457 	    crypt_info,
1458 	    crypt_info->crypt_refcnt,
1459 	    crypt_info->crypt_refcnt + 1);
1460 #endif /* CRYPT_INFO_DEBUG */
1461 	OSAddAtomic(+1, &crypt_info->crypt_refcnt);
1462 }
1463 
1464 void
crypt_info_deallocate(struct pager_crypt_info * crypt_info)1465 crypt_info_deallocate(
1466 	struct pager_crypt_info *crypt_info)
1467 {
1468 #if CRYPT_INFO_DEBUG
1469 	printf("CRYPT_INFO %s: %p ref %d -> %d\n",
1470 	    __FUNCTION__,
1471 	    crypt_info,
1472 	    crypt_info->crypt_refcnt,
1473 	    crypt_info->crypt_refcnt - 1);
1474 #endif /* CRYPT_INFO_DEBUG */
1475 	OSAddAtomic(-1, &crypt_info->crypt_refcnt);
1476 	if (crypt_info->crypt_refcnt == 0) {
1477 		/* deallocate any crypt module data */
1478 		if (crypt_info->crypt_end) {
1479 			crypt_info->crypt_end(crypt_info->crypt_ops);
1480 			crypt_info->crypt_end = NULL;
1481 		}
1482 #if CRYPT_INFO_DEBUG
1483 		printf("CRYPT_INFO %s: freeing %p\n",
1484 		    __FUNCTION__,
1485 		    crypt_info);
1486 #endif /* CRYPT_INFO_DEBUG */
1487 		kfree_type(struct pager_crypt_info, crypt_info);
1488 	}
1489 }
1490 
1491 static uint64_t
apple_protect_pager_purge(apple_protect_pager_t pager)1492 apple_protect_pager_purge(
1493 	apple_protect_pager_t pager)
1494 {
1495 	uint64_t pages_purged;
1496 	vm_object_t object;
1497 
1498 	pages_purged = 0;
1499 	object = memory_object_to_vm_object((memory_object_t) pager);
1500 	assert(object != VM_OBJECT_NULL);
1501 	vm_object_lock(object);
1502 	pages_purged = object->resident_page_count;
1503 	vm_object_reap_pages(object, REAP_DATA_FLUSH);
1504 	pages_purged -= object->resident_page_count;
1505 //	printf("     %s:%d pager %p object %p purged %llu left %d\n", __FUNCTION__, __LINE__, pager, object, pages_purged, object->resident_page_count);
1506 	vm_object_unlock(object);
1507 	return pages_purged;
1508 }
1509 
1510 uint64_t
apple_protect_pager_purge_all(void)1511 apple_protect_pager_purge_all(void)
1512 {
1513 	uint64_t pages_purged;
1514 	apple_protect_pager_t pager;
1515 
1516 	pages_purged = 0;
1517 	lck_mtx_lock(&apple_protect_pager_lock);
1518 	queue_iterate(&apple_protect_pager_queue, pager, apple_protect_pager_t, pager_queue) {
1519 		pages_purged += apple_protect_pager_purge(pager);
1520 	}
1521 	lck_mtx_unlock(&apple_protect_pager_lock);
1522 #if DEVELOPMENT || DEBUG
1523 	printf("   %s:%d pages purged: %llu\n", __FUNCTION__, __LINE__, pages_purged);
1524 #endif /* DEVELOPMENT || DEBUG */
1525 	return pages_purged;
1526 }
1527