xref: /xnu-8020.101.4/osfmk/vm/vm_resident.c (revision e7776783b89a353188416a9a346c6cdb4928faad)
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 /*
29  * @OSF_COPYRIGHT@
30  */
31 /*
32  * Mach Operating System
33  * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
34  * All Rights Reserved.
35  *
36  * Permission to use, copy, modify and distribute this software and its
37  * documentation is hereby granted, provided that both the copyright
38  * notice and this permission notice appear in all copies of the
39  * software, derivative works or modified versions, and any portions
40  * thereof, and that both notices appear in supporting documentation.
41  *
42  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45  *
46  * Carnegie Mellon requests users of this software to return to
47  *
48  *  Software Distribution Coordinator  or  [email protected]
49  *  School of Computer Science
50  *  Carnegie Mellon University
51  *  Pittsburgh PA 15213-3890
52  *
53  * any improvements or extensions that they make and grant Carnegie Mellon
54  * the rights to redistribute these changes.
55  */
56 /*
57  */
58 /*
59  *	File:	vm/vm_page.c
60  *	Author:	Avadis Tevanian, Jr., Michael Wayne Young
61  *
62  *	Resident memory management module.
63  */
64 
65 #include <debug.h>
66 #include <libkern/OSAtomic.h>
67 #include <libkern/OSDebug.h>
68 
69 #include <mach/clock_types.h>
70 #include <mach/vm_prot.h>
71 #include <mach/vm_statistics.h>
72 #include <mach/sdt.h>
73 #include <kern/counter.h>
74 #include <kern/host_statistics.h>
75 #include <kern/sched_prim.h>
76 #include <kern/policy_internal.h>
77 #include <kern/task.h>
78 #include <kern/thread.h>
79 #include <kern/kalloc.h>
80 #include <kern/zalloc_internal.h>
81 #include <kern/ledger.h>
82 #include <vm/pmap.h>
83 #include <vm/vm_init.h>
84 #include <vm/vm_map.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_pageout.h>
87 #include <vm/vm_kern.h>                 /* kernel_memory_allocate() */
88 #include <kern/misc_protos.h>
89 #include <mach_debug/zone_info.h>
90 #include <vm/cpm.h>
91 #include <pexpert/pexpert.h>
92 #include <san/kasan.h>
93 
94 #include <vm/vm_protos.h>
95 #include <vm/memory_object.h>
96 #include <vm/vm_purgeable_internal.h>
97 #include <vm/vm_compressor.h>
98 #if defined (__x86_64__)
99 #include <i386/misc_protos.h>
100 #endif
101 
102 #if CONFIG_PHANTOM_CACHE
103 #include <vm/vm_phantom_cache.h>
104 #endif
105 
106 #if HIBERNATION
107 #include <IOKit/IOHibernatePrivate.h>
108 #include <machine/pal_hibernate.h>
109 #endif /* HIBERNATION */
110 
111 #include <sys/kdebug.h>
112 
113 #if defined(HAS_APPLE_PAC)
114 #include <ptrauth.h>
115 #endif
116 #if defined(__arm64__)
117 #include <arm/cpu_internal.h>
118 #endif /* defined(__arm64__) */
119 
120 #if MACH_ASSERT
121 
122 #define ASSERT_PMAP_FREE(mem) pmap_assert_free(VM_PAGE_GET_PHYS_PAGE(mem))
123 
124 #else /* MACH_ASSERT */
125 
126 #define ASSERT_PMAP_FREE(mem) /* nothing */
127 
128 #endif /* MACH_ASSERT */
129 
130 extern boolean_t vm_pageout_running;
131 extern thread_t  vm_pageout_scan_thread;
132 extern boolean_t vps_dynamic_priority_enabled;
133 
134 char    vm_page_inactive_states[VM_PAGE_Q_STATE_ARRAY_SIZE];
135 char    vm_page_pageable_states[VM_PAGE_Q_STATE_ARRAY_SIZE];
136 char    vm_page_non_speculative_pageable_states[VM_PAGE_Q_STATE_ARRAY_SIZE];
137 char    vm_page_active_or_inactive_states[VM_PAGE_Q_STATE_ARRAY_SIZE];
138 
139 #if CONFIG_SECLUDED_MEMORY
140 struct vm_page_secluded_data vm_page_secluded;
141 #endif /* CONFIG_SECLUDED_MEMORY */
142 
143 #if DEVELOPMENT || DEBUG
144 extern struct memory_object_pager_ops shared_region_pager_ops;
145 unsigned int shared_region_pagers_resident_count = 0;
146 unsigned int shared_region_pagers_resident_peak = 0;
147 #endif /* DEVELOPMENT || DEBUG */
148 
149 int             PERCPU_DATA(start_color);
150 vm_page_t       PERCPU_DATA(free_pages);
151 boolean_t       hibernate_cleaning_in_progress = FALSE;
152 boolean_t       vm_page_free_verify = TRUE;
153 
154 uint32_t        vm_lopage_free_count = 0;
155 uint32_t        vm_lopage_free_limit = 0;
156 uint32_t        vm_lopage_lowater    = 0;
157 boolean_t       vm_lopage_refill = FALSE;
158 boolean_t       vm_lopage_needed = FALSE;
159 
160 lck_mtx_ext_t   vm_page_queue_lock_ext;
161 lck_mtx_ext_t   vm_page_queue_free_lock_ext;
162 lck_mtx_ext_t   vm_purgeable_queue_lock_ext;
163 
164 int             speculative_age_index = 0;
165 int             speculative_steal_index = 0;
166 struct vm_speculative_age_q vm_page_queue_speculative[VM_PAGE_MAX_SPECULATIVE_AGE_Q + 1];
167 
168 boolean_t       hibernation_vmqueues_inspection = FALSE; /* Tracks if the hibernation code is looking at the VM queues.
169                                                           * Updated and checked behind the vm_page_queues_lock. */
170 
171 static void             vm_page_free_prepare(vm_page_t  page);
172 static vm_page_t        vm_page_grab_fictitious_common(ppnum_t, boolean_t);
173 
174 static void vm_tag_init(void);
175 
176 /* for debugging purposes */
177 SECURITY_READ_ONLY_EARLY(uint32_t) vm_packed_from_vm_pages_array_mask =
178     VM_PAGE_PACKED_FROM_ARRAY;
179 SECURITY_READ_ONLY_EARLY(vm_packing_params_t) vm_page_packing_params =
180     VM_PACKING_PARAMS(VM_PAGE_PACKED_PTR);
181 
182 /*
183  *	Associated with page of user-allocatable memory is a
184  *	page structure.
185  */
186 
187 /*
188  *	These variables record the values returned by vm_page_bootstrap,
189  *	for debugging purposes.  The implementation of pmap_steal_memory
190  *	and pmap_startup here also uses them internally.
191  */
192 
193 vm_offset_t virtual_space_start;
194 vm_offset_t virtual_space_end;
195 uint32_t        vm_page_pages;
196 
197 /*
198  *	The vm_page_lookup() routine, which provides for fast
199  *	(virtual memory object, offset) to page lookup, employs
200  *	the following hash table.  The vm_page_{insert,remove}
201  *	routines install and remove associations in the table.
202  *	[This table is often called the virtual-to-physical,
203  *	or VP, table.]
204  */
205 typedef struct {
206 	vm_page_packed_t page_list;
207 #if     MACH_PAGE_HASH_STATS
208 	int             cur_count;              /* current count */
209 	int             hi_count;               /* high water mark */
210 #endif /* MACH_PAGE_HASH_STATS */
211 } vm_page_bucket_t;
212 
213 
214 #define BUCKETS_PER_LOCK        16
215 
216 SECURITY_READ_ONLY_LATE(vm_page_bucket_t *) vm_page_buckets;                /* Array of buckets */
217 SECURITY_READ_ONLY_LATE(unsigned int)       vm_page_bucket_count = 0;       /* How big is array? */
218 SECURITY_READ_ONLY_LATE(unsigned int)       vm_page_hash_mask;              /* Mask for hash function */
219 SECURITY_READ_ONLY_LATE(unsigned int)       vm_page_hash_shift;             /* Shift for hash function */
220 SECURITY_READ_ONLY_LATE(uint32_t)           vm_page_bucket_hash;            /* Basic bucket hash */
221 SECURITY_READ_ONLY_LATE(unsigned int)       vm_page_bucket_lock_count = 0;  /* How big is array of locks? */
222 
223 #ifndef VM_TAG_ACTIVE_UPDATE
224 #error VM_TAG_ACTIVE_UPDATE
225 #endif
226 #ifndef VM_TAG_SIZECLASSES
227 #error VM_TAG_SIZECLASSES
228 #endif
229 
230 /* for debugging */
231 SECURITY_READ_ONLY_LATE(bool) vm_tag_active_update = VM_TAG_ACTIVE_UPDATE;
232 SECURITY_READ_ONLY_LATE(lck_spin_t *) vm_page_bucket_locks;
233 
234 vm_allocation_site_t            vm_allocation_sites_static[VM_KERN_MEMORY_FIRST_DYNAMIC + 1];
235 vm_allocation_site_t *          vm_allocation_sites[VM_MAX_TAG_VALUE];
236 #if VM_TAG_SIZECLASSES
237 static vm_allocation_zone_total_t **vm_allocation_zone_totals;
238 #endif /* VM_TAG_SIZECLASSES */
239 
240 vm_tag_t vm_allocation_tag_highest;
241 
242 #if VM_PAGE_BUCKETS_CHECK
243 boolean_t vm_page_buckets_check_ready = FALSE;
244 #if VM_PAGE_FAKE_BUCKETS
245 vm_page_bucket_t *vm_page_fake_buckets; /* decoy buckets */
246 vm_map_offset_t vm_page_fake_buckets_start, vm_page_fake_buckets_end;
247 #endif /* VM_PAGE_FAKE_BUCKETS */
248 #endif /* VM_PAGE_BUCKETS_CHECK */
249 
250 #if     MACH_PAGE_HASH_STATS
251 /* This routine is only for debug.  It is intended to be called by
252  * hand by a developer using a kernel debugger.  This routine prints
253  * out vm_page_hash table statistics to the kernel debug console.
254  */
255 void
hash_debug(void)256 hash_debug(void)
257 {
258 	int     i;
259 	int     numbuckets = 0;
260 	int     highsum = 0;
261 	int     maxdepth = 0;
262 
263 	for (i = 0; i < vm_page_bucket_count; i++) {
264 		if (vm_page_buckets[i].hi_count) {
265 			numbuckets++;
266 			highsum += vm_page_buckets[i].hi_count;
267 			if (vm_page_buckets[i].hi_count > maxdepth) {
268 				maxdepth = vm_page_buckets[i].hi_count;
269 			}
270 		}
271 	}
272 	printf("Total number of buckets: %d\n", vm_page_bucket_count);
273 	printf("Number used buckets:     %d = %d%%\n",
274 	    numbuckets, 100 * numbuckets / vm_page_bucket_count);
275 	printf("Number unused buckets:   %d = %d%%\n",
276 	    vm_page_bucket_count - numbuckets,
277 	    100 * (vm_page_bucket_count - numbuckets) / vm_page_bucket_count);
278 	printf("Sum of bucket max depth: %d\n", highsum);
279 	printf("Average bucket depth:    %d.%2d\n",
280 	    highsum / vm_page_bucket_count,
281 	    highsum % vm_page_bucket_count);
282 	printf("Maximum bucket depth:    %d\n", maxdepth);
283 }
284 #endif /* MACH_PAGE_HASH_STATS */
285 
286 /*
287  *	The virtual page size is currently implemented as a runtime
288  *	variable, but is constant once initialized using vm_set_page_size.
289  *	This initialization must be done in the machine-dependent
290  *	bootstrap sequence, before calling other machine-independent
291  *	initializations.
292  *
293  *	All references to the virtual page size outside this
294  *	module must use the PAGE_SIZE, PAGE_MASK and PAGE_SHIFT
295  *	constants.
296  */
297 #if defined(__arm__) || defined(__arm64__)
298 vm_size_t       page_size;
299 vm_size_t       page_mask;
300 int             page_shift;
301 #else
302 vm_size_t       page_size  = PAGE_SIZE;
303 vm_size_t       page_mask  = PAGE_MASK;
304 int             page_shift = PAGE_SHIFT;
305 #endif
306 
307 SECURITY_READ_ONLY_LATE(vm_page_t) vm_pages = VM_PAGE_NULL;
308 SECURITY_READ_ONLY_LATE(vm_page_t) vm_page_array_beginning_addr;
309 vm_page_t                          vm_page_array_ending_addr;
310 
311 unsigned int    vm_pages_count = 0;
312 
313 /*
314  *	Resident pages that represent real memory
315  *	are allocated from a set of free lists,
316  *	one per color.
317  */
318 unsigned int    vm_colors;
319 unsigned int    vm_color_mask;                  /* mask is == (vm_colors-1) */
320 unsigned int    vm_cache_geometry_colors = 0;   /* set by hw dependent code during startup */
321 unsigned int    vm_free_magazine_refill_limit = 0;
322 
323 
324 struct vm_page_queue_free_head {
325 	vm_page_queue_head_t    qhead;
326 } VM_PAGE_PACKED_ALIGNED;
327 
328 struct vm_page_queue_free_head  vm_page_queue_free[MAX_COLORS];
329 
330 
331 unsigned int    vm_page_free_wanted;
332 unsigned int    vm_page_free_wanted_privileged;
333 #if CONFIG_SECLUDED_MEMORY
334 unsigned int    vm_page_free_wanted_secluded;
335 #endif /* CONFIG_SECLUDED_MEMORY */
336 unsigned int    vm_page_free_count;
337 
338 /*
339  *	Occasionally, the virtual memory system uses
340  *	resident page structures that do not refer to
341  *	real pages, for example to leave a page with
342  *	important state information in the VP table.
343  *
344  *	These page structures are allocated the way
345  *	most other kernel structures are.
346  */
347 SECURITY_READ_ONLY_LATE(zone_t) vm_page_zone;
348 vm_locks_array_t vm_page_locks;
349 
350 LCK_ATTR_DECLARE(vm_page_lck_attr, 0, 0);
351 LCK_GRP_DECLARE(vm_page_lck_grp_free, "vm_page_free");
352 LCK_GRP_DECLARE(vm_page_lck_grp_queue, "vm_page_queue");
353 LCK_GRP_DECLARE(vm_page_lck_grp_local, "vm_page_queue_local");
354 LCK_GRP_DECLARE(vm_page_lck_grp_purge, "vm_page_purge");
355 LCK_GRP_DECLARE(vm_page_lck_grp_alloc, "vm_page_alloc");
356 LCK_GRP_DECLARE(vm_page_lck_grp_bucket, "vm_page_bucket");
357 LCK_SPIN_DECLARE_ATTR(vm_objects_wired_lock, &vm_page_lck_grp_bucket, &vm_page_lck_attr);
358 LCK_SPIN_DECLARE_ATTR(vm_allocation_sites_lock, &vm_page_lck_grp_bucket, &vm_page_lck_attr);
359 
360 unsigned int    vm_page_local_q_soft_limit = 250;
361 unsigned int    vm_page_local_q_hard_limit = 500;
362 struct vpl     *__zpercpu vm_page_local_q;
363 
364 /* N.B. Guard and fictitious pages must not
365  * be assigned a zero phys_page value.
366  */
367 /*
368  *	Fictitious pages don't have a physical address,
369  *	but we must initialize phys_page to something.
370  *	For debugging, this should be a strange value
371  *	that the pmap module can recognize in assertions.
372  */
373 const ppnum_t vm_page_fictitious_addr = (ppnum_t) -1;
374 
375 /*
376  *	Guard pages are not accessible so they don't
377  *      need a physical address, but we need to enter
378  *	one in the pmap.
379  *	Let's make it recognizable and make sure that
380  *	we don't use a real physical page with that
381  *	physical address.
382  */
383 const ppnum_t vm_page_guard_addr = (ppnum_t) -2;
384 
385 /*
386  *	Resident page structures are also chained on
387  *	queues that are used by the page replacement
388  *	system (pageout daemon).  These queues are
389  *	defined here, but are shared by the pageout
390  *	module.  The inactive queue is broken into
391  *	file backed and anonymous for convenience as the
392  *	pageout daemon often assignes a higher
393  *	importance to anonymous pages (less likely to pick)
394  */
395 vm_page_queue_head_t    vm_page_queue_active VM_PAGE_PACKED_ALIGNED;
396 vm_page_queue_head_t    vm_page_queue_inactive VM_PAGE_PACKED_ALIGNED;
397 #if CONFIG_SECLUDED_MEMORY
398 vm_page_queue_head_t    vm_page_queue_secluded VM_PAGE_PACKED_ALIGNED;
399 #endif /* CONFIG_SECLUDED_MEMORY */
400 vm_page_queue_head_t    vm_page_queue_anonymous VM_PAGE_PACKED_ALIGNED;  /* inactive memory queue for anonymous pages */
401 vm_page_queue_head_t    vm_page_queue_throttled VM_PAGE_PACKED_ALIGNED;
402 
403 queue_head_t    vm_objects_wired;
404 
405 void vm_update_darkwake_mode(boolean_t);
406 
407 #if CONFIG_BACKGROUND_QUEUE
408 vm_page_queue_head_t    vm_page_queue_background VM_PAGE_PACKED_ALIGNED;
409 uint32_t        vm_page_background_target;
410 uint32_t        vm_page_background_target_snapshot;
411 uint32_t        vm_page_background_count;
412 uint64_t        vm_page_background_promoted_count;
413 
414 uint32_t        vm_page_background_internal_count;
415 uint32_t        vm_page_background_external_count;
416 
417 uint32_t        vm_page_background_mode;
418 uint32_t        vm_page_background_exclude_external;
419 #endif
420 
421 unsigned int    vm_page_active_count;
422 unsigned int    vm_page_inactive_count;
423 unsigned int    vm_page_kernelcache_count;
424 #if CONFIG_SECLUDED_MEMORY
425 unsigned int    vm_page_secluded_count;
426 unsigned int    vm_page_secluded_count_free;
427 unsigned int    vm_page_secluded_count_inuse;
428 unsigned int    vm_page_secluded_count_over_target;
429 #endif /* CONFIG_SECLUDED_MEMORY */
430 unsigned int    vm_page_anonymous_count;
431 unsigned int    vm_page_throttled_count;
432 unsigned int    vm_page_speculative_count;
433 
434 unsigned int    vm_page_wire_count;
435 unsigned int    vm_page_wire_count_on_boot = 0;
436 unsigned int    vm_page_stolen_count = 0;
437 unsigned int    vm_page_wire_count_initial;
438 unsigned int    vm_page_gobble_count = 0;
439 unsigned int    vm_page_kern_lpage_count = 0;
440 
441 uint64_t        booter_size;  /* external so it can be found in core dumps */
442 
443 #define VM_PAGE_WIRE_COUNT_WARNING      0
444 #define VM_PAGE_GOBBLE_COUNT_WARNING    0
445 
446 unsigned int    vm_page_purgeable_count = 0; /* # of pages purgeable now */
447 unsigned int    vm_page_purgeable_wired_count = 0; /* # of purgeable pages that are wired now */
448 uint64_t        vm_page_purged_count = 0;    /* total count of purged pages */
449 
450 unsigned int    vm_page_xpmapped_external_count = 0;
451 unsigned int    vm_page_external_count = 0;
452 unsigned int    vm_page_internal_count = 0;
453 unsigned int    vm_page_pageable_external_count = 0;
454 unsigned int    vm_page_pageable_internal_count = 0;
455 
456 #if DEVELOPMENT || DEBUG
457 unsigned int    vm_page_speculative_recreated = 0;
458 unsigned int    vm_page_speculative_created = 0;
459 unsigned int    vm_page_speculative_used = 0;
460 #endif
461 
462 vm_page_queue_head_t    vm_page_queue_cleaned VM_PAGE_PACKED_ALIGNED;
463 
464 unsigned int    vm_page_cleaned_count = 0;
465 
466 uint64_t        max_valid_dma_address = 0xffffffffffffffffULL;
467 ppnum_t         max_valid_low_ppnum = PPNUM_MAX;
468 
469 
470 /*
471  *	Several page replacement parameters are also
472  *	shared with this module, so that page allocation
473  *	(done here in vm_page_alloc) can trigger the
474  *	pageout daemon.
475  */
476 unsigned int    vm_page_free_target = 0;
477 unsigned int    vm_page_free_min = 0;
478 unsigned int    vm_page_throttle_limit = 0;
479 unsigned int    vm_page_inactive_target = 0;
480 #if CONFIG_SECLUDED_MEMORY
481 unsigned int    vm_page_secluded_target = 0;
482 #endif /* CONFIG_SECLUDED_MEMORY */
483 unsigned int    vm_page_anonymous_min = 0;
484 unsigned int    vm_page_free_reserved = 0;
485 
486 
487 /*
488  *	The VM system has a couple of heuristics for deciding
489  *	that pages are "uninteresting" and should be placed
490  *	on the inactive queue as likely candidates for replacement.
491  *	These variables let the heuristics be controlled at run-time
492  *	to make experimentation easier.
493  */
494 
495 boolean_t vm_page_deactivate_hint = TRUE;
496 
497 struct vm_page_stats_reusable vm_page_stats_reusable;
498 
499 /*
500  *	vm_set_page_size:
501  *
502  *	Sets the page size, perhaps based upon the memory
503  *	size.  Must be called before any use of page-size
504  *	dependent functions.
505  *
506  *	Sets page_shift and page_mask from page_size.
507  */
508 void
vm_set_page_size(void)509 vm_set_page_size(void)
510 {
511 	page_size  = PAGE_SIZE;
512 	page_mask  = PAGE_MASK;
513 	page_shift = PAGE_SHIFT;
514 
515 	if ((page_mask & page_size) != 0) {
516 		panic("vm_set_page_size: page size not a power of two");
517 	}
518 
519 	for (page_shift = 0;; page_shift++) {
520 		if ((1U << page_shift) == page_size) {
521 			break;
522 		}
523 	}
524 }
525 
526 #if defined (__x86_64__)
527 
528 #define MAX_CLUMP_SIZE      16
529 #define DEFAULT_CLUMP_SIZE  4
530 
531 unsigned int vm_clump_size, vm_clump_mask, vm_clump_shift, vm_clump_promote_threshold;
532 
533 #if DEVELOPMENT || DEBUG
534 unsigned long vm_clump_stats[MAX_CLUMP_SIZE + 1];
535 unsigned long vm_clump_allocs, vm_clump_inserts, vm_clump_inrange, vm_clump_promotes;
536 
537 static inline void
vm_clump_update_stats(unsigned int c)538 vm_clump_update_stats(unsigned int c)
539 {
540 	assert(c <= vm_clump_size);
541 	if (c > 0 && c <= vm_clump_size) {
542 		vm_clump_stats[c] += c;
543 	}
544 	vm_clump_allocs += c;
545 }
546 #endif  /*  if DEVELOPMENT || DEBUG */
547 
548 /* Called once to setup the VM clump knobs */
549 static void
vm_page_setup_clump(void)550 vm_page_setup_clump( void )
551 {
552 	unsigned int override, n;
553 
554 	vm_clump_size = DEFAULT_CLUMP_SIZE;
555 	if (PE_parse_boot_argn("clump_size", &override, sizeof(override))) {
556 		vm_clump_size = override;
557 	}
558 
559 	if (vm_clump_size > MAX_CLUMP_SIZE) {
560 		panic("vm_page_setup_clump:: clump_size is too large!");
561 	}
562 	if (vm_clump_size < 1) {
563 		panic("vm_page_setup_clump:: clump_size must be >= 1");
564 	}
565 	if ((vm_clump_size & (vm_clump_size - 1)) != 0) {
566 		panic("vm_page_setup_clump:: clump_size must be a power of 2");
567 	}
568 
569 	vm_clump_promote_threshold = vm_clump_size;
570 	vm_clump_mask = vm_clump_size - 1;
571 	for (vm_clump_shift = 0, n = vm_clump_size; n > 1; n >>= 1, vm_clump_shift++) {
572 		;
573 	}
574 
575 #if DEVELOPMENT || DEBUG
576 	bzero(vm_clump_stats, sizeof(vm_clump_stats));
577 	vm_clump_allocs = vm_clump_inserts = vm_clump_inrange = vm_clump_promotes = 0;
578 #endif  /*  if DEVELOPMENT || DEBUG */
579 }
580 
581 #endif  /* #if defined (__x86_64__) */
582 
583 #define COLOR_GROUPS_TO_STEAL   4
584 
585 /* Called once during statup, once the cache geometry is known.
586  */
587 static void
vm_page_set_colors(void)588 vm_page_set_colors( void )
589 {
590 	unsigned int    n, override;
591 
592 #if defined (__x86_64__)
593 	/* adjust #colors because we need to color outside the clump boundary */
594 	vm_cache_geometry_colors >>= vm_clump_shift;
595 #endif
596 	if (PE_parse_boot_argn("colors", &override, sizeof(override))) {                /* colors specified as a boot-arg? */
597 		n = override;
598 	} else if (vm_cache_geometry_colors) {                  /* do we know what the cache geometry is? */
599 		n = vm_cache_geometry_colors;
600 	} else {
601 		n = DEFAULT_COLORS;                             /* use default if all else fails */
602 	}
603 	if (n == 0) {
604 		n = 1;
605 	}
606 	if (n > MAX_COLORS) {
607 		n = MAX_COLORS;
608 	}
609 
610 	/* the count must be a power of 2  */
611 	if ((n & (n - 1)) != 0) {
612 		n = DEFAULT_COLORS;                             /* use default if all else fails */
613 	}
614 	vm_colors = n;
615 	vm_color_mask = n - 1;
616 
617 	vm_free_magazine_refill_limit = vm_colors * COLOR_GROUPS_TO_STEAL;
618 
619 #if defined (__x86_64__)
620 	/* adjust for reduction in colors due to clumping and multiple cores */
621 	if (real_ncpus) {
622 		vm_free_magazine_refill_limit *= (vm_clump_size * real_ncpus);
623 	}
624 #endif
625 }
626 
627 /*
628  * During single threaded early boot we don't initialize all pages.
629  * This avoids some delay during boot. They'll be initialized and
630  * added to the free list as needed or after we are multithreaded by
631  * what becomes the pageout thread.
632  */
633 static boolean_t fill = FALSE;
634 static unsigned int fillval;
635 uint_t vm_delayed_count = 0;    /* when non-zero, indicates we may have more pages to init */
636 ppnum_t delay_above_pnum = PPNUM_MAX;
637 
638 /*
639  * For x86 first 8 Gig initializes quickly and gives us lots of lowmem + mem above to start off with.
640  * If ARM ever uses delayed page initialization, this value may need to be quite different.
641  */
642 #define DEFAULT_DELAY_ABOVE_PHYS_GB (8)
643 
644 /*
645  * When we have to dip into more delayed pages due to low memory, free up
646  * a large chunk to get things back to normal. This avoids contention on the
647  * delayed code allocating page by page.
648  */
649 #define VM_DELAY_PAGE_CHUNK ((1024 * 1024 * 1024) / PAGE_SIZE)
650 
651 /*
652  * Get and initialize the next delayed page.
653  */
654 static vm_page_t
vm_get_delayed_page(int grab_options)655 vm_get_delayed_page(int grab_options)
656 {
657 	vm_page_t p;
658 	ppnum_t   pnum;
659 
660 	/*
661 	 * Get a new page if we have one.
662 	 */
663 	lck_mtx_lock(&vm_page_queue_free_lock);
664 	if (vm_delayed_count == 0) {
665 		lck_mtx_unlock(&vm_page_queue_free_lock);
666 		return NULL;
667 	}
668 	if (!pmap_next_page(&pnum)) {
669 		vm_delayed_count = 0;
670 		lck_mtx_unlock(&vm_page_queue_free_lock);
671 		return NULL;
672 	}
673 
674 	assert(vm_delayed_count > 0);
675 	--vm_delayed_count;
676 
677 #if defined(__x86_64__)
678 	/* x86 cluster code requires increasing phys_page in vm_pages[] */
679 	if (vm_pages_count > 0) {
680 		assert(pnum > vm_pages[vm_pages_count - 1].vmp_phys_page);
681 	}
682 #endif
683 	p = &vm_pages[vm_pages_count];
684 	assert(p < vm_page_array_ending_addr);
685 	vm_page_init(p, pnum, FALSE);
686 	++vm_pages_count;
687 	++vm_page_pages;
688 	lck_mtx_unlock(&vm_page_queue_free_lock);
689 
690 	/*
691 	 * These pages were initially counted as wired, undo that now.
692 	 */
693 	if (grab_options & VM_PAGE_GRAB_Q_LOCK_HELD) {
694 		LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
695 	} else {
696 		LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_NOTOWNED);
697 		vm_page_lockspin_queues();
698 	}
699 	--vm_page_wire_count;
700 	--vm_page_wire_count_initial;
701 	if (vm_page_wire_count_on_boot != 0) {
702 		--vm_page_wire_count_on_boot;
703 	}
704 	if (!(grab_options & VM_PAGE_GRAB_Q_LOCK_HELD)) {
705 		vm_page_unlock_queues();
706 	}
707 
708 
709 	if (fill) {
710 		fillPage(pnum, fillval);
711 	}
712 	return p;
713 }
714 
715 static void vm_page_module_init_delayed(void);
716 
717 /*
718  * Free all remaining delayed pages to the free lists.
719  */
720 void
vm_free_delayed_pages(void)721 vm_free_delayed_pages(void)
722 {
723 	vm_page_t   p;
724 	vm_page_t   list = NULL;
725 	uint_t      cnt = 0;
726 	vm_offset_t start_free_va;
727 	int64_t     free_size;
728 
729 	while ((p = vm_get_delayed_page(VM_PAGE_GRAB_OPTIONS_NONE)) != NULL) {
730 		if (vm_himemory_mode) {
731 			vm_page_release(p, FALSE);
732 		} else {
733 			p->vmp_snext = list;
734 			list = p;
735 		}
736 		++cnt;
737 	}
738 
739 	/*
740 	 * Free the pages in reverse order if not himemory mode.
741 	 * Hence the low memory pages will be first on free lists. (LIFO)
742 	 */
743 	while (list != NULL) {
744 		p = list;
745 		list = p->vmp_snext;
746 		p->vmp_snext = NULL;
747 		vm_page_release(p, FALSE);
748 	}
749 #if DEVELOPMENT || DEBUG
750 	kprintf("vm_free_delayed_pages: initialized %d free pages\n", cnt);
751 #endif
752 
753 	/*
754 	 * Free up any unused full pages at the end of the vm_pages[] array
755 	 */
756 	start_free_va = round_page((vm_offset_t)&vm_pages[vm_pages_count]);
757 
758 #if defined(__x86_64__)
759 	/*
760 	 * Since x86 might have used large pages for vm_pages[], we can't
761 	 * free starting in the middle of a partially used large page.
762 	 */
763 	if (pmap_query_pagesize(kernel_pmap, start_free_va) == I386_LPGBYTES) {
764 		start_free_va = ((start_free_va + I386_LPGMASK) & ~I386_LPGMASK);
765 	}
766 #endif
767 	if (start_free_va < (vm_offset_t)vm_page_array_ending_addr) {
768 		free_size = trunc_page((vm_offset_t)vm_page_array_ending_addr - start_free_va);
769 		if (free_size > 0) {
770 			ml_static_mfree(start_free_va, (vm_offset_t)free_size);
771 			vm_page_array_ending_addr = (void *)start_free_va;
772 
773 			/*
774 			 * Note there's no locking here, as only this thread will ever change this value.
775 			 * The reader, vm_page_diagnose, doesn't grab any locks for the counts it looks at.
776 			 */
777 			vm_page_stolen_count -= (free_size >> PAGE_SHIFT);
778 
779 #if DEVELOPMENT || DEBUG
780 			kprintf("Freeing final unused %ld bytes from vm_pages[] at 0x%lx\n",
781 			    (long)free_size, (long)start_free_va);
782 #endif
783 		}
784 	}
785 
786 
787 	/*
788 	 * now we can create the VM page array zone
789 	 */
790 	vm_page_module_init_delayed();
791 }
792 
793 /*
794  * Try and free up enough delayed pages to match a contig memory allocation.
795  */
796 static void
vm_free_delayed_pages_contig(uint_t npages,ppnum_t max_pnum,ppnum_t pnum_mask)797 vm_free_delayed_pages_contig(
798 	uint_t    npages,
799 	ppnum_t   max_pnum,
800 	ppnum_t   pnum_mask)
801 {
802 	vm_page_t p;
803 	ppnum_t   pnum;
804 	uint_t    cnt = 0;
805 
806 	/*
807 	 * Treat 0 as the absolute max page number.
808 	 */
809 	if (max_pnum == 0) {
810 		max_pnum = PPNUM_MAX;
811 	}
812 
813 	/*
814 	 * Free till we get a properly aligned start page
815 	 */
816 	for (;;) {
817 		p = vm_get_delayed_page(VM_PAGE_GRAB_OPTIONS_NONE);
818 		if (p == NULL) {
819 			return;
820 		}
821 		pnum = VM_PAGE_GET_PHYS_PAGE(p);
822 		vm_page_release(p, FALSE);
823 		if (pnum >= max_pnum) {
824 			return;
825 		}
826 		if ((pnum & pnum_mask) == 0) {
827 			break;
828 		}
829 	}
830 
831 	/*
832 	 * Having a healthy pool of free pages will help performance. We don't
833 	 * want to fall back to the delayed code for every page allocation.
834 	 */
835 	if (vm_page_free_count < VM_DELAY_PAGE_CHUNK) {
836 		npages += VM_DELAY_PAGE_CHUNK;
837 	}
838 
839 	/*
840 	 * Now free up the pages
841 	 */
842 	for (cnt = 1; cnt < npages; ++cnt) {
843 		p = vm_get_delayed_page(VM_PAGE_GRAB_OPTIONS_NONE);
844 		if (p == NULL) {
845 			return;
846 		}
847 		vm_page_release(p, FALSE);
848 	}
849 }
850 
851 #define ROUNDUP_NEXTP2(X) (1U << (32 - __builtin_clz((X) - 1)))
852 
853 void
vm_page_init_local_q(unsigned int num_cpus)854 vm_page_init_local_q(unsigned int num_cpus)
855 {
856 	struct vpl *t_local_q;
857 
858 	/*
859 	 * no point in this for a uni-processor system
860 	 */
861 	if (num_cpus >= 2) {
862 		ml_cpu_info_t cpu_info;
863 
864 		/*
865 		 * Force the allocation alignment to a cacheline,
866 		 * because the `vpl` struct has a lock and will be taken
867 		 * cross CPU so we want to isolate the rest of the per-CPU
868 		 * data to avoid false sharing due to this lock being taken.
869 		 */
870 
871 		ml_cpu_get_info(&cpu_info);
872 
873 		t_local_q = zalloc_percpu_permanent(sizeof(struct vpl),
874 		    cpu_info.cache_line_size - 1);
875 
876 		zpercpu_foreach(lq, t_local_q) {
877 			VPL_LOCK_INIT(lq, &vm_page_lck_grp_local, &vm_page_lck_attr);
878 			vm_page_queue_init(&lq->vpl_queue);
879 		}
880 
881 		/* make the initialization visible to all cores */
882 		os_atomic_store(&vm_page_local_q, t_local_q, release);
883 	}
884 }
885 
886 /*
887  * vm_init_before_launchd
888  *
889  * This should be called right before launchd is loaded.
890  */
891 void
vm_init_before_launchd()892 vm_init_before_launchd()
893 {
894 	vm_page_lockspin_queues();
895 	vm_page_wire_count_on_boot = vm_page_wire_count;
896 	vm_page_unlock_queues();
897 }
898 
899 
900 /*
901  *	vm_page_bootstrap:
902  *
903  *	Initializes the resident memory module.
904  *
905  *	Allocates memory for the page cells, and
906  *	for the object/offset-to-page hash table headers.
907  *	Each page cell is initialized and placed on the free list.
908  *	Returns the range of available kernel virtual memory.
909  */
910 __startup_func
911 void
vm_page_bootstrap(vm_offset_t * startp,vm_offset_t * endp)912 vm_page_bootstrap(
913 	vm_offset_t             *startp,
914 	vm_offset_t             *endp)
915 {
916 	unsigned int            i;
917 	unsigned int            log1;
918 	unsigned int            log2;
919 	unsigned int            size;
920 
921 	/*
922 	 *	Initialize the page queues.
923 	 */
924 
925 	lck_mtx_init_ext(&vm_page_queue_free_lock, &vm_page_queue_free_lock_ext, &vm_page_lck_grp_free, &vm_page_lck_attr);
926 	lck_mtx_init_ext(&vm_page_queue_lock, &vm_page_queue_lock_ext, &vm_page_lck_grp_queue, &vm_page_lck_attr);
927 	lck_mtx_init_ext(&vm_purgeable_queue_lock, &vm_purgeable_queue_lock_ext, &vm_page_lck_grp_purge, &vm_page_lck_attr);
928 
929 	for (i = 0; i < PURGEABLE_Q_TYPE_MAX; i++) {
930 		int group;
931 
932 		purgeable_queues[i].token_q_head = 0;
933 		purgeable_queues[i].token_q_tail = 0;
934 		for (group = 0; group < NUM_VOLATILE_GROUPS; group++) {
935 			queue_init(&purgeable_queues[i].objq[group]);
936 		}
937 
938 		purgeable_queues[i].type = i;
939 		purgeable_queues[i].new_pages = 0;
940 #if MACH_ASSERT
941 		purgeable_queues[i].debug_count_tokens = 0;
942 		purgeable_queues[i].debug_count_objects = 0;
943 #endif
944 	}
945 	;
946 	purgeable_nonvolatile_count = 0;
947 	queue_init(&purgeable_nonvolatile_queue);
948 
949 	for (i = 0; i < MAX_COLORS; i++) {
950 		vm_page_queue_init(&vm_page_queue_free[i].qhead);
951 	}
952 
953 	vm_page_queue_init(&vm_lopage_queue_free);
954 	vm_page_queue_init(&vm_page_queue_active);
955 	vm_page_queue_init(&vm_page_queue_inactive);
956 #if CONFIG_SECLUDED_MEMORY
957 	vm_page_queue_init(&vm_page_queue_secluded);
958 #endif /* CONFIG_SECLUDED_MEMORY */
959 	vm_page_queue_init(&vm_page_queue_cleaned);
960 	vm_page_queue_init(&vm_page_queue_throttled);
961 	vm_page_queue_init(&vm_page_queue_anonymous);
962 	queue_init(&vm_objects_wired);
963 
964 	for (i = 0; i <= VM_PAGE_MAX_SPECULATIVE_AGE_Q; i++) {
965 		vm_page_queue_init(&vm_page_queue_speculative[i].age_q);
966 
967 		vm_page_queue_speculative[i].age_ts.tv_sec = 0;
968 		vm_page_queue_speculative[i].age_ts.tv_nsec = 0;
969 	}
970 #if CONFIG_BACKGROUND_QUEUE
971 	vm_page_queue_init(&vm_page_queue_background);
972 
973 	vm_page_background_count = 0;
974 	vm_page_background_internal_count = 0;
975 	vm_page_background_external_count = 0;
976 	vm_page_background_promoted_count = 0;
977 
978 	vm_page_background_target = (unsigned int)(atop_64(max_mem) / 25);
979 
980 	if (vm_page_background_target > VM_PAGE_BACKGROUND_TARGET_MAX) {
981 		vm_page_background_target = VM_PAGE_BACKGROUND_TARGET_MAX;
982 	}
983 
984 	vm_page_background_mode = VM_PAGE_BG_LEVEL_1;
985 	vm_page_background_exclude_external = 0;
986 
987 	PE_parse_boot_argn("vm_page_bg_mode", &vm_page_background_mode, sizeof(vm_page_background_mode));
988 	PE_parse_boot_argn("vm_page_bg_exclude_external", &vm_page_background_exclude_external, sizeof(vm_page_background_exclude_external));
989 	PE_parse_boot_argn("vm_page_bg_target", &vm_page_background_target, sizeof(vm_page_background_target));
990 
991 	if (vm_page_background_mode > VM_PAGE_BG_LEVEL_1) {
992 		vm_page_background_mode = VM_PAGE_BG_LEVEL_1;
993 	}
994 #endif
995 	vm_page_free_wanted = 0;
996 	vm_page_free_wanted_privileged = 0;
997 #if CONFIG_SECLUDED_MEMORY
998 	vm_page_free_wanted_secluded = 0;
999 #endif /* CONFIG_SECLUDED_MEMORY */
1000 
1001 #if defined (__x86_64__)
1002 	/* this must be called before vm_page_set_colors() */
1003 	vm_page_setup_clump();
1004 #endif
1005 
1006 	vm_page_set_colors();
1007 
1008 	bzero(vm_page_inactive_states, sizeof(vm_page_inactive_states));
1009 	vm_page_inactive_states[VM_PAGE_ON_INACTIVE_INTERNAL_Q] = 1;
1010 	vm_page_inactive_states[VM_PAGE_ON_INACTIVE_EXTERNAL_Q] = 1;
1011 	vm_page_inactive_states[VM_PAGE_ON_INACTIVE_CLEANED_Q] = 1;
1012 
1013 	bzero(vm_page_pageable_states, sizeof(vm_page_pageable_states));
1014 	vm_page_pageable_states[VM_PAGE_ON_INACTIVE_INTERNAL_Q] = 1;
1015 	vm_page_pageable_states[VM_PAGE_ON_INACTIVE_EXTERNAL_Q] = 1;
1016 	vm_page_pageable_states[VM_PAGE_ON_INACTIVE_CLEANED_Q] = 1;
1017 	vm_page_pageable_states[VM_PAGE_ON_ACTIVE_Q] = 1;
1018 	vm_page_pageable_states[VM_PAGE_ON_SPECULATIVE_Q] = 1;
1019 	vm_page_pageable_states[VM_PAGE_ON_THROTTLED_Q] = 1;
1020 #if CONFIG_SECLUDED_MEMORY
1021 	vm_page_pageable_states[VM_PAGE_ON_SECLUDED_Q] = 1;
1022 #endif /* CONFIG_SECLUDED_MEMORY */
1023 
1024 	bzero(vm_page_non_speculative_pageable_states, sizeof(vm_page_non_speculative_pageable_states));
1025 	vm_page_non_speculative_pageable_states[VM_PAGE_ON_INACTIVE_INTERNAL_Q] = 1;
1026 	vm_page_non_speculative_pageable_states[VM_PAGE_ON_INACTIVE_EXTERNAL_Q] = 1;
1027 	vm_page_non_speculative_pageable_states[VM_PAGE_ON_INACTIVE_CLEANED_Q] = 1;
1028 	vm_page_non_speculative_pageable_states[VM_PAGE_ON_ACTIVE_Q] = 1;
1029 	vm_page_non_speculative_pageable_states[VM_PAGE_ON_THROTTLED_Q] = 1;
1030 #if CONFIG_SECLUDED_MEMORY
1031 	vm_page_non_speculative_pageable_states[VM_PAGE_ON_SECLUDED_Q] = 1;
1032 #endif /* CONFIG_SECLUDED_MEMORY */
1033 
1034 	bzero(vm_page_active_or_inactive_states, sizeof(vm_page_active_or_inactive_states));
1035 	vm_page_active_or_inactive_states[VM_PAGE_ON_INACTIVE_INTERNAL_Q] = 1;
1036 	vm_page_active_or_inactive_states[VM_PAGE_ON_INACTIVE_EXTERNAL_Q] = 1;
1037 	vm_page_active_or_inactive_states[VM_PAGE_ON_INACTIVE_CLEANED_Q] = 1;
1038 	vm_page_active_or_inactive_states[VM_PAGE_ON_ACTIVE_Q] = 1;
1039 #if CONFIG_SECLUDED_MEMORY
1040 	vm_page_active_or_inactive_states[VM_PAGE_ON_SECLUDED_Q] = 1;
1041 #endif /* CONFIG_SECLUDED_MEMORY */
1042 
1043 	for (vm_tag_t t = 0; t < VM_KERN_MEMORY_FIRST_DYNAMIC; t++) {
1044 		vm_allocation_sites_static[t].refcount = 2;
1045 		vm_allocation_sites_static[t].tag = t;
1046 		vm_allocation_sites[t] = &vm_allocation_sites_static[t];
1047 	}
1048 	vm_allocation_sites_static[VM_KERN_MEMORY_FIRST_DYNAMIC].refcount = 2;
1049 	vm_allocation_sites_static[VM_KERN_MEMORY_FIRST_DYNAMIC].tag = VM_KERN_MEMORY_ANY;
1050 	vm_allocation_sites[VM_KERN_MEMORY_ANY] = &vm_allocation_sites_static[VM_KERN_MEMORY_FIRST_DYNAMIC];
1051 
1052 	/*
1053 	 *	Steal memory for the map and zone subsystems.
1054 	 */
1055 	kernel_startup_initialize_upto(STARTUP_SUB_PMAP_STEAL);
1056 
1057 	/*
1058 	 *	Allocate (and initialize) the virtual-to-physical
1059 	 *	table hash buckets.
1060 	 *
1061 	 *	The number of buckets should be a power of two to
1062 	 *	get a good hash function.  The following computation
1063 	 *	chooses the first power of two that is greater
1064 	 *	than the number of physical pages in the system.
1065 	 */
1066 
1067 	if (vm_page_bucket_count == 0) {
1068 		unsigned int npages = pmap_free_pages();
1069 
1070 		vm_page_bucket_count = 1;
1071 		while (vm_page_bucket_count < npages) {
1072 			vm_page_bucket_count <<= 1;
1073 		}
1074 	}
1075 	vm_page_bucket_lock_count = (vm_page_bucket_count + BUCKETS_PER_LOCK - 1) / BUCKETS_PER_LOCK;
1076 
1077 	vm_page_hash_mask = vm_page_bucket_count - 1;
1078 
1079 	/*
1080 	 *	Calculate object shift value for hashing algorithm:
1081 	 *		O = log2(sizeof(struct vm_object))
1082 	 *		B = log2(vm_page_bucket_count)
1083 	 *	        hash shifts the object left by
1084 	 *		B/2 - O
1085 	 */
1086 	size = vm_page_bucket_count;
1087 	for (log1 = 0; size > 1; log1++) {
1088 		size /= 2;
1089 	}
1090 	size = sizeof(struct vm_object);
1091 	for (log2 = 0; size > 1; log2++) {
1092 		size /= 2;
1093 	}
1094 	vm_page_hash_shift = log1 / 2 - log2 + 1;
1095 
1096 	vm_page_bucket_hash = 1 << ((log1 + 1) >> 1);           /* Get (ceiling of sqrt of table size) */
1097 	vm_page_bucket_hash |= 1 << ((log1 + 1) >> 2);          /* Get (ceiling of quadroot of table size) */
1098 	vm_page_bucket_hash |= 1;                                                       /* Set bit and add 1 - always must be 1 to insure unique series */
1099 
1100 	if (vm_page_hash_mask & vm_page_bucket_count) {
1101 		printf("vm_page_bootstrap: WARNING -- strange page hash\n");
1102 	}
1103 
1104 #if VM_PAGE_BUCKETS_CHECK
1105 #if VM_PAGE_FAKE_BUCKETS
1106 	/*
1107 	 * Allocate a decoy set of page buckets, to detect
1108 	 * any stomping there.
1109 	 */
1110 	vm_page_fake_buckets = (vm_page_bucket_t *)
1111 	    pmap_steal_memory(vm_page_bucket_count *
1112 	    sizeof(vm_page_bucket_t));
1113 	vm_page_fake_buckets_start = (vm_map_offset_t) vm_page_fake_buckets;
1114 	vm_page_fake_buckets_end =
1115 	    vm_map_round_page((vm_page_fake_buckets_start +
1116 	    (vm_page_bucket_count *
1117 	    sizeof(vm_page_bucket_t))),
1118 	    PAGE_MASK);
1119 	char *cp;
1120 	for (cp = (char *)vm_page_fake_buckets_start;
1121 	    cp < (char *)vm_page_fake_buckets_end;
1122 	    cp++) {
1123 		*cp = 0x5a;
1124 	}
1125 #endif /* VM_PAGE_FAKE_BUCKETS */
1126 #endif /* VM_PAGE_BUCKETS_CHECK */
1127 
1128 	kernel_debug_string_early("vm_page_buckets");
1129 	vm_page_buckets = (vm_page_bucket_t *)
1130 	    pmap_steal_memory(vm_page_bucket_count *
1131 	    sizeof(vm_page_bucket_t));
1132 
1133 	kernel_debug_string_early("vm_page_bucket_locks");
1134 	vm_page_bucket_locks = (lck_spin_t *)
1135 	    pmap_steal_memory(vm_page_bucket_lock_count *
1136 	    sizeof(lck_spin_t));
1137 
1138 	for (i = 0; i < vm_page_bucket_count; i++) {
1139 		vm_page_bucket_t *bucket = &vm_page_buckets[i];
1140 
1141 		bucket->page_list = VM_PAGE_PACK_PTR(VM_PAGE_NULL);
1142 #if     MACH_PAGE_HASH_STATS
1143 		bucket->cur_count = 0;
1144 		bucket->hi_count = 0;
1145 #endif /* MACH_PAGE_HASH_STATS */
1146 	}
1147 
1148 	for (i = 0; i < vm_page_bucket_lock_count; i++) {
1149 		lck_spin_init(&vm_page_bucket_locks[i], &vm_page_lck_grp_bucket, &vm_page_lck_attr);
1150 	}
1151 
1152 	vm_tag_init();
1153 
1154 #if VM_PAGE_BUCKETS_CHECK
1155 	vm_page_buckets_check_ready = TRUE;
1156 #endif /* VM_PAGE_BUCKETS_CHECK */
1157 
1158 	/*
1159 	 *	Machine-dependent code allocates the resident page table.
1160 	 *	It uses vm_page_init to initialize the page frames.
1161 	 *	The code also returns to us the virtual space available
1162 	 *	to the kernel.  We don't trust the pmap module
1163 	 *	to get the alignment right.
1164 	 */
1165 
1166 	kernel_debug_string_early("pmap_startup");
1167 	pmap_startup(&virtual_space_start, &virtual_space_end);
1168 	virtual_space_start = round_page(virtual_space_start);
1169 	virtual_space_end = trunc_page(virtual_space_end);
1170 
1171 	*startp = virtual_space_start;
1172 	*endp = virtual_space_end;
1173 
1174 	/*
1175 	 *	Compute the initial "wire" count.
1176 	 *	Up until now, the pages which have been set aside are not under
1177 	 *	the VM system's control, so although they aren't explicitly
1178 	 *	wired, they nonetheless can't be moved. At this moment,
1179 	 *	all VM managed pages are "free", courtesy of pmap_startup.
1180 	 */
1181 	assert((unsigned int) atop_64(max_mem) == atop_64(max_mem));
1182 	vm_page_wire_count = ((unsigned int) atop_64(max_mem)) -
1183 	    vm_page_free_count - vm_lopage_free_count;
1184 #if CONFIG_SECLUDED_MEMORY
1185 	vm_page_wire_count -= vm_page_secluded_count;
1186 #endif
1187 	vm_page_wire_count_initial = vm_page_wire_count;
1188 
1189 	/* capture this for later use */
1190 	booter_size = ml_get_booter_memory_size();
1191 
1192 	printf("vm_page_bootstrap: %d free pages, %d wired pages, (up to %d of which are delayed free)\n",
1193 	    vm_page_free_count, vm_page_wire_count, vm_delayed_count);
1194 
1195 	kernel_debug_string_early("vm_page_bootstrap complete");
1196 }
1197 
1198 #ifndef MACHINE_PAGES
1199 /*
1200  * This is the early boot time allocator for data structures needed to bootstrap the VM system.
1201  * On x86 it will allocate large pages if size is sufficiently large. We don't need to do this
1202  * on ARM yet, due to the combination of a large base page size and smaller RAM devices.
1203  */
1204 static void *
pmap_steal_memory_internal(vm_size_t size,boolean_t might_free)1205 pmap_steal_memory_internal(
1206 	vm_size_t size,
1207 	boolean_t might_free)
1208 {
1209 	kern_return_t kr;
1210 	vm_offset_t addr;
1211 	vm_offset_t map_addr;
1212 	ppnum_t phys_page;
1213 
1214 	/*
1215 	 * Size needs to be aligned to word size.
1216 	 */
1217 	size = (size + sizeof(void *) - 1) & ~(sizeof(void *) - 1);
1218 
1219 	/*
1220 	 * On the first call, get the initial values for virtual address space
1221 	 * and page align them.
1222 	 */
1223 	if (virtual_space_start == virtual_space_end) {
1224 		pmap_virtual_space(&virtual_space_start, &virtual_space_end);
1225 		virtual_space_start = round_page(virtual_space_start);
1226 		virtual_space_end = trunc_page(virtual_space_end);
1227 
1228 #if defined(__x86_64__)
1229 		/*
1230 		 * Release remaining unused section of preallocated KVA and the 4K page tables
1231 		 * that map it. This makes the VA available for large page mappings.
1232 		 */
1233 		Idle_PTs_release(virtual_space_start, virtual_space_end);
1234 #endif
1235 	}
1236 
1237 	/*
1238 	 * Allocate the virtual space for this request. On x86, we'll align to a large page
1239 	 * address if the size is big enough to back with at least 1 large page.
1240 	 */
1241 #if defined(__x86_64__)
1242 	if (size >= I386_LPGBYTES) {
1243 		virtual_space_start = ((virtual_space_start + I386_LPGMASK) & ~I386_LPGMASK);
1244 	}
1245 #endif
1246 	addr = virtual_space_start;
1247 	virtual_space_start += size;
1248 
1249 	//kprintf("pmap_steal_memory: %08lX - %08lX; size=%08lX\n", (long)addr, (long)virtual_space_start, (long)size);	/* (TEST/DEBUG) */
1250 
1251 	/*
1252 	 * Allocate and map physical pages to back the new virtual space.
1253 	 */
1254 	map_addr = round_page(addr);
1255 	while (map_addr < addr + size) {
1256 #if defined(__x86_64__)
1257 		/*
1258 		 * Back with a large page if properly aligned on x86
1259 		 */
1260 		if ((map_addr & I386_LPGMASK) == 0 &&
1261 		    map_addr + I386_LPGBYTES <= addr + size &&
1262 		    pmap_pre_expand_large(kernel_pmap, map_addr) == KERN_SUCCESS &&
1263 		    pmap_next_page_large(&phys_page) == KERN_SUCCESS) {
1264 			kr = pmap_enter(kernel_pmap, map_addr, phys_page,
1265 			    VM_PROT_READ | VM_PROT_WRITE, VM_PROT_NONE,
1266 			    VM_WIMG_USE_DEFAULT | VM_MEM_SUPERPAGE, FALSE);
1267 
1268 			if (kr != KERN_SUCCESS) {
1269 				panic("pmap_steal_memory: pmap_enter() large failed, new_addr=%#lx, phys_page=%u",
1270 				    (unsigned long)map_addr, phys_page);
1271 			}
1272 			map_addr += I386_LPGBYTES;
1273 			vm_page_wire_count += I386_LPGBYTES >> PAGE_SHIFT;
1274 			vm_page_stolen_count += I386_LPGBYTES >> PAGE_SHIFT;
1275 			vm_page_kern_lpage_count++;
1276 			continue;
1277 		}
1278 #endif
1279 
1280 		if (!pmap_next_page_hi(&phys_page, might_free)) {
1281 			panic("pmap_steal_memory() size: 0x%llx", (uint64_t)size);
1282 		}
1283 
1284 #if defined(__x86_64__)
1285 		pmap_pre_expand(kernel_pmap, map_addr);
1286 #endif
1287 
1288 		kr = pmap_enter(kernel_pmap, map_addr, phys_page,
1289 		    VM_PROT_READ | VM_PROT_WRITE, VM_PROT_NONE,
1290 		    VM_WIMG_USE_DEFAULT, FALSE);
1291 
1292 		if (kr != KERN_SUCCESS) {
1293 			panic("pmap_steal_memory() pmap_enter failed, map_addr=%#lx, phys_page=%u",
1294 			    (unsigned long)map_addr, phys_page);
1295 		}
1296 		map_addr += PAGE_SIZE;
1297 
1298 		/*
1299 		 * Account for newly stolen memory
1300 		 */
1301 		vm_page_wire_count++;
1302 		vm_page_stolen_count++;
1303 	}
1304 
1305 #if defined(__x86_64__)
1306 	/*
1307 	 * The call with might_free is currently the last use of pmap_steal_memory*().
1308 	 * Notify the pmap layer to record which high pages were allocated so far.
1309 	 */
1310 	if (might_free) {
1311 		pmap_hi_pages_done();
1312 	}
1313 #endif
1314 #if KASAN
1315 	kasan_notify_address(round_page(addr), size);
1316 #endif
1317 	return (void *) addr;
1318 }
1319 
1320 void *
pmap_steal_memory(vm_size_t size)1321 pmap_steal_memory(
1322 	vm_size_t size)
1323 {
1324 	return pmap_steal_memory_internal(size, FALSE);
1325 }
1326 
1327 void *
pmap_steal_freeable_memory(vm_size_t size)1328 pmap_steal_freeable_memory(
1329 	vm_size_t size)
1330 {
1331 	return pmap_steal_memory_internal(size, TRUE);
1332 }
1333 
1334 #if defined(__arm64__)
1335 /*
1336  * Retire a page at startup.
1337  * These pages will eventually wind up on the retired_pages_object
1338  * in vm_retire_boot_pages().
1339  */
1340 static vm_page_queue_head_t vm_page_queue_retired VM_PAGE_PACKED_ALIGNED;
1341 static void
vm_page_retire_startup(vm_page_t p)1342 vm_page_retire_startup(vm_page_t p)
1343 {
1344 	p->vmp_q_state = VM_PAGE_NOT_ON_Q;
1345 	p->vmp_error = true;
1346 	p->vmp_unusual = true;
1347 	vm_page_queue_enter(&vm_page_queue_retired, p, vmp_pageq);
1348 	printf("To be retired at boot: page at 0x%llx\n", (long long)ptoa(VM_PAGE_GET_PHYS_PAGE(p)));
1349 }
1350 #endif /* defined(__arm64__) */
1351 
1352 #if CONFIG_SECLUDED_MEMORY
1353 /* boot-args to control secluded memory */
1354 unsigned int secluded_mem_mb = 0;       /* # of MBs of RAM to seclude */
1355 int secluded_for_iokit = 1;             /* IOKit can use secluded memory */
1356 int secluded_for_apps = 1;              /* apps can use secluded memory */
1357 int secluded_for_filecache = 2;         /* filecache can use seclude memory */
1358 #if 11
1359 int secluded_for_fbdp = 0;
1360 #endif
1361 uint64_t secluded_shutoff_trigger = 0;
1362 uint64_t secluded_shutoff_headroom = 150 * 1024 * 1024; /* original value from N56 */
1363 #endif /* CONFIG_SECLUDED_MEMORY */
1364 
1365 
1366 #if defined(__arm__) || defined(__arm64__)
1367 extern void patch_low_glo_vm_page_info(void *, void *, uint32_t);
1368 unsigned int vm_first_phys_ppnum = 0;
1369 #endif
1370 
1371 void vm_page_release_startup(vm_page_t mem);
1372 void
pmap_startup(vm_offset_t * startp,vm_offset_t * endp)1373 pmap_startup(
1374 	vm_offset_t     *startp,
1375 	vm_offset_t     *endp)
1376 {
1377 	unsigned int    i, npages;
1378 	ppnum_t         phys_page;
1379 	uint64_t        mem_sz;
1380 	uint64_t        start_ns;
1381 	uint64_t        now_ns;
1382 	uint_t          low_page_count = 0;
1383 
1384 #if    defined(__LP64__)
1385 	/*
1386 	 * make sure we are aligned on a 64 byte boundary
1387 	 * for VM_PAGE_PACK_PTR (it clips off the low-order
1388 	 * 6 bits of the pointer)
1389 	 */
1390 	if (virtual_space_start != virtual_space_end) {
1391 		virtual_space_start = round_page(virtual_space_start);
1392 	}
1393 #endif
1394 
1395 	/*
1396 	 * We calculate how many page frames we will have
1397 	 * and then allocate the page structures in one chunk.
1398 	 *
1399 	 * Note that the calculation here doesn't take into account
1400 	 * the memory needed to map what's being allocated, i.e. the page
1401 	 * table entries. So the actual number of pages we get will be
1402 	 * less than this. To do someday: include that in the computation.
1403 	 *
1404 	 * Also for ARM, we don't use the count of free_pages, but rather the
1405 	 * range from last page to first page (ignore holes due to retired pages).
1406 	 */
1407 #if defined(__arm__) || defined(__arm64__)
1408 	mem_sz = pmap_free_pages_span() * (uint64_t)PAGE_SIZE;
1409 #else /* defined(__arm__) || defined(__arm64__) */
1410 	mem_sz = pmap_free_pages() * (uint64_t)PAGE_SIZE;
1411 #endif /* defined(__arm__) || defined(__arm64__) */
1412 	mem_sz += round_page(virtual_space_start) - virtual_space_start;        /* Account for any slop */
1413 	npages = (uint_t)(mem_sz / (PAGE_SIZE + sizeof(*vm_pages)));    /* scaled to include the vm_page_ts */
1414 
1415 	vm_pages = (vm_page_t) pmap_steal_freeable_memory(npages * sizeof *vm_pages);
1416 
1417 	/*
1418 	 * Check if we want to initialize pages to a known value
1419 	 */
1420 	if (PE_parse_boot_argn("fill", &fillval, sizeof(fillval))) {
1421 		fill = TRUE;
1422 	}
1423 #if     DEBUG
1424 	/* This slows down booting the DEBUG kernel, particularly on
1425 	 * large memory systems, but is worthwhile in deterministically
1426 	 * trapping uninitialized memory usage.
1427 	 */
1428 	if (!fill) {
1429 		fill = TRUE;
1430 		fillval = 0xDEB8F177;
1431 	}
1432 #endif
1433 	if (fill) {
1434 		kprintf("Filling vm_pages with pattern: 0x%x\n", fillval);
1435 	}
1436 
1437 #if CONFIG_SECLUDED_MEMORY
1438 	/*
1439 	 * Figure out how much secluded memory to have before we start
1440 	 * release pages to free lists.
1441 	 * The default, if specified nowhere else, is no secluded mem.
1442 	 */
1443 	secluded_mem_mb = 0;
1444 	if (max_mem > 1 * 1024 * 1024 * 1024) {
1445 		/* default to 90MB for devices with > 1GB of RAM */
1446 		secluded_mem_mb = 90;
1447 	}
1448 	/* override with value from device tree, if provided */
1449 	PE_get_default("kern.secluded_mem_mb",
1450 	    &secluded_mem_mb, sizeof(secluded_mem_mb));
1451 	/* override with value from boot-args, if provided */
1452 	PE_parse_boot_argn("secluded_mem_mb",
1453 	    &secluded_mem_mb,
1454 	    sizeof(secluded_mem_mb));
1455 
1456 	vm_page_secluded_target = (unsigned int)
1457 	    ((secluded_mem_mb * 1024ULL * 1024ULL) / PAGE_SIZE);
1458 	PE_parse_boot_argn("secluded_for_iokit",
1459 	    &secluded_for_iokit,
1460 	    sizeof(secluded_for_iokit));
1461 	PE_parse_boot_argn("secluded_for_apps",
1462 	    &secluded_for_apps,
1463 	    sizeof(secluded_for_apps));
1464 	PE_parse_boot_argn("secluded_for_filecache",
1465 	    &secluded_for_filecache,
1466 	    sizeof(secluded_for_filecache));
1467 #if 11
1468 	PE_parse_boot_argn("secluded_for_fbdp",
1469 	    &secluded_for_fbdp,
1470 	    sizeof(secluded_for_fbdp));
1471 #endif
1472 
1473 	/*
1474 	 * Allow a really large app to effectively use secluded memory until it exits.
1475 	 */
1476 	if (vm_page_secluded_target != 0) {
1477 		/*
1478 		 * Get an amount from boot-args, else use 1/2 of max_mem.
1479 		 * 1/2 max_mem was chosen from a Peace daemon tentpole test which
1480 		 * used munch to induce jetsam thrashing of false idle daemons on N56.
1481 		 */
1482 		int secluded_shutoff_mb;
1483 		if (PE_parse_boot_argn("secluded_shutoff_mb", &secluded_shutoff_mb,
1484 		    sizeof(secluded_shutoff_mb))) {
1485 			secluded_shutoff_trigger = (uint64_t)secluded_shutoff_mb * 1024 * 1024;
1486 		} else {
1487 			secluded_shutoff_trigger = max_mem / 2;
1488 		}
1489 
1490 		/* ensure the headroom value is sensible and avoid underflows */
1491 		assert(secluded_shutoff_trigger == 0 || secluded_shutoff_trigger > secluded_shutoff_headroom);
1492 	}
1493 
1494 #endif /* CONFIG_SECLUDED_MEMORY */
1495 
1496 #if defined(__x86_64__)
1497 
1498 	/*
1499 	 * Decide how much memory we delay freeing at boot time.
1500 	 */
1501 	uint32_t delay_above_gb;
1502 	if (!PE_parse_boot_argn("delay_above_gb", &delay_above_gb, sizeof(delay_above_gb))) {
1503 		delay_above_gb = DEFAULT_DELAY_ABOVE_PHYS_GB;
1504 	}
1505 
1506 	if (delay_above_gb == 0) {
1507 		delay_above_pnum = PPNUM_MAX;
1508 	} else {
1509 		delay_above_pnum = delay_above_gb * (1024 * 1024 * 1024 / PAGE_SIZE);
1510 	}
1511 
1512 	/* make sure we have sane breathing room: 1G above low memory */
1513 	if (delay_above_pnum <= max_valid_low_ppnum) {
1514 		delay_above_pnum = max_valid_low_ppnum + ((1024 * 1024 * 1024) >> PAGE_SHIFT);
1515 	}
1516 
1517 	if (delay_above_pnum < PPNUM_MAX) {
1518 		printf("pmap_startup() delaying init/free of page nums > 0x%x\n", delay_above_pnum);
1519 	}
1520 
1521 #endif /* defined(__x86_64__) */
1522 
1523 	/*
1524 	 * Initialize and release the page frames.
1525 	 */
1526 	kernel_debug_string_early("page_frame_init");
1527 
1528 	vm_page_array_beginning_addr = &vm_pages[0];
1529 	vm_page_array_ending_addr = &vm_pages[npages];  /* used by ptr packing/unpacking code */
1530 #if VM_PAGE_PACKED_FROM_ARRAY
1531 	if (npages >= VM_PAGE_PACKED_FROM_ARRAY) {
1532 		panic("pmap_startup(): too many pages to support vm_page packing");
1533 	}
1534 #endif
1535 
1536 	vm_delayed_count = 0;
1537 #if defined(__arm64__)
1538 	vm_page_queue_init(&vm_page_queue_retired);
1539 #endif /* defined(__arm64__) */
1540 
1541 	absolutetime_to_nanoseconds(mach_absolute_time(), &start_ns);
1542 	vm_pages_count = 0;
1543 	for (i = 0; i < npages; i++) {
1544 		/* Did we run out of pages? */
1545 		if (!pmap_next_page(&phys_page)) {
1546 			break;
1547 		}
1548 
1549 		if (phys_page < max_valid_low_ppnum) {
1550 			++low_page_count;
1551 		}
1552 
1553 		/* Are we at high enough pages to delay the rest? */
1554 		if (low_page_count > vm_lopage_free_limit && phys_page > delay_above_pnum) {
1555 			vm_delayed_count = pmap_free_pages();
1556 			break;
1557 		}
1558 
1559 #if defined(__arm__) || defined(__arm64__)
1560 		if (i == 0) {
1561 			vm_first_phys_ppnum = phys_page;
1562 			patch_low_glo_vm_page_info((void *)vm_page_array_beginning_addr,
1563 			    (void *)vm_page_array_ending_addr, vm_first_phys_ppnum);
1564 #if defined(__arm64__)
1565 		} else {
1566 			/*
1567 			 * pmap_next_page() may skip over pages reported bad by iboot.
1568 			 */
1569 			while (i < phys_page - vm_first_phys_ppnum && i < npages) {
1570 				++vm_pages_count;
1571 				vm_page_init(&vm_pages[i], i + vm_first_phys_ppnum, FALSE);
1572 				vm_page_retire_startup(&vm_pages[i]);
1573 				++i;
1574 			}
1575 			if (i >= npages) {
1576 				break;
1577 			}
1578 			assert(i == phys_page - vm_first_phys_ppnum);
1579 #endif /* defined(__arm64__) */
1580 		}
1581 #endif /* defined(__arm__) || defined(__arm64__) */
1582 
1583 #if defined(__x86_64__)
1584 		/* The x86 clump freeing code requires increasing ppn's to work correctly */
1585 		if (i > 0) {
1586 			assert(phys_page > vm_pages[i - 1].vmp_phys_page);
1587 		}
1588 #endif
1589 		++vm_pages_count;
1590 		vm_page_init(&vm_pages[i], phys_page, FALSE);
1591 		if (fill) {
1592 			fillPage(phys_page, fillval);
1593 		}
1594 		if (vm_himemory_mode) {
1595 			vm_page_release_startup(&vm_pages[i]);
1596 		}
1597 	}
1598 	vm_page_pages = vm_pages_count; /* used to report to user space */
1599 
1600 	if (!vm_himemory_mode) {
1601 		do {
1602 			if (!vm_pages[--i].vmp_error) {               /* skip retired pages */
1603 				vm_page_release_startup(&vm_pages[i]);
1604 			}
1605 		} while (i != 0);
1606 	}
1607 
1608 	absolutetime_to_nanoseconds(mach_absolute_time(), &now_ns);
1609 	printf("pmap_startup() init/release time: %lld microsec\n", (now_ns - start_ns) / NSEC_PER_USEC);
1610 	printf("pmap_startup() delayed init/release of %d pages\n", vm_delayed_count);
1611 
1612 #if defined(__LP64__)
1613 	if ((vm_page_t)(VM_PAGE_UNPACK_PTR(VM_PAGE_PACK_PTR(&vm_pages[0]))) != &vm_pages[0]) {
1614 		panic("VM_PAGE_PACK_PTR failed on &vm_pages[0] - %p", (void *)&vm_pages[0]);
1615 	}
1616 
1617 	if ((vm_page_t)(VM_PAGE_UNPACK_PTR(VM_PAGE_PACK_PTR(&vm_pages[vm_pages_count - 1]))) != &vm_pages[vm_pages_count - 1]) {
1618 		panic("VM_PAGE_PACK_PTR failed on &vm_pages[vm_pages_count-1] - %p", (void *)&vm_pages[vm_pages_count - 1]);
1619 	}
1620 #endif
1621 
1622 	VM_CHECK_MEMORYSTATUS;
1623 
1624 	/*
1625 	 * We have to re-align virtual_space_start,
1626 	 * because pmap_steal_memory has been using it.
1627 	 */
1628 	virtual_space_start = round_page(virtual_space_start);
1629 	*startp = virtual_space_start;
1630 	*endp = virtual_space_end;
1631 }
1632 #endif  /* MACHINE_PAGES */
1633 
1634 /*
1635  * Create the zone that represents the vm_pages[] array. Nothing ever allocates
1636  * or frees to this zone. It's just here for reporting purposes via zprint command.
1637  * This needs to be done after all initially delayed pages are put on the free lists.
1638  */
1639 static void
vm_page_module_init_delayed(void)1640 vm_page_module_init_delayed(void)
1641 {
1642 	(void)zone_create_ext("vm pages array", sizeof(struct vm_page),
1643 	    ZC_NOGZALLOC, ZONE_ID_VM_PAGES, ^(zone_t z) {
1644 		uint64_t vm_page_zone_pages, vm_page_array_zone_data_size;
1645 
1646 		zone_set_exhaustible(z, 0);
1647 		/*
1648 		 * Reflect size and usage information for vm_pages[].
1649 		 */
1650 
1651 		z->z_elems_avail = (uint32_t)(vm_page_array_ending_addr - vm_pages);
1652 		z->z_elems_free = z->z_elems_avail - vm_pages_count;
1653 		zpercpu_get_cpu(z->z_stats, 0)->zs_mem_allocated =
1654 		vm_pages_count * sizeof(struct vm_page);
1655 		vm_page_array_zone_data_size = (uint64_t)vm_page_array_ending_addr - (uint64_t)vm_pages;
1656 		vm_page_zone_pages = atop(round_page((vm_offset_t)vm_page_array_zone_data_size));
1657 		z->z_wired_cur += vm_page_zone_pages;
1658 		z->z_wired_hwm = z->z_wired_cur;
1659 		z->z_va_cur = z->z_wired_cur;
1660 		/* since zone accounts for these, take them out of stolen */
1661 		VM_PAGE_MOVE_STOLEN(vm_page_zone_pages);
1662 	});
1663 }
1664 
1665 /*
1666  * Create the vm_pages zone. This is used for the vm_page structures for the pages
1667  * that are scavanged from other boot time usages by ml_static_mfree(). As such,
1668  * this needs to happen in early VM bootstrap.
1669  */
1670 
1671 __startup_func
1672 static void
vm_page_module_init(void)1673 vm_page_module_init(void)
1674 {
1675 	vm_size_t vm_page_with_ppnum_size;
1676 
1677 	/*
1678 	 * Since the pointers to elements in this zone will be packed, they
1679 	 * must have appropriate size. Not strictly what sizeof() reports.
1680 	 */
1681 	vm_page_with_ppnum_size =
1682 	    (sizeof(struct vm_page_with_ppnum) + (VM_PAGE_PACKED_PTR_ALIGNMENT - 1)) &
1683 	    ~(VM_PAGE_PACKED_PTR_ALIGNMENT - 1);
1684 
1685 	vm_page_zone = zone_create_ext("vm pages", vm_page_with_ppnum_size,
1686 	    ZC_NOGZALLOC | ZC_ALIGNMENT_REQUIRED | ZC_VM_LP64 | ZC_NOTBITAG,
1687 	    ZONE_ID_ANY, ^(zone_t z) {
1688 		/*
1689 		 * The number "10" is a small number that is larger than the number
1690 		 * of fictitious pages that any single caller will attempt to allocate
1691 		 * without blocking.
1692 		 *
1693 		 * The largest such number at the moment is kernel_memory_allocate()
1694 		 * when 2 guard pages are asked. 10 is simply a somewhat larger number,
1695 		 * taking into account the 50% hysteresis the zone allocator uses.
1696 		 *
1697 		 * Note: this works at all because the zone allocator
1698 		 *       doesn't ever allocate fictitious pages.
1699 		 */
1700 		z->z_elems_rsv = 10;
1701 	});
1702 }
1703 STARTUP(ZALLOC, STARTUP_RANK_SECOND, vm_page_module_init);
1704 
1705 /*
1706  *	Routine:	vm_page_create
1707  *	Purpose:
1708  *		After the VM system is up, machine-dependent code
1709  *		may stumble across more physical memory.  For example,
1710  *		memory that it was reserving for a frame buffer.
1711  *		vm_page_create turns this memory into available pages.
1712  */
1713 
1714 void
vm_page_create(ppnum_t start,ppnum_t end)1715 vm_page_create(
1716 	ppnum_t start,
1717 	ppnum_t end)
1718 {
1719 	ppnum_t         phys_page;
1720 	vm_page_t       m;
1721 
1722 	for (phys_page = start;
1723 	    phys_page < end;
1724 	    phys_page++) {
1725 		m = vm_page_grab_fictitious_common(phys_page, TRUE);
1726 		m->vmp_fictitious = FALSE;
1727 		pmap_clear_noencrypt(phys_page);
1728 
1729 		lck_mtx_lock(&vm_page_queue_free_lock);
1730 		vm_page_pages++;
1731 		lck_mtx_unlock(&vm_page_queue_free_lock);
1732 		vm_page_release(m, FALSE);
1733 	}
1734 }
1735 
1736 #if defined(__arm64__)
1737 /*
1738  * Like vm_page_create(), except we want to immediately retire the page,
1739  * not put it on the free list.
1740  */
1741 void
vm_page_create_retired(ppnum_t phys_page)1742 vm_page_create_retired(
1743 	ppnum_t   phys_page)
1744 {
1745 	vm_page_t m;
1746 
1747 	m = vm_page_grab_fictitious_common(phys_page, TRUE);
1748 	m->vmp_fictitious = FALSE;
1749 	pmap_clear_noencrypt(phys_page);
1750 	m->vmp_error = true;
1751 	m->vmp_unusual = true;
1752 	vm_page_lock_queues();
1753 	m->vmp_q_state = VM_PAGE_IS_WIRED;
1754 	m->vmp_wire_count++;
1755 	vm_page_unlock_queues();
1756 
1757 	lck_mtx_lock(&vm_page_queue_free_lock);
1758 	vm_page_pages++;
1759 	lck_mtx_unlock(&vm_page_queue_free_lock);
1760 
1761 	vm_object_lock(retired_pages_object);
1762 	vm_page_insert_wired(m, retired_pages_object, ptoa(VM_PAGE_GET_PHYS_PAGE(m)), VM_KERN_MEMORY_RETIRED);
1763 	vm_object_unlock(retired_pages_object);
1764 	pmap_retire_page(VM_PAGE_GET_PHYS_PAGE(m));
1765 }
1766 #endif /* defined(__arm64__) */
1767 
1768 /*
1769  *	vm_page_hash:
1770  *
1771  *	Distributes the object/offset key pair among hash buckets.
1772  *
1773  *	NOTE:	The bucket count must be a power of 2
1774  */
1775 #define vm_page_hash(object, offset) (\
1776 	( (natural_t)((uintptr_t)object * vm_page_bucket_hash) + ((uint32_t)atop_64(offset) ^ vm_page_bucket_hash))\
1777 	 & vm_page_hash_mask)
1778 
1779 
1780 /*
1781  *	vm_page_insert:		[ internal use only ]
1782  *
1783  *	Inserts the given mem entry into the object/object-page
1784  *	table and object list.
1785  *
1786  *	The object must be locked.
1787  */
1788 void
vm_page_insert(vm_page_t mem,vm_object_t object,vm_object_offset_t offset)1789 vm_page_insert(
1790 	vm_page_t               mem,
1791 	vm_object_t             object,
1792 	vm_object_offset_t      offset)
1793 {
1794 	vm_page_insert_internal(mem, object, offset, VM_KERN_MEMORY_NONE, FALSE, TRUE, FALSE, FALSE, NULL);
1795 }
1796 
1797 void
vm_page_insert_wired(vm_page_t mem,vm_object_t object,vm_object_offset_t offset,vm_tag_t tag)1798 vm_page_insert_wired(
1799 	vm_page_t               mem,
1800 	vm_object_t             object,
1801 	vm_object_offset_t      offset,
1802 	vm_tag_t                tag)
1803 {
1804 	vm_page_insert_internal(mem, object, offset, tag, FALSE, TRUE, FALSE, FALSE, NULL);
1805 }
1806 
1807 void
vm_page_insert_internal(vm_page_t mem,vm_object_t object,vm_object_offset_t offset,vm_tag_t tag,boolean_t queues_lock_held,boolean_t insert_in_hash,boolean_t batch_pmap_op,boolean_t batch_accounting,uint64_t * delayed_ledger_update)1808 vm_page_insert_internal(
1809 	vm_page_t               mem,
1810 	vm_object_t             object,
1811 	vm_object_offset_t      offset,
1812 	vm_tag_t                tag,
1813 	boolean_t               queues_lock_held,
1814 	boolean_t               insert_in_hash,
1815 	boolean_t               batch_pmap_op,
1816 	boolean_t               batch_accounting,
1817 	uint64_t                *delayed_ledger_update)
1818 {
1819 	vm_page_bucket_t        *bucket;
1820 	lck_spin_t              *bucket_lock;
1821 	int                     hash_id;
1822 	task_t                  owner;
1823 	int                     ledger_idx_volatile;
1824 	int                     ledger_idx_nonvolatile;
1825 	int                     ledger_idx_volatile_compressed;
1826 	int                     ledger_idx_nonvolatile_compressed;
1827 	boolean_t               do_footprint;
1828 
1829 #if 0
1830 	/*
1831 	 * we may not hold the page queue lock
1832 	 * so this check isn't safe to make
1833 	 */
1834 	VM_PAGE_CHECK(mem);
1835 #endif
1836 
1837 	assertf(page_aligned(offset), "0x%llx\n", offset);
1838 
1839 	assert(!VM_PAGE_WIRED(mem) || mem->vmp_private || mem->vmp_fictitious || (tag != VM_KERN_MEMORY_NONE));
1840 
1841 	/* the vm_submap_object is only a placeholder for submaps */
1842 	assert(object != vm_submap_object);
1843 
1844 	vm_object_lock_assert_exclusive(object);
1845 	LCK_MTX_ASSERT(&vm_page_queue_lock,
1846 	    queues_lock_held ? LCK_MTX_ASSERT_OWNED
1847 	    : LCK_MTX_ASSERT_NOTOWNED);
1848 
1849 	if (queues_lock_held == FALSE) {
1850 		assert(!VM_PAGE_PAGEABLE(mem));
1851 	}
1852 
1853 	if (insert_in_hash == TRUE) {
1854 #if DEBUG || VM_PAGE_BUCKETS_CHECK
1855 		if (mem->vmp_tabled || mem->vmp_object) {
1856 			panic("vm_page_insert: page %p for (obj=%p,off=0x%llx) "
1857 			    "already in (obj=%p,off=0x%llx)",
1858 			    mem, object, offset, VM_PAGE_OBJECT(mem), mem->vmp_offset);
1859 		}
1860 #endif
1861 		if (object->internal && (offset >= object->vo_size)) {
1862 			panic("vm_page_insert_internal: (page=%p,obj=%p,off=0x%llx,size=0x%llx) inserted at offset past object bounds",
1863 			    mem, object, offset, object->vo_size);
1864 		}
1865 
1866 		assert(vm_page_lookup(object, offset) == VM_PAGE_NULL);
1867 
1868 		/*
1869 		 *	Record the object/offset pair in this page
1870 		 */
1871 
1872 		mem->vmp_object = VM_PAGE_PACK_OBJECT(object);
1873 		mem->vmp_offset = offset;
1874 
1875 #if CONFIG_SECLUDED_MEMORY
1876 		if (object->eligible_for_secluded) {
1877 			vm_page_secluded.eligible_for_secluded++;
1878 		}
1879 #endif /* CONFIG_SECLUDED_MEMORY */
1880 
1881 		/*
1882 		 *	Insert it into the object_object/offset hash table
1883 		 */
1884 		hash_id = vm_page_hash(object, offset);
1885 		bucket = &vm_page_buckets[hash_id];
1886 		bucket_lock = &vm_page_bucket_locks[hash_id / BUCKETS_PER_LOCK];
1887 
1888 		lck_spin_lock_grp(bucket_lock, &vm_page_lck_grp_bucket);
1889 
1890 		mem->vmp_next_m = bucket->page_list;
1891 		bucket->page_list = VM_PAGE_PACK_PTR(mem);
1892 		assert(mem == (vm_page_t)(VM_PAGE_UNPACK_PTR(bucket->page_list)));
1893 
1894 #if     MACH_PAGE_HASH_STATS
1895 		if (++bucket->cur_count > bucket->hi_count) {
1896 			bucket->hi_count = bucket->cur_count;
1897 		}
1898 #endif /* MACH_PAGE_HASH_STATS */
1899 		mem->vmp_hashed = TRUE;
1900 		lck_spin_unlock(bucket_lock);
1901 	}
1902 
1903 	{
1904 		unsigned int    cache_attr;
1905 
1906 		cache_attr = object->wimg_bits & VM_WIMG_MASK;
1907 
1908 		if (cache_attr != VM_WIMG_USE_DEFAULT) {
1909 			PMAP_SET_CACHE_ATTR(mem, object, cache_attr, batch_pmap_op);
1910 		}
1911 	}
1912 	/*
1913 	 *	Now link into the object's list of backed pages.
1914 	 */
1915 	vm_page_queue_enter(&object->memq, mem, vmp_listq);
1916 	object->memq_hint = mem;
1917 	mem->vmp_tabled = TRUE;
1918 
1919 	/*
1920 	 *	Show that the object has one more resident page.
1921 	 */
1922 
1923 	object->resident_page_count++;
1924 	if (VM_PAGE_WIRED(mem)) {
1925 		assert(mem->vmp_wire_count > 0);
1926 		VM_OBJECT_WIRED_PAGE_UPDATE_START(object);
1927 		VM_OBJECT_WIRED_PAGE_ADD(object, mem);
1928 		VM_OBJECT_WIRED_PAGE_UPDATE_END(object, tag);
1929 	}
1930 	assert(object->resident_page_count >= object->wired_page_count);
1931 
1932 #if DEVELOPMENT || DEBUG
1933 	if (object->object_is_shared_cache &&
1934 	    object->pager != NULL &&
1935 	    object->pager->mo_pager_ops == &shared_region_pager_ops) {
1936 		int new, old;
1937 		assert(!object->internal);
1938 		new = OSAddAtomic(+1, &shared_region_pagers_resident_count);
1939 		do {
1940 			old = shared_region_pagers_resident_peak;
1941 		} while (old < new &&
1942 		    !OSCompareAndSwap(old, new, &shared_region_pagers_resident_peak));
1943 	}
1944 #endif /* DEVELOPMENT || DEBUG */
1945 
1946 	if (batch_accounting == FALSE) {
1947 		if (object->internal) {
1948 			OSAddAtomic(1, &vm_page_internal_count);
1949 		} else {
1950 			OSAddAtomic(1, &vm_page_external_count);
1951 		}
1952 	}
1953 
1954 	/*
1955 	 * It wouldn't make sense to insert a "reusable" page in
1956 	 * an object (the page would have been marked "reusable" only
1957 	 * at the time of a madvise(MADV_FREE_REUSABLE) if it was already
1958 	 * in the object at that time).
1959 	 * But a page could be inserted in a "all_reusable" object, if
1960 	 * something faults it in (a vm_read() from another task or a
1961 	 * "use-after-free" issue in user space, for example).  It can
1962 	 * also happen if we're relocating a page from that object to
1963 	 * a different physical page during a physically-contiguous
1964 	 * allocation.
1965 	 */
1966 	assert(!mem->vmp_reusable);
1967 	if (object->all_reusable) {
1968 		OSAddAtomic(+1, &vm_page_stats_reusable.reusable_count);
1969 	}
1970 
1971 	if (object->purgable == VM_PURGABLE_DENY &&
1972 	    !object->vo_ledger_tag) {
1973 		owner = TASK_NULL;
1974 	} else {
1975 		owner = VM_OBJECT_OWNER(object);
1976 		vm_object_ledger_tag_ledgers(object,
1977 		    &ledger_idx_volatile,
1978 		    &ledger_idx_nonvolatile,
1979 		    &ledger_idx_volatile_compressed,
1980 		    &ledger_idx_nonvolatile_compressed,
1981 		    &do_footprint);
1982 	}
1983 	if (owner &&
1984 	    (object->purgable == VM_PURGABLE_NONVOLATILE ||
1985 	    object->purgable == VM_PURGABLE_DENY ||
1986 	    VM_PAGE_WIRED(mem))) {
1987 		if (delayed_ledger_update) {
1988 			*delayed_ledger_update += PAGE_SIZE;
1989 		} else {
1990 			/* more non-volatile bytes */
1991 			ledger_credit(owner->ledger,
1992 			    ledger_idx_nonvolatile,
1993 			    PAGE_SIZE);
1994 			if (do_footprint) {
1995 				/* more footprint */
1996 				ledger_credit(owner->ledger,
1997 				    task_ledgers.phys_footprint,
1998 				    PAGE_SIZE);
1999 			}
2000 		}
2001 	} else if (owner &&
2002 	    (object->purgable == VM_PURGABLE_VOLATILE ||
2003 	    object->purgable == VM_PURGABLE_EMPTY)) {
2004 		assert(!VM_PAGE_WIRED(mem));
2005 		/* more volatile bytes */
2006 		ledger_credit(owner->ledger,
2007 		    ledger_idx_volatile,
2008 		    PAGE_SIZE);
2009 	}
2010 
2011 	if (object->purgable == VM_PURGABLE_VOLATILE) {
2012 		if (VM_PAGE_WIRED(mem)) {
2013 			OSAddAtomic(+1, &vm_page_purgeable_wired_count);
2014 		} else {
2015 			OSAddAtomic(+1, &vm_page_purgeable_count);
2016 		}
2017 	} else if (object->purgable == VM_PURGABLE_EMPTY &&
2018 	    mem->vmp_q_state == VM_PAGE_ON_THROTTLED_Q) {
2019 		/*
2020 		 * This page belongs to a purged VM object but hasn't
2021 		 * been purged (because it was "busy").
2022 		 * It's in the "throttled" queue and hence not
2023 		 * visible to vm_pageout_scan().  Move it to a pageable
2024 		 * queue, so that it can eventually be reclaimed, instead
2025 		 * of lingering in the "empty" object.
2026 		 */
2027 		if (queues_lock_held == FALSE) {
2028 			vm_page_lockspin_queues();
2029 		}
2030 		vm_page_deactivate(mem);
2031 		if (queues_lock_held == FALSE) {
2032 			vm_page_unlock_queues();
2033 		}
2034 	}
2035 
2036 #if VM_OBJECT_TRACKING_OP_MODIFIED
2037 	if (vm_object_tracking_btlog &&
2038 	    object->internal &&
2039 	    object->resident_page_count == 0 &&
2040 	    object->pager == NULL &&
2041 	    object->shadow != NULL &&
2042 	    object->shadow->copy == object) {
2043 		btlog_record(vm_object_tracking_btlog, object,
2044 		    VM_OBJECT_TRACKING_OP_MODIFIED,
2045 		    btref_get(__builtin_frame_address(0), 0));
2046 	}
2047 #endif /* VM_OBJECT_TRACKING_OP_MODIFIED */
2048 }
2049 
2050 /*
2051  *	vm_page_replace:
2052  *
2053  *	Exactly like vm_page_insert, except that we first
2054  *	remove any existing page at the given offset in object.
2055  *
2056  *	The object must be locked.
2057  */
2058 void
vm_page_replace(vm_page_t mem,vm_object_t object,vm_object_offset_t offset)2059 vm_page_replace(
2060 	vm_page_t               mem,
2061 	vm_object_t             object,
2062 	vm_object_offset_t      offset)
2063 {
2064 	vm_page_bucket_t *bucket;
2065 	vm_page_t        found_m = VM_PAGE_NULL;
2066 	lck_spin_t      *bucket_lock;
2067 	int             hash_id;
2068 
2069 #if 0
2070 	/*
2071 	 * we don't hold the page queue lock
2072 	 * so this check isn't safe to make
2073 	 */
2074 	VM_PAGE_CHECK(mem);
2075 #endif
2076 	vm_object_lock_assert_exclusive(object);
2077 #if DEBUG || VM_PAGE_BUCKETS_CHECK
2078 	if (mem->vmp_tabled || mem->vmp_object) {
2079 		panic("vm_page_replace: page %p for (obj=%p,off=0x%llx) "
2080 		    "already in (obj=%p,off=0x%llx)",
2081 		    mem, object, offset, VM_PAGE_OBJECT(mem), mem->vmp_offset);
2082 	}
2083 #endif
2084 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_NOTOWNED);
2085 
2086 	assert(!VM_PAGE_PAGEABLE(mem));
2087 
2088 	/*
2089 	 *	Record the object/offset pair in this page
2090 	 */
2091 	mem->vmp_object = VM_PAGE_PACK_OBJECT(object);
2092 	mem->vmp_offset = offset;
2093 
2094 	/*
2095 	 *	Insert it into the object_object/offset hash table,
2096 	 *	replacing any page that might have been there.
2097 	 */
2098 
2099 	hash_id = vm_page_hash(object, offset);
2100 	bucket = &vm_page_buckets[hash_id];
2101 	bucket_lock = &vm_page_bucket_locks[hash_id / BUCKETS_PER_LOCK];
2102 
2103 	lck_spin_lock_grp(bucket_lock, &vm_page_lck_grp_bucket);
2104 
2105 	if (bucket->page_list) {
2106 		vm_page_packed_t *mp = &bucket->page_list;
2107 		vm_page_t m = (vm_page_t)(VM_PAGE_UNPACK_PTR(*mp));
2108 
2109 		do {
2110 			/*
2111 			 * compare packed object pointers
2112 			 */
2113 			if (m->vmp_object == mem->vmp_object && m->vmp_offset == offset) {
2114 				/*
2115 				 * Remove old page from hash list
2116 				 */
2117 				*mp = m->vmp_next_m;
2118 				m->vmp_hashed = FALSE;
2119 				m->vmp_next_m = VM_PAGE_PACK_PTR(NULL);
2120 
2121 				found_m = m;
2122 				break;
2123 			}
2124 			mp = &m->vmp_next_m;
2125 		} while ((m = (vm_page_t)(VM_PAGE_UNPACK_PTR(*mp))));
2126 
2127 		mem->vmp_next_m = bucket->page_list;
2128 	} else {
2129 		mem->vmp_next_m = VM_PAGE_PACK_PTR(NULL);
2130 	}
2131 	/*
2132 	 * insert new page at head of hash list
2133 	 */
2134 	bucket->page_list = VM_PAGE_PACK_PTR(mem);
2135 	mem->vmp_hashed = TRUE;
2136 
2137 	lck_spin_unlock(bucket_lock);
2138 
2139 	if (found_m) {
2140 		/*
2141 		 * there was already a page at the specified
2142 		 * offset for this object... remove it from
2143 		 * the object and free it back to the free list
2144 		 */
2145 		vm_page_free_unlocked(found_m, FALSE);
2146 	}
2147 	vm_page_insert_internal(mem, object, offset, VM_KERN_MEMORY_NONE, FALSE, FALSE, FALSE, FALSE, NULL);
2148 }
2149 
2150 /*
2151  *	vm_page_remove:		[ internal use only ]
2152  *
2153  *	Removes the given mem entry from the object/offset-page
2154  *	table and the object page list.
2155  *
2156  *	The object must be locked.
2157  */
2158 
2159 void
vm_page_remove(vm_page_t mem,boolean_t remove_from_hash)2160 vm_page_remove(
2161 	vm_page_t       mem,
2162 	boolean_t       remove_from_hash)
2163 {
2164 	vm_page_bucket_t *bucket;
2165 	vm_page_t       this;
2166 	lck_spin_t      *bucket_lock;
2167 	int             hash_id;
2168 	task_t          owner;
2169 	vm_object_t     m_object;
2170 	int             ledger_idx_volatile;
2171 	int             ledger_idx_nonvolatile;
2172 	int             ledger_idx_volatile_compressed;
2173 	int             ledger_idx_nonvolatile_compressed;
2174 	int             do_footprint;
2175 
2176 	m_object = VM_PAGE_OBJECT(mem);
2177 
2178 	vm_object_lock_assert_exclusive(m_object);
2179 	assert(mem->vmp_tabled);
2180 	assert(!mem->vmp_cleaning);
2181 	assert(!mem->vmp_laundry);
2182 
2183 	if (VM_PAGE_PAGEABLE(mem)) {
2184 		LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
2185 	}
2186 #if 0
2187 	/*
2188 	 * we don't hold the page queue lock
2189 	 * so this check isn't safe to make
2190 	 */
2191 	VM_PAGE_CHECK(mem);
2192 #endif
2193 	if (remove_from_hash == TRUE) {
2194 		/*
2195 		 *	Remove from the object_object/offset hash table
2196 		 */
2197 		hash_id = vm_page_hash(m_object, mem->vmp_offset);
2198 		bucket = &vm_page_buckets[hash_id];
2199 		bucket_lock = &vm_page_bucket_locks[hash_id / BUCKETS_PER_LOCK];
2200 
2201 		lck_spin_lock_grp(bucket_lock, &vm_page_lck_grp_bucket);
2202 
2203 		if ((this = (vm_page_t)(VM_PAGE_UNPACK_PTR(bucket->page_list))) == mem) {
2204 			/* optimize for common case */
2205 
2206 			bucket->page_list = mem->vmp_next_m;
2207 		} else {
2208 			vm_page_packed_t        *prev;
2209 
2210 			for (prev = &this->vmp_next_m;
2211 			    (this = (vm_page_t)(VM_PAGE_UNPACK_PTR(*prev))) != mem;
2212 			    prev = &this->vmp_next_m) {
2213 				continue;
2214 			}
2215 			*prev = this->vmp_next_m;
2216 		}
2217 #if     MACH_PAGE_HASH_STATS
2218 		bucket->cur_count--;
2219 #endif /* MACH_PAGE_HASH_STATS */
2220 		mem->vmp_hashed = FALSE;
2221 		this->vmp_next_m = VM_PAGE_PACK_PTR(NULL);
2222 		lck_spin_unlock(bucket_lock);
2223 	}
2224 	/*
2225 	 *	Now remove from the object's list of backed pages.
2226 	 */
2227 
2228 	vm_page_remove_internal(mem);
2229 
2230 	/*
2231 	 *	And show that the object has one fewer resident
2232 	 *	page.
2233 	 */
2234 
2235 	assert(m_object->resident_page_count > 0);
2236 	m_object->resident_page_count--;
2237 
2238 #if DEVELOPMENT || DEBUG
2239 	if (m_object->object_is_shared_cache &&
2240 	    m_object->pager != NULL &&
2241 	    m_object->pager->mo_pager_ops == &shared_region_pager_ops) {
2242 		assert(!m_object->internal);
2243 		OSAddAtomic(-1, &shared_region_pagers_resident_count);
2244 	}
2245 #endif /* DEVELOPMENT || DEBUG */
2246 
2247 	if (m_object->internal) {
2248 #if DEBUG
2249 		assert(vm_page_internal_count);
2250 #endif /* DEBUG */
2251 
2252 		OSAddAtomic(-1, &vm_page_internal_count);
2253 	} else {
2254 		assert(vm_page_external_count);
2255 		OSAddAtomic(-1, &vm_page_external_count);
2256 
2257 		if (mem->vmp_xpmapped) {
2258 			assert(vm_page_xpmapped_external_count);
2259 			OSAddAtomic(-1, &vm_page_xpmapped_external_count);
2260 		}
2261 	}
2262 	if (!m_object->internal &&
2263 	    m_object->cached_list.next &&
2264 	    m_object->cached_list.prev) {
2265 		if (m_object->resident_page_count == 0) {
2266 			vm_object_cache_remove(m_object);
2267 		}
2268 	}
2269 
2270 	if (VM_PAGE_WIRED(mem)) {
2271 		assert(mem->vmp_wire_count > 0);
2272 		VM_OBJECT_WIRED_PAGE_UPDATE_START(m_object);
2273 		VM_OBJECT_WIRED_PAGE_REMOVE(m_object, mem);
2274 		VM_OBJECT_WIRED_PAGE_UPDATE_END(m_object, m_object->wire_tag);
2275 	}
2276 	assert(m_object->resident_page_count >=
2277 	    m_object->wired_page_count);
2278 	if (mem->vmp_reusable) {
2279 		assert(m_object->reusable_page_count > 0);
2280 		m_object->reusable_page_count--;
2281 		assert(m_object->reusable_page_count <=
2282 		    m_object->resident_page_count);
2283 		mem->vmp_reusable = FALSE;
2284 		OSAddAtomic(-1, &vm_page_stats_reusable.reusable_count);
2285 		vm_page_stats_reusable.reused_remove++;
2286 	} else if (m_object->all_reusable) {
2287 		OSAddAtomic(-1, &vm_page_stats_reusable.reusable_count);
2288 		vm_page_stats_reusable.reused_remove++;
2289 	}
2290 
2291 	if (m_object->purgable == VM_PURGABLE_DENY &&
2292 	    !m_object->vo_ledger_tag) {
2293 		owner = TASK_NULL;
2294 	} else {
2295 		owner = VM_OBJECT_OWNER(m_object);
2296 		vm_object_ledger_tag_ledgers(m_object,
2297 		    &ledger_idx_volatile,
2298 		    &ledger_idx_nonvolatile,
2299 		    &ledger_idx_volatile_compressed,
2300 		    &ledger_idx_nonvolatile_compressed,
2301 		    &do_footprint);
2302 	}
2303 	if (owner &&
2304 	    (m_object->purgable == VM_PURGABLE_NONVOLATILE ||
2305 	    m_object->purgable == VM_PURGABLE_DENY ||
2306 	    VM_PAGE_WIRED(mem))) {
2307 		/* less non-volatile bytes */
2308 		ledger_debit(owner->ledger,
2309 		    ledger_idx_nonvolatile,
2310 		    PAGE_SIZE);
2311 		if (do_footprint) {
2312 			/* less footprint */
2313 			ledger_debit(owner->ledger,
2314 			    task_ledgers.phys_footprint,
2315 			    PAGE_SIZE);
2316 		}
2317 	} else if (owner &&
2318 	    (m_object->purgable == VM_PURGABLE_VOLATILE ||
2319 	    m_object->purgable == VM_PURGABLE_EMPTY)) {
2320 		assert(!VM_PAGE_WIRED(mem));
2321 		/* less volatile bytes */
2322 		ledger_debit(owner->ledger,
2323 		    ledger_idx_volatile,
2324 		    PAGE_SIZE);
2325 	}
2326 	if (m_object->purgable == VM_PURGABLE_VOLATILE) {
2327 		if (VM_PAGE_WIRED(mem)) {
2328 			assert(vm_page_purgeable_wired_count > 0);
2329 			OSAddAtomic(-1, &vm_page_purgeable_wired_count);
2330 		} else {
2331 			assert(vm_page_purgeable_count > 0);
2332 			OSAddAtomic(-1, &vm_page_purgeable_count);
2333 		}
2334 	}
2335 
2336 	if (m_object->set_cache_attr == TRUE) {
2337 		pmap_set_cache_attributes(VM_PAGE_GET_PHYS_PAGE(mem), 0);
2338 	}
2339 
2340 	mem->vmp_tabled = FALSE;
2341 	mem->vmp_object = 0;
2342 	mem->vmp_offset = (vm_object_offset_t) -1;
2343 }
2344 
2345 
2346 /*
2347  *	vm_page_lookup:
2348  *
2349  *	Returns the page associated with the object/offset
2350  *	pair specified; if none is found, VM_PAGE_NULL is returned.
2351  *
2352  *	The object must be locked.  No side effects.
2353  */
2354 
2355 #define VM_PAGE_HASH_LOOKUP_THRESHOLD   10
2356 
2357 #if DEBUG_VM_PAGE_LOOKUP
2358 
2359 struct {
2360 	uint64_t        vpl_total;
2361 	uint64_t        vpl_empty_obj;
2362 	uint64_t        vpl_bucket_NULL;
2363 	uint64_t        vpl_hit_hint;
2364 	uint64_t        vpl_hit_hint_next;
2365 	uint64_t        vpl_hit_hint_prev;
2366 	uint64_t        vpl_fast;
2367 	uint64_t        vpl_slow;
2368 	uint64_t        vpl_hit;
2369 	uint64_t        vpl_miss;
2370 
2371 	uint64_t        vpl_fast_elapsed;
2372 	uint64_t        vpl_slow_elapsed;
2373 } vm_page_lookup_stats __attribute__((aligned(8)));
2374 
2375 #endif
2376 
2377 #define KDP_VM_PAGE_WALK_MAX    1000
2378 
2379 vm_page_t
kdp_vm_page_lookup(vm_object_t object,vm_object_offset_t offset)2380 kdp_vm_page_lookup(
2381 	vm_object_t             object,
2382 	vm_object_offset_t      offset)
2383 {
2384 	vm_page_t cur_page;
2385 	int num_traversed = 0;
2386 
2387 	if (not_in_kdp) {
2388 		panic("panic: kdp_vm_page_lookup done outside of kernel debugger");
2389 	}
2390 
2391 	vm_page_queue_iterate(&object->memq, cur_page, vmp_listq) {
2392 		if (cur_page->vmp_offset == offset) {
2393 			return cur_page;
2394 		}
2395 		num_traversed++;
2396 
2397 		if (num_traversed >= KDP_VM_PAGE_WALK_MAX) {
2398 			return VM_PAGE_NULL;
2399 		}
2400 	}
2401 
2402 	return VM_PAGE_NULL;
2403 }
2404 
2405 vm_page_t
vm_page_lookup(vm_object_t object,vm_object_offset_t offset)2406 vm_page_lookup(
2407 	vm_object_t             object,
2408 	vm_object_offset_t      offset)
2409 {
2410 	vm_page_t       mem;
2411 	vm_page_bucket_t *bucket;
2412 	vm_page_queue_entry_t   qe;
2413 	lck_spin_t      *bucket_lock = NULL;
2414 	int             hash_id;
2415 #if DEBUG_VM_PAGE_LOOKUP
2416 	uint64_t        start, elapsed;
2417 
2418 	OSAddAtomic64(1, &vm_page_lookup_stats.vpl_total);
2419 #endif
2420 
2421 #if CONFIG_KERNEL_TBI
2422 	if (VM_KERNEL_ADDRESS(offset)) {
2423 		offset = VM_KERNEL_STRIP_UPTR(offset);
2424 	}
2425 #endif /* CONFIG_KERNEL_TBI */
2426 
2427 	vm_object_lock_assert_held(object);
2428 	assertf(page_aligned(offset), "offset 0x%llx\n", offset);
2429 
2430 	if (object->resident_page_count == 0) {
2431 #if DEBUG_VM_PAGE_LOOKUP
2432 		OSAddAtomic64(1, &vm_page_lookup_stats.vpl_empty_obj);
2433 #endif
2434 		return VM_PAGE_NULL;
2435 	}
2436 
2437 	mem = object->memq_hint;
2438 
2439 	if (mem != VM_PAGE_NULL) {
2440 		assert(VM_PAGE_OBJECT(mem) == object);
2441 
2442 		if (mem->vmp_offset == offset) {
2443 #if DEBUG_VM_PAGE_LOOKUP
2444 			OSAddAtomic64(1, &vm_page_lookup_stats.vpl_hit_hint);
2445 #endif
2446 			return mem;
2447 		}
2448 		qe = (vm_page_queue_entry_t)vm_page_queue_next(&mem->vmp_listq);
2449 
2450 		if (!vm_page_queue_end(&object->memq, qe)) {
2451 			vm_page_t       next_page;
2452 
2453 			next_page = (vm_page_t)((uintptr_t)qe);
2454 			assert(VM_PAGE_OBJECT(next_page) == object);
2455 
2456 			if (next_page->vmp_offset == offset) {
2457 				object->memq_hint = next_page; /* new hint */
2458 #if DEBUG_VM_PAGE_LOOKUP
2459 				OSAddAtomic64(1, &vm_page_lookup_stats.vpl_hit_hint_next);
2460 #endif
2461 				return next_page;
2462 			}
2463 		}
2464 		qe = (vm_page_queue_entry_t)vm_page_queue_prev(&mem->vmp_listq);
2465 
2466 		if (!vm_page_queue_end(&object->memq, qe)) {
2467 			vm_page_t prev_page;
2468 
2469 			prev_page = (vm_page_t)((uintptr_t)qe);
2470 			assert(VM_PAGE_OBJECT(prev_page) == object);
2471 
2472 			if (prev_page->vmp_offset == offset) {
2473 				object->memq_hint = prev_page; /* new hint */
2474 #if DEBUG_VM_PAGE_LOOKUP
2475 				OSAddAtomic64(1, &vm_page_lookup_stats.vpl_hit_hint_prev);
2476 #endif
2477 				return prev_page;
2478 			}
2479 		}
2480 	}
2481 	/*
2482 	 * Search the hash table for this object/offset pair
2483 	 */
2484 	hash_id = vm_page_hash(object, offset);
2485 	bucket = &vm_page_buckets[hash_id];
2486 
2487 	/*
2488 	 * since we hold the object lock, we are guaranteed that no
2489 	 * new pages can be inserted into this object... this in turn
2490 	 * guarantess that the page we're looking for can't exist
2491 	 * if the bucket it hashes to is currently NULL even when looked
2492 	 * at outside the scope of the hash bucket lock... this is a
2493 	 * really cheap optimiztion to avoid taking the lock
2494 	 */
2495 	if (!bucket->page_list) {
2496 #if DEBUG_VM_PAGE_LOOKUP
2497 		OSAddAtomic64(1, &vm_page_lookup_stats.vpl_bucket_NULL);
2498 #endif
2499 		return VM_PAGE_NULL;
2500 	}
2501 
2502 #if DEBUG_VM_PAGE_LOOKUP
2503 	start = mach_absolute_time();
2504 #endif
2505 	if (object->resident_page_count <= VM_PAGE_HASH_LOOKUP_THRESHOLD) {
2506 		/*
2507 		 * on average, it's roughly 3 times faster to run a short memq list
2508 		 * than to take the spin lock and go through the hash list
2509 		 */
2510 		mem = (vm_page_t)vm_page_queue_first(&object->memq);
2511 
2512 		while (!vm_page_queue_end(&object->memq, (vm_page_queue_entry_t)mem)) {
2513 			if (mem->vmp_offset == offset) {
2514 				break;
2515 			}
2516 
2517 			mem = (vm_page_t)vm_page_queue_next(&mem->vmp_listq);
2518 		}
2519 		if (vm_page_queue_end(&object->memq, (vm_page_queue_entry_t)mem)) {
2520 			mem = NULL;
2521 		}
2522 	} else {
2523 		vm_page_object_t        packed_object;
2524 
2525 		packed_object = VM_PAGE_PACK_OBJECT(object);
2526 
2527 		bucket_lock = &vm_page_bucket_locks[hash_id / BUCKETS_PER_LOCK];
2528 
2529 		lck_spin_lock_grp(bucket_lock, &vm_page_lck_grp_bucket);
2530 
2531 		for (mem = (vm_page_t)(VM_PAGE_UNPACK_PTR(bucket->page_list));
2532 		    mem != VM_PAGE_NULL;
2533 		    mem = (vm_page_t)(VM_PAGE_UNPACK_PTR(mem->vmp_next_m))) {
2534 #if 0
2535 			/*
2536 			 * we don't hold the page queue lock
2537 			 * so this check isn't safe to make
2538 			 */
2539 			VM_PAGE_CHECK(mem);
2540 #endif
2541 			if ((mem->vmp_object == packed_object) && (mem->vmp_offset == offset)) {
2542 				break;
2543 			}
2544 		}
2545 		lck_spin_unlock(bucket_lock);
2546 	}
2547 
2548 #if DEBUG_VM_PAGE_LOOKUP
2549 	elapsed = mach_absolute_time() - start;
2550 
2551 	if (bucket_lock) {
2552 		OSAddAtomic64(1, &vm_page_lookup_stats.vpl_slow);
2553 		OSAddAtomic64(elapsed, &vm_page_lookup_stats.vpl_slow_elapsed);
2554 	} else {
2555 		OSAddAtomic64(1, &vm_page_lookup_stats.vpl_fast);
2556 		OSAddAtomic64(elapsed, &vm_page_lookup_stats.vpl_fast_elapsed);
2557 	}
2558 	if (mem != VM_PAGE_NULL) {
2559 		OSAddAtomic64(1, &vm_page_lookup_stats.vpl_hit);
2560 	} else {
2561 		OSAddAtomic64(1, &vm_page_lookup_stats.vpl_miss);
2562 	}
2563 #endif
2564 	if (mem != VM_PAGE_NULL) {
2565 		assert(VM_PAGE_OBJECT(mem) == object);
2566 
2567 		object->memq_hint = mem;
2568 	}
2569 	return mem;
2570 }
2571 
2572 
2573 /*
2574  *	vm_page_rename:
2575  *
2576  *	Move the given memory entry from its
2577  *	current object to the specified target object/offset.
2578  *
2579  *	The object must be locked.
2580  */
2581 void
vm_page_rename(vm_page_t mem,vm_object_t new_object,vm_object_offset_t new_offset)2582 vm_page_rename(
2583 	vm_page_t               mem,
2584 	vm_object_t             new_object,
2585 	vm_object_offset_t      new_offset)
2586 {
2587 	boolean_t       internal_to_external, external_to_internal;
2588 	vm_tag_t        tag;
2589 	vm_object_t     m_object;
2590 
2591 	m_object = VM_PAGE_OBJECT(mem);
2592 
2593 	assert(m_object != new_object);
2594 	assert(m_object);
2595 
2596 	/*
2597 	 *	Changes to mem->vmp_object require the page lock because
2598 	 *	the pageout daemon uses that lock to get the object.
2599 	 */
2600 	vm_page_lockspin_queues();
2601 
2602 	internal_to_external = FALSE;
2603 	external_to_internal = FALSE;
2604 
2605 	if (mem->vmp_q_state == VM_PAGE_ON_ACTIVE_LOCAL_Q) {
2606 		/*
2607 		 * it's much easier to get the vm_page_pageable_xxx accounting correct
2608 		 * if we first move the page to the active queue... it's going to end
2609 		 * up there anyway, and we don't do vm_page_rename's frequently enough
2610 		 * for this to matter.
2611 		 */
2612 		vm_page_queues_remove(mem, FALSE);
2613 		vm_page_activate(mem);
2614 	}
2615 	if (VM_PAGE_PAGEABLE(mem)) {
2616 		if (m_object->internal && !new_object->internal) {
2617 			internal_to_external = TRUE;
2618 		}
2619 		if (!m_object->internal && new_object->internal) {
2620 			external_to_internal = TRUE;
2621 		}
2622 	}
2623 
2624 	tag = m_object->wire_tag;
2625 	vm_page_remove(mem, TRUE);
2626 	vm_page_insert_internal(mem, new_object, new_offset, tag, TRUE, TRUE, FALSE, FALSE, NULL);
2627 
2628 	if (internal_to_external) {
2629 		vm_page_pageable_internal_count--;
2630 		vm_page_pageable_external_count++;
2631 	} else if (external_to_internal) {
2632 		vm_page_pageable_external_count--;
2633 		vm_page_pageable_internal_count++;
2634 	}
2635 
2636 	vm_page_unlock_queues();
2637 }
2638 
2639 /*
2640  *	vm_page_init:
2641  *
2642  *	Initialize the fields in a new page.
2643  *	This takes a structure with random values and initializes it
2644  *	so that it can be given to vm_page_release or vm_page_insert.
2645  */
2646 void
vm_page_init(vm_page_t mem,ppnum_t phys_page,boolean_t lopage)2647 vm_page_init(
2648 	vm_page_t mem,
2649 	ppnum_t   phys_page,
2650 	boolean_t lopage)
2651 {
2652 	uint_t    i;
2653 	uintptr_t *p;
2654 
2655 	assert(phys_page);
2656 
2657 #if DEBUG
2658 	if ((phys_page != vm_page_fictitious_addr) && (phys_page != vm_page_guard_addr)) {
2659 		if (!(pmap_valid_page(phys_page))) {
2660 			panic("vm_page_init: non-DRAM phys_page 0x%x", phys_page);
2661 		}
2662 	}
2663 #endif /* DEBUG */
2664 
2665 	/*
2666 	 * Initialize the fields of the vm_page. If adding any new fields to vm_page,
2667 	 * try to use initial values which match 0. This minimizes the number of writes
2668 	 * needed for boot-time initialization.
2669 	 *
2670 	 * Kernel bzero() isn't an inline yet, so do it by hand for performance.
2671 	 */
2672 	assert(VM_PAGE_NOT_ON_Q == 0);
2673 	assert(sizeof(*mem) % sizeof(uintptr_t) == 0);
2674 	for (p = (uintptr_t *)(void *)mem, i = sizeof(*mem) / sizeof(uintptr_t); i != 0; --i) {
2675 		*p++ = 0;
2676 	}
2677 	mem->vmp_offset = (vm_object_offset_t)-1;
2678 	mem->vmp_busy = TRUE;
2679 	mem->vmp_lopage = lopage;
2680 
2681 	VM_PAGE_SET_PHYS_PAGE(mem, phys_page);
2682 #if 0
2683 	/*
2684 	 * we're leaving this turned off for now... currently pages
2685 	 * come off the free list and are either immediately dirtied/referenced
2686 	 * due to zero-fill or COW faults, or are used to read or write files...
2687 	 * in the file I/O case, the UPL mechanism takes care of clearing
2688 	 * the state of the HW ref/mod bits in a somewhat fragile way.
2689 	 * Since we may change the way this works in the future (to toughen it up),
2690 	 * I'm leaving this as a reminder of where these bits could get cleared
2691 	 */
2692 
2693 	/*
2694 	 * make sure both the h/w referenced and modified bits are
2695 	 * clear at this point... we are especially dependent on
2696 	 * not finding a 'stale' h/w modified in a number of spots
2697 	 * once this page goes back into use
2698 	 */
2699 	pmap_clear_refmod(phys_page, VM_MEM_MODIFIED | VM_MEM_REFERENCED);
2700 #endif
2701 }
2702 
2703 /*
2704  *	vm_page_grab_fictitious:
2705  *
2706  *	Remove a fictitious page from the free list.
2707  *	Returns VM_PAGE_NULL if there are no free pages.
2708  */
2709 
2710 static vm_page_t
vm_page_grab_fictitious_common(ppnum_t phys_addr,boolean_t canwait)2711 vm_page_grab_fictitious_common(ppnum_t phys_addr, boolean_t canwait)
2712 {
2713 	vm_page_t m;
2714 
2715 	m = zalloc_flags(vm_page_zone, canwait ? Z_WAITOK : Z_NOWAIT);
2716 	if (m) {
2717 		vm_page_init(m, phys_addr, FALSE);
2718 		m->vmp_fictitious = TRUE;
2719 	}
2720 	return m;
2721 }
2722 
2723 vm_page_t
vm_page_grab_fictitious(boolean_t canwait)2724 vm_page_grab_fictitious(boolean_t canwait)
2725 {
2726 	return vm_page_grab_fictitious_common(vm_page_fictitious_addr, canwait);
2727 }
2728 
2729 int vm_guard_count;
2730 
2731 
2732 vm_page_t
vm_page_grab_guard(boolean_t canwait)2733 vm_page_grab_guard(boolean_t canwait)
2734 {
2735 	vm_page_t page;
2736 	page = vm_page_grab_fictitious_common(vm_page_guard_addr, canwait);
2737 	if (page) {
2738 		OSAddAtomic(1, &vm_guard_count);
2739 	}
2740 	return page;
2741 }
2742 
2743 
2744 /*
2745  *	vm_page_release_fictitious:
2746  *
2747  *	Release a fictitious page to the zone pool
2748  */
2749 void
vm_page_release_fictitious(vm_page_t m)2750 vm_page_release_fictitious(
2751 	vm_page_t m)
2752 {
2753 	assert((m->vmp_q_state == VM_PAGE_NOT_ON_Q) || (m->vmp_q_state == VM_PAGE_IS_WIRED));
2754 	assert(m->vmp_fictitious);
2755 	assert(VM_PAGE_GET_PHYS_PAGE(m) == vm_page_fictitious_addr ||
2756 	    VM_PAGE_GET_PHYS_PAGE(m) == vm_page_guard_addr);
2757 
2758 
2759 	if (VM_PAGE_GET_PHYS_PAGE(m) == vm_page_guard_addr) {
2760 		OSAddAtomic(-1, &vm_guard_count);
2761 	}
2762 
2763 	zfree(vm_page_zone, m);
2764 }
2765 
2766 /*
2767  *	vm_pool_low():
2768  *
2769  *	Return true if it is not likely that a non-vm_privileged thread
2770  *	can get memory without blocking.  Advisory only, since the
2771  *	situation may change under us.
2772  */
2773 bool
vm_pool_low(void)2774 vm_pool_low(void)
2775 {
2776 	/* No locking, at worst we will fib. */
2777 	return vm_page_free_count <= vm_page_free_reserved;
2778 }
2779 
2780 boolean_t vm_darkwake_mode = FALSE;
2781 
2782 /*
2783  * vm_update_darkwake_mode():
2784  *
2785  * Tells the VM that the system is in / out of darkwake.
2786  *
2787  * Today, the VM only lowers/raises the background queue target
2788  * so as to favor consuming more/less background pages when
2789  * darwake is ON/OFF.
2790  *
2791  * We might need to do more things in the future.
2792  */
2793 
2794 void
vm_update_darkwake_mode(boolean_t darkwake_mode)2795 vm_update_darkwake_mode(boolean_t darkwake_mode)
2796 {
2797 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_NOTOWNED);
2798 
2799 	vm_page_lockspin_queues();
2800 
2801 	if (vm_darkwake_mode == darkwake_mode) {
2802 		/*
2803 		 * No change.
2804 		 */
2805 		vm_page_unlock_queues();
2806 		return;
2807 	}
2808 
2809 	vm_darkwake_mode = darkwake_mode;
2810 
2811 	if (vm_darkwake_mode == TRUE) {
2812 #if CONFIG_BACKGROUND_QUEUE
2813 
2814 		/* save background target to restore later */
2815 		vm_page_background_target_snapshot = vm_page_background_target;
2816 
2817 		/* target is set to 0...no protection for background pages */
2818 		vm_page_background_target = 0;
2819 
2820 #endif /* CONFIG_BACKGROUND_QUEUE */
2821 	} else if (vm_darkwake_mode == FALSE) {
2822 #if CONFIG_BACKGROUND_QUEUE
2823 
2824 		if (vm_page_background_target_snapshot) {
2825 			vm_page_background_target = vm_page_background_target_snapshot;
2826 		}
2827 #endif /* CONFIG_BACKGROUND_QUEUE */
2828 	}
2829 	vm_page_unlock_queues();
2830 }
2831 
2832 #if CONFIG_BACKGROUND_QUEUE
2833 
2834 void
vm_page_update_background_state(vm_page_t mem)2835 vm_page_update_background_state(vm_page_t mem)
2836 {
2837 	if (vm_page_background_mode == VM_PAGE_BG_DISABLED) {
2838 		return;
2839 	}
2840 
2841 	if (mem->vmp_in_background == FALSE) {
2842 		return;
2843 	}
2844 
2845 	task_t  my_task = current_task_early();
2846 
2847 	if (my_task) {
2848 		if (task_get_darkwake_mode(my_task)) {
2849 			return;
2850 		}
2851 	}
2852 
2853 #if BACKGROUNDQ_BASED_ON_QOS
2854 	if (proc_get_effective_thread_policy(current_thread(), TASK_POLICY_QOS) <= THREAD_QOS_LEGACY) {
2855 		return;
2856 	}
2857 #else
2858 	if (my_task) {
2859 		if (proc_get_effective_task_policy(my_task, TASK_POLICY_DARWIN_BG)) {
2860 			return;
2861 		}
2862 	}
2863 #endif
2864 	vm_page_lockspin_queues();
2865 
2866 	mem->vmp_in_background = FALSE;
2867 	vm_page_background_promoted_count++;
2868 
2869 	vm_page_remove_from_backgroundq(mem);
2870 
2871 	vm_page_unlock_queues();
2872 }
2873 
2874 
2875 void
vm_page_assign_background_state(vm_page_t mem)2876 vm_page_assign_background_state(vm_page_t mem)
2877 {
2878 	if (vm_page_background_mode == VM_PAGE_BG_DISABLED) {
2879 		return;
2880 	}
2881 
2882 	task_t  my_task = current_task_early();
2883 
2884 	if (my_task) {
2885 		if (task_get_darkwake_mode(my_task)) {
2886 			mem->vmp_in_background = TRUE;
2887 			return;
2888 		}
2889 	}
2890 
2891 #if BACKGROUNDQ_BASED_ON_QOS
2892 	if (proc_get_effective_thread_policy(current_thread(), TASK_POLICY_QOS) <= THREAD_QOS_LEGACY) {
2893 		mem->vmp_in_background = TRUE;
2894 	} else {
2895 		mem->vmp_in_background = FALSE;
2896 	}
2897 #else
2898 	if (my_task) {
2899 		mem->vmp_in_background = proc_get_effective_task_policy(my_task, TASK_POLICY_DARWIN_BG);
2900 	}
2901 #endif
2902 }
2903 
2904 
2905 void
vm_page_remove_from_backgroundq(vm_page_t mem)2906 vm_page_remove_from_backgroundq(
2907 	vm_page_t       mem)
2908 {
2909 	vm_object_t     m_object;
2910 
2911 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
2912 
2913 	if (mem->vmp_on_backgroundq) {
2914 		vm_page_queue_remove(&vm_page_queue_background, mem, vmp_backgroundq);
2915 
2916 		mem->vmp_backgroundq.next = 0;
2917 		mem->vmp_backgroundq.prev = 0;
2918 		mem->vmp_on_backgroundq = FALSE;
2919 
2920 		vm_page_background_count--;
2921 
2922 		m_object = VM_PAGE_OBJECT(mem);
2923 
2924 		if (m_object->internal) {
2925 			vm_page_background_internal_count--;
2926 		} else {
2927 			vm_page_background_external_count--;
2928 		}
2929 	} else {
2930 		assert(VM_PAGE_UNPACK_PTR(mem->vmp_backgroundq.next) == (uintptr_t)NULL &&
2931 		    VM_PAGE_UNPACK_PTR(mem->vmp_backgroundq.prev) == (uintptr_t)NULL);
2932 	}
2933 }
2934 
2935 
2936 void
vm_page_add_to_backgroundq(vm_page_t mem,boolean_t first)2937 vm_page_add_to_backgroundq(
2938 	vm_page_t       mem,
2939 	boolean_t       first)
2940 {
2941 	vm_object_t     m_object;
2942 
2943 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
2944 
2945 	if (vm_page_background_mode == VM_PAGE_BG_DISABLED) {
2946 		return;
2947 	}
2948 
2949 	if (mem->vmp_on_backgroundq == FALSE) {
2950 		m_object = VM_PAGE_OBJECT(mem);
2951 
2952 		if (vm_page_background_exclude_external && !m_object->internal) {
2953 			return;
2954 		}
2955 
2956 		if (first == TRUE) {
2957 			vm_page_queue_enter_first(&vm_page_queue_background, mem, vmp_backgroundq);
2958 		} else {
2959 			vm_page_queue_enter(&vm_page_queue_background, mem, vmp_backgroundq);
2960 		}
2961 		mem->vmp_on_backgroundq = TRUE;
2962 
2963 		vm_page_background_count++;
2964 
2965 		if (m_object->internal) {
2966 			vm_page_background_internal_count++;
2967 		} else {
2968 			vm_page_background_external_count++;
2969 		}
2970 	}
2971 }
2972 
2973 #endif /* CONFIG_BACKGROUND_QUEUE */
2974 
2975 /*
2976  * This can be switched to FALSE to help debug drivers
2977  * that are having problems with memory > 4G.
2978  */
2979 boolean_t       vm_himemory_mode = TRUE;
2980 
2981 /*
2982  * this interface exists to support hardware controllers
2983  * incapable of generating DMAs with more than 32 bits
2984  * of address on platforms with physical memory > 4G...
2985  */
2986 unsigned int    vm_lopages_allocated_q = 0;
2987 unsigned int    vm_lopages_allocated_cpm_success = 0;
2988 unsigned int    vm_lopages_allocated_cpm_failed = 0;
2989 vm_page_queue_head_t    vm_lopage_queue_free VM_PAGE_PACKED_ALIGNED;
2990 
2991 vm_page_t
vm_page_grablo(void)2992 vm_page_grablo(void)
2993 {
2994 	vm_page_t       mem;
2995 
2996 	if (vm_lopage_needed == FALSE) {
2997 		return vm_page_grab();
2998 	}
2999 
3000 	lck_mtx_lock_spin(&vm_page_queue_free_lock);
3001 
3002 	if (!vm_page_queue_empty(&vm_lopage_queue_free)) {
3003 		vm_page_queue_remove_first(&vm_lopage_queue_free, mem, vmp_pageq);
3004 		assert(vm_lopage_free_count);
3005 		assert(mem->vmp_q_state == VM_PAGE_ON_FREE_LOPAGE_Q);
3006 		mem->vmp_q_state = VM_PAGE_NOT_ON_Q;
3007 
3008 		vm_lopage_free_count--;
3009 		vm_lopages_allocated_q++;
3010 
3011 		if (vm_lopage_free_count < vm_lopage_lowater) {
3012 			vm_lopage_refill = TRUE;
3013 		}
3014 
3015 		lck_mtx_unlock(&vm_page_queue_free_lock);
3016 
3017 #if CONFIG_BACKGROUND_QUEUE
3018 		vm_page_assign_background_state(mem);
3019 #endif
3020 	} else {
3021 		lck_mtx_unlock(&vm_page_queue_free_lock);
3022 
3023 		if (cpm_allocate(PAGE_SIZE, &mem, atop(PPNUM_MAX), 0, FALSE, KMA_LOMEM) != KERN_SUCCESS) {
3024 			lck_mtx_lock_spin(&vm_page_queue_free_lock);
3025 			vm_lopages_allocated_cpm_failed++;
3026 			lck_mtx_unlock(&vm_page_queue_free_lock);
3027 
3028 			return VM_PAGE_NULL;
3029 		}
3030 		assert(mem->vmp_q_state == VM_PAGE_NOT_ON_Q);
3031 
3032 		mem->vmp_busy = TRUE;
3033 
3034 		vm_page_lockspin_queues();
3035 
3036 		mem->vmp_gobbled = FALSE;
3037 		vm_page_gobble_count--;
3038 		vm_page_wire_count--;
3039 
3040 		vm_lopages_allocated_cpm_success++;
3041 		vm_page_unlock_queues();
3042 	}
3043 	assert(mem->vmp_busy);
3044 	assert(!mem->vmp_pmapped);
3045 	assert(!mem->vmp_wpmapped);
3046 	assert(!pmap_is_noencrypt(VM_PAGE_GET_PHYS_PAGE(mem)));
3047 
3048 	VM_PAGE_ZERO_PAGEQ_ENTRY(mem);
3049 
3050 	counter_inc(&vm_page_grab_count);
3051 	VM_DEBUG_EVENT(vm_page_grab, VM_PAGE_GRAB, DBG_FUNC_NONE, 0, 1, 0, 0);
3052 
3053 	return mem;
3054 }
3055 
3056 /*
3057  *	vm_page_grab:
3058  *
3059  *	first try to grab a page from the per-cpu free list...
3060  *	this must be done while pre-emption is disabled... if
3061  *      a page is available, we're done...
3062  *	if no page is available, grab the vm_page_queue_free_lock
3063  *	and see if current number of free pages would allow us
3064  *      to grab at least 1... if not, return VM_PAGE_NULL as before...
3065  *	if there are pages available, disable preemption and
3066  *      recheck the state of the per-cpu free list... we could
3067  *	have been preempted and moved to a different cpu, or
3068  *      some other thread could have re-filled it... if still
3069  *	empty, figure out how many pages we can steal from the
3070  *	global free queue and move to the per-cpu queue...
3071  *	return 1 of these pages when done... only wakeup the
3072  *      pageout_scan thread if we moved pages from the global
3073  *	list... no need for the wakeup if we've satisfied the
3074  *	request from the per-cpu queue.
3075  */
3076 
3077 #if CONFIG_SECLUDED_MEMORY
3078 vm_page_t vm_page_grab_secluded(void);
3079 #endif /* CONFIG_SECLUDED_MEMORY */
3080 
3081 static inline void
3082 vm_page_grab_diags(void);
3083 
3084 vm_page_t
vm_page_grab(void)3085 vm_page_grab(void)
3086 {
3087 	return vm_page_grab_options(VM_PAGE_GRAB_OPTIONS_NONE);
3088 }
3089 
3090 #if HIBERNATION
3091 boolean_t       hibernate_rebuild_needed = FALSE;
3092 #endif /* HIBERNATION */
3093 
3094 vm_page_t
vm_page_grab_options(int grab_options)3095 vm_page_grab_options(
3096 	int grab_options)
3097 {
3098 	vm_page_t       mem;
3099 
3100 	disable_preemption();
3101 
3102 	if ((mem = *PERCPU_GET(free_pages))) {
3103 return_page_from_cpu_list:
3104 		assert(mem->vmp_q_state == VM_PAGE_ON_FREE_LOCAL_Q);
3105 
3106 #if HIBERNATION
3107 		if (hibernate_rebuild_needed) {
3108 			panic("%s:%d should not modify cpu->free_pages while hibernating", __FUNCTION__, __LINE__);
3109 		}
3110 #endif /* HIBERNATION */
3111 
3112 		vm_page_grab_diags();
3113 
3114 		vm_offset_t pcpu_base = current_percpu_base();
3115 		counter_inc_preemption_disabled(&vm_page_grab_count);
3116 		*PERCPU_GET_WITH_BASE(pcpu_base, free_pages) = mem->vmp_snext;
3117 		VM_DEBUG_EVENT(vm_page_grab, VM_PAGE_GRAB, DBG_FUNC_NONE, grab_options, 0, 0, 0);
3118 
3119 		enable_preemption();
3120 		VM_PAGE_ZERO_PAGEQ_ENTRY(mem);
3121 		mem->vmp_q_state = VM_PAGE_NOT_ON_Q;
3122 
3123 		assert(mem->vmp_listq.next == 0 && mem->vmp_listq.prev == 0);
3124 		assert(mem->vmp_tabled == FALSE);
3125 		assert(mem->vmp_object == 0);
3126 		assert(!mem->vmp_laundry);
3127 		ASSERT_PMAP_FREE(mem);
3128 		assert(mem->vmp_busy);
3129 		assert(!mem->vmp_pmapped);
3130 		assert(!mem->vmp_wpmapped);
3131 		assert(!pmap_is_noencrypt(VM_PAGE_GET_PHYS_PAGE(mem)));
3132 
3133 #if CONFIG_BACKGROUND_QUEUE
3134 		vm_page_assign_background_state(mem);
3135 #endif
3136 		return mem;
3137 	}
3138 	enable_preemption();
3139 
3140 
3141 	/*
3142 	 *	Optionally produce warnings if the wire or gobble
3143 	 *	counts exceed some threshold.
3144 	 */
3145 #if VM_PAGE_WIRE_COUNT_WARNING
3146 	if (vm_page_wire_count >= VM_PAGE_WIRE_COUNT_WARNING) {
3147 		printf("mk: vm_page_grab(): high wired page count of %d\n",
3148 		    vm_page_wire_count);
3149 	}
3150 #endif
3151 #if VM_PAGE_GOBBLE_COUNT_WARNING
3152 	if (vm_page_gobble_count >= VM_PAGE_GOBBLE_COUNT_WARNING) {
3153 		printf("mk: vm_page_grab(): high gobbled page count of %d\n",
3154 		    vm_page_gobble_count);
3155 	}
3156 #endif
3157 
3158 	/*
3159 	 * If free count is low and we have delayed pages from early boot,
3160 	 * get one of those instead.
3161 	 */
3162 	if (__improbable(vm_delayed_count > 0 &&
3163 	    vm_page_free_count <= vm_page_free_target &&
3164 	    (mem = vm_get_delayed_page(grab_options)) != NULL)) {
3165 		return mem;
3166 	}
3167 
3168 	lck_mtx_lock_spin(&vm_page_queue_free_lock);
3169 
3170 	/*
3171 	 *	Only let privileged threads (involved in pageout)
3172 	 *	dip into the reserved pool.
3173 	 */
3174 	if ((vm_page_free_count < vm_page_free_reserved) &&
3175 	    !(current_thread()->options & TH_OPT_VMPRIV)) {
3176 		/* no page for us in the free queue... */
3177 		lck_mtx_unlock(&vm_page_queue_free_lock);
3178 		mem = VM_PAGE_NULL;
3179 
3180 #if CONFIG_SECLUDED_MEMORY
3181 		/* ... but can we try and grab from the secluded queue? */
3182 		if (vm_page_secluded_count > 0 &&
3183 		    ((grab_options & VM_PAGE_GRAB_SECLUDED) ||
3184 		    task_can_use_secluded_mem(current_task(), TRUE))) {
3185 			mem = vm_page_grab_secluded();
3186 			if (grab_options & VM_PAGE_GRAB_SECLUDED) {
3187 				vm_page_secluded.grab_for_iokit++;
3188 				if (mem) {
3189 					vm_page_secluded.grab_for_iokit_success++;
3190 				}
3191 			}
3192 			if (mem) {
3193 				VM_CHECK_MEMORYSTATUS;
3194 
3195 				vm_page_grab_diags();
3196 				counter_inc(&vm_page_grab_count);
3197 				VM_DEBUG_EVENT(vm_page_grab, VM_PAGE_GRAB, DBG_FUNC_NONE, grab_options, 0, 0, 0);
3198 
3199 				return mem;
3200 			}
3201 		}
3202 #else /* CONFIG_SECLUDED_MEMORY */
3203 		(void) grab_options;
3204 #endif /* CONFIG_SECLUDED_MEMORY */
3205 	} else {
3206 		vm_page_t        head;
3207 		vm_page_t        tail;
3208 		unsigned int     pages_to_steal;
3209 		unsigned int     color;
3210 		unsigned int clump_end, sub_count;
3211 
3212 		while (vm_page_free_count == 0) {
3213 			lck_mtx_unlock(&vm_page_queue_free_lock);
3214 			/*
3215 			 * must be a privileged thread to be
3216 			 * in this state since a non-privileged
3217 			 * thread would have bailed if we were
3218 			 * under the vm_page_free_reserved mark
3219 			 */
3220 			VM_PAGE_WAIT();
3221 			lck_mtx_lock_spin(&vm_page_queue_free_lock);
3222 		}
3223 
3224 		disable_preemption();
3225 
3226 		if ((mem = *PERCPU_GET(free_pages))) {
3227 			lck_mtx_unlock(&vm_page_queue_free_lock);
3228 
3229 			/*
3230 			 * we got preempted and moved to another processor
3231 			 * or we got preempted and someone else ran and filled the cache
3232 			 */
3233 			goto return_page_from_cpu_list;
3234 		}
3235 		if (vm_page_free_count <= vm_page_free_reserved) {
3236 			pages_to_steal = 1;
3237 		} else {
3238 			if (vm_free_magazine_refill_limit <= (vm_page_free_count - vm_page_free_reserved)) {
3239 				pages_to_steal = vm_free_magazine_refill_limit;
3240 			} else {
3241 				pages_to_steal = (vm_page_free_count - vm_page_free_reserved);
3242 			}
3243 		}
3244 		color = *PERCPU_GET(start_color);
3245 		head = tail = NULL;
3246 
3247 		vm_page_free_count -= pages_to_steal;
3248 		clump_end = sub_count = 0;
3249 
3250 		while (pages_to_steal--) {
3251 			while (vm_page_queue_empty(&vm_page_queue_free[color].qhead)) {
3252 				color = (color + 1) & vm_color_mask;
3253 			}
3254 #if defined(__x86_64__)
3255 			vm_page_queue_remove_first_with_clump(&vm_page_queue_free[color].qhead,
3256 			    mem, clump_end);
3257 #else
3258 			vm_page_queue_remove_first(&vm_page_queue_free[color].qhead,
3259 			    mem, vmp_pageq);
3260 #endif
3261 
3262 			assert(mem->vmp_q_state == VM_PAGE_ON_FREE_Q);
3263 
3264 			VM_PAGE_ZERO_PAGEQ_ENTRY(mem);
3265 
3266 #if defined(__arm__) || defined(__arm64__)
3267 			color = (color + 1) & vm_color_mask;
3268 #else
3269 
3270 #if DEVELOPMENT || DEBUG
3271 
3272 			sub_count++;
3273 			if (clump_end) {
3274 				vm_clump_update_stats(sub_count);
3275 				sub_count = 0;
3276 				color = (color + 1) & vm_color_mask;
3277 			}
3278 #else
3279 			if (clump_end) {
3280 				color = (color + 1) & vm_color_mask;
3281 			}
3282 
3283 #endif /* if DEVELOPMENT || DEBUG */
3284 
3285 #endif  /* if defined(__arm__) || defined(__arm64__) */
3286 
3287 			if (head == NULL) {
3288 				head = mem;
3289 			} else {
3290 				tail->vmp_snext = mem;
3291 			}
3292 			tail = mem;
3293 
3294 			assert(mem->vmp_listq.next == 0 && mem->vmp_listq.prev == 0);
3295 			assert(mem->vmp_tabled == FALSE);
3296 			assert(mem->vmp_object == 0);
3297 			assert(!mem->vmp_laundry);
3298 
3299 			mem->vmp_q_state = VM_PAGE_ON_FREE_LOCAL_Q;
3300 
3301 			ASSERT_PMAP_FREE(mem);
3302 			assert(mem->vmp_busy);
3303 			assert(!mem->vmp_pmapped);
3304 			assert(!mem->vmp_wpmapped);
3305 			assert(!pmap_is_noencrypt(VM_PAGE_GET_PHYS_PAGE(mem)));
3306 		}
3307 #if defined (__x86_64__) && (DEVELOPMENT || DEBUG)
3308 		vm_clump_update_stats(sub_count);
3309 #endif
3310 		lck_mtx_unlock(&vm_page_queue_free_lock);
3311 
3312 #if HIBERNATION
3313 		if (hibernate_rebuild_needed) {
3314 			panic("%s:%d should not modify cpu->free_pages while hibernating", __FUNCTION__, __LINE__);
3315 		}
3316 #endif /* HIBERNATION */
3317 		vm_offset_t pcpu_base = current_percpu_base();
3318 		*PERCPU_GET_WITH_BASE(pcpu_base, free_pages) = head->vmp_snext;
3319 		*PERCPU_GET_WITH_BASE(pcpu_base, start_color) = color;
3320 
3321 		/*
3322 		 * satisfy this request
3323 		 */
3324 		vm_page_grab_diags();
3325 		counter_inc_preemption_disabled(&vm_page_grab_count);
3326 		VM_DEBUG_EVENT(vm_page_grab, VM_PAGE_GRAB, DBG_FUNC_NONE, grab_options, 0, 0, 0);
3327 		mem = head;
3328 		assert(mem->vmp_q_state == VM_PAGE_ON_FREE_LOCAL_Q);
3329 
3330 		VM_PAGE_ZERO_PAGEQ_ENTRY(mem);
3331 		mem->vmp_q_state = VM_PAGE_NOT_ON_Q;
3332 
3333 		enable_preemption();
3334 	}
3335 	/*
3336 	 *	Decide if we should poke the pageout daemon.
3337 	 *	We do this if the free count is less than the low
3338 	 *	water mark. VM Pageout Scan will keep running till
3339 	 *	the free_count > free_target (& hence above free_min).
3340 	 *	This wakeup is to catch the possibility of the counts
3341 	 *	dropping between VM Pageout Scan parking and this check.
3342 	 *
3343 	 *	We don't have the counts locked ... if they change a little,
3344 	 *	it doesn't really matter.
3345 	 */
3346 	if (vm_page_free_count < vm_page_free_min) {
3347 		lck_mtx_lock(&vm_page_queue_free_lock);
3348 		if (vm_pageout_running == FALSE) {
3349 			lck_mtx_unlock(&vm_page_queue_free_lock);
3350 			thread_wakeup((event_t) &vm_page_free_wanted);
3351 		} else {
3352 			lck_mtx_unlock(&vm_page_queue_free_lock);
3353 		}
3354 	}
3355 
3356 	VM_CHECK_MEMORYSTATUS;
3357 
3358 	if (mem) {
3359 //		dbgLog(VM_PAGE_GET_PHYS_PAGE(mem), vm_page_free_count, vm_page_wire_count, 4);	/* (TEST/DEBUG) */
3360 
3361 #if CONFIG_BACKGROUND_QUEUE
3362 		vm_page_assign_background_state(mem);
3363 #endif
3364 	}
3365 	return mem;
3366 }
3367 
3368 #if CONFIG_SECLUDED_MEMORY
3369 vm_page_t
vm_page_grab_secluded(void)3370 vm_page_grab_secluded(void)
3371 {
3372 	vm_page_t       mem;
3373 	vm_object_t     object;
3374 	int             refmod_state;
3375 
3376 	if (vm_page_secluded_count == 0) {
3377 		/* no secluded pages to grab... */
3378 		return VM_PAGE_NULL;
3379 	}
3380 
3381 	/* secluded queue is protected by the VM page queue lock */
3382 	vm_page_lock_queues();
3383 
3384 	if (vm_page_secluded_count == 0) {
3385 		/* no secluded pages to grab... */
3386 		vm_page_unlock_queues();
3387 		return VM_PAGE_NULL;
3388 	}
3389 
3390 #if 00
3391 	/* can we grab from the secluded queue? */
3392 	if (vm_page_secluded_count > vm_page_secluded_target ||
3393 	    (vm_page_secluded_count > 0 &&
3394 	    task_can_use_secluded_mem(current_task(), TRUE))) {
3395 		/* OK */
3396 	} else {
3397 		/* can't grab from secluded queue... */
3398 		vm_page_unlock_queues();
3399 		return VM_PAGE_NULL;
3400 	}
3401 #endif
3402 
3403 	/* we can grab a page from secluded queue! */
3404 	assert((vm_page_secluded_count_free +
3405 	    vm_page_secluded_count_inuse) ==
3406 	    vm_page_secluded_count);
3407 	if (current_task()->task_can_use_secluded_mem) {
3408 		assert(num_tasks_can_use_secluded_mem > 0);
3409 	}
3410 	assert(!vm_page_queue_empty(&vm_page_queue_secluded));
3411 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
3412 	mem = (vm_page_t)vm_page_queue_first(&vm_page_queue_secluded);
3413 	assert(mem->vmp_q_state == VM_PAGE_ON_SECLUDED_Q);
3414 	vm_page_queues_remove(mem, TRUE);
3415 
3416 	object = VM_PAGE_OBJECT(mem);
3417 
3418 	assert(!mem->vmp_fictitious);
3419 	assert(!VM_PAGE_WIRED(mem));
3420 	if (object == VM_OBJECT_NULL) {
3421 		/* free for grab! */
3422 		vm_page_unlock_queues();
3423 		vm_page_secluded.grab_success_free++;
3424 
3425 		assert(mem->vmp_busy);
3426 		assert(mem->vmp_q_state == VM_PAGE_NOT_ON_Q);
3427 		assert(VM_PAGE_OBJECT(mem) == VM_OBJECT_NULL);
3428 		assert(mem->vmp_pageq.next == 0);
3429 		assert(mem->vmp_pageq.prev == 0);
3430 		assert(mem->vmp_listq.next == 0);
3431 		assert(mem->vmp_listq.prev == 0);
3432 #if CONFIG_BACKGROUND_QUEUE
3433 		assert(mem->vmp_on_backgroundq == 0);
3434 		assert(mem->vmp_backgroundq.next == 0);
3435 		assert(mem->vmp_backgroundq.prev == 0);
3436 #endif /* CONFIG_BACKGROUND_QUEUE */
3437 		return mem;
3438 	}
3439 
3440 	assert(!object->internal);
3441 //	vm_page_pageable_external_count--;
3442 
3443 	if (!vm_object_lock_try(object)) {
3444 //		printf("SECLUDED: page %p: object %p locked\n", mem, object);
3445 		vm_page_secluded.grab_failure_locked++;
3446 reactivate_secluded_page:
3447 		vm_page_activate(mem);
3448 		vm_page_unlock_queues();
3449 		return VM_PAGE_NULL;
3450 	}
3451 	if (mem->vmp_busy ||
3452 	    mem->vmp_cleaning ||
3453 	    mem->vmp_laundry) {
3454 		/* can't steal page in this state... */
3455 		vm_object_unlock(object);
3456 		vm_page_secluded.grab_failure_state++;
3457 		goto reactivate_secluded_page;
3458 	}
3459 
3460 	mem->vmp_busy = TRUE;
3461 	refmod_state = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(mem));
3462 	if (refmod_state & VM_MEM_REFERENCED) {
3463 		mem->vmp_reference = TRUE;
3464 	}
3465 	if (refmod_state & VM_MEM_MODIFIED) {
3466 		SET_PAGE_DIRTY(mem, FALSE);
3467 	}
3468 	if (mem->vmp_dirty || mem->vmp_precious) {
3469 		/* can't grab a dirty page; re-activate */
3470 //		printf("SECLUDED: dirty page %p\n", mem);
3471 		PAGE_WAKEUP_DONE(mem);
3472 		vm_page_secluded.grab_failure_dirty++;
3473 		vm_object_unlock(object);
3474 		goto reactivate_secluded_page;
3475 	}
3476 	if (mem->vmp_reference) {
3477 		/* it's been used but we do need to grab a page... */
3478 	}
3479 
3480 	vm_page_unlock_queues();
3481 
3482 	/* finish what vm_page_free() would have done... */
3483 	vm_page_free_prepare_object(mem, TRUE);
3484 	vm_object_unlock(object);
3485 	object = VM_OBJECT_NULL;
3486 	if (vm_page_free_verify) {
3487 		ASSERT_PMAP_FREE(mem);
3488 	}
3489 	pmap_clear_noencrypt(VM_PAGE_GET_PHYS_PAGE(mem));
3490 	vm_page_secluded.grab_success_other++;
3491 
3492 	assert(mem->vmp_busy);
3493 	assert(mem->vmp_q_state == VM_PAGE_NOT_ON_Q);
3494 	assert(VM_PAGE_OBJECT(mem) == VM_OBJECT_NULL);
3495 	assert(mem->vmp_pageq.next == 0);
3496 	assert(mem->vmp_pageq.prev == 0);
3497 	assert(mem->vmp_listq.next == 0);
3498 	assert(mem->vmp_listq.prev == 0);
3499 #if CONFIG_BACKGROUND_QUEUE
3500 	assert(mem->vmp_on_backgroundq == 0);
3501 	assert(mem->vmp_backgroundq.next == 0);
3502 	assert(mem->vmp_backgroundq.prev == 0);
3503 #endif /* CONFIG_BACKGROUND_QUEUE */
3504 
3505 	return mem;
3506 }
3507 
3508 uint64_t
vm_page_secluded_drain(void)3509 vm_page_secluded_drain(void)
3510 {
3511 	vm_page_t local_freeq;
3512 	int local_freed;
3513 	uint64_t num_reclaimed;
3514 	unsigned int saved_secluded_count, saved_secluded_target;
3515 
3516 	num_reclaimed = 0;
3517 	local_freeq = NULL;
3518 	local_freed = 0;
3519 
3520 	vm_page_lock_queues();
3521 
3522 	saved_secluded_count = vm_page_secluded_count;
3523 	saved_secluded_target = vm_page_secluded_target;
3524 	vm_page_secluded_target = 0;
3525 	VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE();
3526 	while (vm_page_secluded_count) {
3527 		vm_page_t secluded_page;
3528 
3529 		assert((vm_page_secluded_count_free +
3530 		    vm_page_secluded_count_inuse) ==
3531 		    vm_page_secluded_count);
3532 		secluded_page = (vm_page_t)vm_page_queue_first(&vm_page_queue_secluded);
3533 		assert(secluded_page->vmp_q_state == VM_PAGE_ON_SECLUDED_Q);
3534 
3535 		vm_page_queues_remove(secluded_page, FALSE);
3536 		assert(!secluded_page->vmp_fictitious);
3537 		assert(!VM_PAGE_WIRED(secluded_page));
3538 
3539 		if (secluded_page->vmp_object == 0) {
3540 			/* transfer to free queue */
3541 			assert(secluded_page->vmp_busy);
3542 			secluded_page->vmp_snext = local_freeq;
3543 			local_freeq = secluded_page;
3544 			local_freed += 1;
3545 		} else {
3546 			/* transfer to head of active queue */
3547 			vm_page_enqueue_active(secluded_page, FALSE);
3548 			secluded_page = VM_PAGE_NULL;
3549 		}
3550 		num_reclaimed++;
3551 	}
3552 	vm_page_secluded_target = saved_secluded_target;
3553 	VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE();
3554 
3555 //	printf("FBDP %s:%d secluded_count %d->%d, target %d, reclaimed %lld\n", __FUNCTION__, __LINE__, saved_secluded_count, vm_page_secluded_count, vm_page_secluded_target, num_reclaimed);
3556 
3557 	vm_page_unlock_queues();
3558 
3559 	if (local_freed) {
3560 		vm_page_free_list(local_freeq, TRUE);
3561 		local_freeq = NULL;
3562 		local_freed = 0;
3563 	}
3564 
3565 	return num_reclaimed;
3566 }
3567 #endif /* CONFIG_SECLUDED_MEMORY */
3568 
3569 
3570 static inline void
vm_page_grab_diags()3571 vm_page_grab_diags()
3572 {
3573 #if DEVELOPMENT || DEBUG
3574 	task_t task = current_task_early();
3575 	if (task == NULL) {
3576 		return;
3577 	}
3578 
3579 	ledger_credit(task->ledger, task_ledgers.pages_grabbed, 1);
3580 #endif /* DEVELOPMENT || DEBUG */
3581 }
3582 
3583 /*
3584  *	vm_page_release:
3585  *
3586  *	Return a page to the free list.
3587  */
3588 
3589 void
vm_page_release(vm_page_t mem,boolean_t page_queues_locked)3590 vm_page_release(
3591 	vm_page_t       mem,
3592 	boolean_t       page_queues_locked)
3593 {
3594 	unsigned int    color;
3595 	int     need_wakeup = 0;
3596 	int     need_priv_wakeup = 0;
3597 #if CONFIG_SECLUDED_MEMORY
3598 	int     need_secluded_wakeup = 0;
3599 #endif /* CONFIG_SECLUDED_MEMORY */
3600 	event_t wakeup_event = NULL;
3601 
3602 	if (page_queues_locked) {
3603 		LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
3604 	} else {
3605 		LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_NOTOWNED);
3606 	}
3607 
3608 	assert(!mem->vmp_private && !mem->vmp_fictitious);
3609 	if (vm_page_free_verify) {
3610 		ASSERT_PMAP_FREE(mem);
3611 	}
3612 //	dbgLog(VM_PAGE_GET_PHYS_PAGE(mem), vm_page_free_count, vm_page_wire_count, 5);	/* (TEST/DEBUG) */
3613 
3614 	pmap_clear_noencrypt(VM_PAGE_GET_PHYS_PAGE(mem));
3615 
3616 	lck_mtx_lock_spin(&vm_page_queue_free_lock);
3617 
3618 	assert(mem->vmp_q_state == VM_PAGE_NOT_ON_Q);
3619 	assert(mem->vmp_busy);
3620 	assert(!mem->vmp_laundry);
3621 	assert(mem->vmp_object == 0);
3622 	assert(mem->vmp_pageq.next == 0 && mem->vmp_pageq.prev == 0);
3623 	assert(mem->vmp_listq.next == 0 && mem->vmp_listq.prev == 0);
3624 #if CONFIG_BACKGROUND_QUEUE
3625 	assert(mem->vmp_backgroundq.next == 0 &&
3626 	    mem->vmp_backgroundq.prev == 0 &&
3627 	    mem->vmp_on_backgroundq == FALSE);
3628 #endif
3629 	if ((mem->vmp_lopage == TRUE || vm_lopage_refill == TRUE) &&
3630 	    vm_lopage_free_count < vm_lopage_free_limit &&
3631 	    VM_PAGE_GET_PHYS_PAGE(mem) < max_valid_low_ppnum) {
3632 		/*
3633 		 * this exists to support hardware controllers
3634 		 * incapable of generating DMAs with more than 32 bits
3635 		 * of address on platforms with physical memory > 4G...
3636 		 */
3637 		vm_page_queue_enter_first(&vm_lopage_queue_free, mem, vmp_pageq);
3638 		vm_lopage_free_count++;
3639 
3640 		if (vm_lopage_free_count >= vm_lopage_free_limit) {
3641 			vm_lopage_refill = FALSE;
3642 		}
3643 
3644 		mem->vmp_q_state = VM_PAGE_ON_FREE_LOPAGE_Q;
3645 		mem->vmp_lopage = TRUE;
3646 #if CONFIG_SECLUDED_MEMORY
3647 	} else if (vm_page_free_count > vm_page_free_reserved &&
3648 	    vm_page_secluded_count < vm_page_secluded_target &&
3649 	    num_tasks_can_use_secluded_mem == 0) {
3650 		/*
3651 		 * XXX FBDP TODO: also avoid refilling secluded queue
3652 		 * when some IOKit objects are already grabbing from it...
3653 		 */
3654 		if (!page_queues_locked) {
3655 			if (!vm_page_trylock_queues()) {
3656 				/* take locks in right order */
3657 				lck_mtx_unlock(&vm_page_queue_free_lock);
3658 				vm_page_lock_queues();
3659 				lck_mtx_lock_spin(&vm_page_queue_free_lock);
3660 			}
3661 		}
3662 		mem->vmp_lopage = FALSE;
3663 		LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
3664 		vm_page_queue_enter_first(&vm_page_queue_secluded, mem, vmp_pageq);
3665 		mem->vmp_q_state = VM_PAGE_ON_SECLUDED_Q;
3666 		vm_page_secluded_count++;
3667 		VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE();
3668 		vm_page_secluded_count_free++;
3669 		if (!page_queues_locked) {
3670 			vm_page_unlock_queues();
3671 		}
3672 		LCK_MTX_ASSERT(&vm_page_queue_free_lock, LCK_MTX_ASSERT_OWNED);
3673 		if (vm_page_free_wanted_secluded > 0) {
3674 			vm_page_free_wanted_secluded--;
3675 			need_secluded_wakeup = 1;
3676 		}
3677 #endif /* CONFIG_SECLUDED_MEMORY */
3678 	} else {
3679 		mem->vmp_lopage = FALSE;
3680 		mem->vmp_q_state = VM_PAGE_ON_FREE_Q;
3681 
3682 		color = VM_PAGE_GET_COLOR(mem);
3683 #if defined(__x86_64__)
3684 		vm_page_queue_enter_clump(&vm_page_queue_free[color].qhead, mem);
3685 #else
3686 		vm_page_queue_enter(&vm_page_queue_free[color].qhead, mem, vmp_pageq);
3687 #endif
3688 		vm_page_free_count++;
3689 		/*
3690 		 *	Check if we should wake up someone waiting for page.
3691 		 *	But don't bother waking them unless they can allocate.
3692 		 *
3693 		 *	We wakeup only one thread, to prevent starvation.
3694 		 *	Because the scheduling system handles wait queues FIFO,
3695 		 *	if we wakeup all waiting threads, one greedy thread
3696 		 *	can starve multiple niceguy threads.  When the threads
3697 		 *	all wakeup, the greedy threads runs first, grabs the page,
3698 		 *	and waits for another page.  It will be the first to run
3699 		 *	when the next page is freed.
3700 		 *
3701 		 *	However, there is a slight danger here.
3702 		 *	The thread we wake might not use the free page.
3703 		 *	Then the other threads could wait indefinitely
3704 		 *	while the page goes unused.  To forestall this,
3705 		 *	the pageout daemon will keep making free pages
3706 		 *	as long as vm_page_free_wanted is non-zero.
3707 		 */
3708 
3709 		assert(vm_page_free_count > 0);
3710 		if (vm_page_free_wanted_privileged > 0) {
3711 			vm_page_free_wanted_privileged--;
3712 			need_priv_wakeup = 1;
3713 #if CONFIG_SECLUDED_MEMORY
3714 		} else if (vm_page_free_wanted_secluded > 0 &&
3715 		    vm_page_free_count > vm_page_free_reserved) {
3716 			vm_page_free_wanted_secluded--;
3717 			need_secluded_wakeup = 1;
3718 #endif /* CONFIG_SECLUDED_MEMORY */
3719 		} else if (vm_page_free_wanted > 0 &&
3720 		    vm_page_free_count > vm_page_free_reserved) {
3721 			vm_page_free_wanted--;
3722 			need_wakeup = 1;
3723 		}
3724 	}
3725 	vm_pageout_vminfo.vm_page_pages_freed++;
3726 
3727 	VM_DEBUG_CONSTANT_EVENT(vm_page_release, VM_PAGE_RELEASE, DBG_FUNC_NONE, 1, 0, 0, 0);
3728 
3729 	lck_mtx_unlock(&vm_page_queue_free_lock);
3730 
3731 	if (need_priv_wakeup) {
3732 		wakeup_event = &vm_page_free_wanted_privileged;
3733 	}
3734 #if CONFIG_SECLUDED_MEMORY
3735 	else if (need_secluded_wakeup) {
3736 		wakeup_event = &vm_page_free_wanted_secluded;
3737 	}
3738 #endif /* CONFIG_SECLUDED_MEMORY */
3739 	else if (need_wakeup) {
3740 		wakeup_event = &vm_page_free_count;
3741 	}
3742 
3743 	if (wakeup_event) {
3744 		if (vps_dynamic_priority_enabled == TRUE) {
3745 			thread_t thread_woken = NULL;
3746 			wakeup_one_with_inheritor((event_t) wakeup_event, THREAD_AWAKENED, LCK_WAKE_DO_NOT_TRANSFER_PUSH, &thread_woken);
3747 			/*
3748 			 * (80947592) if this is the last reference on this
3749 			 * thread, calling thread_deallocate() here
3750 			 * might take the tasks_threads_lock,
3751 			 * sadly thread_create_internal is doing several
3752 			 * allocations under this lock, which can result in
3753 			 * deadlocks with the pageout scan daemon.
3754 			 *
3755 			 * FIXME: we should disallow allocations under the
3756 			 * task_thread_locks, but that is a larger fix to make.
3757 			 */
3758 			thread_deallocate_safe(thread_woken);
3759 		} else {
3760 			thread_wakeup_one((event_t) wakeup_event);
3761 		}
3762 	}
3763 
3764 	VM_CHECK_MEMORYSTATUS;
3765 }
3766 
3767 /*
3768  * This version of vm_page_release() is used only at startup
3769  * when we are single-threaded and pages are being released
3770  * for the first time. Hence, no locking or unnecessary checks are made.
3771  * Note: VM_CHECK_MEMORYSTATUS invoked by the caller.
3772  */
3773 void
vm_page_release_startup(vm_page_t mem)3774 vm_page_release_startup(
3775 	vm_page_t       mem)
3776 {
3777 	vm_page_queue_t queue_free;
3778 
3779 	if (vm_lopage_free_count < vm_lopage_free_limit &&
3780 	    VM_PAGE_GET_PHYS_PAGE(mem) < max_valid_low_ppnum) {
3781 		mem->vmp_lopage = TRUE;
3782 		mem->vmp_q_state = VM_PAGE_ON_FREE_LOPAGE_Q;
3783 		vm_lopage_free_count++;
3784 		queue_free = &vm_lopage_queue_free;
3785 #if CONFIG_SECLUDED_MEMORY
3786 	} else if (vm_page_secluded_count < vm_page_secluded_target) {
3787 		mem->vmp_lopage = FALSE;
3788 		mem->vmp_q_state = VM_PAGE_ON_SECLUDED_Q;
3789 		vm_page_secluded_count++;
3790 		VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE();
3791 		vm_page_secluded_count_free++;
3792 		queue_free = &vm_page_queue_secluded;
3793 #endif /* CONFIG_SECLUDED_MEMORY */
3794 	} else {
3795 		mem->vmp_lopage = FALSE;
3796 		mem->vmp_q_state = VM_PAGE_ON_FREE_Q;
3797 		vm_page_free_count++;
3798 		queue_free = &vm_page_queue_free[VM_PAGE_GET_COLOR(mem)].qhead;
3799 	}
3800 	if (mem->vmp_q_state == VM_PAGE_ON_FREE_Q) {
3801 #if defined(__x86_64__)
3802 		vm_page_queue_enter_clump(queue_free, mem);
3803 #else
3804 		vm_page_queue_enter(queue_free, mem, vmp_pageq);
3805 #endif
3806 	} else {
3807 		vm_page_queue_enter_first(queue_free, mem, vmp_pageq);
3808 	}
3809 }
3810 
3811 /*
3812  *	vm_page_wait:
3813  *
3814  *	Wait for a page to become available.
3815  *	If there are plenty of free pages, then we don't sleep.
3816  *
3817  *	Returns:
3818  *		TRUE:  There may be another page, try again
3819  *		FALSE: We were interrupted out of our wait, don't try again
3820  */
3821 
3822 boolean_t
vm_page_wait(int interruptible)3823 vm_page_wait(
3824 	int     interruptible )
3825 {
3826 	/*
3827 	 *	We can't use vm_page_free_reserved to make this
3828 	 *	determination.  Consider: some thread might
3829 	 *	need to allocate two pages.  The first allocation
3830 	 *	succeeds, the second fails.  After the first page is freed,
3831 	 *	a call to vm_page_wait must really block.
3832 	 */
3833 	kern_return_t   wait_result;
3834 	int             need_wakeup = 0;
3835 	int             is_privileged = current_thread()->options & TH_OPT_VMPRIV;
3836 	event_t         wait_event = NULL;
3837 
3838 	lck_mtx_lock_spin(&vm_page_queue_free_lock);
3839 
3840 	if (is_privileged && vm_page_free_count) {
3841 		lck_mtx_unlock(&vm_page_queue_free_lock);
3842 		return TRUE;
3843 	}
3844 
3845 	if (vm_page_free_count >= vm_page_free_target) {
3846 		lck_mtx_unlock(&vm_page_queue_free_lock);
3847 		return TRUE;
3848 	}
3849 
3850 	if (is_privileged) {
3851 		if (vm_page_free_wanted_privileged++ == 0) {
3852 			need_wakeup = 1;
3853 		}
3854 		wait_event = (event_t)&vm_page_free_wanted_privileged;
3855 #if CONFIG_SECLUDED_MEMORY
3856 	} else if (secluded_for_apps &&
3857 	    task_can_use_secluded_mem(current_task(), FALSE)) {
3858 #if 00
3859 		/* XXX FBDP: need pageq lock for this... */
3860 		/* XXX FBDP: might wait even if pages available, */
3861 		/* XXX FBDP: hopefully not for too long... */
3862 		if (vm_page_secluded_count > 0) {
3863 			lck_mtx_unlock(&vm_page_queue_free_lock);
3864 			return TRUE;
3865 		}
3866 #endif
3867 		if (vm_page_free_wanted_secluded++ == 0) {
3868 			need_wakeup = 1;
3869 		}
3870 		wait_event = (event_t)&vm_page_free_wanted_secluded;
3871 #endif /* CONFIG_SECLUDED_MEMORY */
3872 	} else {
3873 		if (vm_page_free_wanted++ == 0) {
3874 			need_wakeup = 1;
3875 		}
3876 		wait_event = (event_t)&vm_page_free_count;
3877 	}
3878 
3879 	/*
3880 	 * We don't do a vm_pageout_scan wakeup if we already have
3881 	 * some waiters because vm_pageout_scan checks for waiters
3882 	 * before it returns and does so behind the vm_page_queue_free_lock,
3883 	 * which we own when we bump the waiter counts.
3884 	 */
3885 
3886 	if (vps_dynamic_priority_enabled == TRUE) {
3887 		/*
3888 		 * We are waking up vm_pageout_scan here. If it needs
3889 		 * the vm_page_queue_free_lock before we unlock it
3890 		 * we'll end up just blocking and incur an extra
3891 		 * context switch. Could be a perf. issue.
3892 		 */
3893 
3894 		if (need_wakeup) {
3895 			thread_wakeup((event_t)&vm_page_free_wanted);
3896 		}
3897 
3898 		/*
3899 		 * LD: This event is going to get recorded every time because
3900 		 * we don't get back THREAD_WAITING from lck_mtx_sleep_with_inheritor.
3901 		 * We just block in that routine.
3902 		 */
3903 		VM_DEBUG_CONSTANT_EVENT(vm_page_wait_block, VM_PAGE_WAIT_BLOCK, DBG_FUNC_START,
3904 		    vm_page_free_wanted_privileged,
3905 		    vm_page_free_wanted,
3906 #if CONFIG_SECLUDED_MEMORY
3907 		    vm_page_free_wanted_secluded,
3908 #else /* CONFIG_SECLUDED_MEMORY */
3909 		    0,
3910 #endif /* CONFIG_SECLUDED_MEMORY */
3911 		    0);
3912 		wait_result =  lck_mtx_sleep_with_inheritor(&vm_page_queue_free_lock,
3913 		    LCK_SLEEP_UNLOCK,
3914 		    wait_event,
3915 		    vm_pageout_scan_thread,
3916 		    interruptible,
3917 		    0);
3918 	} else {
3919 		wait_result = assert_wait(wait_event, interruptible);
3920 
3921 		lck_mtx_unlock(&vm_page_queue_free_lock);
3922 
3923 		if (need_wakeup) {
3924 			thread_wakeup((event_t)&vm_page_free_wanted);
3925 		}
3926 
3927 		if (wait_result == THREAD_WAITING) {
3928 			VM_DEBUG_CONSTANT_EVENT(vm_page_wait_block, VM_PAGE_WAIT_BLOCK, DBG_FUNC_START,
3929 			    vm_page_free_wanted_privileged,
3930 			    vm_page_free_wanted,
3931 #if CONFIG_SECLUDED_MEMORY
3932 			    vm_page_free_wanted_secluded,
3933 #else /* CONFIG_SECLUDED_MEMORY */
3934 			    0,
3935 #endif /* CONFIG_SECLUDED_MEMORY */
3936 			    0);
3937 			wait_result = thread_block(THREAD_CONTINUE_NULL);
3938 			VM_DEBUG_CONSTANT_EVENT(vm_page_wait_block,
3939 			    VM_PAGE_WAIT_BLOCK, DBG_FUNC_END, 0, 0, 0, 0);
3940 		}
3941 	}
3942 
3943 	return (wait_result == THREAD_AWAKENED) || (wait_result == THREAD_NOT_WAITING);
3944 }
3945 
3946 /*
3947  *	vm_page_alloc:
3948  *
3949  *	Allocate and return a memory cell associated
3950  *	with this VM object/offset pair.
3951  *
3952  *	Object must be locked.
3953  */
3954 
3955 vm_page_t
vm_page_alloc(vm_object_t object,vm_object_offset_t offset)3956 vm_page_alloc(
3957 	vm_object_t             object,
3958 	vm_object_offset_t      offset)
3959 {
3960 	vm_page_t       mem;
3961 	int             grab_options;
3962 
3963 	vm_object_lock_assert_exclusive(object);
3964 	grab_options = 0;
3965 #if CONFIG_SECLUDED_MEMORY
3966 	if (object->can_grab_secluded) {
3967 		grab_options |= VM_PAGE_GRAB_SECLUDED;
3968 	}
3969 #endif /* CONFIG_SECLUDED_MEMORY */
3970 	mem = vm_page_grab_options(grab_options);
3971 	if (mem == VM_PAGE_NULL) {
3972 		return VM_PAGE_NULL;
3973 	}
3974 
3975 	vm_page_insert(mem, object, offset);
3976 
3977 	return mem;
3978 }
3979 
3980 /*
3981  *	vm_page_free_prepare:
3982  *
3983  *	Removes page from any queue it may be on
3984  *	and disassociates it from its VM object.
3985  *
3986  *	Object and page queues must be locked prior to entry.
3987  */
3988 static void
vm_page_free_prepare(vm_page_t mem)3989 vm_page_free_prepare(
3990 	vm_page_t       mem)
3991 {
3992 	vm_page_free_prepare_queues(mem);
3993 	vm_page_free_prepare_object(mem, TRUE);
3994 }
3995 
3996 
3997 void
vm_page_free_prepare_queues(vm_page_t mem)3998 vm_page_free_prepare_queues(
3999 	vm_page_t       mem)
4000 {
4001 	vm_object_t     m_object;
4002 
4003 	VM_PAGE_CHECK(mem);
4004 
4005 	assert(mem->vmp_q_state != VM_PAGE_ON_FREE_Q);
4006 	assert(!mem->vmp_cleaning);
4007 	m_object = VM_PAGE_OBJECT(mem);
4008 
4009 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
4010 	if (m_object) {
4011 		vm_object_lock_assert_exclusive(m_object);
4012 	}
4013 	if (mem->vmp_laundry) {
4014 		/*
4015 		 * We may have to free a page while it's being laundered
4016 		 * if we lost its pager (due to a forced unmount, for example).
4017 		 * We need to call vm_pageout_steal_laundry() before removing
4018 		 * the page from its VM object, so that we can remove it
4019 		 * from its pageout queue and adjust the laundry accounting
4020 		 */
4021 		vm_pageout_steal_laundry(mem, TRUE);
4022 	}
4023 
4024 	vm_page_queues_remove(mem, TRUE);
4025 
4026 	if (VM_PAGE_WIRED(mem)) {
4027 		assert(mem->vmp_wire_count > 0);
4028 
4029 		if (m_object) {
4030 			VM_OBJECT_WIRED_PAGE_UPDATE_START(m_object);
4031 			VM_OBJECT_WIRED_PAGE_REMOVE(m_object, mem);
4032 			VM_OBJECT_WIRED_PAGE_UPDATE_END(m_object, m_object->wire_tag);
4033 
4034 			assert(m_object->resident_page_count >=
4035 			    m_object->wired_page_count);
4036 
4037 			if (m_object->purgable == VM_PURGABLE_VOLATILE) {
4038 				OSAddAtomic(+1, &vm_page_purgeable_count);
4039 				assert(vm_page_purgeable_wired_count > 0);
4040 				OSAddAtomic(-1, &vm_page_purgeable_wired_count);
4041 			}
4042 			if ((m_object->purgable == VM_PURGABLE_VOLATILE ||
4043 			    m_object->purgable == VM_PURGABLE_EMPTY) &&
4044 			    m_object->vo_owner != TASK_NULL) {
4045 				task_t          owner;
4046 				int             ledger_idx_volatile;
4047 				int             ledger_idx_nonvolatile;
4048 				int             ledger_idx_volatile_compressed;
4049 				int             ledger_idx_nonvolatile_compressed;
4050 				boolean_t       do_footprint;
4051 
4052 				owner = VM_OBJECT_OWNER(m_object);
4053 				vm_object_ledger_tag_ledgers(
4054 					m_object,
4055 					&ledger_idx_volatile,
4056 					&ledger_idx_nonvolatile,
4057 					&ledger_idx_volatile_compressed,
4058 					&ledger_idx_nonvolatile_compressed,
4059 					&do_footprint);
4060 				/*
4061 				 * While wired, this page was accounted
4062 				 * as "non-volatile" but it should now
4063 				 * be accounted as "volatile".
4064 				 */
4065 				/* one less "non-volatile"... */
4066 				ledger_debit(owner->ledger,
4067 				    ledger_idx_nonvolatile,
4068 				    PAGE_SIZE);
4069 				if (do_footprint) {
4070 					/* ... and "phys_footprint" */
4071 					ledger_debit(owner->ledger,
4072 					    task_ledgers.phys_footprint,
4073 					    PAGE_SIZE);
4074 				}
4075 				/* one more "volatile" */
4076 				ledger_credit(owner->ledger,
4077 				    ledger_idx_volatile,
4078 				    PAGE_SIZE);
4079 			}
4080 		}
4081 		if (!mem->vmp_private && !mem->vmp_fictitious) {
4082 			vm_page_wire_count--;
4083 		}
4084 
4085 		mem->vmp_q_state = VM_PAGE_NOT_ON_Q;
4086 		mem->vmp_wire_count = 0;
4087 		assert(!mem->vmp_gobbled);
4088 	} else if (mem->vmp_gobbled) {
4089 		if (!mem->vmp_private && !mem->vmp_fictitious) {
4090 			vm_page_wire_count--;
4091 		}
4092 		vm_page_gobble_count--;
4093 	}
4094 }
4095 
4096 
4097 void
vm_page_free_prepare_object(vm_page_t mem,boolean_t remove_from_hash)4098 vm_page_free_prepare_object(
4099 	vm_page_t       mem,
4100 	boolean_t       remove_from_hash)
4101 {
4102 	if (mem->vmp_tabled) {
4103 		vm_page_remove(mem, remove_from_hash);  /* clears tabled, object, offset */
4104 	}
4105 	PAGE_WAKEUP(mem);               /* clears wanted */
4106 
4107 	if (mem->vmp_private) {
4108 		mem->vmp_private = FALSE;
4109 		mem->vmp_fictitious = TRUE;
4110 		VM_PAGE_SET_PHYS_PAGE(mem, vm_page_fictitious_addr);
4111 	}
4112 	if (!mem->vmp_fictitious) {
4113 		assert(mem->vmp_pageq.next == 0);
4114 		assert(mem->vmp_pageq.prev == 0);
4115 		assert(mem->vmp_listq.next == 0);
4116 		assert(mem->vmp_listq.prev == 0);
4117 #if CONFIG_BACKGROUND_QUEUE
4118 		assert(mem->vmp_backgroundq.next == 0);
4119 		assert(mem->vmp_backgroundq.prev == 0);
4120 #endif /* CONFIG_BACKGROUND_QUEUE */
4121 		assert(mem->vmp_next_m == 0);
4122 		ASSERT_PMAP_FREE(mem);
4123 		vm_page_init(mem, VM_PAGE_GET_PHYS_PAGE(mem), mem->vmp_lopage);
4124 	}
4125 }
4126 
4127 
4128 /*
4129  *	vm_page_free:
4130  *
4131  *	Returns the given page to the free list,
4132  *	disassociating it with any VM object.
4133  *
4134  *	Object and page queues must be locked prior to entry.
4135  */
4136 void
vm_page_free(vm_page_t mem)4137 vm_page_free(
4138 	vm_page_t       mem)
4139 {
4140 	vm_page_free_prepare(mem);
4141 
4142 	if (mem->vmp_fictitious) {
4143 		vm_page_release_fictitious(mem);
4144 	} else {
4145 		vm_page_release(mem,
4146 		    TRUE);             /* page queues are locked */
4147 	}
4148 }
4149 
4150 
4151 void
vm_page_free_unlocked(vm_page_t mem,boolean_t remove_from_hash)4152 vm_page_free_unlocked(
4153 	vm_page_t       mem,
4154 	boolean_t       remove_from_hash)
4155 {
4156 	vm_page_lockspin_queues();
4157 	vm_page_free_prepare_queues(mem);
4158 	vm_page_unlock_queues();
4159 
4160 	vm_page_free_prepare_object(mem, remove_from_hash);
4161 
4162 	if (mem->vmp_fictitious) {
4163 		vm_page_release_fictitious(mem);
4164 	} else {
4165 		vm_page_release(mem, FALSE); /* page queues are not locked */
4166 	}
4167 }
4168 
4169 
4170 /*
4171  * Free a list of pages.  The list can be up to several hundred pages,
4172  * as blocked up by vm_pageout_scan().
4173  * The big win is not having to take the free list lock once
4174  * per page.
4175  *
4176  * The VM page queues lock (vm_page_queue_lock) should NOT be held.
4177  * The VM page free queues lock (vm_page_queue_free_lock) should NOT be held.
4178  */
4179 void
vm_page_free_list(vm_page_t freeq,boolean_t prepare_object)4180 vm_page_free_list(
4181 	vm_page_t       freeq,
4182 	boolean_t       prepare_object)
4183 {
4184 	vm_page_t       mem;
4185 	vm_page_t       nxt;
4186 	vm_page_t       local_freeq;
4187 	int             pg_count;
4188 
4189 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_NOTOWNED);
4190 	LCK_MTX_ASSERT(&vm_page_queue_free_lock, LCK_MTX_ASSERT_NOTOWNED);
4191 
4192 	while (freeq) {
4193 		pg_count = 0;
4194 		local_freeq = VM_PAGE_NULL;
4195 		mem = freeq;
4196 
4197 		/*
4198 		 * break up the processing into smaller chunks so
4199 		 * that we can 'pipeline' the pages onto the
4200 		 * free list w/o introducing too much
4201 		 * contention on the global free queue lock
4202 		 */
4203 		while (mem && pg_count < 64) {
4204 			assert((mem->vmp_q_state == VM_PAGE_NOT_ON_Q) ||
4205 			    (mem->vmp_q_state == VM_PAGE_IS_WIRED));
4206 #if CONFIG_BACKGROUND_QUEUE
4207 			assert(mem->vmp_backgroundq.next == 0 &&
4208 			    mem->vmp_backgroundq.prev == 0 &&
4209 			    mem->vmp_on_backgroundq == FALSE);
4210 #endif
4211 			nxt = mem->vmp_snext;
4212 			mem->vmp_snext = NULL;
4213 			assert(mem->vmp_pageq.prev == 0);
4214 
4215 			if (vm_page_free_verify && !mem->vmp_fictitious && !mem->vmp_private) {
4216 				ASSERT_PMAP_FREE(mem);
4217 			}
4218 			if (prepare_object == TRUE) {
4219 				vm_page_free_prepare_object(mem, TRUE);
4220 			}
4221 
4222 			if (!mem->vmp_fictitious) {
4223 				assert(mem->vmp_busy);
4224 
4225 				if ((mem->vmp_lopage == TRUE || vm_lopage_refill == TRUE) &&
4226 				    vm_lopage_free_count < vm_lopage_free_limit &&
4227 				    VM_PAGE_GET_PHYS_PAGE(mem) < max_valid_low_ppnum) {
4228 					vm_page_release(mem, FALSE); /* page queues are not locked */
4229 #if CONFIG_SECLUDED_MEMORY
4230 				} else if (vm_page_secluded_count < vm_page_secluded_target &&
4231 				    num_tasks_can_use_secluded_mem == 0) {
4232 					vm_page_release(mem,
4233 					    FALSE);             /* page queues are not locked */
4234 #endif /* CONFIG_SECLUDED_MEMORY */
4235 				} else {
4236 					/*
4237 					 * IMPORTANT: we can't set the page "free" here
4238 					 * because that would make the page eligible for
4239 					 * a physically-contiguous allocation (see
4240 					 * vm_page_find_contiguous()) right away (we don't
4241 					 * hold the vm_page_queue_free lock).  That would
4242 					 * cause trouble because the page is not actually
4243 					 * in the free queue yet...
4244 					 */
4245 					mem->vmp_snext = local_freeq;
4246 					local_freeq = mem;
4247 					pg_count++;
4248 
4249 					pmap_clear_noencrypt(VM_PAGE_GET_PHYS_PAGE(mem));
4250 				}
4251 			} else {
4252 				assert(VM_PAGE_GET_PHYS_PAGE(mem) == vm_page_fictitious_addr ||
4253 				    VM_PAGE_GET_PHYS_PAGE(mem) == vm_page_guard_addr);
4254 				vm_page_release_fictitious(mem);
4255 			}
4256 			mem = nxt;
4257 		}
4258 		freeq = mem;
4259 
4260 		if ((mem = local_freeq)) {
4261 			unsigned int    avail_free_count;
4262 			unsigned int    need_wakeup = 0;
4263 			unsigned int    need_priv_wakeup = 0;
4264 #if CONFIG_SECLUDED_MEMORY
4265 			unsigned int    need_wakeup_secluded = 0;
4266 #endif /* CONFIG_SECLUDED_MEMORY */
4267 			event_t         priv_wakeup_event, secluded_wakeup_event, normal_wakeup_event;
4268 			boolean_t       priv_wakeup_all, secluded_wakeup_all, normal_wakeup_all;
4269 
4270 			lck_mtx_lock_spin(&vm_page_queue_free_lock);
4271 
4272 			while (mem) {
4273 				int     color;
4274 
4275 				nxt = mem->vmp_snext;
4276 
4277 				assert(mem->vmp_q_state == VM_PAGE_NOT_ON_Q);
4278 				assert(mem->vmp_busy);
4279 				mem->vmp_lopage = FALSE;
4280 				mem->vmp_q_state = VM_PAGE_ON_FREE_Q;
4281 
4282 				color = VM_PAGE_GET_COLOR(mem);
4283 #if defined(__x86_64__)
4284 				vm_page_queue_enter_clump(&vm_page_queue_free[color].qhead, mem);
4285 #else
4286 				vm_page_queue_enter(&vm_page_queue_free[color].qhead,
4287 				    mem, vmp_pageq);
4288 #endif
4289 				mem = nxt;
4290 			}
4291 			vm_pageout_vminfo.vm_page_pages_freed += pg_count;
4292 			vm_page_free_count += pg_count;
4293 			avail_free_count = vm_page_free_count;
4294 
4295 			VM_DEBUG_CONSTANT_EVENT(vm_page_release, VM_PAGE_RELEASE, DBG_FUNC_NONE, pg_count, 0, 0, 0);
4296 
4297 			if (vm_page_free_wanted_privileged > 0 && avail_free_count > 0) {
4298 				if (avail_free_count < vm_page_free_wanted_privileged) {
4299 					need_priv_wakeup = avail_free_count;
4300 					vm_page_free_wanted_privileged -= avail_free_count;
4301 					avail_free_count = 0;
4302 				} else {
4303 					need_priv_wakeup = vm_page_free_wanted_privileged;
4304 					avail_free_count -= vm_page_free_wanted_privileged;
4305 					vm_page_free_wanted_privileged = 0;
4306 				}
4307 			}
4308 #if CONFIG_SECLUDED_MEMORY
4309 			if (vm_page_free_wanted_secluded > 0 &&
4310 			    avail_free_count > vm_page_free_reserved) {
4311 				unsigned int available_pages;
4312 				available_pages = (avail_free_count -
4313 				    vm_page_free_reserved);
4314 				if (available_pages <
4315 				    vm_page_free_wanted_secluded) {
4316 					need_wakeup_secluded = available_pages;
4317 					vm_page_free_wanted_secluded -=
4318 					    available_pages;
4319 					avail_free_count -= available_pages;
4320 				} else {
4321 					need_wakeup_secluded =
4322 					    vm_page_free_wanted_secluded;
4323 					avail_free_count -=
4324 					    vm_page_free_wanted_secluded;
4325 					vm_page_free_wanted_secluded = 0;
4326 				}
4327 			}
4328 #endif /* CONFIG_SECLUDED_MEMORY */
4329 			if (vm_page_free_wanted > 0 && avail_free_count > vm_page_free_reserved) {
4330 				unsigned int  available_pages;
4331 
4332 				available_pages = avail_free_count - vm_page_free_reserved;
4333 
4334 				if (available_pages >= vm_page_free_wanted) {
4335 					need_wakeup = vm_page_free_wanted;
4336 					vm_page_free_wanted = 0;
4337 				} else {
4338 					need_wakeup = available_pages;
4339 					vm_page_free_wanted -= available_pages;
4340 				}
4341 			}
4342 			lck_mtx_unlock(&vm_page_queue_free_lock);
4343 
4344 			priv_wakeup_event = NULL;
4345 			secluded_wakeup_event = NULL;
4346 			normal_wakeup_event = NULL;
4347 
4348 			priv_wakeup_all = FALSE;
4349 			secluded_wakeup_all = FALSE;
4350 			normal_wakeup_all = FALSE;
4351 
4352 
4353 			if (need_priv_wakeup != 0) {
4354 				/*
4355 				 * There shouldn't be that many VM-privileged threads,
4356 				 * so let's wake them all up, even if we don't quite
4357 				 * have enough pages to satisfy them all.
4358 				 */
4359 				priv_wakeup_event = (event_t)&vm_page_free_wanted_privileged;
4360 				priv_wakeup_all = TRUE;
4361 			}
4362 #if CONFIG_SECLUDED_MEMORY
4363 			if (need_wakeup_secluded != 0 &&
4364 			    vm_page_free_wanted_secluded == 0) {
4365 				secluded_wakeup_event = (event_t)&vm_page_free_wanted_secluded;
4366 				secluded_wakeup_all = TRUE;
4367 				need_wakeup_secluded = 0;
4368 			} else {
4369 				secluded_wakeup_event = (event_t)&vm_page_free_wanted_secluded;
4370 			}
4371 #endif /* CONFIG_SECLUDED_MEMORY */
4372 			if (need_wakeup != 0 && vm_page_free_wanted == 0) {
4373 				/*
4374 				 * We don't expect to have any more waiters
4375 				 * after this, so let's wake them all up at
4376 				 * once.
4377 				 */
4378 				normal_wakeup_event = (event_t) &vm_page_free_count;
4379 				normal_wakeup_all = TRUE;
4380 				need_wakeup = 0;
4381 			} else {
4382 				normal_wakeup_event = (event_t) &vm_page_free_count;
4383 			}
4384 
4385 			if (priv_wakeup_event ||
4386 #if CONFIG_SECLUDED_MEMORY
4387 			    secluded_wakeup_event ||
4388 #endif /* CONFIG_SECLUDED_MEMORY */
4389 			    normal_wakeup_event) {
4390 				if (vps_dynamic_priority_enabled == TRUE) {
4391 					thread_t thread_woken = NULL;
4392 
4393 					if (priv_wakeup_all == TRUE) {
4394 						wakeup_all_with_inheritor(priv_wakeup_event, THREAD_AWAKENED);
4395 					}
4396 
4397 #if CONFIG_SECLUDED_MEMORY
4398 					if (secluded_wakeup_all == TRUE) {
4399 						wakeup_all_with_inheritor(secluded_wakeup_event, THREAD_AWAKENED);
4400 					}
4401 
4402 					while (need_wakeup_secluded-- != 0) {
4403 						/*
4404 						 * Wake up one waiter per page we just released.
4405 						 */
4406 						wakeup_one_with_inheritor(secluded_wakeup_event, THREAD_AWAKENED, LCK_WAKE_DO_NOT_TRANSFER_PUSH, &thread_woken);
4407 						thread_deallocate(thread_woken);
4408 					}
4409 #endif /* CONFIG_SECLUDED_MEMORY */
4410 
4411 					if (normal_wakeup_all == TRUE) {
4412 						wakeup_all_with_inheritor(normal_wakeup_event, THREAD_AWAKENED);
4413 					}
4414 
4415 					while (need_wakeup-- != 0) {
4416 						/*
4417 						 * Wake up one waiter per page we just released.
4418 						 */
4419 						wakeup_one_with_inheritor(normal_wakeup_event, THREAD_AWAKENED, LCK_WAKE_DO_NOT_TRANSFER_PUSH, &thread_woken);
4420 						thread_deallocate(thread_woken);
4421 					}
4422 				} else {
4423 					/*
4424 					 * Non-priority-aware wakeups.
4425 					 */
4426 
4427 					if (priv_wakeup_all == TRUE) {
4428 						thread_wakeup(priv_wakeup_event);
4429 					}
4430 
4431 #if CONFIG_SECLUDED_MEMORY
4432 					if (secluded_wakeup_all == TRUE) {
4433 						thread_wakeup(secluded_wakeup_event);
4434 					}
4435 
4436 					while (need_wakeup_secluded-- != 0) {
4437 						/*
4438 						 * Wake up one waiter per page we just released.
4439 						 */
4440 						thread_wakeup_one(secluded_wakeup_event);
4441 					}
4442 
4443 #endif /* CONFIG_SECLUDED_MEMORY */
4444 					if (normal_wakeup_all == TRUE) {
4445 						thread_wakeup(normal_wakeup_event);
4446 					}
4447 
4448 					while (need_wakeup-- != 0) {
4449 						/*
4450 						 * Wake up one waiter per page we just released.
4451 						 */
4452 						thread_wakeup_one(normal_wakeup_event);
4453 					}
4454 				}
4455 			}
4456 
4457 			VM_CHECK_MEMORYSTATUS;
4458 		}
4459 	}
4460 }
4461 
4462 
4463 /*
4464  *	vm_page_wire:
4465  *
4466  *	Mark this page as wired down by yet
4467  *	another map, removing it from paging queues
4468  *	as necessary.
4469  *
4470  *	The page's object and the page queues must be locked.
4471  */
4472 
4473 
4474 void
vm_page_wire(vm_page_t mem,vm_tag_t tag,boolean_t check_memorystatus)4475 vm_page_wire(
4476 	vm_page_t mem,
4477 	vm_tag_t           tag,
4478 	boolean_t          check_memorystatus)
4479 {
4480 	vm_object_t     m_object;
4481 
4482 	m_object = VM_PAGE_OBJECT(mem);
4483 
4484 //	dbgLog(current_thread(), mem->vmp_offset, m_object, 1);	/* (TEST/DEBUG) */
4485 
4486 	VM_PAGE_CHECK(mem);
4487 	if (m_object) {
4488 		vm_object_lock_assert_exclusive(m_object);
4489 	} else {
4490 		/*
4491 		 * In theory, the page should be in an object before it
4492 		 * gets wired, since we need to hold the object lock
4493 		 * to update some fields in the page structure.
4494 		 * However, some code (i386 pmap, for example) might want
4495 		 * to wire a page before it gets inserted into an object.
4496 		 * That's somewhat OK, as long as nobody else can get to
4497 		 * that page and update it at the same time.
4498 		 */
4499 	}
4500 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
4501 	if (!VM_PAGE_WIRED(mem)) {
4502 		if (mem->vmp_laundry) {
4503 			vm_pageout_steal_laundry(mem, TRUE);
4504 		}
4505 
4506 		vm_page_queues_remove(mem, TRUE);
4507 
4508 		assert(mem->vmp_wire_count == 0);
4509 		mem->vmp_q_state = VM_PAGE_IS_WIRED;
4510 
4511 		if (m_object) {
4512 			VM_OBJECT_WIRED_PAGE_UPDATE_START(m_object);
4513 			VM_OBJECT_WIRED_PAGE_ADD(m_object, mem);
4514 			VM_OBJECT_WIRED_PAGE_UPDATE_END(m_object, tag);
4515 
4516 			assert(m_object->resident_page_count >=
4517 			    m_object->wired_page_count);
4518 			if (m_object->purgable == VM_PURGABLE_VOLATILE) {
4519 				assert(vm_page_purgeable_count > 0);
4520 				OSAddAtomic(-1, &vm_page_purgeable_count);
4521 				OSAddAtomic(1, &vm_page_purgeable_wired_count);
4522 			}
4523 			if ((m_object->purgable == VM_PURGABLE_VOLATILE ||
4524 			    m_object->purgable == VM_PURGABLE_EMPTY) &&
4525 			    m_object->vo_owner != TASK_NULL) {
4526 				task_t          owner;
4527 				int             ledger_idx_volatile;
4528 				int             ledger_idx_nonvolatile;
4529 				int             ledger_idx_volatile_compressed;
4530 				int             ledger_idx_nonvolatile_compressed;
4531 				boolean_t       do_footprint;
4532 
4533 				owner = VM_OBJECT_OWNER(m_object);
4534 				vm_object_ledger_tag_ledgers(
4535 					m_object,
4536 					&ledger_idx_volatile,
4537 					&ledger_idx_nonvolatile,
4538 					&ledger_idx_volatile_compressed,
4539 					&ledger_idx_nonvolatile_compressed,
4540 					&do_footprint);
4541 				/* less volatile bytes */
4542 				ledger_debit(owner->ledger,
4543 				    ledger_idx_volatile,
4544 				    PAGE_SIZE);
4545 				/* more not-quite-volatile bytes */
4546 				ledger_credit(owner->ledger,
4547 				    ledger_idx_nonvolatile,
4548 				    PAGE_SIZE);
4549 				if (do_footprint) {
4550 					/* more footprint */
4551 					ledger_credit(owner->ledger,
4552 					    task_ledgers.phys_footprint,
4553 					    PAGE_SIZE);
4554 				}
4555 			}
4556 			if (m_object->all_reusable) {
4557 				/*
4558 				 * Wired pages are not counted as "re-usable"
4559 				 * in "all_reusable" VM objects, so nothing
4560 				 * to do here.
4561 				 */
4562 			} else if (mem->vmp_reusable) {
4563 				/*
4564 				 * This page is not "re-usable" when it's
4565 				 * wired, so adjust its state and the
4566 				 * accounting.
4567 				 */
4568 				vm_object_reuse_pages(m_object,
4569 				    mem->vmp_offset,
4570 				    mem->vmp_offset + PAGE_SIZE_64,
4571 				    FALSE);
4572 			}
4573 		}
4574 		assert(!mem->vmp_reusable);
4575 
4576 		if (!mem->vmp_private && !mem->vmp_fictitious && !mem->vmp_gobbled) {
4577 			vm_page_wire_count++;
4578 		}
4579 		if (mem->vmp_gobbled) {
4580 			vm_page_gobble_count--;
4581 		}
4582 		mem->vmp_gobbled = FALSE;
4583 
4584 		if (check_memorystatus == TRUE) {
4585 			VM_CHECK_MEMORYSTATUS;
4586 		}
4587 	}
4588 	assert(!mem->vmp_gobbled);
4589 	assert(mem->vmp_q_state == VM_PAGE_IS_WIRED);
4590 	mem->vmp_wire_count++;
4591 	if (__improbable(mem->vmp_wire_count == 0)) {
4592 		panic("vm_page_wire(%p): wire_count overflow", mem);
4593 	}
4594 	VM_PAGE_CHECK(mem);
4595 }
4596 
4597 /*
4598  *	vm_page_unwire:
4599  *
4600  *	Release one wiring of this page, potentially
4601  *	enabling it to be paged again.
4602  *
4603  *	The page's object and the page queues must be locked.
4604  */
4605 void
vm_page_unwire(vm_page_t mem,boolean_t queueit)4606 vm_page_unwire(
4607 	vm_page_t       mem,
4608 	boolean_t       queueit)
4609 {
4610 	vm_object_t     m_object;
4611 
4612 	m_object = VM_PAGE_OBJECT(mem);
4613 
4614 //	dbgLog(current_thread(), mem->vmp_offset, m_object, 0);	/* (TEST/DEBUG) */
4615 
4616 	VM_PAGE_CHECK(mem);
4617 	assert(VM_PAGE_WIRED(mem));
4618 	assert(mem->vmp_wire_count > 0);
4619 	assert(!mem->vmp_gobbled);
4620 	assert(m_object != VM_OBJECT_NULL);
4621 	vm_object_lock_assert_exclusive(m_object);
4622 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
4623 	if (--mem->vmp_wire_count == 0) {
4624 		mem->vmp_q_state = VM_PAGE_NOT_ON_Q;
4625 
4626 		VM_OBJECT_WIRED_PAGE_UPDATE_START(m_object);
4627 		VM_OBJECT_WIRED_PAGE_REMOVE(m_object, mem);
4628 		VM_OBJECT_WIRED_PAGE_UPDATE_END(m_object, m_object->wire_tag);
4629 		if (!mem->vmp_private && !mem->vmp_fictitious) {
4630 			vm_page_wire_count--;
4631 		}
4632 
4633 		assert(m_object->resident_page_count >=
4634 		    m_object->wired_page_count);
4635 		if (m_object->purgable == VM_PURGABLE_VOLATILE) {
4636 			OSAddAtomic(+1, &vm_page_purgeable_count);
4637 			assert(vm_page_purgeable_wired_count > 0);
4638 			OSAddAtomic(-1, &vm_page_purgeable_wired_count);
4639 		}
4640 		if ((m_object->purgable == VM_PURGABLE_VOLATILE ||
4641 		    m_object->purgable == VM_PURGABLE_EMPTY) &&
4642 		    m_object->vo_owner != TASK_NULL) {
4643 			task_t          owner;
4644 			int             ledger_idx_volatile;
4645 			int             ledger_idx_nonvolatile;
4646 			int             ledger_idx_volatile_compressed;
4647 			int             ledger_idx_nonvolatile_compressed;
4648 			boolean_t       do_footprint;
4649 
4650 			owner = VM_OBJECT_OWNER(m_object);
4651 			vm_object_ledger_tag_ledgers(
4652 				m_object,
4653 				&ledger_idx_volatile,
4654 				&ledger_idx_nonvolatile,
4655 				&ledger_idx_volatile_compressed,
4656 				&ledger_idx_nonvolatile_compressed,
4657 				&do_footprint);
4658 			/* more volatile bytes */
4659 			ledger_credit(owner->ledger,
4660 			    ledger_idx_volatile,
4661 			    PAGE_SIZE);
4662 			/* less not-quite-volatile bytes */
4663 			ledger_debit(owner->ledger,
4664 			    ledger_idx_nonvolatile,
4665 			    PAGE_SIZE);
4666 			if (do_footprint) {
4667 				/* less footprint */
4668 				ledger_debit(owner->ledger,
4669 				    task_ledgers.phys_footprint,
4670 				    PAGE_SIZE);
4671 			}
4672 		}
4673 		assert(m_object != kernel_object);
4674 		assert(mem->vmp_pageq.next == 0 && mem->vmp_pageq.prev == 0);
4675 
4676 		if (queueit == TRUE) {
4677 			if (m_object->purgable == VM_PURGABLE_EMPTY) {
4678 				vm_page_deactivate(mem);
4679 			} else {
4680 				vm_page_activate(mem);
4681 			}
4682 		}
4683 
4684 		VM_CHECK_MEMORYSTATUS;
4685 	}
4686 	VM_PAGE_CHECK(mem);
4687 }
4688 
4689 /*
4690  *	vm_page_deactivate:
4691  *
4692  *	Returns the given page to the inactive list,
4693  *	indicating that no physical maps have access
4694  *	to this page.  [Used by the physical mapping system.]
4695  *
4696  *	The page queues must be locked.
4697  */
4698 void
vm_page_deactivate(vm_page_t m)4699 vm_page_deactivate(
4700 	vm_page_t       m)
4701 {
4702 	vm_page_deactivate_internal(m, TRUE);
4703 }
4704 
4705 
4706 void
vm_page_deactivate_internal(vm_page_t m,boolean_t clear_hw_reference)4707 vm_page_deactivate_internal(
4708 	vm_page_t       m,
4709 	boolean_t       clear_hw_reference)
4710 {
4711 	vm_object_t     m_object;
4712 
4713 	m_object = VM_PAGE_OBJECT(m);
4714 
4715 	VM_PAGE_CHECK(m);
4716 	assert(m_object != kernel_object);
4717 	assert(VM_PAGE_GET_PHYS_PAGE(m) != vm_page_guard_addr);
4718 
4719 //	dbgLog(VM_PAGE_GET_PHYS_PAGE(m), vm_page_free_count, vm_page_wire_count, 6);	/* (TEST/DEBUG) */
4720 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
4721 	/*
4722 	 *	This page is no longer very interesting.  If it was
4723 	 *	interesting (active or inactive/referenced), then we
4724 	 *	clear the reference bit and (re)enter it in the
4725 	 *	inactive queue.  Note wired pages should not have
4726 	 *	their reference bit cleared.
4727 	 */
4728 	assert( !(m->vmp_absent && !m->vmp_unusual));
4729 
4730 	if (m->vmp_gobbled) {           /* can this happen? */
4731 		assert( !VM_PAGE_WIRED(m));
4732 
4733 		if (!m->vmp_private && !m->vmp_fictitious) {
4734 			vm_page_wire_count--;
4735 		}
4736 		vm_page_gobble_count--;
4737 		m->vmp_gobbled = FALSE;
4738 	}
4739 	/*
4740 	 * if this page is currently on the pageout queue, we can't do the
4741 	 * vm_page_queues_remove (which doesn't handle the pageout queue case)
4742 	 * and we can't remove it manually since we would need the object lock
4743 	 * (which is not required here) to decrement the activity_in_progress
4744 	 * reference which is held on the object while the page is in the pageout queue...
4745 	 * just let the normal laundry processing proceed
4746 	 */
4747 	if (m->vmp_laundry || m->vmp_private || m->vmp_fictitious ||
4748 	    (m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) ||
4749 	    (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q) ||
4750 	    VM_PAGE_WIRED(m)) {
4751 		return;
4752 	}
4753 	if (!m->vmp_absent && clear_hw_reference == TRUE) {
4754 		pmap_clear_reference(VM_PAGE_GET_PHYS_PAGE(m));
4755 	}
4756 
4757 	m->vmp_reference = FALSE;
4758 	m->vmp_no_cache = FALSE;
4759 
4760 	if (!VM_PAGE_INACTIVE(m)) {
4761 		vm_page_queues_remove(m, FALSE);
4762 
4763 		if (!VM_DYNAMIC_PAGING_ENABLED() &&
4764 		    m->vmp_dirty && m_object->internal &&
4765 		    (m_object->purgable == VM_PURGABLE_DENY ||
4766 		    m_object->purgable == VM_PURGABLE_NONVOLATILE ||
4767 		    m_object->purgable == VM_PURGABLE_VOLATILE)) {
4768 			vm_page_check_pageable_safe(m);
4769 			vm_page_queue_enter(&vm_page_queue_throttled, m, vmp_pageq);
4770 			m->vmp_q_state = VM_PAGE_ON_THROTTLED_Q;
4771 			vm_page_throttled_count++;
4772 		} else {
4773 			if (m_object->named && m_object->ref_count == 1) {
4774 				vm_page_speculate(m, FALSE);
4775 #if DEVELOPMENT || DEBUG
4776 				vm_page_speculative_recreated++;
4777 #endif
4778 			} else {
4779 				vm_page_enqueue_inactive(m, FALSE);
4780 			}
4781 		}
4782 	}
4783 }
4784 
4785 /*
4786  * vm_page_enqueue_cleaned
4787  *
4788  * Put the page on the cleaned queue, mark it cleaned, etc.
4789  * Being on the cleaned queue (and having m->clean_queue set)
4790  * does ** NOT ** guarantee that the page is clean!
4791  *
4792  * Call with the queues lock held.
4793  */
4794 
4795 void
vm_page_enqueue_cleaned(vm_page_t m)4796 vm_page_enqueue_cleaned(vm_page_t m)
4797 {
4798 	vm_object_t     m_object;
4799 
4800 	m_object = VM_PAGE_OBJECT(m);
4801 
4802 	assert(VM_PAGE_GET_PHYS_PAGE(m) != vm_page_guard_addr);
4803 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
4804 	assert( !(m->vmp_absent && !m->vmp_unusual));
4805 
4806 	if (VM_PAGE_WIRED(m)) {
4807 		return;
4808 	}
4809 
4810 	if (m->vmp_gobbled) {
4811 		if (!m->vmp_private && !m->vmp_fictitious) {
4812 			vm_page_wire_count--;
4813 		}
4814 		vm_page_gobble_count--;
4815 		m->vmp_gobbled = FALSE;
4816 	}
4817 	/*
4818 	 * if this page is currently on the pageout queue, we can't do the
4819 	 * vm_page_queues_remove (which doesn't handle the pageout queue case)
4820 	 * and we can't remove it manually since we would need the object lock
4821 	 * (which is not required here) to decrement the activity_in_progress
4822 	 * reference which is held on the object while the page is in the pageout queue...
4823 	 * just let the normal laundry processing proceed
4824 	 */
4825 	if (m->vmp_laundry || m->vmp_private || m->vmp_fictitious ||
4826 	    (m->vmp_q_state == VM_PAGE_ON_INACTIVE_CLEANED_Q) ||
4827 	    (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q)) {
4828 		return;
4829 	}
4830 	vm_page_queues_remove(m, FALSE);
4831 
4832 	vm_page_check_pageable_safe(m);
4833 	vm_page_queue_enter(&vm_page_queue_cleaned, m, vmp_pageq);
4834 	m->vmp_q_state = VM_PAGE_ON_INACTIVE_CLEANED_Q;
4835 	vm_page_cleaned_count++;
4836 
4837 	vm_page_inactive_count++;
4838 	if (m_object->internal) {
4839 		vm_page_pageable_internal_count++;
4840 	} else {
4841 		vm_page_pageable_external_count++;
4842 	}
4843 #if CONFIG_BACKGROUND_QUEUE
4844 	if (m->vmp_in_background) {
4845 		vm_page_add_to_backgroundq(m, TRUE);
4846 	}
4847 #endif
4848 	VM_PAGEOUT_DEBUG(vm_pageout_enqueued_cleaned, 1);
4849 }
4850 
4851 /*
4852  *	vm_page_activate:
4853  *
4854  *	Put the specified page on the active list (if appropriate).
4855  *
4856  *	The page queues must be locked.
4857  */
4858 
4859 void
vm_page_activate(vm_page_t m)4860 vm_page_activate(
4861 	vm_page_t       m)
4862 {
4863 	vm_object_t     m_object;
4864 
4865 	m_object = VM_PAGE_OBJECT(m);
4866 
4867 	VM_PAGE_CHECK(m);
4868 #ifdef  FIXME_4778297
4869 	assert(m_object != kernel_object);
4870 #endif
4871 	assert(VM_PAGE_GET_PHYS_PAGE(m) != vm_page_guard_addr);
4872 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
4873 	assert( !(m->vmp_absent && !m->vmp_unusual));
4874 
4875 	if (m->vmp_gobbled) {
4876 		assert( !VM_PAGE_WIRED(m));
4877 		if (!m->vmp_private && !m->vmp_fictitious) {
4878 			vm_page_wire_count--;
4879 		}
4880 		vm_page_gobble_count--;
4881 		m->vmp_gobbled = FALSE;
4882 	}
4883 	/*
4884 	 * if this page is currently on the pageout queue, we can't do the
4885 	 * vm_page_queues_remove (which doesn't handle the pageout queue case)
4886 	 * and we can't remove it manually since we would need the object lock
4887 	 * (which is not required here) to decrement the activity_in_progress
4888 	 * reference which is held on the object while the page is in the pageout queue...
4889 	 * just let the normal laundry processing proceed
4890 	 */
4891 	if (m->vmp_laundry || m->vmp_private || m->vmp_fictitious ||
4892 	    (m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) ||
4893 	    (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q)) {
4894 		return;
4895 	}
4896 
4897 #if DEBUG
4898 	if (m->vmp_q_state == VM_PAGE_ON_ACTIVE_Q) {
4899 		panic("vm_page_activate: already active");
4900 	}
4901 #endif
4902 
4903 	if (m->vmp_q_state == VM_PAGE_ON_SPECULATIVE_Q) {
4904 		DTRACE_VM2(pgrec, int, 1, (uint64_t *), NULL);
4905 		DTRACE_VM2(pgfrec, int, 1, (uint64_t *), NULL);
4906 	}
4907 
4908 	vm_page_queues_remove(m, FALSE);
4909 
4910 	if (!VM_PAGE_WIRED(m)) {
4911 		vm_page_check_pageable_safe(m);
4912 		if (!VM_DYNAMIC_PAGING_ENABLED() &&
4913 		    m->vmp_dirty && m_object->internal &&
4914 		    (m_object->purgable == VM_PURGABLE_DENY ||
4915 		    m_object->purgable == VM_PURGABLE_NONVOLATILE ||
4916 		    m_object->purgable == VM_PURGABLE_VOLATILE)) {
4917 			vm_page_queue_enter(&vm_page_queue_throttled, m, vmp_pageq);
4918 			m->vmp_q_state = VM_PAGE_ON_THROTTLED_Q;
4919 			vm_page_throttled_count++;
4920 		} else {
4921 #if CONFIG_SECLUDED_MEMORY
4922 			if (secluded_for_filecache &&
4923 			    vm_page_secluded_target != 0 &&
4924 			    num_tasks_can_use_secluded_mem == 0 &&
4925 			    m_object->eligible_for_secluded) {
4926 				vm_page_queue_enter(&vm_page_queue_secluded, m, vmp_pageq);
4927 				m->vmp_q_state = VM_PAGE_ON_SECLUDED_Q;
4928 				vm_page_secluded_count++;
4929 				VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE();
4930 				vm_page_secluded_count_inuse++;
4931 				assert(!m_object->internal);
4932 //				vm_page_pageable_external_count++;
4933 			} else
4934 #endif /* CONFIG_SECLUDED_MEMORY */
4935 			vm_page_enqueue_active(m, FALSE);
4936 		}
4937 		m->vmp_reference = TRUE;
4938 		m->vmp_no_cache = FALSE;
4939 	}
4940 	VM_PAGE_CHECK(m);
4941 }
4942 
4943 
4944 /*
4945  *      vm_page_speculate:
4946  *
4947  *      Put the specified page on the speculative list (if appropriate).
4948  *
4949  *      The page queues must be locked.
4950  */
4951 void
vm_page_speculate(vm_page_t m,boolean_t new)4952 vm_page_speculate(
4953 	vm_page_t       m,
4954 	boolean_t       new)
4955 {
4956 	struct vm_speculative_age_q     *aq;
4957 	vm_object_t     m_object;
4958 
4959 	m_object = VM_PAGE_OBJECT(m);
4960 
4961 	VM_PAGE_CHECK(m);
4962 	vm_page_check_pageable_safe(m);
4963 
4964 	assert(VM_PAGE_GET_PHYS_PAGE(m) != vm_page_guard_addr);
4965 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
4966 	assert( !(m->vmp_absent && !m->vmp_unusual));
4967 	assert(m_object->internal == FALSE);
4968 
4969 	/*
4970 	 * if this page is currently on the pageout queue, we can't do the
4971 	 * vm_page_queues_remove (which doesn't handle the pageout queue case)
4972 	 * and we can't remove it manually since we would need the object lock
4973 	 * (which is not required here) to decrement the activity_in_progress
4974 	 * reference which is held on the object while the page is in the pageout queue...
4975 	 * just let the normal laundry processing proceed
4976 	 */
4977 	if (m->vmp_laundry || m->vmp_private || m->vmp_fictitious ||
4978 	    (m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) ||
4979 	    (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q)) {
4980 		return;
4981 	}
4982 
4983 	vm_page_queues_remove(m, FALSE);
4984 
4985 	if (!VM_PAGE_WIRED(m)) {
4986 		mach_timespec_t         ts;
4987 		clock_sec_t sec;
4988 		clock_nsec_t nsec;
4989 
4990 		clock_get_system_nanotime(&sec, &nsec);
4991 		ts.tv_sec = (unsigned int) sec;
4992 		ts.tv_nsec = nsec;
4993 
4994 		if (vm_page_speculative_count == 0) {
4995 			speculative_age_index = VM_PAGE_MIN_SPECULATIVE_AGE_Q;
4996 			speculative_steal_index = VM_PAGE_MIN_SPECULATIVE_AGE_Q;
4997 
4998 			aq = &vm_page_queue_speculative[speculative_age_index];
4999 
5000 			/*
5001 			 * set the timer to begin a new group
5002 			 */
5003 			aq->age_ts.tv_sec = vm_pageout_state.vm_page_speculative_q_age_ms / 1000;
5004 			aq->age_ts.tv_nsec = (vm_pageout_state.vm_page_speculative_q_age_ms % 1000) * 1000 * NSEC_PER_USEC;
5005 
5006 			ADD_MACH_TIMESPEC(&aq->age_ts, &ts);
5007 		} else {
5008 			aq = &vm_page_queue_speculative[speculative_age_index];
5009 
5010 			if (CMP_MACH_TIMESPEC(&ts, &aq->age_ts) >= 0) {
5011 				speculative_age_index++;
5012 
5013 				if (speculative_age_index > VM_PAGE_MAX_SPECULATIVE_AGE_Q) {
5014 					speculative_age_index = VM_PAGE_MIN_SPECULATIVE_AGE_Q;
5015 				}
5016 				if (speculative_age_index == speculative_steal_index) {
5017 					speculative_steal_index = speculative_age_index + 1;
5018 
5019 					if (speculative_steal_index > VM_PAGE_MAX_SPECULATIVE_AGE_Q) {
5020 						speculative_steal_index = VM_PAGE_MIN_SPECULATIVE_AGE_Q;
5021 					}
5022 				}
5023 				aq = &vm_page_queue_speculative[speculative_age_index];
5024 
5025 				if (!vm_page_queue_empty(&aq->age_q)) {
5026 					vm_page_speculate_ageit(aq);
5027 				}
5028 
5029 				aq->age_ts.tv_sec = vm_pageout_state.vm_page_speculative_q_age_ms / 1000;
5030 				aq->age_ts.tv_nsec = (vm_pageout_state.vm_page_speculative_q_age_ms % 1000) * 1000 * NSEC_PER_USEC;
5031 
5032 				ADD_MACH_TIMESPEC(&aq->age_ts, &ts);
5033 			}
5034 		}
5035 		vm_page_enqueue_tail(&aq->age_q, &m->vmp_pageq);
5036 		m->vmp_q_state = VM_PAGE_ON_SPECULATIVE_Q;
5037 		vm_page_speculative_count++;
5038 		vm_page_pageable_external_count++;
5039 
5040 		if (new == TRUE) {
5041 			vm_object_lock_assert_exclusive(m_object);
5042 
5043 			m_object->pages_created++;
5044 #if DEVELOPMENT || DEBUG
5045 			vm_page_speculative_created++;
5046 #endif
5047 		}
5048 	}
5049 	VM_PAGE_CHECK(m);
5050 }
5051 
5052 
5053 /*
5054  * move pages from the specified aging bin to
5055  * the speculative bin that pageout_scan claims from
5056  *
5057  *      The page queues must be locked.
5058  */
5059 void
vm_page_speculate_ageit(struct vm_speculative_age_q * aq)5060 vm_page_speculate_ageit(struct vm_speculative_age_q *aq)
5061 {
5062 	struct vm_speculative_age_q     *sq;
5063 	vm_page_t       t;
5064 
5065 	sq = &vm_page_queue_speculative[VM_PAGE_SPECULATIVE_AGED_Q];
5066 
5067 	if (vm_page_queue_empty(&sq->age_q)) {
5068 		sq->age_q.next = aq->age_q.next;
5069 		sq->age_q.prev = aq->age_q.prev;
5070 
5071 		t = (vm_page_t)VM_PAGE_UNPACK_PTR(sq->age_q.next);
5072 		t->vmp_pageq.prev = VM_PAGE_PACK_PTR(&sq->age_q);
5073 
5074 		t = (vm_page_t)VM_PAGE_UNPACK_PTR(sq->age_q.prev);
5075 		t->vmp_pageq.next = VM_PAGE_PACK_PTR(&sq->age_q);
5076 	} else {
5077 		t = (vm_page_t)VM_PAGE_UNPACK_PTR(sq->age_q.prev);
5078 		t->vmp_pageq.next = aq->age_q.next;
5079 
5080 		t = (vm_page_t)VM_PAGE_UNPACK_PTR(aq->age_q.next);
5081 		t->vmp_pageq.prev = sq->age_q.prev;
5082 
5083 		t = (vm_page_t)VM_PAGE_UNPACK_PTR(aq->age_q.prev);
5084 		t->vmp_pageq.next = VM_PAGE_PACK_PTR(&sq->age_q);
5085 
5086 		sq->age_q.prev = aq->age_q.prev;
5087 	}
5088 	vm_page_queue_init(&aq->age_q);
5089 }
5090 
5091 
5092 void
vm_page_lru(vm_page_t m)5093 vm_page_lru(
5094 	vm_page_t       m)
5095 {
5096 	VM_PAGE_CHECK(m);
5097 	assert(VM_PAGE_OBJECT(m) != kernel_object);
5098 	assert(VM_PAGE_GET_PHYS_PAGE(m) != vm_page_guard_addr);
5099 
5100 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
5101 
5102 	if (m->vmp_q_state == VM_PAGE_ON_INACTIVE_EXTERNAL_Q) {
5103 		/*
5104 		 * we don't need to do all the other work that
5105 		 * vm_page_queues_remove and vm_page_enqueue_inactive
5106 		 * bring along for the ride
5107 		 */
5108 		assert(!m->vmp_laundry);
5109 		assert(!m->vmp_private);
5110 
5111 		m->vmp_no_cache = FALSE;
5112 
5113 		vm_page_queue_remove(&vm_page_queue_inactive, m, vmp_pageq);
5114 		vm_page_queue_enter(&vm_page_queue_inactive, m, vmp_pageq);
5115 
5116 		return;
5117 	}
5118 	/*
5119 	 * if this page is currently on the pageout queue, we can't do the
5120 	 * vm_page_queues_remove (which doesn't handle the pageout queue case)
5121 	 * and we can't remove it manually since we would need the object lock
5122 	 * (which is not required here) to decrement the activity_in_progress
5123 	 * reference which is held on the object while the page is in the pageout queue...
5124 	 * just let the normal laundry processing proceed
5125 	 */
5126 	if (m->vmp_laundry || m->vmp_private ||
5127 	    (m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) ||
5128 	    (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q) ||
5129 	    VM_PAGE_WIRED(m)) {
5130 		return;
5131 	}
5132 
5133 	m->vmp_no_cache = FALSE;
5134 
5135 	vm_page_queues_remove(m, FALSE);
5136 
5137 	vm_page_enqueue_inactive(m, FALSE);
5138 }
5139 
5140 
5141 void
vm_page_reactivate_all_throttled(void)5142 vm_page_reactivate_all_throttled(void)
5143 {
5144 	vm_page_t       first_throttled, last_throttled;
5145 	vm_page_t       first_active;
5146 	vm_page_t       m;
5147 	int             extra_active_count;
5148 	int             extra_internal_count, extra_external_count;
5149 	vm_object_t     m_object;
5150 
5151 	if (!VM_DYNAMIC_PAGING_ENABLED()) {
5152 		return;
5153 	}
5154 
5155 	extra_active_count = 0;
5156 	extra_internal_count = 0;
5157 	extra_external_count = 0;
5158 	vm_page_lock_queues();
5159 	if (!vm_page_queue_empty(&vm_page_queue_throttled)) {
5160 		/*
5161 		 * Switch "throttled" pages to "active".
5162 		 */
5163 		vm_page_queue_iterate(&vm_page_queue_throttled, m, vmp_pageq) {
5164 			VM_PAGE_CHECK(m);
5165 			assert(m->vmp_q_state == VM_PAGE_ON_THROTTLED_Q);
5166 
5167 			m_object = VM_PAGE_OBJECT(m);
5168 
5169 			extra_active_count++;
5170 			if (m_object->internal) {
5171 				extra_internal_count++;
5172 			} else {
5173 				extra_external_count++;
5174 			}
5175 
5176 			m->vmp_q_state = VM_PAGE_ON_ACTIVE_Q;
5177 			VM_PAGE_CHECK(m);
5178 #if CONFIG_BACKGROUND_QUEUE
5179 			if (m->vmp_in_background) {
5180 				vm_page_add_to_backgroundq(m, FALSE);
5181 			}
5182 #endif
5183 		}
5184 
5185 		/*
5186 		 * Transfer the entire throttled queue to a regular LRU page queues.
5187 		 * We insert it at the head of the active queue, so that these pages
5188 		 * get re-evaluated by the LRU algorithm first, since they've been
5189 		 * completely out of it until now.
5190 		 */
5191 		first_throttled = (vm_page_t) vm_page_queue_first(&vm_page_queue_throttled);
5192 		last_throttled = (vm_page_t) vm_page_queue_last(&vm_page_queue_throttled);
5193 		first_active = (vm_page_t) vm_page_queue_first(&vm_page_queue_active);
5194 		if (vm_page_queue_empty(&vm_page_queue_active)) {
5195 			vm_page_queue_active.prev = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(last_throttled);
5196 		} else {
5197 			first_active->vmp_pageq.prev = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(last_throttled);
5198 		}
5199 		vm_page_queue_active.next = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(first_throttled);
5200 		first_throttled->vmp_pageq.prev = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(&vm_page_queue_active);
5201 		last_throttled->vmp_pageq.next = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(first_active);
5202 
5203 #if DEBUG
5204 		printf("reactivated %d throttled pages\n", vm_page_throttled_count);
5205 #endif
5206 		vm_page_queue_init(&vm_page_queue_throttled);
5207 		/*
5208 		 * Adjust the global page counts.
5209 		 */
5210 		vm_page_active_count += extra_active_count;
5211 		vm_page_pageable_internal_count += extra_internal_count;
5212 		vm_page_pageable_external_count += extra_external_count;
5213 		vm_page_throttled_count = 0;
5214 	}
5215 	assert(vm_page_throttled_count == 0);
5216 	assert(vm_page_queue_empty(&vm_page_queue_throttled));
5217 	vm_page_unlock_queues();
5218 }
5219 
5220 
5221 /*
5222  * move pages from the indicated local queue to the global active queue
5223  * its ok to fail if we're below the hard limit and force == FALSE
5224  * the nolocks == TRUE case is to allow this function to be run on
5225  * the hibernate path
5226  */
5227 
5228 void
vm_page_reactivate_local(uint32_t lid,boolean_t force,boolean_t nolocks)5229 vm_page_reactivate_local(uint32_t lid, boolean_t force, boolean_t nolocks)
5230 {
5231 	struct vpl      *lq;
5232 	vm_page_t       first_local, last_local;
5233 	vm_page_t       first_active;
5234 	vm_page_t       m;
5235 	uint32_t        count = 0;
5236 
5237 	if (vm_page_local_q == NULL) {
5238 		return;
5239 	}
5240 
5241 	lq = zpercpu_get_cpu(vm_page_local_q, lid);
5242 
5243 	if (nolocks == FALSE) {
5244 		if (lq->vpl_count < vm_page_local_q_hard_limit && force == FALSE) {
5245 			if (!vm_page_trylockspin_queues()) {
5246 				return;
5247 			}
5248 		} else {
5249 			vm_page_lockspin_queues();
5250 		}
5251 
5252 		VPL_LOCK(&lq->vpl_lock);
5253 	}
5254 	if (lq->vpl_count) {
5255 		/*
5256 		 * Switch "local" pages to "active".
5257 		 */
5258 		assert(!vm_page_queue_empty(&lq->vpl_queue));
5259 
5260 		vm_page_queue_iterate(&lq->vpl_queue, m, vmp_pageq) {
5261 			VM_PAGE_CHECK(m);
5262 			vm_page_check_pageable_safe(m);
5263 			assert(m->vmp_q_state == VM_PAGE_ON_ACTIVE_LOCAL_Q);
5264 			assert(!m->vmp_fictitious);
5265 
5266 			if (m->vmp_local_id != lid) {
5267 				panic("vm_page_reactivate_local: found vm_page_t(%p) with wrong cpuid", m);
5268 			}
5269 
5270 			m->vmp_local_id = 0;
5271 			m->vmp_q_state = VM_PAGE_ON_ACTIVE_Q;
5272 			VM_PAGE_CHECK(m);
5273 #if CONFIG_BACKGROUND_QUEUE
5274 			if (m->vmp_in_background) {
5275 				vm_page_add_to_backgroundq(m, FALSE);
5276 			}
5277 #endif
5278 			count++;
5279 		}
5280 		if (count != lq->vpl_count) {
5281 			panic("vm_page_reactivate_local: count = %d, vm_page_local_count = %d", count, lq->vpl_count);
5282 		}
5283 
5284 		/*
5285 		 * Transfer the entire local queue to a regular LRU page queues.
5286 		 */
5287 		first_local = (vm_page_t) vm_page_queue_first(&lq->vpl_queue);
5288 		last_local = (vm_page_t) vm_page_queue_last(&lq->vpl_queue);
5289 		first_active = (vm_page_t) vm_page_queue_first(&vm_page_queue_active);
5290 
5291 		if (vm_page_queue_empty(&vm_page_queue_active)) {
5292 			vm_page_queue_active.prev = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(last_local);
5293 		} else {
5294 			first_active->vmp_pageq.prev = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(last_local);
5295 		}
5296 		vm_page_queue_active.next = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(first_local);
5297 		first_local->vmp_pageq.prev = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(&vm_page_queue_active);
5298 		last_local->vmp_pageq.next = VM_PAGE_CONVERT_TO_QUEUE_ENTRY(first_active);
5299 
5300 		vm_page_queue_init(&lq->vpl_queue);
5301 		/*
5302 		 * Adjust the global page counts.
5303 		 */
5304 		vm_page_active_count += lq->vpl_count;
5305 		vm_page_pageable_internal_count += lq->vpl_internal_count;
5306 		vm_page_pageable_external_count += lq->vpl_external_count;
5307 		lq->vpl_count = 0;
5308 		lq->vpl_internal_count = 0;
5309 		lq->vpl_external_count = 0;
5310 	}
5311 	assert(vm_page_queue_empty(&lq->vpl_queue));
5312 
5313 	if (nolocks == FALSE) {
5314 		VPL_UNLOCK(&lq->vpl_lock);
5315 
5316 		vm_page_balance_inactive(count / 4);
5317 		vm_page_unlock_queues();
5318 	}
5319 }
5320 
5321 /*
5322  *	vm_page_part_zero_fill:
5323  *
5324  *	Zero-fill a part of the page.
5325  */
5326 #define PMAP_ZERO_PART_PAGE_IMPLEMENTED
5327 void
vm_page_part_zero_fill(vm_page_t m,vm_offset_t m_pa,vm_size_t len)5328 vm_page_part_zero_fill(
5329 	vm_page_t       m,
5330 	vm_offset_t     m_pa,
5331 	vm_size_t       len)
5332 {
5333 #if 0
5334 	/*
5335 	 * we don't hold the page queue lock
5336 	 * so this check isn't safe to make
5337 	 */
5338 	VM_PAGE_CHECK(m);
5339 #endif
5340 
5341 #ifdef PMAP_ZERO_PART_PAGE_IMPLEMENTED
5342 	pmap_zero_part_page(VM_PAGE_GET_PHYS_PAGE(m), m_pa, len);
5343 #else
5344 	vm_page_t       tmp;
5345 	while (1) {
5346 		tmp = vm_page_grab();
5347 		if (tmp == VM_PAGE_NULL) {
5348 			vm_page_wait(THREAD_UNINT);
5349 			continue;
5350 		}
5351 		break;
5352 	}
5353 	vm_page_zero_fill(tmp);
5354 	if (m_pa != 0) {
5355 		vm_page_part_copy(m, 0, tmp, 0, m_pa);
5356 	}
5357 	if ((m_pa + len) < PAGE_SIZE) {
5358 		vm_page_part_copy(m, m_pa + len, tmp,
5359 		    m_pa + len, PAGE_SIZE - (m_pa + len));
5360 	}
5361 	vm_page_copy(tmp, m);
5362 	VM_PAGE_FREE(tmp);
5363 #endif
5364 }
5365 
5366 /*
5367  *	vm_page_zero_fill:
5368  *
5369  *	Zero-fill the specified page.
5370  */
5371 void
vm_page_zero_fill(vm_page_t m)5372 vm_page_zero_fill(
5373 	vm_page_t       m)
5374 {
5375 #if 0
5376 	/*
5377 	 * we don't hold the page queue lock
5378 	 * so this check isn't safe to make
5379 	 */
5380 	VM_PAGE_CHECK(m);
5381 #endif
5382 
5383 //	dbgTrace(0xAEAEAEAE, VM_PAGE_GET_PHYS_PAGE(m), 0);		/* (BRINGUP) */
5384 	pmap_zero_page(VM_PAGE_GET_PHYS_PAGE(m));
5385 }
5386 
5387 /*
5388  *	vm_page_part_copy:
5389  *
5390  *	copy part of one page to another
5391  */
5392 
5393 void
vm_page_part_copy(vm_page_t src_m,vm_offset_t src_pa,vm_page_t dst_m,vm_offset_t dst_pa,vm_size_t len)5394 vm_page_part_copy(
5395 	vm_page_t       src_m,
5396 	vm_offset_t     src_pa,
5397 	vm_page_t       dst_m,
5398 	vm_offset_t     dst_pa,
5399 	vm_size_t       len)
5400 {
5401 #if 0
5402 	/*
5403 	 * we don't hold the page queue lock
5404 	 * so this check isn't safe to make
5405 	 */
5406 	VM_PAGE_CHECK(src_m);
5407 	VM_PAGE_CHECK(dst_m);
5408 #endif
5409 	pmap_copy_part_page(VM_PAGE_GET_PHYS_PAGE(src_m), src_pa,
5410 	    VM_PAGE_GET_PHYS_PAGE(dst_m), dst_pa, len);
5411 }
5412 
5413 /*
5414  *	vm_page_copy:
5415  *
5416  *	Copy one page to another
5417  */
5418 
5419 int vm_page_copy_cs_validations = 0;
5420 int vm_page_copy_cs_tainted = 0;
5421 
5422 void
vm_page_copy(vm_page_t src_m,vm_page_t dest_m)5423 vm_page_copy(
5424 	vm_page_t       src_m,
5425 	vm_page_t       dest_m)
5426 {
5427 	vm_object_t     src_m_object;
5428 
5429 	src_m_object = VM_PAGE_OBJECT(src_m);
5430 
5431 #if 0
5432 	/*
5433 	 * we don't hold the page queue lock
5434 	 * so this check isn't safe to make
5435 	 */
5436 	VM_PAGE_CHECK(src_m);
5437 	VM_PAGE_CHECK(dest_m);
5438 #endif
5439 	vm_object_lock_assert_held(src_m_object);
5440 
5441 	if (src_m_object != VM_OBJECT_NULL &&
5442 	    src_m_object->code_signed) {
5443 		/*
5444 		 * We're copying a page from a code-signed object.
5445 		 * Whoever ends up mapping the copy page might care about
5446 		 * the original page's integrity, so let's validate the
5447 		 * source page now.
5448 		 */
5449 		vm_page_copy_cs_validations++;
5450 		vm_page_validate_cs(src_m, PAGE_SIZE, 0);
5451 #if DEVELOPMENT || DEBUG
5452 		DTRACE_VM4(codesigned_copy,
5453 		    vm_object_t, src_m_object,
5454 		    vm_object_offset_t, src_m->vmp_offset,
5455 		    int, src_m->vmp_cs_validated,
5456 		    int, src_m->vmp_cs_tainted);
5457 #endif /* DEVELOPMENT || DEBUG */
5458 	}
5459 
5460 	/*
5461 	 * Propagate the cs_tainted bit to the copy page. Do not propagate
5462 	 * the cs_validated bit.
5463 	 */
5464 	dest_m->vmp_cs_tainted = src_m->vmp_cs_tainted;
5465 	dest_m->vmp_cs_nx = src_m->vmp_cs_nx;
5466 	if (dest_m->vmp_cs_tainted) {
5467 		vm_page_copy_cs_tainted++;
5468 	}
5469 	dest_m->vmp_error = src_m->vmp_error; /* sliding src_m might have failed... */
5470 	pmap_copy_page(VM_PAGE_GET_PHYS_PAGE(src_m), VM_PAGE_GET_PHYS_PAGE(dest_m));
5471 }
5472 
5473 #if MACH_ASSERT
5474 static void
_vm_page_print(vm_page_t p)5475 _vm_page_print(
5476 	vm_page_t       p)
5477 {
5478 	printf("vm_page %p: \n", p);
5479 	printf("  pageq: next=%p prev=%p\n",
5480 	    (vm_page_t)VM_PAGE_UNPACK_PTR(p->vmp_pageq.next),
5481 	    (vm_page_t)VM_PAGE_UNPACK_PTR(p->vmp_pageq.prev));
5482 	printf("  listq: next=%p prev=%p\n",
5483 	    (vm_page_t)(VM_PAGE_UNPACK_PTR(p->vmp_listq.next)),
5484 	    (vm_page_t)(VM_PAGE_UNPACK_PTR(p->vmp_listq.prev)));
5485 	printf("  next=%p\n", (vm_page_t)(VM_PAGE_UNPACK_PTR(p->vmp_next_m)));
5486 	printf("  object=%p offset=0x%llx\n", VM_PAGE_OBJECT(p), p->vmp_offset);
5487 	printf("  wire_count=%u\n", p->vmp_wire_count);
5488 	printf("  q_state=%u\n", p->vmp_q_state);
5489 
5490 	printf("  %slaundry, %sref, %sgobbled, %sprivate\n",
5491 	    (p->vmp_laundry ? "" : "!"),
5492 	    (p->vmp_reference ? "" : "!"),
5493 	    (p->vmp_gobbled ? "" : "!"),
5494 	    (p->vmp_private ? "" : "!"));
5495 	printf("  %sbusy, %swanted, %stabled, %sfictitious, %spmapped, %swpmapped\n",
5496 	    (p->vmp_busy ? "" : "!"),
5497 	    (p->vmp_wanted ? "" : "!"),
5498 	    (p->vmp_tabled ? "" : "!"),
5499 	    (p->vmp_fictitious ? "" : "!"),
5500 	    (p->vmp_pmapped ? "" : "!"),
5501 	    (p->vmp_wpmapped ? "" : "!"));
5502 	printf("  %sfree_when_done, %sabsent, %serror, %sdirty, %scleaning, %sprecious, %sclustered\n",
5503 	    (p->vmp_free_when_done ? "" : "!"),
5504 	    (p->vmp_absent ? "" : "!"),
5505 	    (p->vmp_error ? "" : "!"),
5506 	    (p->vmp_dirty ? "" : "!"),
5507 	    (p->vmp_cleaning ? "" : "!"),
5508 	    (p->vmp_precious ? "" : "!"),
5509 	    (p->vmp_clustered ? "" : "!"));
5510 	printf("  %soverwriting, %srestart, %sunusual\n",
5511 	    (p->vmp_overwriting ? "" : "!"),
5512 	    (p->vmp_restart ? "" : "!"),
5513 	    (p->vmp_unusual ? "" : "!"));
5514 	printf("  cs_validated=%d, cs_tainted=%d, cs_nx=%d, %sno_cache\n",
5515 	    p->vmp_cs_validated,
5516 	    p->vmp_cs_tainted,
5517 	    p->vmp_cs_nx,
5518 	    (p->vmp_no_cache ? "" : "!"));
5519 
5520 	printf("phys_page=0x%x\n", VM_PAGE_GET_PHYS_PAGE(p));
5521 }
5522 
5523 /*
5524  *	Check that the list of pages is ordered by
5525  *	ascending physical address and has no holes.
5526  */
5527 static int
vm_page_verify_contiguous(vm_page_t pages,unsigned int npages)5528 vm_page_verify_contiguous(
5529 	vm_page_t       pages,
5530 	unsigned int    npages)
5531 {
5532 	vm_page_t               m;
5533 	unsigned int            page_count;
5534 	vm_offset_t             prev_addr;
5535 
5536 	prev_addr = VM_PAGE_GET_PHYS_PAGE(pages);
5537 	page_count = 1;
5538 	for (m = NEXT_PAGE(pages); m != VM_PAGE_NULL; m = NEXT_PAGE(m)) {
5539 		if (VM_PAGE_GET_PHYS_PAGE(m) != prev_addr + 1) {
5540 			printf("m %p prev_addr 0x%lx, current addr 0x%x\n",
5541 			    m, (long)prev_addr, VM_PAGE_GET_PHYS_PAGE(m));
5542 			printf("pages %p page_count %d npages %d\n", pages, page_count, npages);
5543 			panic("vm_page_verify_contiguous:  not contiguous!");
5544 		}
5545 		prev_addr = VM_PAGE_GET_PHYS_PAGE(m);
5546 		++page_count;
5547 	}
5548 	if (page_count != npages) {
5549 		printf("pages %p actual count 0x%x but requested 0x%x\n",
5550 		    pages, page_count, npages);
5551 		panic("vm_page_verify_contiguous:  count error");
5552 	}
5553 	return 1;
5554 }
5555 
5556 
5557 /*
5558  *	Check the free lists for proper length etc.
5559  */
5560 static boolean_t vm_page_verify_this_free_list_enabled = FALSE;
5561 static unsigned int
vm_page_verify_free_list(vm_page_queue_head_t * vm_page_queue,unsigned int color,vm_page_t look_for_page,boolean_t expect_page)5562 vm_page_verify_free_list(
5563 	vm_page_queue_head_t    *vm_page_queue,
5564 	unsigned int    color,
5565 	vm_page_t       look_for_page,
5566 	boolean_t       expect_page)
5567 {
5568 	unsigned int    npages;
5569 	vm_page_t       m;
5570 	vm_page_t       prev_m;
5571 	boolean_t       found_page;
5572 
5573 	if (!vm_page_verify_this_free_list_enabled) {
5574 		return 0;
5575 	}
5576 
5577 	found_page = FALSE;
5578 	npages = 0;
5579 	prev_m = (vm_page_t)((uintptr_t)vm_page_queue);
5580 
5581 	vm_page_queue_iterate(vm_page_queue, m, vmp_pageq) {
5582 		if (m == look_for_page) {
5583 			found_page = TRUE;
5584 		}
5585 		if ((vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.prev) != prev_m) {
5586 			panic("vm_page_verify_free_list(color=%u, npages=%u): page %p corrupted prev ptr %p instead of %p",
5587 			    color, npages, m, (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.prev), prev_m);
5588 		}
5589 		if (!m->vmp_busy) {
5590 			panic("vm_page_verify_free_list(color=%u, npages=%u): page %p not busy",
5591 			    color, npages, m);
5592 		}
5593 		if (color != (unsigned int) -1) {
5594 			if (VM_PAGE_GET_COLOR(m) != color) {
5595 				panic("vm_page_verify_free_list(color=%u, npages=%u): page %p wrong color %u instead of %u",
5596 				    color, npages, m, VM_PAGE_GET_COLOR(m), color);
5597 			}
5598 			if (m->vmp_q_state != VM_PAGE_ON_FREE_Q) {
5599 				panic("vm_page_verify_free_list(color=%u, npages=%u): page %p - expecting q_state == VM_PAGE_ON_FREE_Q, found %d",
5600 				    color, npages, m, m->vmp_q_state);
5601 			}
5602 		} else {
5603 			if (m->vmp_q_state != VM_PAGE_ON_FREE_LOCAL_Q) {
5604 				panic("vm_page_verify_free_list(npages=%u): local page %p - expecting q_state == VM_PAGE_ON_FREE_LOCAL_Q, found %d",
5605 				    npages, m, m->vmp_q_state);
5606 			}
5607 		}
5608 		++npages;
5609 		prev_m = m;
5610 	}
5611 	if (look_for_page != VM_PAGE_NULL) {
5612 		unsigned int other_color;
5613 
5614 		if (expect_page && !found_page) {
5615 			printf("vm_page_verify_free_list(color=%u, npages=%u): page %p not found phys=%u\n",
5616 			    color, npages, look_for_page, VM_PAGE_GET_PHYS_PAGE(look_for_page));
5617 			_vm_page_print(look_for_page);
5618 			for (other_color = 0;
5619 			    other_color < vm_colors;
5620 			    other_color++) {
5621 				if (other_color == color) {
5622 					continue;
5623 				}
5624 				vm_page_verify_free_list(&vm_page_queue_free[other_color].qhead,
5625 				    other_color, look_for_page, FALSE);
5626 			}
5627 			if (color == (unsigned int) -1) {
5628 				vm_page_verify_free_list(&vm_lopage_queue_free,
5629 				    (unsigned int) -1, look_for_page, FALSE);
5630 			}
5631 			panic("vm_page_verify_free_list(color=%u)", color);
5632 		}
5633 		if (!expect_page && found_page) {
5634 			printf("vm_page_verify_free_list(color=%u, npages=%u): page %p found phys=%u\n",
5635 			    color, npages, look_for_page, VM_PAGE_GET_PHYS_PAGE(look_for_page));
5636 		}
5637 	}
5638 	return npages;
5639 }
5640 
5641 static boolean_t vm_page_verify_all_free_lists_enabled = FALSE;
5642 static void
vm_page_verify_free_lists(void)5643 vm_page_verify_free_lists( void )
5644 {
5645 	unsigned int    color, npages, nlopages;
5646 	boolean_t       toggle = TRUE;
5647 
5648 	if (!vm_page_verify_all_free_lists_enabled) {
5649 		return;
5650 	}
5651 
5652 	npages = 0;
5653 
5654 	lck_mtx_lock(&vm_page_queue_free_lock);
5655 
5656 	if (vm_page_verify_this_free_list_enabled == TRUE) {
5657 		/*
5658 		 * This variable has been set globally for extra checking of
5659 		 * each free list Q. Since we didn't set it, we don't own it
5660 		 * and we shouldn't toggle it.
5661 		 */
5662 		toggle = FALSE;
5663 	}
5664 
5665 	if (toggle == TRUE) {
5666 		vm_page_verify_this_free_list_enabled = TRUE;
5667 	}
5668 
5669 	for (color = 0; color < vm_colors; color++) {
5670 		npages += vm_page_verify_free_list(&vm_page_queue_free[color].qhead,
5671 		    color, VM_PAGE_NULL, FALSE);
5672 	}
5673 	nlopages = vm_page_verify_free_list(&vm_lopage_queue_free,
5674 	    (unsigned int) -1,
5675 	    VM_PAGE_NULL, FALSE);
5676 	if (npages != vm_page_free_count || nlopages != vm_lopage_free_count) {
5677 		panic("vm_page_verify_free_lists:  "
5678 		    "npages %u free_count %d nlopages %u lo_free_count %u",
5679 		    npages, vm_page_free_count, nlopages, vm_lopage_free_count);
5680 	}
5681 
5682 	if (toggle == TRUE) {
5683 		vm_page_verify_this_free_list_enabled = FALSE;
5684 	}
5685 
5686 	lck_mtx_unlock(&vm_page_queue_free_lock);
5687 }
5688 
5689 #endif  /* MACH_ASSERT */
5690 
5691 
5692 extern boolean_t(*volatile consider_buffer_cache_collect)(int);
5693 
5694 /*
5695  *	CONTIGUOUS PAGE ALLOCATION
5696  *
5697  *	Find a region large enough to contain at least n pages
5698  *	of contiguous physical memory.
5699  *
5700  *	This is done by traversing the vm_page_t array in a linear fashion
5701  *	we assume that the vm_page_t array has the avaiable physical pages in an
5702  *	ordered, ascending list... this is currently true of all our implementations
5703  *      and must remain so... there can be 'holes' in the array...  we also can
5704  *	no longer tolerate the vm_page_t's in the list being 'freed' and reclaimed
5705  *      which use to happen via 'vm_page_convert'... that function was no longer
5706  *      being called and was removed...
5707  *
5708  *	The basic flow consists of stabilizing some of the interesting state of
5709  *	a vm_page_t behind the vm_page_queue and vm_page_free locks... we start our
5710  *	sweep at the beginning of the array looking for pages that meet our criterea
5711  *	for a 'stealable' page... currently we are pretty conservative... if the page
5712  *	meets this criterea and is physically contiguous to the previous page in the 'run'
5713  *      we keep developing it.  If we hit a page that doesn't fit, we reset our state
5714  *	and start to develop a new run... if at this point we've already considered
5715  *      at least MAX_CONSIDERED_BEFORE_YIELD pages, we'll drop the 2 locks we hold,
5716  *	and mutex_pause (which will yield the processor), to keep the latency low w/r
5717  *	to other threads trying to acquire free pages (or move pages from q to q),
5718  *	and then continue from the spot we left off... we only make 1 pass through the
5719  *	array.  Once we have a 'run' that is long enough, we'll go into the loop which
5720  *      which steals the pages from the queues they're currently on... pages on the free
5721  *	queue can be stolen directly... pages that are on any of the other queues
5722  *	must be removed from the object they are tabled on... this requires taking the
5723  *      object lock... we do this as a 'try' to prevent deadlocks... if the 'try' fails
5724  *	or if the state of the page behind the vm_object lock is no longer viable, we'll
5725  *	dump the pages we've currently stolen back to the free list, and pick up our
5726  *	scan from the point where we aborted the 'current' run.
5727  *
5728  *
5729  *	Requirements:
5730  *		- neither vm_page_queue nor vm_free_list lock can be held on entry
5731  *
5732  *	Returns a pointer to a list of gobbled/wired pages or VM_PAGE_NULL.
5733  *
5734  * Algorithm:
5735  */
5736 
5737 #define MAX_CONSIDERED_BEFORE_YIELD     1000
5738 
5739 
5740 #define RESET_STATE_OF_RUN()    \
5741 	MACRO_BEGIN             \
5742 	prevcontaddr = -2;      \
5743 	start_pnum = -1;        \
5744 	free_considered = 0;    \
5745 	substitute_needed = 0;  \
5746 	npages = 0;             \
5747 	MACRO_END
5748 
5749 /*
5750  * Can we steal in-use (i.e. not free) pages when searching for
5751  * physically-contiguous pages ?
5752  */
5753 #define VM_PAGE_FIND_CONTIGUOUS_CAN_STEAL 1
5754 
5755 static unsigned int vm_page_find_contiguous_last_idx = 0, vm_page_lomem_find_contiguous_last_idx = 0;
5756 #if DEBUG
5757 int vm_page_find_contig_debug = 0;
5758 #endif
5759 
5760 static vm_page_t
vm_page_find_contiguous(unsigned int contig_pages,ppnum_t max_pnum,ppnum_t pnum_mask,boolean_t wire,int flags)5761 vm_page_find_contiguous(
5762 	unsigned int    contig_pages,
5763 	ppnum_t         max_pnum,
5764 	ppnum_t     pnum_mask,
5765 	boolean_t       wire,
5766 	int             flags)
5767 {
5768 	vm_page_t       m = NULL;
5769 	ppnum_t         prevcontaddr = 0;
5770 	ppnum_t         start_pnum = 0;
5771 	unsigned int    npages = 0, considered = 0, scanned = 0;
5772 	unsigned int    page_idx = 0, start_idx = 0, last_idx = 0, orig_last_idx = 0;
5773 	unsigned int    idx_last_contig_page_found = 0;
5774 	int             free_considered = 0, free_available = 0;
5775 	int             substitute_needed = 0;
5776 	int             zone_gc_called = 0;
5777 	boolean_t       wrapped;
5778 	kern_return_t   kr;
5779 #if DEBUG
5780 	clock_sec_t     tv_start_sec = 0, tv_end_sec = 0;
5781 	clock_usec_t    tv_start_usec = 0, tv_end_usec = 0;
5782 #endif
5783 
5784 	int             yielded = 0;
5785 	int             dumped_run = 0;
5786 	int             stolen_pages = 0;
5787 	int             compressed_pages = 0;
5788 
5789 
5790 	if (contig_pages == 0) {
5791 		return VM_PAGE_NULL;
5792 	}
5793 
5794 full_scan_again:
5795 
5796 #if MACH_ASSERT
5797 	vm_page_verify_free_lists();
5798 #endif
5799 #if DEBUG
5800 	clock_get_system_microtime(&tv_start_sec, &tv_start_usec);
5801 #endif
5802 	PAGE_REPLACEMENT_ALLOWED(TRUE);
5803 
5804 	/*
5805 	 * If there are still delayed pages, try to free up some that match.
5806 	 */
5807 	if (__improbable(vm_delayed_count != 0 && contig_pages != 0)) {
5808 		vm_free_delayed_pages_contig(contig_pages, max_pnum, pnum_mask);
5809 	}
5810 
5811 	vm_page_lock_queues();
5812 	lck_mtx_lock(&vm_page_queue_free_lock);
5813 
5814 	RESET_STATE_OF_RUN();
5815 
5816 	scanned = 0;
5817 	considered = 0;
5818 	free_available = vm_page_free_count - vm_page_free_reserved;
5819 
5820 	wrapped = FALSE;
5821 
5822 	if (flags & KMA_LOMEM) {
5823 		idx_last_contig_page_found = vm_page_lomem_find_contiguous_last_idx;
5824 	} else {
5825 		idx_last_contig_page_found =  vm_page_find_contiguous_last_idx;
5826 	}
5827 
5828 	orig_last_idx = idx_last_contig_page_found;
5829 	last_idx = orig_last_idx;
5830 
5831 	for (page_idx = last_idx, start_idx = last_idx;
5832 	    npages < contig_pages && page_idx < vm_pages_count;
5833 	    page_idx++) {
5834 retry:
5835 		if (wrapped &&
5836 		    npages == 0 &&
5837 		    page_idx >= orig_last_idx) {
5838 			/*
5839 			 * We're back where we started and we haven't
5840 			 * found any suitable contiguous range.  Let's
5841 			 * give up.
5842 			 */
5843 			break;
5844 		}
5845 		scanned++;
5846 		m = &vm_pages[page_idx];
5847 
5848 		assert(!m->vmp_fictitious);
5849 		assert(!m->vmp_private);
5850 
5851 		if (max_pnum && VM_PAGE_GET_PHYS_PAGE(m) > max_pnum) {
5852 			/* no more low pages... */
5853 			break;
5854 		}
5855 		if (!npages & ((VM_PAGE_GET_PHYS_PAGE(m) & pnum_mask) != 0)) {
5856 			/*
5857 			 * not aligned
5858 			 */
5859 			RESET_STATE_OF_RUN();
5860 		} else if (VM_PAGE_WIRED(m) || m->vmp_gobbled ||
5861 		    m->vmp_laundry || m->vmp_wanted ||
5862 		    m->vmp_cleaning || m->vmp_overwriting || m->vmp_free_when_done) {
5863 			/*
5864 			 * page is in a transient state
5865 			 * or a state we don't want to deal
5866 			 * with, so don't consider it which
5867 			 * means starting a new run
5868 			 */
5869 			RESET_STATE_OF_RUN();
5870 		} else if ((m->vmp_q_state == VM_PAGE_NOT_ON_Q) ||
5871 		    (m->vmp_q_state == VM_PAGE_ON_FREE_LOCAL_Q) ||
5872 		    (m->vmp_q_state == VM_PAGE_ON_FREE_LOPAGE_Q) ||
5873 		    (m->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q)) {
5874 			/*
5875 			 * page needs to be on one of our queues (other then the pageout or special free queues)
5876 			 * or it needs to belong to the compressor pool (which is now indicated
5877 			 * by vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR and falls out
5878 			 * from the check for VM_PAGE_NOT_ON_Q)
5879 			 * in order for it to be stable behind the
5880 			 * locks we hold at this point...
5881 			 * if not, don't consider it which
5882 			 * means starting a new run
5883 			 */
5884 			RESET_STATE_OF_RUN();
5885 		} else if ((m->vmp_q_state != VM_PAGE_ON_FREE_Q) && (!m->vmp_tabled || m->vmp_busy)) {
5886 			/*
5887 			 * pages on the free list are always 'busy'
5888 			 * so we couldn't test for 'busy' in the check
5889 			 * for the transient states... pages that are
5890 			 * 'free' are never 'tabled', so we also couldn't
5891 			 * test for 'tabled'.  So we check here to make
5892 			 * sure that a non-free page is not busy and is
5893 			 * tabled on an object...
5894 			 * if not, don't consider it which
5895 			 * means starting a new run
5896 			 */
5897 			RESET_STATE_OF_RUN();
5898 		} else {
5899 			if (VM_PAGE_GET_PHYS_PAGE(m) != prevcontaddr + 1) {
5900 				if ((VM_PAGE_GET_PHYS_PAGE(m) & pnum_mask) != 0) {
5901 					RESET_STATE_OF_RUN();
5902 					goto did_consider;
5903 				} else {
5904 					npages = 1;
5905 					start_idx = page_idx;
5906 					start_pnum = VM_PAGE_GET_PHYS_PAGE(m);
5907 				}
5908 			} else {
5909 				npages++;
5910 			}
5911 			prevcontaddr = VM_PAGE_GET_PHYS_PAGE(m);
5912 
5913 			VM_PAGE_CHECK(m);
5914 			if (m->vmp_q_state == VM_PAGE_ON_FREE_Q) {
5915 				free_considered++;
5916 			} else {
5917 				/*
5918 				 * This page is not free.
5919 				 * If we can't steal used pages,
5920 				 * we have to give up this run
5921 				 * and keep looking.
5922 				 * Otherwise, we might need to
5923 				 * move the contents of this page
5924 				 * into a substitute page.
5925 				 */
5926 #if VM_PAGE_FIND_CONTIGUOUS_CAN_STEAL
5927 				if (m->vmp_pmapped || m->vmp_dirty || m->vmp_precious) {
5928 					substitute_needed++;
5929 				}
5930 #else
5931 				RESET_STATE_OF_RUN();
5932 #endif
5933 			}
5934 
5935 			if ((free_considered + substitute_needed) > free_available) {
5936 				/*
5937 				 * if we let this run continue
5938 				 * we will end up dropping the vm_page_free_count
5939 				 * below the reserve limit... we need to abort
5940 				 * this run, but we can at least re-consider this
5941 				 * page... thus the jump back to 'retry'
5942 				 */
5943 				RESET_STATE_OF_RUN();
5944 
5945 				if (free_available && considered <= MAX_CONSIDERED_BEFORE_YIELD) {
5946 					considered++;
5947 					goto retry;
5948 				}
5949 				/*
5950 				 * free_available == 0
5951 				 * so can't consider any free pages... if
5952 				 * we went to retry in this case, we'd
5953 				 * get stuck looking at the same page
5954 				 * w/o making any forward progress
5955 				 * we also want to take this path if we've already
5956 				 * reached our limit that controls the lock latency
5957 				 */
5958 			}
5959 		}
5960 did_consider:
5961 		if (considered > MAX_CONSIDERED_BEFORE_YIELD && npages <= 1) {
5962 			PAGE_REPLACEMENT_ALLOWED(FALSE);
5963 
5964 			lck_mtx_unlock(&vm_page_queue_free_lock);
5965 			vm_page_unlock_queues();
5966 
5967 			mutex_pause(0);
5968 
5969 			PAGE_REPLACEMENT_ALLOWED(TRUE);
5970 
5971 			vm_page_lock_queues();
5972 			lck_mtx_lock(&vm_page_queue_free_lock);
5973 
5974 			RESET_STATE_OF_RUN();
5975 			/*
5976 			 * reset our free page limit since we
5977 			 * dropped the lock protecting the vm_page_free_queue
5978 			 */
5979 			free_available = vm_page_free_count - vm_page_free_reserved;
5980 			considered = 0;
5981 
5982 			yielded++;
5983 
5984 			goto retry;
5985 		}
5986 		considered++;
5987 	}
5988 	m = VM_PAGE_NULL;
5989 
5990 	if (npages != contig_pages) {
5991 		if (!wrapped) {
5992 			/*
5993 			 * We didn't find a contiguous range but we didn't
5994 			 * start from the very first page.
5995 			 * Start again from the very first page.
5996 			 */
5997 			RESET_STATE_OF_RUN();
5998 			if (flags & KMA_LOMEM) {
5999 				idx_last_contig_page_found  = vm_page_lomem_find_contiguous_last_idx = 0;
6000 			} else {
6001 				idx_last_contig_page_found = vm_page_find_contiguous_last_idx = 0;
6002 			}
6003 			last_idx = 0;
6004 			page_idx = last_idx;
6005 			wrapped = TRUE;
6006 			goto retry;
6007 		}
6008 		lck_mtx_unlock(&vm_page_queue_free_lock);
6009 	} else {
6010 		vm_page_t       m1;
6011 		vm_page_t       m2;
6012 		unsigned int    cur_idx;
6013 		unsigned int    tmp_start_idx;
6014 		vm_object_t     locked_object = VM_OBJECT_NULL;
6015 		boolean_t       abort_run = FALSE;
6016 
6017 		assert(page_idx - start_idx == contig_pages);
6018 
6019 		tmp_start_idx = start_idx;
6020 
6021 		/*
6022 		 * first pass through to pull the free pages
6023 		 * off of the free queue so that in case we
6024 		 * need substitute pages, we won't grab any
6025 		 * of the free pages in the run... we'll clear
6026 		 * the 'free' bit in the 2nd pass, and even in
6027 		 * an abort_run case, we'll collect all of the
6028 		 * free pages in this run and return them to the free list
6029 		 */
6030 		while (start_idx < page_idx) {
6031 			m1 = &vm_pages[start_idx++];
6032 
6033 #if !VM_PAGE_FIND_CONTIGUOUS_CAN_STEAL
6034 			assert(m1->vmp_q_state == VM_PAGE_ON_FREE_Q);
6035 #endif
6036 
6037 			if (m1->vmp_q_state == VM_PAGE_ON_FREE_Q) {
6038 				unsigned int color;
6039 
6040 				color = VM_PAGE_GET_COLOR(m1);
6041 #if MACH_ASSERT
6042 				vm_page_verify_free_list(&vm_page_queue_free[color].qhead, color, m1, TRUE);
6043 #endif
6044 				vm_page_queue_remove(&vm_page_queue_free[color].qhead, m1, vmp_pageq);
6045 
6046 				VM_PAGE_ZERO_PAGEQ_ENTRY(m1);
6047 #if MACH_ASSERT
6048 				vm_page_verify_free_list(&vm_page_queue_free[color].qhead, color, VM_PAGE_NULL, FALSE);
6049 #endif
6050 				/*
6051 				 * Clear the "free" bit so that this page
6052 				 * does not get considered for another
6053 				 * concurrent physically-contiguous allocation.
6054 				 */
6055 				m1->vmp_q_state = VM_PAGE_NOT_ON_Q;
6056 				assert(m1->vmp_busy);
6057 
6058 				vm_page_free_count--;
6059 			}
6060 		}
6061 		if (flags & KMA_LOMEM) {
6062 			vm_page_lomem_find_contiguous_last_idx = page_idx;
6063 		} else {
6064 			vm_page_find_contiguous_last_idx = page_idx;
6065 		}
6066 
6067 		/*
6068 		 * we can drop the free queue lock at this point since
6069 		 * we've pulled any 'free' candidates off of the list
6070 		 * we need it dropped so that we can do a vm_page_grab
6071 		 * when substituing for pmapped/dirty pages
6072 		 */
6073 		lck_mtx_unlock(&vm_page_queue_free_lock);
6074 
6075 		start_idx = tmp_start_idx;
6076 		cur_idx = page_idx - 1;
6077 
6078 		while (start_idx++ < page_idx) {
6079 			/*
6080 			 * must go through the list from back to front
6081 			 * so that the page list is created in the
6082 			 * correct order - low -> high phys addresses
6083 			 */
6084 			m1 = &vm_pages[cur_idx--];
6085 
6086 			if (m1->vmp_object == 0) {
6087 				/*
6088 				 * page has already been removed from
6089 				 * the free list in the 1st pass
6090 				 */
6091 				assert(m1->vmp_q_state == VM_PAGE_NOT_ON_Q);
6092 				assert(m1->vmp_offset == (vm_object_offset_t) -1);
6093 				assert(m1->vmp_busy);
6094 				assert(!m1->vmp_wanted);
6095 				assert(!m1->vmp_laundry);
6096 			} else {
6097 				vm_object_t object;
6098 				int refmod;
6099 				boolean_t disconnected, reusable;
6100 
6101 				if (abort_run == TRUE) {
6102 					continue;
6103 				}
6104 
6105 				assert(m1->vmp_q_state != VM_PAGE_NOT_ON_Q);
6106 
6107 				object = VM_PAGE_OBJECT(m1);
6108 
6109 				if (object != locked_object) {
6110 					if (locked_object) {
6111 						vm_object_unlock(locked_object);
6112 						locked_object = VM_OBJECT_NULL;
6113 					}
6114 					if (vm_object_lock_try(object)) {
6115 						locked_object = object;
6116 					}
6117 				}
6118 				if (locked_object == VM_OBJECT_NULL ||
6119 				    (VM_PAGE_WIRED(m1) || m1->vmp_gobbled ||
6120 				    m1->vmp_laundry || m1->vmp_wanted ||
6121 				    m1->vmp_cleaning || m1->vmp_overwriting || m1->vmp_free_when_done || m1->vmp_busy) ||
6122 				    (m1->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q)) {
6123 					if (locked_object) {
6124 						vm_object_unlock(locked_object);
6125 						locked_object = VM_OBJECT_NULL;
6126 					}
6127 					tmp_start_idx = cur_idx;
6128 					abort_run = TRUE;
6129 					continue;
6130 				}
6131 
6132 				disconnected = FALSE;
6133 				reusable = FALSE;
6134 
6135 				if ((m1->vmp_reusable ||
6136 				    object->all_reusable) &&
6137 				    (m1->vmp_q_state == VM_PAGE_ON_INACTIVE_INTERNAL_Q) &&
6138 				    !m1->vmp_dirty &&
6139 				    !m1->vmp_reference) {
6140 					/* reusable page... */
6141 					refmod = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m1));
6142 					disconnected = TRUE;
6143 					if (refmod == 0) {
6144 						/*
6145 						 * ... not reused: can steal
6146 						 * without relocating contents.
6147 						 */
6148 						reusable = TRUE;
6149 					}
6150 				}
6151 
6152 				if ((m1->vmp_pmapped &&
6153 				    !reusable) ||
6154 				    m1->vmp_dirty ||
6155 				    m1->vmp_precious) {
6156 					vm_object_offset_t offset;
6157 
6158 					m2 = vm_page_grab_options(VM_PAGE_GRAB_Q_LOCK_HELD);
6159 
6160 					if (m2 == VM_PAGE_NULL) {
6161 						if (locked_object) {
6162 							vm_object_unlock(locked_object);
6163 							locked_object = VM_OBJECT_NULL;
6164 						}
6165 						tmp_start_idx = cur_idx;
6166 						abort_run = TRUE;
6167 						continue;
6168 					}
6169 					if (!disconnected) {
6170 						if (m1->vmp_pmapped) {
6171 							refmod = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m1));
6172 						} else {
6173 							refmod = 0;
6174 						}
6175 					}
6176 
6177 					/* copy the page's contents */
6178 					pmap_copy_page(VM_PAGE_GET_PHYS_PAGE(m1), VM_PAGE_GET_PHYS_PAGE(m2));
6179 					/* copy the page's state */
6180 					assert(!VM_PAGE_WIRED(m1));
6181 					assert(m1->vmp_q_state != VM_PAGE_ON_FREE_Q);
6182 					assert(m1->vmp_q_state != VM_PAGE_ON_PAGEOUT_Q);
6183 					assert(!m1->vmp_laundry);
6184 					m2->vmp_reference       = m1->vmp_reference;
6185 					assert(!m1->vmp_gobbled);
6186 					assert(!m1->vmp_private);
6187 					m2->vmp_no_cache        = m1->vmp_no_cache;
6188 					m2->vmp_xpmapped        = 0;
6189 					assert(!m1->vmp_busy);
6190 					assert(!m1->vmp_wanted);
6191 					assert(!m1->vmp_fictitious);
6192 					m2->vmp_pmapped = m1->vmp_pmapped; /* should flush cache ? */
6193 					m2->vmp_wpmapped        = m1->vmp_wpmapped;
6194 					assert(!m1->vmp_free_when_done);
6195 					m2->vmp_absent  = m1->vmp_absent;
6196 					m2->vmp_error   = m1->vmp_error;
6197 					m2->vmp_dirty   = m1->vmp_dirty;
6198 					assert(!m1->vmp_cleaning);
6199 					m2->vmp_precious        = m1->vmp_precious;
6200 					m2->vmp_clustered       = m1->vmp_clustered;
6201 					assert(!m1->vmp_overwriting);
6202 					m2->vmp_restart = m1->vmp_restart;
6203 					m2->vmp_unusual = m1->vmp_unusual;
6204 					m2->vmp_cs_validated = m1->vmp_cs_validated;
6205 					m2->vmp_cs_tainted      = m1->vmp_cs_tainted;
6206 					m2->vmp_cs_nx   = m1->vmp_cs_nx;
6207 
6208 					/*
6209 					 * If m1 had really been reusable,
6210 					 * we would have just stolen it, so
6211 					 * let's not propagate it's "reusable"
6212 					 * bit and assert that m2 is not
6213 					 * marked as "reusable".
6214 					 */
6215 					// m2->vmp_reusable	= m1->vmp_reusable;
6216 					assert(!m2->vmp_reusable);
6217 
6218 					// assert(!m1->vmp_lopage);
6219 
6220 					if (m1->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) {
6221 						m2->vmp_q_state = VM_PAGE_USED_BY_COMPRESSOR;
6222 					}
6223 
6224 					/*
6225 					 * page may need to be flushed if
6226 					 * it is marshalled into a UPL
6227 					 * that is going to be used by a device
6228 					 * that doesn't support coherency
6229 					 */
6230 					m2->vmp_written_by_kernel = TRUE;
6231 
6232 					/*
6233 					 * make sure we clear the ref/mod state
6234 					 * from the pmap layer... else we risk
6235 					 * inheriting state from the last time
6236 					 * this page was used...
6237 					 */
6238 					pmap_clear_refmod(VM_PAGE_GET_PHYS_PAGE(m2), VM_MEM_MODIFIED | VM_MEM_REFERENCED);
6239 
6240 					if (refmod & VM_MEM_REFERENCED) {
6241 						m2->vmp_reference = TRUE;
6242 					}
6243 					if (refmod & VM_MEM_MODIFIED) {
6244 						SET_PAGE_DIRTY(m2, TRUE);
6245 					}
6246 					offset = m1->vmp_offset;
6247 
6248 					/*
6249 					 * completely cleans up the state
6250 					 * of the page so that it is ready
6251 					 * to be put onto the free list, or
6252 					 * for this purpose it looks like it
6253 					 * just came off of the free list
6254 					 */
6255 					vm_page_free_prepare(m1);
6256 
6257 					/*
6258 					 * now put the substitute page
6259 					 * on the object
6260 					 */
6261 					vm_page_insert_internal(m2, locked_object, offset, VM_KERN_MEMORY_NONE, TRUE, TRUE, FALSE, FALSE, NULL);
6262 
6263 					if (m2->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) {
6264 						m2->vmp_pmapped = TRUE;
6265 						m2->vmp_wpmapped = TRUE;
6266 
6267 						PMAP_ENTER(kernel_pmap, (vm_map_offset_t)m2->vmp_offset, m2,
6268 						    VM_PROT_READ | VM_PROT_WRITE, VM_PROT_NONE, 0, TRUE, kr);
6269 
6270 						assert(kr == KERN_SUCCESS);
6271 
6272 						compressed_pages++;
6273 					} else {
6274 						if (m2->vmp_reference) {
6275 							vm_page_activate(m2);
6276 						} else {
6277 							vm_page_deactivate(m2);
6278 						}
6279 					}
6280 					PAGE_WAKEUP_DONE(m2);
6281 				} else {
6282 					assert(m1->vmp_q_state != VM_PAGE_USED_BY_COMPRESSOR);
6283 
6284 					/*
6285 					 * completely cleans up the state
6286 					 * of the page so that it is ready
6287 					 * to be put onto the free list, or
6288 					 * for this purpose it looks like it
6289 					 * just came off of the free list
6290 					 */
6291 					vm_page_free_prepare(m1);
6292 				}
6293 
6294 				stolen_pages++;
6295 			}
6296 #if CONFIG_BACKGROUND_QUEUE
6297 			vm_page_assign_background_state(m1);
6298 #endif
6299 			VM_PAGE_ZERO_PAGEQ_ENTRY(m1);
6300 			m1->vmp_snext = m;
6301 			m = m1;
6302 		}
6303 		if (locked_object) {
6304 			vm_object_unlock(locked_object);
6305 			locked_object = VM_OBJECT_NULL;
6306 		}
6307 
6308 		if (abort_run == TRUE) {
6309 			/*
6310 			 * want the index of the last
6311 			 * page in this run that was
6312 			 * successfully 'stolen', so back
6313 			 * it up 1 for the auto-decrement on use
6314 			 * and 1 more to bump back over this page
6315 			 */
6316 			page_idx = tmp_start_idx + 2;
6317 			if (page_idx >= vm_pages_count) {
6318 				if (wrapped) {
6319 					if (m != VM_PAGE_NULL) {
6320 						vm_page_unlock_queues();
6321 						vm_page_free_list(m, FALSE);
6322 						vm_page_lock_queues();
6323 						m = VM_PAGE_NULL;
6324 					}
6325 					dumped_run++;
6326 					goto done_scanning;
6327 				}
6328 				page_idx = last_idx = 0;
6329 				wrapped = TRUE;
6330 			}
6331 			abort_run = FALSE;
6332 
6333 			/*
6334 			 * We didn't find a contiguous range but we didn't
6335 			 * start from the very first page.
6336 			 * Start again from the very first page.
6337 			 */
6338 			RESET_STATE_OF_RUN();
6339 
6340 			if (flags & KMA_LOMEM) {
6341 				idx_last_contig_page_found  = vm_page_lomem_find_contiguous_last_idx = page_idx;
6342 			} else {
6343 				idx_last_contig_page_found = vm_page_find_contiguous_last_idx = page_idx;
6344 			}
6345 
6346 			last_idx = page_idx;
6347 
6348 			if (m != VM_PAGE_NULL) {
6349 				vm_page_unlock_queues();
6350 				vm_page_free_list(m, FALSE);
6351 				vm_page_lock_queues();
6352 				m = VM_PAGE_NULL;
6353 			}
6354 			dumped_run++;
6355 
6356 			lck_mtx_lock(&vm_page_queue_free_lock);
6357 			/*
6358 			 * reset our free page limit since we
6359 			 * dropped the lock protecting the vm_page_free_queue
6360 			 */
6361 			free_available = vm_page_free_count - vm_page_free_reserved;
6362 			goto retry;
6363 		}
6364 
6365 		for (m1 = m; m1 != VM_PAGE_NULL; m1 = NEXT_PAGE(m1)) {
6366 			assert(m1->vmp_q_state == VM_PAGE_NOT_ON_Q);
6367 			assert(m1->vmp_wire_count == 0);
6368 
6369 			if (wire == TRUE) {
6370 				m1->vmp_wire_count++;
6371 				m1->vmp_q_state = VM_PAGE_IS_WIRED;
6372 			} else {
6373 				m1->vmp_gobbled = TRUE;
6374 			}
6375 		}
6376 		if (wire == FALSE) {
6377 			vm_page_gobble_count += npages;
6378 		}
6379 
6380 		/*
6381 		 * gobbled pages are also counted as wired pages
6382 		 */
6383 		vm_page_wire_count += npages;
6384 
6385 		assert(vm_page_verify_contiguous(m, npages));
6386 	}
6387 done_scanning:
6388 	PAGE_REPLACEMENT_ALLOWED(FALSE);
6389 
6390 	vm_page_unlock_queues();
6391 
6392 #if DEBUG
6393 	clock_get_system_microtime(&tv_end_sec, &tv_end_usec);
6394 
6395 	tv_end_sec -= tv_start_sec;
6396 	if (tv_end_usec < tv_start_usec) {
6397 		tv_end_sec--;
6398 		tv_end_usec += 1000000;
6399 	}
6400 	tv_end_usec -= tv_start_usec;
6401 	if (tv_end_usec >= 1000000) {
6402 		tv_end_sec++;
6403 		tv_end_sec -= 1000000;
6404 	}
6405 	if (vm_page_find_contig_debug) {
6406 		printf("%s(num=%d,low=%d): found %d pages at 0x%llx in %ld.%06ds...  started at %d...  scanned %d pages...  yielded %d times...  dumped run %d times... stole %d pages... stole %d compressed pages\n",
6407 		    __func__, contig_pages, max_pnum, npages, (vm_object_offset_t)start_pnum << PAGE_SHIFT,
6408 		    (long)tv_end_sec, tv_end_usec, orig_last_idx,
6409 		        scanned, yielded, dumped_run, stolen_pages, compressed_pages);
6410 	}
6411 
6412 #endif
6413 #if MACH_ASSERT
6414 	vm_page_verify_free_lists();
6415 #endif
6416 	if (m == NULL && zone_gc_called < 2) {
6417 		printf("%s(num=%d,low=%d): found %d pages at 0x%llx...scanned %d pages...  yielded %d times...  dumped run %d times... stole %d pages... stole %d compressed pages... wired count is %d\n",
6418 		    __func__, contig_pages, max_pnum, npages, (vm_object_offset_t)start_pnum << PAGE_SHIFT,
6419 		        scanned, yielded, dumped_run, stolen_pages, compressed_pages, vm_page_wire_count);
6420 
6421 		if (consider_buffer_cache_collect != NULL) {
6422 			(void)(*consider_buffer_cache_collect)(1);
6423 		}
6424 
6425 		zone_gc(zone_gc_called ? ZONE_GC_DRAIN : ZONE_GC_TRIM);
6426 
6427 		zone_gc_called++;
6428 
6429 		printf("vm_page_find_contiguous: zone_gc called... wired count is %d\n", vm_page_wire_count);
6430 		goto full_scan_again;
6431 	}
6432 
6433 	return m;
6434 }
6435 
6436 /*
6437  *	Allocate a list of contiguous, wired pages.
6438  */
6439 kern_return_t
cpm_allocate(vm_size_t size,vm_page_t * list,ppnum_t max_pnum,ppnum_t pnum_mask,boolean_t wire,int flags)6440 cpm_allocate(
6441 	vm_size_t       size,
6442 	vm_page_t       *list,
6443 	ppnum_t         max_pnum,
6444 	ppnum_t         pnum_mask,
6445 	boolean_t       wire,
6446 	int             flags)
6447 {
6448 	vm_page_t               pages;
6449 	unsigned int            npages;
6450 
6451 	if (size % PAGE_SIZE != 0) {
6452 		return KERN_INVALID_ARGUMENT;
6453 	}
6454 
6455 	npages = (unsigned int) (size / PAGE_SIZE);
6456 	if (npages != size / PAGE_SIZE) {
6457 		/* 32-bit overflow */
6458 		return KERN_INVALID_ARGUMENT;
6459 	}
6460 
6461 	/*
6462 	 *	Obtain a pointer to a subset of the free
6463 	 *	list large enough to satisfy the request;
6464 	 *	the region will be physically contiguous.
6465 	 */
6466 	pages = vm_page_find_contiguous(npages, max_pnum, pnum_mask, wire, flags);
6467 
6468 	if (pages == VM_PAGE_NULL) {
6469 		return KERN_NO_SPACE;
6470 	}
6471 	/*
6472 	 * determine need for wakeups
6473 	 */
6474 	if (vm_page_free_count < vm_page_free_min) {
6475 		lck_mtx_lock(&vm_page_queue_free_lock);
6476 		if (vm_pageout_running == FALSE) {
6477 			lck_mtx_unlock(&vm_page_queue_free_lock);
6478 			thread_wakeup((event_t) &vm_page_free_wanted);
6479 		} else {
6480 			lck_mtx_unlock(&vm_page_queue_free_lock);
6481 		}
6482 	}
6483 
6484 	VM_CHECK_MEMORYSTATUS;
6485 
6486 	/*
6487 	 *	The CPM pages should now be available and
6488 	 *	ordered by ascending physical address.
6489 	 */
6490 	assert(vm_page_verify_contiguous(pages, npages));
6491 
6492 	*list = pages;
6493 	return KERN_SUCCESS;
6494 }
6495 
6496 
6497 unsigned int vm_max_delayed_work_limit = DEFAULT_DELAYED_WORK_LIMIT;
6498 
6499 /*
6500  * when working on a 'run' of pages, it is necessary to hold
6501  * the vm_page_queue_lock (a hot global lock) for certain operations
6502  * on the page... however, the majority of the work can be done
6503  * while merely holding the object lock... in fact there are certain
6504  * collections of pages that don't require any work brokered by the
6505  * vm_page_queue_lock... to mitigate the time spent behind the global
6506  * lock, go to a 2 pass algorithm... collect pages up to DELAYED_WORK_LIMIT
6507  * while doing all of the work that doesn't require the vm_page_queue_lock...
6508  * then call vm_page_do_delayed_work to acquire the vm_page_queue_lock and do the
6509  * necessary work for each page... we will grab the busy bit on the page
6510  * if it's not already held so that vm_page_do_delayed_work can drop the object lock
6511  * if it can't immediately take the vm_page_queue_lock in order to compete
6512  * for the locks in the same order that vm_pageout_scan takes them.
6513  * the operation names are modeled after the names of the routines that
6514  * need to be called in order to make the changes very obvious in the
6515  * original loop
6516  */
6517 
6518 void
vm_page_do_delayed_work(vm_object_t object,vm_tag_t tag,struct vm_page_delayed_work * dwp,int dw_count)6519 vm_page_do_delayed_work(
6520 	vm_object_t     object,
6521 	vm_tag_t        tag,
6522 	struct vm_page_delayed_work *dwp,
6523 	int             dw_count)
6524 {
6525 	int             j;
6526 	vm_page_t       m;
6527 	vm_page_t       local_free_q = VM_PAGE_NULL;
6528 
6529 	/*
6530 	 * pageout_scan takes the vm_page_lock_queues first
6531 	 * then tries for the object lock... to avoid what
6532 	 * is effectively a lock inversion, we'll go to the
6533 	 * trouble of taking them in that same order... otherwise
6534 	 * if this object contains the majority of the pages resident
6535 	 * in the UBC (or a small set of large objects actively being
6536 	 * worked on contain the majority of the pages), we could
6537 	 * cause the pageout_scan thread to 'starve' in its attempt
6538 	 * to find pages to move to the free queue, since it has to
6539 	 * successfully acquire the object lock of any candidate page
6540 	 * before it can steal/clean it.
6541 	 */
6542 	if (!vm_page_trylockspin_queues()) {
6543 		vm_object_unlock(object);
6544 
6545 		/*
6546 		 * "Turnstile enabled vm_pageout_scan" can be runnable
6547 		 * for a very long time without getting on a core.
6548 		 * If this is a higher priority thread it could be
6549 		 * waiting here for a very long time respecting the fact
6550 		 * that pageout_scan would like its object after VPS does
6551 		 * a mutex_pause(0).
6552 		 * So we cap the number of yields in the vm_object_lock_avoid()
6553 		 * case to a single mutex_pause(0) which will give vm_pageout_scan
6554 		 * 10us to run and grab the object if needed.
6555 		 */
6556 		vm_page_lockspin_queues();
6557 
6558 		for (j = 0;; j++) {
6559 			if ((!vm_object_lock_avoid(object) ||
6560 			    (vps_dynamic_priority_enabled && (j > 0))) &&
6561 			    _vm_object_lock_try(object)) {
6562 				break;
6563 			}
6564 			vm_page_unlock_queues();
6565 			mutex_pause(j);
6566 			vm_page_lockspin_queues();
6567 		}
6568 	}
6569 	for (j = 0; j < dw_count; j++, dwp++) {
6570 		m = dwp->dw_m;
6571 
6572 		if (dwp->dw_mask & DW_vm_pageout_throttle_up) {
6573 			vm_pageout_throttle_up(m);
6574 		}
6575 #if CONFIG_PHANTOM_CACHE
6576 		if (dwp->dw_mask & DW_vm_phantom_cache_update) {
6577 			vm_phantom_cache_update(m);
6578 		}
6579 #endif
6580 		if (dwp->dw_mask & DW_vm_page_wire) {
6581 			vm_page_wire(m, tag, FALSE);
6582 		} else if (dwp->dw_mask & DW_vm_page_unwire) {
6583 			boolean_t       queueit;
6584 
6585 			queueit = (dwp->dw_mask & (DW_vm_page_free | DW_vm_page_deactivate_internal)) ? FALSE : TRUE;
6586 
6587 			vm_page_unwire(m, queueit);
6588 		}
6589 		if (dwp->dw_mask & DW_vm_page_free) {
6590 			vm_page_free_prepare_queues(m);
6591 
6592 			assert(m->vmp_pageq.next == 0 && m->vmp_pageq.prev == 0);
6593 			/*
6594 			 * Add this page to our list of reclaimed pages,
6595 			 * to be freed later.
6596 			 */
6597 			m->vmp_snext = local_free_q;
6598 			local_free_q = m;
6599 		} else {
6600 			if (dwp->dw_mask & DW_vm_page_deactivate_internal) {
6601 				vm_page_deactivate_internal(m, FALSE);
6602 			} else if (dwp->dw_mask & DW_vm_page_activate) {
6603 				if (m->vmp_q_state != VM_PAGE_ON_ACTIVE_Q) {
6604 					vm_page_activate(m);
6605 				}
6606 			} else if (dwp->dw_mask & DW_vm_page_speculate) {
6607 				vm_page_speculate(m, TRUE);
6608 			} else if (dwp->dw_mask & DW_enqueue_cleaned) {
6609 				/*
6610 				 * if we didn't hold the object lock and did this,
6611 				 * we might disconnect the page, then someone might
6612 				 * soft fault it back in, then we would put it on the
6613 				 * cleaned queue, and so we would have a referenced (maybe even dirty)
6614 				 * page on that queue, which we don't want
6615 				 */
6616 				int refmod_state = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m));
6617 
6618 				if ((refmod_state & VM_MEM_REFERENCED)) {
6619 					/*
6620 					 * this page has been touched since it got cleaned; let's activate it
6621 					 * if it hasn't already been
6622 					 */
6623 					VM_PAGEOUT_DEBUG(vm_pageout_enqueued_cleaned, 1);
6624 					VM_PAGEOUT_DEBUG(vm_pageout_cleaned_reactivated, 1);
6625 
6626 					if (m->vmp_q_state != VM_PAGE_ON_ACTIVE_Q) {
6627 						vm_page_activate(m);
6628 					}
6629 				} else {
6630 					m->vmp_reference = FALSE;
6631 					vm_page_enqueue_cleaned(m);
6632 				}
6633 			} else if (dwp->dw_mask & DW_vm_page_lru) {
6634 				vm_page_lru(m);
6635 			} else if (dwp->dw_mask & DW_VM_PAGE_QUEUES_REMOVE) {
6636 				if (m->vmp_q_state != VM_PAGE_ON_PAGEOUT_Q) {
6637 					vm_page_queues_remove(m, TRUE);
6638 				}
6639 			}
6640 			if (dwp->dw_mask & DW_set_reference) {
6641 				m->vmp_reference = TRUE;
6642 			} else if (dwp->dw_mask & DW_clear_reference) {
6643 				m->vmp_reference = FALSE;
6644 			}
6645 
6646 			if (dwp->dw_mask & DW_move_page) {
6647 				if (m->vmp_q_state != VM_PAGE_ON_PAGEOUT_Q) {
6648 					vm_page_queues_remove(m, FALSE);
6649 
6650 					assert(VM_PAGE_OBJECT(m) != kernel_object);
6651 
6652 					vm_page_enqueue_inactive(m, FALSE);
6653 				}
6654 			}
6655 			if (dwp->dw_mask & DW_clear_busy) {
6656 				m->vmp_busy = FALSE;
6657 			}
6658 
6659 			if (dwp->dw_mask & DW_PAGE_WAKEUP) {
6660 				PAGE_WAKEUP(m);
6661 			}
6662 		}
6663 	}
6664 	vm_page_unlock_queues();
6665 
6666 	if (local_free_q) {
6667 		vm_page_free_list(local_free_q, TRUE);
6668 	}
6669 
6670 	VM_CHECK_MEMORYSTATUS;
6671 }
6672 
6673 kern_return_t
vm_page_alloc_list(int page_count,kma_flags_t flags,vm_page_t * list)6674 vm_page_alloc_list(
6675 	int         page_count,
6676 	kma_flags_t flags,
6677 	vm_page_t  *list)
6678 {
6679 	vm_page_t       page_list = VM_PAGE_NULL;
6680 	vm_page_t       mem;
6681 	kern_return_t   kr = KERN_SUCCESS;
6682 	int             page_grab_count = 0;
6683 	mach_vm_size_t  map_size = ptoa_64(page_count);
6684 #if DEVELOPMENT || DEBUG
6685 	task_t          task = current_task_early();
6686 #endif /* DEVELOPMENT || DEBUG */
6687 
6688 	for (int i = 0; i < page_count; i++) {
6689 		for (;;) {
6690 			if (flags & KMA_LOMEM) {
6691 				mem = vm_page_grablo();
6692 			} else {
6693 				mem = vm_page_grab();
6694 			}
6695 
6696 			if (mem != VM_PAGE_NULL) {
6697 				break;
6698 			}
6699 
6700 			if (flags & KMA_NOPAGEWAIT) {
6701 				kr = KERN_RESOURCE_SHORTAGE;
6702 				goto out;
6703 			}
6704 			if ((flags & KMA_LOMEM) && (vm_lopage_needed == TRUE)) {
6705 				kr = KERN_RESOURCE_SHORTAGE;
6706 				goto out;
6707 			}
6708 
6709 			/* VM privileged threads should have waited in vm_page_grab() and not get here. */
6710 			assert(!(current_thread()->options & TH_OPT_VMPRIV));
6711 
6712 			uint64_t unavailable = (vm_page_wire_count + vm_page_free_target) * PAGE_SIZE;
6713 			if (unavailable > max_mem || map_size > (max_mem - unavailable)) {
6714 				kr = KERN_RESOURCE_SHORTAGE;
6715 				goto out;
6716 			}
6717 			VM_PAGE_WAIT();
6718 		}
6719 
6720 		page_grab_count++;
6721 		mem->vmp_snext = page_list;
6722 		page_list = mem;
6723 	}
6724 
6725 	if (KMA_ZERO & flags) {
6726 		for (mem = page_list; mem; mem = mem->vmp_snext) {
6727 			vm_page_zero_fill(mem);
6728 		}
6729 	}
6730 
6731 out:
6732 #if DEBUG || DEVELOPMENT
6733 	if (task != NULL) {
6734 		ledger_credit(task->ledger, task_ledgers.pages_grabbed_kern, page_grab_count);
6735 	}
6736 #endif
6737 
6738 	if (kr == KERN_SUCCESS) {
6739 		*list = page_list;
6740 	} else {
6741 		vm_page_free_list(page_list, FALSE);
6742 	}
6743 
6744 	return kr;
6745 }
6746 
6747 void
vm_page_set_offset(vm_page_t page,vm_object_offset_t offset)6748 vm_page_set_offset(vm_page_t page, vm_object_offset_t offset)
6749 {
6750 	page->vmp_offset = offset;
6751 }
6752 
6753 vm_page_t
vm_page_get_next(vm_page_t page)6754 vm_page_get_next(vm_page_t page)
6755 {
6756 	return page->vmp_snext;
6757 }
6758 
6759 vm_object_offset_t
vm_page_get_offset(vm_page_t page)6760 vm_page_get_offset(vm_page_t page)
6761 {
6762 	return page->vmp_offset;
6763 }
6764 
6765 ppnum_t
vm_page_get_phys_page(vm_page_t page)6766 vm_page_get_phys_page(vm_page_t page)
6767 {
6768 	return VM_PAGE_GET_PHYS_PAGE(page);
6769 }
6770 
6771 
6772 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
6773 
6774 #if HIBERNATION
6775 
6776 static vm_page_t hibernate_gobble_queue;
6777 
6778 static int  hibernate_drain_pageout_queue(struct vm_pageout_queue *);
6779 static int  hibernate_flush_dirty_pages(int);
6780 static int  hibernate_flush_queue(vm_page_queue_head_t *, int);
6781 
6782 void hibernate_flush_wait(void);
6783 void hibernate_mark_in_progress(void);
6784 void hibernate_clear_in_progress(void);
6785 
6786 void            hibernate_free_range(int, int);
6787 void            hibernate_hash_insert_page(vm_page_t);
6788 uint32_t        hibernate_mark_as_unneeded(addr64_t, addr64_t, hibernate_page_list_t *, hibernate_page_list_t *);
6789 uint32_t        hibernate_teardown_vm_structs(hibernate_page_list_t *, hibernate_page_list_t *);
6790 ppnum_t         hibernate_lookup_paddr(unsigned int);
6791 
6792 struct hibernate_statistics {
6793 	int hibernate_considered;
6794 	int hibernate_reentered_on_q;
6795 	int hibernate_found_dirty;
6796 	int hibernate_skipped_cleaning;
6797 	int hibernate_skipped_transient;
6798 	int hibernate_skipped_precious;
6799 	int hibernate_skipped_external;
6800 	int hibernate_queue_nolock;
6801 	int hibernate_queue_paused;
6802 	int hibernate_throttled;
6803 	int hibernate_throttle_timeout;
6804 	int hibernate_drained;
6805 	int hibernate_drain_timeout;
6806 	int cd_lock_failed;
6807 	int cd_found_precious;
6808 	int cd_found_wired;
6809 	int cd_found_busy;
6810 	int cd_found_unusual;
6811 	int cd_found_cleaning;
6812 	int cd_found_laundry;
6813 	int cd_found_dirty;
6814 	int cd_found_xpmapped;
6815 	int cd_skipped_xpmapped;
6816 	int cd_local_free;
6817 	int cd_total_free;
6818 	int cd_vm_page_wire_count;
6819 	int cd_vm_struct_pages_unneeded;
6820 	int cd_pages;
6821 	int cd_discarded;
6822 	int cd_count_wire;
6823 } hibernate_stats;
6824 
6825 
6826 /*
6827  * clamp the number of 'xpmapped' pages we'll sweep into the hibernation image
6828  * so that we don't overrun the estimated image size, which would
6829  * result in a hibernation failure.
6830  *
6831  * We use a size value instead of pages because we don't want to take up more space
6832  * on disk if the system has a 16K page size vs 4K. Also, we are not guaranteed
6833  * to have that additional space available.
6834  *
6835  * Since this was set at 40000 pages on X86 we are going to use 160MB as our
6836  * xpmapped size.
6837  */
6838 #define HIBERNATE_XPMAPPED_LIMIT        ((160 * 1024 * 1024ULL) / PAGE_SIZE)
6839 
6840 
6841 static int
hibernate_drain_pageout_queue(struct vm_pageout_queue * q)6842 hibernate_drain_pageout_queue(struct vm_pageout_queue *q)
6843 {
6844 	wait_result_t   wait_result;
6845 
6846 	vm_page_lock_queues();
6847 
6848 	while (!vm_page_queue_empty(&q->pgo_pending)) {
6849 		q->pgo_draining = TRUE;
6850 
6851 		assert_wait_timeout((event_t) (&q->pgo_laundry + 1), THREAD_INTERRUPTIBLE, 5000, 1000 * NSEC_PER_USEC);
6852 
6853 		vm_page_unlock_queues();
6854 
6855 		wait_result = thread_block(THREAD_CONTINUE_NULL);
6856 
6857 		if (wait_result == THREAD_TIMED_OUT && !vm_page_queue_empty(&q->pgo_pending)) {
6858 			hibernate_stats.hibernate_drain_timeout++;
6859 
6860 			if (q == &vm_pageout_queue_external) {
6861 				return 0;
6862 			}
6863 
6864 			return 1;
6865 		}
6866 		vm_page_lock_queues();
6867 
6868 		hibernate_stats.hibernate_drained++;
6869 	}
6870 	vm_page_unlock_queues();
6871 
6872 	return 0;
6873 }
6874 
6875 
6876 boolean_t hibernate_skip_external = FALSE;
6877 
6878 static int
hibernate_flush_queue(vm_page_queue_head_t * q,int qcount)6879 hibernate_flush_queue(vm_page_queue_head_t *q, int qcount)
6880 {
6881 	vm_page_t       m;
6882 	vm_object_t     l_object = NULL;
6883 	vm_object_t     m_object = NULL;
6884 	int             refmod_state = 0;
6885 	int             try_failed_count = 0;
6886 	int             retval = 0;
6887 	int             current_run = 0;
6888 	struct  vm_pageout_queue *iq;
6889 	struct  vm_pageout_queue *eq;
6890 	struct  vm_pageout_queue *tq;
6891 
6892 	KDBG(IOKDBG_CODE(DBG_HIBERNATE, 4) | DBG_FUNC_START,
6893 	    VM_KERNEL_UNSLIDE_OR_PERM(q), qcount);
6894 
6895 	iq = &vm_pageout_queue_internal;
6896 	eq = &vm_pageout_queue_external;
6897 
6898 	vm_page_lock_queues();
6899 
6900 	while (qcount && !vm_page_queue_empty(q)) {
6901 		if (current_run++ == 1000) {
6902 			if (hibernate_should_abort()) {
6903 				retval = 1;
6904 				break;
6905 			}
6906 			current_run = 0;
6907 		}
6908 
6909 		m = (vm_page_t) vm_page_queue_first(q);
6910 		m_object = VM_PAGE_OBJECT(m);
6911 
6912 		/*
6913 		 * check to see if we currently are working
6914 		 * with the same object... if so, we've
6915 		 * already got the lock
6916 		 */
6917 		if (m_object != l_object) {
6918 			/*
6919 			 * the object associated with candidate page is
6920 			 * different from the one we were just working
6921 			 * with... dump the lock if we still own it
6922 			 */
6923 			if (l_object != NULL) {
6924 				vm_object_unlock(l_object);
6925 				l_object = NULL;
6926 			}
6927 			/*
6928 			 * Try to lock object; since we've alread got the
6929 			 * page queues lock, we can only 'try' for this one.
6930 			 * if the 'try' fails, we need to do a mutex_pause
6931 			 * to allow the owner of the object lock a chance to
6932 			 * run...
6933 			 */
6934 			if (!vm_object_lock_try_scan(m_object)) {
6935 				if (try_failed_count > 20) {
6936 					hibernate_stats.hibernate_queue_nolock++;
6937 
6938 					goto reenter_pg_on_q;
6939 				}
6940 
6941 				vm_page_unlock_queues();
6942 				mutex_pause(try_failed_count++);
6943 				vm_page_lock_queues();
6944 
6945 				hibernate_stats.hibernate_queue_paused++;
6946 				continue;
6947 			} else {
6948 				l_object = m_object;
6949 			}
6950 		}
6951 		if (!m_object->alive || m->vmp_cleaning || m->vmp_laundry || m->vmp_busy || m->vmp_absent || m->vmp_error) {
6952 			/*
6953 			 * page is not to be cleaned
6954 			 * put it back on the head of its queue
6955 			 */
6956 			if (m->vmp_cleaning) {
6957 				hibernate_stats.hibernate_skipped_cleaning++;
6958 			} else {
6959 				hibernate_stats.hibernate_skipped_transient++;
6960 			}
6961 
6962 			goto reenter_pg_on_q;
6963 		}
6964 		if (m_object->copy == VM_OBJECT_NULL) {
6965 			if (m_object->purgable == VM_PURGABLE_VOLATILE || m_object->purgable == VM_PURGABLE_EMPTY) {
6966 				/*
6967 				 * let the normal hibernate image path
6968 				 * deal with these
6969 				 */
6970 				goto reenter_pg_on_q;
6971 			}
6972 		}
6973 		if (!m->vmp_dirty && m->vmp_pmapped) {
6974 			refmod_state = pmap_get_refmod(VM_PAGE_GET_PHYS_PAGE(m));
6975 
6976 			if ((refmod_state & VM_MEM_MODIFIED)) {
6977 				SET_PAGE_DIRTY(m, FALSE);
6978 			}
6979 		} else {
6980 			refmod_state = 0;
6981 		}
6982 
6983 		if (!m->vmp_dirty) {
6984 			/*
6985 			 * page is not to be cleaned
6986 			 * put it back on the head of its queue
6987 			 */
6988 			if (m->vmp_precious) {
6989 				hibernate_stats.hibernate_skipped_precious++;
6990 			}
6991 
6992 			goto reenter_pg_on_q;
6993 		}
6994 
6995 		if (hibernate_skip_external == TRUE && !m_object->internal) {
6996 			hibernate_stats.hibernate_skipped_external++;
6997 
6998 			goto reenter_pg_on_q;
6999 		}
7000 		tq = NULL;
7001 
7002 		if (m_object->internal) {
7003 			if (VM_PAGE_Q_THROTTLED(iq)) {
7004 				tq = iq;
7005 			}
7006 		} else if (VM_PAGE_Q_THROTTLED(eq)) {
7007 			tq = eq;
7008 		}
7009 
7010 		if (tq != NULL) {
7011 			wait_result_t   wait_result;
7012 			int             wait_count = 5;
7013 
7014 			if (l_object != NULL) {
7015 				vm_object_unlock(l_object);
7016 				l_object = NULL;
7017 			}
7018 
7019 			while (retval == 0) {
7020 				tq->pgo_throttled = TRUE;
7021 
7022 				assert_wait_timeout((event_t) &tq->pgo_laundry, THREAD_INTERRUPTIBLE, 1000, 1000 * NSEC_PER_USEC);
7023 
7024 				vm_page_unlock_queues();
7025 
7026 				wait_result = thread_block(THREAD_CONTINUE_NULL);
7027 
7028 				vm_page_lock_queues();
7029 
7030 				if (wait_result != THREAD_TIMED_OUT) {
7031 					break;
7032 				}
7033 				if (!VM_PAGE_Q_THROTTLED(tq)) {
7034 					break;
7035 				}
7036 
7037 				if (hibernate_should_abort()) {
7038 					retval = 1;
7039 				}
7040 
7041 				if (--wait_count == 0) {
7042 					hibernate_stats.hibernate_throttle_timeout++;
7043 
7044 					if (tq == eq) {
7045 						hibernate_skip_external = TRUE;
7046 						break;
7047 					}
7048 					retval = 1;
7049 				}
7050 			}
7051 			if (retval) {
7052 				break;
7053 			}
7054 
7055 			hibernate_stats.hibernate_throttled++;
7056 
7057 			continue;
7058 		}
7059 		/*
7060 		 * we've already factored out pages in the laundry which
7061 		 * means this page can't be on the pageout queue so it's
7062 		 * safe to do the vm_page_queues_remove
7063 		 */
7064 		vm_page_queues_remove(m, TRUE);
7065 
7066 		if (m_object->internal == TRUE) {
7067 			pmap_disconnect_options(VM_PAGE_GET_PHYS_PAGE(m), PMAP_OPTIONS_COMPRESSOR, NULL);
7068 		}
7069 
7070 		vm_pageout_cluster(m);
7071 
7072 		hibernate_stats.hibernate_found_dirty++;
7073 
7074 		goto next_pg;
7075 
7076 reenter_pg_on_q:
7077 		vm_page_queue_remove(q, m, vmp_pageq);
7078 		vm_page_queue_enter(q, m, vmp_pageq);
7079 
7080 		hibernate_stats.hibernate_reentered_on_q++;
7081 next_pg:
7082 		hibernate_stats.hibernate_considered++;
7083 
7084 		qcount--;
7085 		try_failed_count = 0;
7086 	}
7087 	if (l_object != NULL) {
7088 		vm_object_unlock(l_object);
7089 		l_object = NULL;
7090 	}
7091 
7092 	vm_page_unlock_queues();
7093 
7094 	KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 4) | DBG_FUNC_END, hibernate_stats.hibernate_found_dirty, retval, 0, 0, 0);
7095 
7096 	return retval;
7097 }
7098 
7099 
7100 static int
hibernate_flush_dirty_pages(int pass)7101 hibernate_flush_dirty_pages(int pass)
7102 {
7103 	struct vm_speculative_age_q     *aq;
7104 	uint32_t        i;
7105 
7106 	if (vm_page_local_q) {
7107 		zpercpu_foreach_cpu(lid) {
7108 			vm_page_reactivate_local(lid, TRUE, FALSE);
7109 		}
7110 	}
7111 
7112 	for (i = 0; i <= VM_PAGE_MAX_SPECULATIVE_AGE_Q; i++) {
7113 		int             qcount;
7114 		vm_page_t       m;
7115 
7116 		aq = &vm_page_queue_speculative[i];
7117 
7118 		if (vm_page_queue_empty(&aq->age_q)) {
7119 			continue;
7120 		}
7121 		qcount = 0;
7122 
7123 		vm_page_lockspin_queues();
7124 
7125 		vm_page_queue_iterate(&aq->age_q, m, vmp_pageq) {
7126 			qcount++;
7127 		}
7128 		vm_page_unlock_queues();
7129 
7130 		if (qcount) {
7131 			if (hibernate_flush_queue(&aq->age_q, qcount)) {
7132 				return 1;
7133 			}
7134 		}
7135 	}
7136 	if (hibernate_flush_queue(&vm_page_queue_inactive, vm_page_inactive_count - vm_page_anonymous_count - vm_page_cleaned_count)) {
7137 		return 1;
7138 	}
7139 	/* XXX FBDP TODO: flush secluded queue */
7140 	if (hibernate_flush_queue(&vm_page_queue_anonymous, vm_page_anonymous_count)) {
7141 		return 1;
7142 	}
7143 	if (hibernate_flush_queue(&vm_page_queue_cleaned, vm_page_cleaned_count)) {
7144 		return 1;
7145 	}
7146 	if (hibernate_drain_pageout_queue(&vm_pageout_queue_internal)) {
7147 		return 1;
7148 	}
7149 
7150 	if (pass == 1) {
7151 		vm_compressor_record_warmup_start();
7152 	}
7153 
7154 	if (hibernate_flush_queue(&vm_page_queue_active, vm_page_active_count)) {
7155 		if (pass == 1) {
7156 			vm_compressor_record_warmup_end();
7157 		}
7158 		return 1;
7159 	}
7160 	if (hibernate_drain_pageout_queue(&vm_pageout_queue_internal)) {
7161 		if (pass == 1) {
7162 			vm_compressor_record_warmup_end();
7163 		}
7164 		return 1;
7165 	}
7166 	if (pass == 1) {
7167 		vm_compressor_record_warmup_end();
7168 	}
7169 
7170 	if (hibernate_skip_external == FALSE && hibernate_drain_pageout_queue(&vm_pageout_queue_external)) {
7171 		return 1;
7172 	}
7173 
7174 	return 0;
7175 }
7176 
7177 
7178 void
hibernate_reset_stats()7179 hibernate_reset_stats()
7180 {
7181 	bzero(&hibernate_stats, sizeof(struct hibernate_statistics));
7182 }
7183 
7184 
7185 int
hibernate_flush_memory()7186 hibernate_flush_memory()
7187 {
7188 	int     retval;
7189 
7190 	assert(VM_CONFIG_COMPRESSOR_IS_PRESENT);
7191 
7192 	KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 3) | DBG_FUNC_START, vm_page_free_count, 0, 0, 0, 0);
7193 
7194 	hibernate_cleaning_in_progress = TRUE;
7195 	hibernate_skip_external = FALSE;
7196 
7197 	if ((retval = hibernate_flush_dirty_pages(1)) == 0) {
7198 		KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 10) | DBG_FUNC_START, VM_PAGE_COMPRESSOR_COUNT, 0, 0, 0, 0);
7199 
7200 		vm_compressor_flush();
7201 
7202 		KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 10) | DBG_FUNC_END, VM_PAGE_COMPRESSOR_COUNT, 0, 0, 0, 0);
7203 
7204 		if (consider_buffer_cache_collect != NULL) {
7205 			unsigned int orig_wire_count;
7206 
7207 			KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 7) | DBG_FUNC_START, 0, 0, 0, 0, 0);
7208 			orig_wire_count = vm_page_wire_count;
7209 
7210 			(void)(*consider_buffer_cache_collect)(1);
7211 			zone_gc(ZONE_GC_DRAIN);
7212 
7213 			HIBLOG("hibernate_flush_memory: buffer_cache_gc freed up %d wired pages\n", orig_wire_count - vm_page_wire_count);
7214 
7215 			KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 7) | DBG_FUNC_END, orig_wire_count - vm_page_wire_count, 0, 0, 0, 0);
7216 		}
7217 	}
7218 	hibernate_cleaning_in_progress = FALSE;
7219 
7220 	KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 3) | DBG_FUNC_END, vm_page_free_count, hibernate_stats.hibernate_found_dirty, retval, 0, 0);
7221 
7222 	if (retval) {
7223 		HIBLOG("hibernate_flush_memory() failed to finish - vm_page_compressor_count(%d)\n", VM_PAGE_COMPRESSOR_COUNT);
7224 	}
7225 
7226 
7227 	HIBPRINT("hibernate_flush_memory() considered(%d) reentered_on_q(%d) found_dirty(%d)\n",
7228 	    hibernate_stats.hibernate_considered,
7229 	    hibernate_stats.hibernate_reentered_on_q,
7230 	    hibernate_stats.hibernate_found_dirty);
7231 	HIBPRINT("   skipped_cleaning(%d) skipped_transient(%d) skipped_precious(%d) skipped_external(%d) queue_nolock(%d)\n",
7232 	    hibernate_stats.hibernate_skipped_cleaning,
7233 	    hibernate_stats.hibernate_skipped_transient,
7234 	    hibernate_stats.hibernate_skipped_precious,
7235 	    hibernate_stats.hibernate_skipped_external,
7236 	    hibernate_stats.hibernate_queue_nolock);
7237 	HIBPRINT("   queue_paused(%d) throttled(%d) throttle_timeout(%d) drained(%d) drain_timeout(%d)\n",
7238 	    hibernate_stats.hibernate_queue_paused,
7239 	    hibernate_stats.hibernate_throttled,
7240 	    hibernate_stats.hibernate_throttle_timeout,
7241 	    hibernate_stats.hibernate_drained,
7242 	    hibernate_stats.hibernate_drain_timeout);
7243 
7244 	return retval;
7245 }
7246 
7247 
7248 static void
hibernate_page_list_zero(hibernate_page_list_t * list)7249 hibernate_page_list_zero(hibernate_page_list_t *list)
7250 {
7251 	uint32_t             bank;
7252 	hibernate_bitmap_t * bitmap;
7253 
7254 	bitmap = &list->bank_bitmap[0];
7255 	for (bank = 0; bank < list->bank_count; bank++) {
7256 		uint32_t last_bit;
7257 
7258 		bzero((void *) &bitmap->bitmap[0], bitmap->bitmapwords << 2);
7259 		// set out-of-bound bits at end of bitmap.
7260 		last_bit = ((bitmap->last_page - bitmap->first_page + 1) & 31);
7261 		if (last_bit) {
7262 			bitmap->bitmap[bitmap->bitmapwords - 1] = (0xFFFFFFFF >> last_bit);
7263 		}
7264 
7265 		bitmap = (hibernate_bitmap_t *) &bitmap->bitmap[bitmap->bitmapwords];
7266 	}
7267 }
7268 
7269 void
hibernate_free_gobble_pages(void)7270 hibernate_free_gobble_pages(void)
7271 {
7272 	vm_page_t m, next;
7273 	uint32_t  count = 0;
7274 
7275 	m = (vm_page_t) hibernate_gobble_queue;
7276 	while (m) {
7277 		next = m->vmp_snext;
7278 		vm_page_free(m);
7279 		count++;
7280 		m = next;
7281 	}
7282 	hibernate_gobble_queue = VM_PAGE_NULL;
7283 
7284 	if (count) {
7285 		HIBLOG("Freed %d pages\n", count);
7286 	}
7287 }
7288 
7289 static boolean_t
hibernate_consider_discard(vm_page_t m,boolean_t preflight)7290 hibernate_consider_discard(vm_page_t m, boolean_t preflight)
7291 {
7292 	vm_object_t object = NULL;
7293 	int                  refmod_state;
7294 	boolean_t            discard = FALSE;
7295 
7296 	do{
7297 		if (m->vmp_private) {
7298 			panic("hibernate_consider_discard: private");
7299 		}
7300 
7301 		object = VM_PAGE_OBJECT(m);
7302 
7303 		if (!vm_object_lock_try(object)) {
7304 			object = NULL;
7305 			if (!preflight) {
7306 				hibernate_stats.cd_lock_failed++;
7307 			}
7308 			break;
7309 		}
7310 		if (VM_PAGE_WIRED(m)) {
7311 			if (!preflight) {
7312 				hibernate_stats.cd_found_wired++;
7313 			}
7314 			break;
7315 		}
7316 		if (m->vmp_precious) {
7317 			if (!preflight) {
7318 				hibernate_stats.cd_found_precious++;
7319 			}
7320 			break;
7321 		}
7322 		if (m->vmp_busy || !object->alive) {
7323 			/*
7324 			 *	Somebody is playing with this page.
7325 			 */
7326 			if (!preflight) {
7327 				hibernate_stats.cd_found_busy++;
7328 			}
7329 			break;
7330 		}
7331 		if (m->vmp_absent || m->vmp_unusual || m->vmp_error) {
7332 			/*
7333 			 * If it's unusual in anyway, ignore it
7334 			 */
7335 			if (!preflight) {
7336 				hibernate_stats.cd_found_unusual++;
7337 			}
7338 			break;
7339 		}
7340 		if (m->vmp_cleaning) {
7341 			if (!preflight) {
7342 				hibernate_stats.cd_found_cleaning++;
7343 			}
7344 			break;
7345 		}
7346 		if (m->vmp_laundry) {
7347 			if (!preflight) {
7348 				hibernate_stats.cd_found_laundry++;
7349 			}
7350 			break;
7351 		}
7352 		if (!m->vmp_dirty) {
7353 			refmod_state = pmap_get_refmod(VM_PAGE_GET_PHYS_PAGE(m));
7354 
7355 			if (refmod_state & VM_MEM_REFERENCED) {
7356 				m->vmp_reference = TRUE;
7357 			}
7358 			if (refmod_state & VM_MEM_MODIFIED) {
7359 				SET_PAGE_DIRTY(m, FALSE);
7360 			}
7361 		}
7362 
7363 		/*
7364 		 * If it's clean or purgeable we can discard the page on wakeup.
7365 		 */
7366 		discard = (!m->vmp_dirty)
7367 		    || (VM_PURGABLE_VOLATILE == object->purgable)
7368 		    || (VM_PURGABLE_EMPTY == object->purgable);
7369 
7370 
7371 		if (discard == FALSE) {
7372 			if (!preflight) {
7373 				hibernate_stats.cd_found_dirty++;
7374 			}
7375 		} else if (m->vmp_xpmapped && m->vmp_reference && !object->internal) {
7376 			if (hibernate_stats.cd_found_xpmapped < HIBERNATE_XPMAPPED_LIMIT) {
7377 				if (!preflight) {
7378 					hibernate_stats.cd_found_xpmapped++;
7379 				}
7380 				discard = FALSE;
7381 			} else {
7382 				if (!preflight) {
7383 					hibernate_stats.cd_skipped_xpmapped++;
7384 				}
7385 			}
7386 		}
7387 	}while (FALSE);
7388 
7389 	if (object) {
7390 		vm_object_unlock(object);
7391 	}
7392 
7393 	return discard;
7394 }
7395 
7396 
7397 static void
hibernate_discard_page(vm_page_t m)7398 hibernate_discard_page(vm_page_t m)
7399 {
7400 	vm_object_t m_object;
7401 
7402 	if (m->vmp_absent || m->vmp_unusual || m->vmp_error) {
7403 		/*
7404 		 * If it's unusual in anyway, ignore
7405 		 */
7406 		return;
7407 	}
7408 
7409 	m_object = VM_PAGE_OBJECT(m);
7410 
7411 #if MACH_ASSERT || DEBUG
7412 	if (!vm_object_lock_try(m_object)) {
7413 		panic("hibernate_discard_page(%p) !vm_object_lock_try", m);
7414 	}
7415 #else
7416 	/* No need to lock page queue for token delete, hibernate_vm_unlock()
7417 	 *  makes sure these locks are uncontended before sleep */
7418 #endif /* MACH_ASSERT || DEBUG */
7419 
7420 	if (m->vmp_pmapped == TRUE) {
7421 		__unused int refmod_state = pmap_disconnect(VM_PAGE_GET_PHYS_PAGE(m));
7422 	}
7423 
7424 	if (m->vmp_laundry) {
7425 		panic("hibernate_discard_page(%p) laundry", m);
7426 	}
7427 	if (m->vmp_private) {
7428 		panic("hibernate_discard_page(%p) private", m);
7429 	}
7430 	if (m->vmp_fictitious) {
7431 		panic("hibernate_discard_page(%p) fictitious", m);
7432 	}
7433 
7434 	if (VM_PURGABLE_VOLATILE == m_object->purgable) {
7435 		/* object should be on a queue */
7436 		assert((m_object->objq.next != NULL) && (m_object->objq.prev != NULL));
7437 		purgeable_q_t old_queue = vm_purgeable_object_remove(m_object);
7438 		assert(old_queue);
7439 		if (m_object->purgeable_when_ripe) {
7440 			vm_purgeable_token_delete_first(old_queue);
7441 		}
7442 		vm_object_lock_assert_exclusive(m_object);
7443 		m_object->purgable = VM_PURGABLE_EMPTY;
7444 
7445 		/*
7446 		 * Purgeable ledgers:  pages of VOLATILE and EMPTY objects are
7447 		 * accounted in the "volatile" ledger, so no change here.
7448 		 * We have to update vm_page_purgeable_count, though, since we're
7449 		 * effectively purging this object.
7450 		 */
7451 		unsigned int delta;
7452 		assert(m_object->resident_page_count >= m_object->wired_page_count);
7453 		delta = (m_object->resident_page_count - m_object->wired_page_count);
7454 		assert(vm_page_purgeable_count >= delta);
7455 		assert(delta > 0);
7456 		OSAddAtomic(-delta, (SInt32 *)&vm_page_purgeable_count);
7457 	}
7458 
7459 	vm_page_free(m);
7460 
7461 #if MACH_ASSERT || DEBUG
7462 	vm_object_unlock(m_object);
7463 #endif  /* MACH_ASSERT || DEBUG */
7464 }
7465 
7466 /*
7467  *  Grab locks for hibernate_page_list_setall()
7468  */
7469 void
hibernate_vm_lock_queues(void)7470 hibernate_vm_lock_queues(void)
7471 {
7472 	vm_object_lock(compressor_object);
7473 	vm_page_lock_queues();
7474 	lck_mtx_lock(&vm_page_queue_free_lock);
7475 	lck_mtx_lock(&vm_purgeable_queue_lock);
7476 
7477 	if (vm_page_local_q) {
7478 		zpercpu_foreach(lq, vm_page_local_q) {
7479 			VPL_LOCK(&lq->vpl_lock);
7480 		}
7481 	}
7482 }
7483 
7484 void
hibernate_vm_unlock_queues(void)7485 hibernate_vm_unlock_queues(void)
7486 {
7487 	if (vm_page_local_q) {
7488 		zpercpu_foreach(lq, vm_page_local_q) {
7489 			VPL_UNLOCK(&lq->vpl_lock);
7490 		}
7491 	}
7492 	lck_mtx_unlock(&vm_purgeable_queue_lock);
7493 	lck_mtx_unlock(&vm_page_queue_free_lock);
7494 	vm_page_unlock_queues();
7495 	vm_object_unlock(compressor_object);
7496 }
7497 
7498 /*
7499  *  Bits zero in the bitmaps => page needs to be saved. All pages default to be saved,
7500  *  pages known to VM to not need saving are subtracted.
7501  *  Wired pages to be saved are present in page_list_wired, pageable in page_list.
7502  */
7503 
7504 void
hibernate_page_list_setall(hibernate_page_list_t * page_list,hibernate_page_list_t * page_list_wired,hibernate_page_list_t * page_list_pal,boolean_t preflight,boolean_t will_discard,uint32_t * pagesOut)7505 hibernate_page_list_setall(hibernate_page_list_t * page_list,
7506     hibernate_page_list_t * page_list_wired,
7507     hibernate_page_list_t * page_list_pal,
7508     boolean_t preflight,
7509     boolean_t will_discard,
7510     uint32_t * pagesOut)
7511 {
7512 	uint64_t start, end, nsec;
7513 	vm_page_t m;
7514 	vm_page_t next;
7515 	uint32_t pages = page_list->page_count;
7516 	uint32_t count_anonymous = 0, count_throttled = 0, count_compressor = 0;
7517 	uint32_t count_inactive = 0, count_active = 0, count_speculative = 0, count_cleaned = 0;
7518 	uint32_t count_wire = pages;
7519 	uint32_t count_discard_active    = 0;
7520 	uint32_t count_discard_inactive  = 0;
7521 	uint32_t count_discard_cleaned   = 0;
7522 	uint32_t count_discard_purgeable = 0;
7523 	uint32_t count_discard_speculative = 0;
7524 	uint32_t count_discard_vm_struct_pages = 0;
7525 	uint32_t i;
7526 	uint32_t             bank;
7527 	hibernate_bitmap_t * bitmap;
7528 	hibernate_bitmap_t * bitmap_wired;
7529 	boolean_t                    discard_all;
7530 	boolean_t            discard = FALSE;
7531 
7532 	HIBLOG("hibernate_page_list_setall(preflight %d) start\n", preflight);
7533 
7534 	if (preflight) {
7535 		page_list       = NULL;
7536 		page_list_wired = NULL;
7537 		page_list_pal   = NULL;
7538 		discard_all     = FALSE;
7539 	} else {
7540 		discard_all     = will_discard;
7541 	}
7542 
7543 #if MACH_ASSERT || DEBUG
7544 	if (!preflight) {
7545 		assert(hibernate_vm_locks_are_safe());
7546 		vm_page_lock_queues();
7547 		if (vm_page_local_q) {
7548 			zpercpu_foreach(lq, vm_page_local_q) {
7549 				VPL_LOCK(&lq->vpl_lock);
7550 			}
7551 		}
7552 	}
7553 #endif  /* MACH_ASSERT || DEBUG */
7554 
7555 
7556 	KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 8) | DBG_FUNC_START, count_wire, 0, 0, 0, 0);
7557 
7558 	clock_get_uptime(&start);
7559 
7560 	if (!preflight) {
7561 		hibernate_page_list_zero(page_list);
7562 		hibernate_page_list_zero(page_list_wired);
7563 		hibernate_page_list_zero(page_list_pal);
7564 
7565 		hibernate_stats.cd_vm_page_wire_count = vm_page_wire_count;
7566 		hibernate_stats.cd_pages = pages;
7567 	}
7568 
7569 	if (vm_page_local_q) {
7570 		zpercpu_foreach_cpu(lid) {
7571 			vm_page_reactivate_local(lid, TRUE, !preflight);
7572 		}
7573 	}
7574 
7575 	if (preflight) {
7576 		vm_object_lock(compressor_object);
7577 		vm_page_lock_queues();
7578 		lck_mtx_lock(&vm_page_queue_free_lock);
7579 	}
7580 
7581 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
7582 
7583 	hibernation_vmqueues_inspection = TRUE;
7584 
7585 	m = (vm_page_t) hibernate_gobble_queue;
7586 	while (m) {
7587 		pages--;
7588 		count_wire--;
7589 		if (!preflight) {
7590 			hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7591 			hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7592 		}
7593 		m = m->vmp_snext;
7594 	}
7595 
7596 	if (!preflight) {
7597 		percpu_foreach(free_pages_head, free_pages) {
7598 			for (m = *free_pages_head; m; m = m->vmp_snext) {
7599 				assert(m->vmp_q_state == VM_PAGE_ON_FREE_LOCAL_Q);
7600 
7601 				pages--;
7602 				count_wire--;
7603 				hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7604 				hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7605 
7606 				hibernate_stats.cd_local_free++;
7607 				hibernate_stats.cd_total_free++;
7608 			}
7609 		}
7610 	}
7611 
7612 	for (i = 0; i < vm_colors; i++) {
7613 		vm_page_queue_iterate(&vm_page_queue_free[i].qhead, m, vmp_pageq) {
7614 			assert(m->vmp_q_state == VM_PAGE_ON_FREE_Q);
7615 
7616 			pages--;
7617 			count_wire--;
7618 			if (!preflight) {
7619 				hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7620 				hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7621 
7622 				hibernate_stats.cd_total_free++;
7623 			}
7624 		}
7625 	}
7626 
7627 	vm_page_queue_iterate(&vm_lopage_queue_free, m, vmp_pageq) {
7628 		assert(m->vmp_q_state == VM_PAGE_ON_FREE_LOPAGE_Q);
7629 
7630 		pages--;
7631 		count_wire--;
7632 		if (!preflight) {
7633 			hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7634 			hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7635 
7636 			hibernate_stats.cd_total_free++;
7637 		}
7638 	}
7639 
7640 	m = (vm_page_t) vm_page_queue_first(&vm_page_queue_throttled);
7641 	while (m && !vm_page_queue_end(&vm_page_queue_throttled, (vm_page_queue_entry_t)m)) {
7642 		assert(m->vmp_q_state == VM_PAGE_ON_THROTTLED_Q);
7643 
7644 		next = (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.next);
7645 		discard = FALSE;
7646 		if ((kIOHibernateModeDiscardCleanInactive & gIOHibernateMode)
7647 		    && hibernate_consider_discard(m, preflight)) {
7648 			if (!preflight) {
7649 				hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7650 			}
7651 			count_discard_inactive++;
7652 			discard = discard_all;
7653 		} else {
7654 			count_throttled++;
7655 		}
7656 		count_wire--;
7657 		if (!preflight) {
7658 			hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7659 		}
7660 
7661 		if (discard) {
7662 			hibernate_discard_page(m);
7663 		}
7664 		m = next;
7665 	}
7666 
7667 	m = (vm_page_t)vm_page_queue_first(&vm_page_queue_anonymous);
7668 	while (m && !vm_page_queue_end(&vm_page_queue_anonymous, (vm_page_queue_entry_t)m)) {
7669 		assert(m->vmp_q_state == VM_PAGE_ON_INACTIVE_INTERNAL_Q);
7670 
7671 		next = (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.next);
7672 		discard = FALSE;
7673 		if ((kIOHibernateModeDiscardCleanInactive & gIOHibernateMode) &&
7674 		    hibernate_consider_discard(m, preflight)) {
7675 			if (!preflight) {
7676 				hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7677 			}
7678 			if (m->vmp_dirty) {
7679 				count_discard_purgeable++;
7680 			} else {
7681 				count_discard_inactive++;
7682 			}
7683 			discard = discard_all;
7684 		} else {
7685 			count_anonymous++;
7686 		}
7687 		count_wire--;
7688 		if (!preflight) {
7689 			hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7690 		}
7691 		if (discard) {
7692 			hibernate_discard_page(m);
7693 		}
7694 		m = next;
7695 	}
7696 
7697 	m = (vm_page_t) vm_page_queue_first(&vm_page_queue_cleaned);
7698 	while (m && !vm_page_queue_end(&vm_page_queue_cleaned, (vm_page_queue_entry_t)m)) {
7699 		assert(m->vmp_q_state == VM_PAGE_ON_INACTIVE_CLEANED_Q);
7700 
7701 		next = (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.next);
7702 		discard = FALSE;
7703 		if ((kIOHibernateModeDiscardCleanInactive & gIOHibernateMode) &&
7704 		    hibernate_consider_discard(m, preflight)) {
7705 			if (!preflight) {
7706 				hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7707 			}
7708 			if (m->vmp_dirty) {
7709 				count_discard_purgeable++;
7710 			} else {
7711 				count_discard_cleaned++;
7712 			}
7713 			discard = discard_all;
7714 		} else {
7715 			count_cleaned++;
7716 		}
7717 		count_wire--;
7718 		if (!preflight) {
7719 			hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7720 		}
7721 		if (discard) {
7722 			hibernate_discard_page(m);
7723 		}
7724 		m = next;
7725 	}
7726 
7727 	m = (vm_page_t) vm_page_queue_first(&vm_page_queue_active);
7728 	while (m && !vm_page_queue_end(&vm_page_queue_active, (vm_page_queue_entry_t)m)) {
7729 		assert(m->vmp_q_state == VM_PAGE_ON_ACTIVE_Q);
7730 
7731 		next = (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.next);
7732 		discard = FALSE;
7733 		if ((kIOHibernateModeDiscardCleanActive & gIOHibernateMode) &&
7734 		    hibernate_consider_discard(m, preflight)) {
7735 			if (!preflight) {
7736 				hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7737 			}
7738 			if (m->vmp_dirty) {
7739 				count_discard_purgeable++;
7740 			} else {
7741 				count_discard_active++;
7742 			}
7743 			discard = discard_all;
7744 		} else {
7745 			count_active++;
7746 		}
7747 		count_wire--;
7748 		if (!preflight) {
7749 			hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7750 		}
7751 		if (discard) {
7752 			hibernate_discard_page(m);
7753 		}
7754 		m = next;
7755 	}
7756 
7757 	m = (vm_page_t) vm_page_queue_first(&vm_page_queue_inactive);
7758 	while (m && !vm_page_queue_end(&vm_page_queue_inactive, (vm_page_queue_entry_t)m)) {
7759 		assert(m->vmp_q_state == VM_PAGE_ON_INACTIVE_EXTERNAL_Q);
7760 
7761 		next = (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.next);
7762 		discard = FALSE;
7763 		if ((kIOHibernateModeDiscardCleanInactive & gIOHibernateMode) &&
7764 		    hibernate_consider_discard(m, preflight)) {
7765 			if (!preflight) {
7766 				hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7767 			}
7768 			if (m->vmp_dirty) {
7769 				count_discard_purgeable++;
7770 			} else {
7771 				count_discard_inactive++;
7772 			}
7773 			discard = discard_all;
7774 		} else {
7775 			count_inactive++;
7776 		}
7777 		count_wire--;
7778 		if (!preflight) {
7779 			hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7780 		}
7781 		if (discard) {
7782 			hibernate_discard_page(m);
7783 		}
7784 		m = next;
7785 	}
7786 	/* XXX FBDP TODO: secluded queue */
7787 
7788 	for (i = 0; i <= VM_PAGE_MAX_SPECULATIVE_AGE_Q; i++) {
7789 		m = (vm_page_t) vm_page_queue_first(&vm_page_queue_speculative[i].age_q);
7790 		while (m && !vm_page_queue_end(&vm_page_queue_speculative[i].age_q, (vm_page_queue_entry_t)m)) {
7791 			assertf(m->vmp_q_state == VM_PAGE_ON_SPECULATIVE_Q,
7792 			    "Bad page: %p (0x%x:0x%x) on queue %d has state: %d (Discard: %d, Preflight: %d)",
7793 			    m, m->vmp_pageq.next, m->vmp_pageq.prev, i, m->vmp_q_state, discard, preflight);
7794 
7795 			next = (vm_page_t)VM_PAGE_UNPACK_PTR(m->vmp_pageq.next);
7796 			discard = FALSE;
7797 			if ((kIOHibernateModeDiscardCleanInactive & gIOHibernateMode) &&
7798 			    hibernate_consider_discard(m, preflight)) {
7799 				if (!preflight) {
7800 					hibernate_page_bitset(page_list, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7801 				}
7802 				count_discard_speculative++;
7803 				discard = discard_all;
7804 			} else {
7805 				count_speculative++;
7806 			}
7807 			count_wire--;
7808 			if (!preflight) {
7809 				hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7810 			}
7811 			if (discard) {
7812 				hibernate_discard_page(m);
7813 			}
7814 			m = next;
7815 		}
7816 	}
7817 
7818 	vm_page_queue_iterate(&compressor_object->memq, m, vmp_listq) {
7819 		assert(m->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR);
7820 
7821 		count_compressor++;
7822 		count_wire--;
7823 		if (!preflight) {
7824 			hibernate_page_bitset(page_list_wired, TRUE, VM_PAGE_GET_PHYS_PAGE(m));
7825 		}
7826 	}
7827 
7828 	if (preflight == FALSE && discard_all == TRUE) {
7829 		KDBG(IOKDBG_CODE(DBG_HIBERNATE, 12) | DBG_FUNC_START);
7830 
7831 		HIBLOG("hibernate_teardown started\n");
7832 		count_discard_vm_struct_pages = hibernate_teardown_vm_structs(page_list, page_list_wired);
7833 		HIBLOG("hibernate_teardown completed - discarded %d\n", count_discard_vm_struct_pages);
7834 
7835 		pages -= count_discard_vm_struct_pages;
7836 		count_wire -= count_discard_vm_struct_pages;
7837 
7838 		hibernate_stats.cd_vm_struct_pages_unneeded = count_discard_vm_struct_pages;
7839 
7840 		KDBG(IOKDBG_CODE(DBG_HIBERNATE, 12) | DBG_FUNC_END);
7841 	}
7842 
7843 	if (!preflight) {
7844 		// pull wired from hibernate_bitmap
7845 		bitmap = &page_list->bank_bitmap[0];
7846 		bitmap_wired = &page_list_wired->bank_bitmap[0];
7847 		for (bank = 0; bank < page_list->bank_count; bank++) {
7848 			for (i = 0; i < bitmap->bitmapwords; i++) {
7849 				bitmap->bitmap[i] = bitmap->bitmap[i] | ~bitmap_wired->bitmap[i];
7850 			}
7851 			bitmap = (hibernate_bitmap_t *)&bitmap->bitmap[bitmap->bitmapwords];
7852 			bitmap_wired = (hibernate_bitmap_t *) &bitmap_wired->bitmap[bitmap_wired->bitmapwords];
7853 		}
7854 	}
7855 
7856 	// machine dependent adjustments
7857 	hibernate_page_list_setall_machine(page_list, page_list_wired, preflight, &pages);
7858 
7859 	if (!preflight) {
7860 		hibernate_stats.cd_count_wire = count_wire;
7861 		hibernate_stats.cd_discarded = count_discard_active + count_discard_inactive + count_discard_purgeable +
7862 		    count_discard_speculative + count_discard_cleaned + count_discard_vm_struct_pages;
7863 	}
7864 
7865 	clock_get_uptime(&end);
7866 	absolutetime_to_nanoseconds(end - start, &nsec);
7867 	HIBLOG("hibernate_page_list_setall time: %qd ms\n", nsec / 1000000ULL);
7868 
7869 	HIBLOG("pages %d, wire %d, act %d, inact %d, cleaned %d spec %d, zf %d, throt %d, compr %d, xpmapped %d\n  %s discard act %d inact %d purgeable %d spec %d cleaned %d\n",
7870 	    pages, count_wire, count_active, count_inactive, count_cleaned, count_speculative, count_anonymous, count_throttled, count_compressor, hibernate_stats.cd_found_xpmapped,
7871 	    discard_all ? "did" : "could",
7872 	    count_discard_active, count_discard_inactive, count_discard_purgeable, count_discard_speculative, count_discard_cleaned);
7873 
7874 	if (hibernate_stats.cd_skipped_xpmapped) {
7875 		HIBLOG("WARNING: hibernate_page_list_setall skipped %d xpmapped pages\n", hibernate_stats.cd_skipped_xpmapped);
7876 	}
7877 
7878 	*pagesOut = pages - count_discard_active - count_discard_inactive - count_discard_purgeable - count_discard_speculative - count_discard_cleaned;
7879 
7880 	if (preflight && will_discard) {
7881 		*pagesOut -= count_compressor + count_throttled + count_anonymous + count_inactive + count_cleaned + count_speculative + count_active;
7882 		/*
7883 		 * We try to keep max HIBERNATE_XPMAPPED_LIMIT pages around in the hibernation image
7884 		 * even if these are clean and so we need to size the hibernation image accordingly.
7885 		 *
7886 		 * NB: We have to assume all HIBERNATE_XPMAPPED_LIMIT pages might show up because 'dirty'
7887 		 * xpmapped pages aren't distinguishable from other 'dirty' pages in preflight. So we might
7888 		 * only see part of the xpmapped pages if we look at 'cd_found_xpmapped' which solely tracks
7889 		 * clean xpmapped pages.
7890 		 *
7891 		 * Since these pages are all cleaned by the time we are in the post-preflight phase, we might
7892 		 * see a much larger number in 'cd_found_xpmapped' now than we did in the preflight phase
7893 		 */
7894 		*pagesOut +=  HIBERNATE_XPMAPPED_LIMIT;
7895 	}
7896 
7897 	hibernation_vmqueues_inspection = FALSE;
7898 
7899 #if MACH_ASSERT || DEBUG
7900 	if (!preflight) {
7901 		if (vm_page_local_q) {
7902 			zpercpu_foreach(lq, vm_page_local_q) {
7903 				VPL_UNLOCK(&lq->vpl_lock);
7904 			}
7905 		}
7906 		vm_page_unlock_queues();
7907 	}
7908 #endif  /* MACH_ASSERT || DEBUG */
7909 
7910 	if (preflight) {
7911 		lck_mtx_unlock(&vm_page_queue_free_lock);
7912 		vm_page_unlock_queues();
7913 		vm_object_unlock(compressor_object);
7914 	}
7915 
7916 	KERNEL_DEBUG_CONSTANT(IOKDBG_CODE(DBG_HIBERNATE, 8) | DBG_FUNC_END, count_wire, *pagesOut, 0, 0, 0);
7917 }
7918 
7919 void
hibernate_page_list_discard(hibernate_page_list_t * page_list)7920 hibernate_page_list_discard(hibernate_page_list_t * page_list)
7921 {
7922 	uint64_t  start, end, nsec;
7923 	vm_page_t m;
7924 	vm_page_t next;
7925 	uint32_t  i;
7926 	uint32_t  count_discard_active    = 0;
7927 	uint32_t  count_discard_inactive  = 0;
7928 	uint32_t  count_discard_purgeable = 0;
7929 	uint32_t  count_discard_cleaned   = 0;
7930 	uint32_t  count_discard_speculative = 0;
7931 
7932 
7933 #if MACH_ASSERT || DEBUG
7934 	vm_page_lock_queues();
7935 	if (vm_page_local_q) {
7936 		zpercpu_foreach(lq, vm_page_local_q) {
7937 			VPL_LOCK(&lq->vpl_lock);
7938 		}
7939 	}
7940 #endif  /* MACH_ASSERT || DEBUG */
7941 
7942 	clock_get_uptime(&start);
7943 
7944 	m = (vm_page_t) vm_page_queue_first(&vm_page_queue_anonymous);
7945 	while (m && !vm_page_queue_end(&vm_page_queue_anonymous, (vm_page_queue_entry_t)m)) {
7946 		assert(m->vmp_q_state == VM_PAGE_ON_INACTIVE_INTERNAL_Q);
7947 
7948 		next = (vm_page_t) VM_PAGE_UNPACK_PTR(m->vmp_pageq.next);
7949 		if (hibernate_page_bittst(page_list, VM_PAGE_GET_PHYS_PAGE(m))) {
7950 			if (m->vmp_dirty) {
7951 				count_discard_purgeable++;
7952 			} else {
7953 				count_discard_inactive++;
7954 			}
7955 			hibernate_discard_page(m);
7956 		}
7957 		m = next;
7958 	}
7959 
7960 	for (i = 0; i <= VM_PAGE_MAX_SPECULATIVE_AGE_Q; i++) {
7961 		m = (vm_page_t) vm_page_queue_first(&vm_page_queue_speculative[i].age_q);
7962 		while (m && !vm_page_queue_end(&vm_page_queue_speculative[i].age_q, (vm_page_queue_entry_t)m)) {
7963 			assert(m->vmp_q_state == VM_PAGE_ON_SPECULATIVE_Q);
7964 
7965 			next = (vm_page_t) VM_PAGE_UNPACK_PTR(m->vmp_pageq.next);
7966 			if (hibernate_page_bittst(page_list, VM_PAGE_GET_PHYS_PAGE(m))) {
7967 				count_discard_speculative++;
7968 				hibernate_discard_page(m);
7969 			}
7970 			m = next;
7971 		}
7972 	}
7973 
7974 	m = (vm_page_t) vm_page_queue_first(&vm_page_queue_inactive);
7975 	while (m && !vm_page_queue_end(&vm_page_queue_inactive, (vm_page_queue_entry_t)m)) {
7976 		assert(m->vmp_q_state == VM_PAGE_ON_INACTIVE_EXTERNAL_Q);
7977 
7978 		next = (vm_page_t) VM_PAGE_UNPACK_PTR(m->vmp_pageq.next);
7979 		if (hibernate_page_bittst(page_list, VM_PAGE_GET_PHYS_PAGE(m))) {
7980 			if (m->vmp_dirty) {
7981 				count_discard_purgeable++;
7982 			} else {
7983 				count_discard_inactive++;
7984 			}
7985 			hibernate_discard_page(m);
7986 		}
7987 		m = next;
7988 	}
7989 	/* XXX FBDP TODO: secluded queue */
7990 
7991 	m = (vm_page_t) vm_page_queue_first(&vm_page_queue_active);
7992 	while (m && !vm_page_queue_end(&vm_page_queue_active, (vm_page_queue_entry_t)m)) {
7993 		assert(m->vmp_q_state == VM_PAGE_ON_ACTIVE_Q);
7994 
7995 		next = (vm_page_t) VM_PAGE_UNPACK_PTR(m->vmp_pageq.next);
7996 		if (hibernate_page_bittst(page_list, VM_PAGE_GET_PHYS_PAGE(m))) {
7997 			if (m->vmp_dirty) {
7998 				count_discard_purgeable++;
7999 			} else {
8000 				count_discard_active++;
8001 			}
8002 			hibernate_discard_page(m);
8003 		}
8004 		m = next;
8005 	}
8006 
8007 	m = (vm_page_t) vm_page_queue_first(&vm_page_queue_cleaned);
8008 	while (m && !vm_page_queue_end(&vm_page_queue_cleaned, (vm_page_queue_entry_t)m)) {
8009 		assert(m->vmp_q_state == VM_PAGE_ON_INACTIVE_CLEANED_Q);
8010 
8011 		next = (vm_page_t) VM_PAGE_UNPACK_PTR(m->vmp_pageq.next);
8012 		if (hibernate_page_bittst(page_list, VM_PAGE_GET_PHYS_PAGE(m))) {
8013 			if (m->vmp_dirty) {
8014 				count_discard_purgeable++;
8015 			} else {
8016 				count_discard_cleaned++;
8017 			}
8018 			hibernate_discard_page(m);
8019 		}
8020 		m = next;
8021 	}
8022 
8023 #if MACH_ASSERT || DEBUG
8024 	if (vm_page_local_q) {
8025 		zpercpu_foreach(lq, vm_page_local_q) {
8026 			VPL_UNLOCK(&lq->vpl_lock);
8027 		}
8028 	}
8029 	vm_page_unlock_queues();
8030 #endif  /* MACH_ASSERT || DEBUG */
8031 
8032 	clock_get_uptime(&end);
8033 	absolutetime_to_nanoseconds(end - start, &nsec);
8034 	HIBLOG("hibernate_page_list_discard time: %qd ms, discarded act %d inact %d purgeable %d spec %d cleaned %d\n",
8035 	    nsec / 1000000ULL,
8036 	    count_discard_active, count_discard_inactive, count_discard_purgeable, count_discard_speculative, count_discard_cleaned);
8037 }
8038 
8039 boolean_t       hibernate_paddr_map_inited = FALSE;
8040 unsigned int    hibernate_teardown_last_valid_compact_indx = -1;
8041 vm_page_t       hibernate_rebuild_hash_list = NULL;
8042 
8043 unsigned int    hibernate_teardown_found_tabled_pages = 0;
8044 unsigned int    hibernate_teardown_found_created_pages = 0;
8045 unsigned int    hibernate_teardown_found_free_pages = 0;
8046 unsigned int    hibernate_teardown_vm_page_free_count;
8047 
8048 
8049 struct ppnum_mapping {
8050 	struct ppnum_mapping    *ppnm_next;
8051 	ppnum_t                 ppnm_base_paddr;
8052 	unsigned int            ppnm_sindx;
8053 	unsigned int            ppnm_eindx;
8054 };
8055 
8056 struct ppnum_mapping    *ppnm_head;
8057 struct ppnum_mapping    *ppnm_last_found = NULL;
8058 
8059 
8060 void
hibernate_create_paddr_map(void)8061 hibernate_create_paddr_map(void)
8062 {
8063 	unsigned int    i;
8064 	ppnum_t         next_ppnum_in_run = 0;
8065 	struct ppnum_mapping *ppnm = NULL;
8066 
8067 	if (hibernate_paddr_map_inited == FALSE) {
8068 		for (i = 0; i < vm_pages_count; i++) {
8069 			if (ppnm) {
8070 				ppnm->ppnm_eindx = i;
8071 			}
8072 
8073 			if (ppnm == NULL || VM_PAGE_GET_PHYS_PAGE(&vm_pages[i]) != next_ppnum_in_run) {
8074 				ppnm = zalloc_permanent_type(struct ppnum_mapping);
8075 
8076 				ppnm->ppnm_next = ppnm_head;
8077 				ppnm_head = ppnm;
8078 
8079 				ppnm->ppnm_sindx = i;
8080 				ppnm->ppnm_base_paddr = VM_PAGE_GET_PHYS_PAGE(&vm_pages[i]);
8081 			}
8082 			next_ppnum_in_run = VM_PAGE_GET_PHYS_PAGE(&vm_pages[i]) + 1;
8083 		}
8084 		ppnm->ppnm_eindx = vm_pages_count;
8085 
8086 		hibernate_paddr_map_inited = TRUE;
8087 	}
8088 }
8089 
8090 ppnum_t
hibernate_lookup_paddr(unsigned int indx)8091 hibernate_lookup_paddr(unsigned int indx)
8092 {
8093 	struct ppnum_mapping *ppnm = NULL;
8094 
8095 	ppnm = ppnm_last_found;
8096 
8097 	if (ppnm) {
8098 		if (indx >= ppnm->ppnm_sindx && indx < ppnm->ppnm_eindx) {
8099 			goto done;
8100 		}
8101 	}
8102 	for (ppnm = ppnm_head; ppnm; ppnm = ppnm->ppnm_next) {
8103 		if (indx >= ppnm->ppnm_sindx && indx < ppnm->ppnm_eindx) {
8104 			ppnm_last_found = ppnm;
8105 			break;
8106 		}
8107 	}
8108 	if (ppnm == NULL) {
8109 		panic("hibernate_lookup_paddr of %d failed", indx);
8110 	}
8111 done:
8112 	return ppnm->ppnm_base_paddr + (indx - ppnm->ppnm_sindx);
8113 }
8114 
8115 
8116 uint32_t
hibernate_mark_as_unneeded(addr64_t saddr,addr64_t eaddr,hibernate_page_list_t * page_list,hibernate_page_list_t * page_list_wired)8117 hibernate_mark_as_unneeded(addr64_t saddr, addr64_t eaddr, hibernate_page_list_t *page_list, hibernate_page_list_t *page_list_wired)
8118 {
8119 	addr64_t        saddr_aligned;
8120 	addr64_t        eaddr_aligned;
8121 	addr64_t        addr;
8122 	ppnum_t         paddr;
8123 	unsigned int    mark_as_unneeded_pages = 0;
8124 
8125 	saddr_aligned = (saddr + PAGE_MASK_64) & ~PAGE_MASK_64;
8126 	eaddr_aligned = eaddr & ~PAGE_MASK_64;
8127 
8128 	for (addr = saddr_aligned; addr < eaddr_aligned; addr += PAGE_SIZE_64) {
8129 		paddr = pmap_find_phys(kernel_pmap, addr);
8130 
8131 		assert(paddr);
8132 
8133 		hibernate_page_bitset(page_list, TRUE, paddr);
8134 		hibernate_page_bitset(page_list_wired, TRUE, paddr);
8135 
8136 		mark_as_unneeded_pages++;
8137 	}
8138 	return mark_as_unneeded_pages;
8139 }
8140 
8141 
8142 void
hibernate_hash_insert_page(vm_page_t mem)8143 hibernate_hash_insert_page(vm_page_t mem)
8144 {
8145 	vm_page_bucket_t *bucket;
8146 	int             hash_id;
8147 	vm_object_t     m_object;
8148 
8149 	m_object = VM_PAGE_OBJECT(mem);
8150 
8151 	assert(mem->vmp_hashed);
8152 	assert(m_object);
8153 	assert(mem->vmp_offset != (vm_object_offset_t) -1);
8154 
8155 	/*
8156 	 *	Insert it into the object_object/offset hash table
8157 	 */
8158 	hash_id = vm_page_hash(m_object, mem->vmp_offset);
8159 	bucket = &vm_page_buckets[hash_id];
8160 
8161 	mem->vmp_next_m = bucket->page_list;
8162 	bucket->page_list = VM_PAGE_PACK_PTR(mem);
8163 }
8164 
8165 
8166 void
hibernate_free_range(int sindx,int eindx)8167 hibernate_free_range(int sindx, int eindx)
8168 {
8169 	vm_page_t       mem;
8170 	unsigned int    color;
8171 
8172 	while (sindx < eindx) {
8173 		mem = &vm_pages[sindx];
8174 
8175 		vm_page_init(mem, hibernate_lookup_paddr(sindx), FALSE);
8176 
8177 		mem->vmp_lopage = FALSE;
8178 		mem->vmp_q_state = VM_PAGE_ON_FREE_Q;
8179 
8180 		color = VM_PAGE_GET_COLOR(mem);
8181 #if defined(__x86_64__)
8182 		vm_page_queue_enter_clump(&vm_page_queue_free[color].qhead, mem);
8183 #else
8184 		vm_page_queue_enter(&vm_page_queue_free[color].qhead, mem, vmp_pageq);
8185 #endif
8186 		vm_page_free_count++;
8187 
8188 		sindx++;
8189 	}
8190 }
8191 
8192 void
hibernate_rebuild_vm_structs(void)8193 hibernate_rebuild_vm_structs(void)
8194 {
8195 	int             i, cindx, sindx, eindx;
8196 	vm_page_t       mem, tmem, mem_next;
8197 	AbsoluteTime    startTime, endTime;
8198 	uint64_t        nsec;
8199 
8200 	if (hibernate_rebuild_needed == FALSE) {
8201 		return;
8202 	}
8203 
8204 	KDBG(IOKDBG_CODE(DBG_HIBERNATE, 13) | DBG_FUNC_START);
8205 	HIBLOG("hibernate_rebuild started\n");
8206 
8207 	clock_get_uptime(&startTime);
8208 
8209 	pal_hib_rebuild_pmap_structs();
8210 
8211 	bzero(&vm_page_buckets[0], vm_page_bucket_count * sizeof(vm_page_bucket_t));
8212 	eindx = vm_pages_count;
8213 
8214 	/*
8215 	 * Mark all the vm_pages[] that have not been initialized yet as being
8216 	 * transient. This is needed to ensure that buddy page search is corrrect.
8217 	 * Without this random data in these vm_pages[] can trip the buddy search
8218 	 */
8219 	for (i = hibernate_teardown_last_valid_compact_indx + 1; i < eindx; ++i) {
8220 		vm_pages[i].vmp_q_state = VM_PAGE_NOT_ON_Q;
8221 	}
8222 
8223 	for (cindx = hibernate_teardown_last_valid_compact_indx; cindx >= 0; cindx--) {
8224 		mem = &vm_pages[cindx];
8225 		assert(mem->vmp_q_state != VM_PAGE_ON_FREE_Q);
8226 		/*
8227 		 * hibernate_teardown_vm_structs leaves the location where
8228 		 * this vm_page_t must be located in "next".
8229 		 */
8230 		tmem = (vm_page_t)(VM_PAGE_UNPACK_PTR(mem->vmp_next_m));
8231 		mem->vmp_next_m = VM_PAGE_PACK_PTR(NULL);
8232 
8233 		sindx = (int)(tmem - &vm_pages[0]);
8234 
8235 		if (mem != tmem) {
8236 			/*
8237 			 * this vm_page_t was moved by hibernate_teardown_vm_structs,
8238 			 * so move it back to its real location
8239 			 */
8240 			*tmem = *mem;
8241 			mem = tmem;
8242 		}
8243 		if (mem->vmp_hashed) {
8244 			hibernate_hash_insert_page(mem);
8245 		}
8246 		/*
8247 		 * the 'hole' between this vm_page_t and the previous
8248 		 * vm_page_t we moved needs to be initialized as
8249 		 * a range of free vm_page_t's
8250 		 */
8251 		hibernate_free_range(sindx + 1, eindx);
8252 
8253 		eindx = sindx;
8254 	}
8255 	if (sindx) {
8256 		hibernate_free_range(0, sindx);
8257 	}
8258 
8259 	assert(vm_page_free_count == hibernate_teardown_vm_page_free_count);
8260 
8261 	/*
8262 	 * process the list of vm_page_t's that were entered in the hash,
8263 	 * but were not located in the vm_pages arrary... these are
8264 	 * vm_page_t's that were created on the fly (i.e. fictitious)
8265 	 */
8266 	for (mem = hibernate_rebuild_hash_list; mem; mem = mem_next) {
8267 		mem_next = (vm_page_t)(VM_PAGE_UNPACK_PTR(mem->vmp_next_m));
8268 
8269 		mem->vmp_next_m = 0;
8270 		hibernate_hash_insert_page(mem);
8271 	}
8272 	hibernate_rebuild_hash_list = NULL;
8273 
8274 	clock_get_uptime(&endTime);
8275 	SUB_ABSOLUTETIME(&endTime, &startTime);
8276 	absolutetime_to_nanoseconds(endTime, &nsec);
8277 
8278 	HIBLOG("hibernate_rebuild completed - took %qd msecs\n", nsec / 1000000ULL);
8279 
8280 	hibernate_rebuild_needed = FALSE;
8281 
8282 	KDBG(IOKDBG_CODE(DBG_HIBERNATE, 13) | DBG_FUNC_END);
8283 }
8284 
8285 uint32_t
hibernate_teardown_vm_structs(hibernate_page_list_t * page_list,hibernate_page_list_t * page_list_wired)8286 hibernate_teardown_vm_structs(hibernate_page_list_t *page_list, hibernate_page_list_t *page_list_wired)
8287 {
8288 	unsigned int    i;
8289 	unsigned int    compact_target_indx;
8290 	vm_page_t       mem, mem_next;
8291 	vm_page_bucket_t *bucket;
8292 	unsigned int    mark_as_unneeded_pages = 0;
8293 	unsigned int    unneeded_vm_page_bucket_pages = 0;
8294 	unsigned int    unneeded_vm_pages_pages = 0;
8295 	unsigned int    unneeded_pmap_pages = 0;
8296 	addr64_t        start_of_unneeded = 0;
8297 	addr64_t        end_of_unneeded = 0;
8298 
8299 
8300 	if (hibernate_should_abort()) {
8301 		return 0;
8302 	}
8303 
8304 	hibernate_rebuild_needed = TRUE;
8305 
8306 	HIBLOG("hibernate_teardown: wired_pages %d, free_pages %d, active_pages %d, inactive_pages %d, speculative_pages %d, cleaned_pages %d, compressor_pages %d\n",
8307 	    vm_page_wire_count, vm_page_free_count, vm_page_active_count, vm_page_inactive_count, vm_page_speculative_count,
8308 	    vm_page_cleaned_count, compressor_object->resident_page_count);
8309 
8310 	for (i = 0; i < vm_page_bucket_count; i++) {
8311 		bucket = &vm_page_buckets[i];
8312 
8313 		for (mem = (vm_page_t)(VM_PAGE_UNPACK_PTR(bucket->page_list)); mem != VM_PAGE_NULL; mem = mem_next) {
8314 			assert(mem->vmp_hashed);
8315 
8316 			mem_next = (vm_page_t)(VM_PAGE_UNPACK_PTR(mem->vmp_next_m));
8317 
8318 			if (mem < &vm_pages[0] || mem >= &vm_pages[vm_pages_count]) {
8319 				mem->vmp_next_m = VM_PAGE_PACK_PTR(hibernate_rebuild_hash_list);
8320 				hibernate_rebuild_hash_list = mem;
8321 			}
8322 		}
8323 	}
8324 	unneeded_vm_page_bucket_pages = hibernate_mark_as_unneeded((addr64_t)&vm_page_buckets[0], (addr64_t)&vm_page_buckets[vm_page_bucket_count], page_list, page_list_wired);
8325 	mark_as_unneeded_pages += unneeded_vm_page_bucket_pages;
8326 
8327 	hibernate_teardown_vm_page_free_count = vm_page_free_count;
8328 
8329 	compact_target_indx = 0;
8330 
8331 	for (i = 0; i < vm_pages_count; i++) {
8332 		mem = &vm_pages[i];
8333 
8334 		if (mem->vmp_q_state == VM_PAGE_ON_FREE_Q) {
8335 			unsigned int color;
8336 
8337 			assert(mem->vmp_busy);
8338 			assert(!mem->vmp_lopage);
8339 
8340 			color = VM_PAGE_GET_COLOR(mem);
8341 
8342 			vm_page_queue_remove(&vm_page_queue_free[color].qhead, mem, vmp_pageq);
8343 
8344 			VM_PAGE_ZERO_PAGEQ_ENTRY(mem);
8345 
8346 			vm_page_free_count--;
8347 
8348 			hibernate_teardown_found_free_pages++;
8349 
8350 			if (vm_pages[compact_target_indx].vmp_q_state != VM_PAGE_ON_FREE_Q) {
8351 				compact_target_indx = i;
8352 			}
8353 		} else {
8354 			/*
8355 			 * record this vm_page_t's original location
8356 			 * we need this even if it doesn't get moved
8357 			 * as an indicator to the rebuild function that
8358 			 * we don't have to move it
8359 			 */
8360 			mem->vmp_next_m = VM_PAGE_PACK_PTR(mem);
8361 
8362 			if (vm_pages[compact_target_indx].vmp_q_state == VM_PAGE_ON_FREE_Q) {
8363 				/*
8364 				 * we've got a hole to fill, so
8365 				 * move this vm_page_t to it's new home
8366 				 */
8367 				vm_pages[compact_target_indx] = *mem;
8368 				mem->vmp_q_state = VM_PAGE_ON_FREE_Q;
8369 
8370 				hibernate_teardown_last_valid_compact_indx = compact_target_indx;
8371 				compact_target_indx++;
8372 			} else {
8373 				hibernate_teardown_last_valid_compact_indx = i;
8374 			}
8375 		}
8376 	}
8377 	unneeded_vm_pages_pages = hibernate_mark_as_unneeded((addr64_t)&vm_pages[hibernate_teardown_last_valid_compact_indx + 1],
8378 	    (addr64_t)&vm_pages[vm_pages_count - 1], page_list, page_list_wired);
8379 	mark_as_unneeded_pages += unneeded_vm_pages_pages;
8380 
8381 	pal_hib_teardown_pmap_structs(&start_of_unneeded, &end_of_unneeded);
8382 
8383 	if (start_of_unneeded) {
8384 		unneeded_pmap_pages = hibernate_mark_as_unneeded(start_of_unneeded, end_of_unneeded, page_list, page_list_wired);
8385 		mark_as_unneeded_pages += unneeded_pmap_pages;
8386 	}
8387 	HIBLOG("hibernate_teardown: mark_as_unneeded_pages %d, %d, %d\n", unneeded_vm_page_bucket_pages, unneeded_vm_pages_pages, unneeded_pmap_pages);
8388 
8389 	return mark_as_unneeded_pages;
8390 }
8391 
8392 
8393 #endif /* HIBERNATION */
8394 
8395 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
8396 
8397 #include <mach_vm_debug.h>
8398 #if     MACH_VM_DEBUG
8399 
8400 #include <mach_debug/hash_info.h>
8401 #include <vm/vm_debug.h>
8402 
8403 /*
8404  *	Routine:	vm_page_info
8405  *	Purpose:
8406  *		Return information about the global VP table.
8407  *		Fills the buffer with as much information as possible
8408  *		and returns the desired size of the buffer.
8409  *	Conditions:
8410  *		Nothing locked.  The caller should provide
8411  *		possibly-pageable memory.
8412  */
8413 
8414 unsigned int
vm_page_info(hash_info_bucket_t * info,unsigned int count)8415 vm_page_info(
8416 	hash_info_bucket_t *info,
8417 	unsigned int count)
8418 {
8419 	unsigned int i;
8420 	lck_spin_t      *bucket_lock;
8421 
8422 	if (vm_page_bucket_count < count) {
8423 		count = vm_page_bucket_count;
8424 	}
8425 
8426 	for (i = 0; i < count; i++) {
8427 		vm_page_bucket_t *bucket = &vm_page_buckets[i];
8428 		unsigned int bucket_count = 0;
8429 		vm_page_t m;
8430 
8431 		bucket_lock = &vm_page_bucket_locks[i / BUCKETS_PER_LOCK];
8432 		lck_spin_lock_grp(bucket_lock, &vm_page_lck_grp_bucket);
8433 
8434 		for (m = (vm_page_t)(VM_PAGE_UNPACK_PTR(bucket->page_list));
8435 		    m != VM_PAGE_NULL;
8436 		    m = (vm_page_t)(VM_PAGE_UNPACK_PTR(m->vmp_next_m))) {
8437 			bucket_count++;
8438 		}
8439 
8440 		lck_spin_unlock(bucket_lock);
8441 
8442 		/* don't touch pageable memory while holding locks */
8443 		info[i].hib_count = bucket_count;
8444 	}
8445 
8446 	return vm_page_bucket_count;
8447 }
8448 #endif  /* MACH_VM_DEBUG */
8449 
8450 #if VM_PAGE_BUCKETS_CHECK
8451 void
vm_page_buckets_check(void)8452 vm_page_buckets_check(void)
8453 {
8454 	unsigned int i;
8455 	vm_page_t p;
8456 	unsigned int p_hash;
8457 	vm_page_bucket_t *bucket;
8458 	lck_spin_t      *bucket_lock;
8459 
8460 	if (!vm_page_buckets_check_ready) {
8461 		return;
8462 	}
8463 
8464 #if HIBERNATION
8465 	if (hibernate_rebuild_needed ||
8466 	    hibernate_rebuild_hash_list) {
8467 		panic("BUCKET_CHECK: hibernation in progress: "
8468 		    "rebuild_needed=%d rebuild_hash_list=%p\n",
8469 		    hibernate_rebuild_needed,
8470 		    hibernate_rebuild_hash_list);
8471 	}
8472 #endif /* HIBERNATION */
8473 
8474 #if VM_PAGE_FAKE_BUCKETS
8475 	char *cp;
8476 	for (cp = (char *) vm_page_fake_buckets_start;
8477 	    cp < (char *) vm_page_fake_buckets_end;
8478 	    cp++) {
8479 		if (*cp != 0x5a) {
8480 			panic("BUCKET_CHECK: corruption at %p in fake buckets "
8481 			    "[0x%llx:0x%llx]\n",
8482 			    cp,
8483 			    (uint64_t) vm_page_fake_buckets_start,
8484 			    (uint64_t) vm_page_fake_buckets_end);
8485 		}
8486 	}
8487 #endif /* VM_PAGE_FAKE_BUCKETS */
8488 
8489 	for (i = 0; i < vm_page_bucket_count; i++) {
8490 		vm_object_t     p_object;
8491 
8492 		bucket = &vm_page_buckets[i];
8493 		if (!bucket->page_list) {
8494 			continue;
8495 		}
8496 
8497 		bucket_lock = &vm_page_bucket_locks[i / BUCKETS_PER_LOCK];
8498 		lck_spin_lock_grp(bucket_lock, &vm_page_lck_grp_bucket);
8499 		p = (vm_page_t)(VM_PAGE_UNPACK_PTR(bucket->page_list));
8500 
8501 		while (p != VM_PAGE_NULL) {
8502 			p_object = VM_PAGE_OBJECT(p);
8503 
8504 			if (!p->vmp_hashed) {
8505 				panic("BUCKET_CHECK: page %p (%p,0x%llx) "
8506 				    "hash %d in bucket %d at %p "
8507 				    "is not hashed\n",
8508 				    p, p_object, p->vmp_offset,
8509 				    p_hash, i, bucket);
8510 			}
8511 			p_hash = vm_page_hash(p_object, p->vmp_offset);
8512 			if (p_hash != i) {
8513 				panic("BUCKET_CHECK: corruption in bucket %d "
8514 				    "at %p: page %p object %p offset 0x%llx "
8515 				    "hash %d\n",
8516 				    i, bucket, p, p_object, p->vmp_offset,
8517 				    p_hash);
8518 			}
8519 			p = (vm_page_t)(VM_PAGE_UNPACK_PTR(p->vmp_next_m));
8520 		}
8521 		lck_spin_unlock(bucket_lock);
8522 	}
8523 
8524 //	printf("BUCKET_CHECK: checked buckets\n");
8525 }
8526 #endif /* VM_PAGE_BUCKETS_CHECK */
8527 
8528 /*
8529  * 'vm_fault_enter' will place newly created pages (zero-fill and COW) onto the
8530  * local queues if they exist... its the only spot in the system where we add pages
8531  * to those queues...  once on those queues, those pages can only move to one of the
8532  * global page queues or the free queues... they NEVER move from local q to local q.
8533  * the 'local' state is stable when vm_page_queues_remove is called since we're behind
8534  * the global vm_page_queue_lock at this point...  we still need to take the local lock
8535  * in case this operation is being run on a different CPU then the local queue's identity,
8536  * but we don't have to worry about the page moving to a global queue or becoming wired
8537  * while we're grabbing the local lock since those operations would require the global
8538  * vm_page_queue_lock to be held, and we already own it.
8539  *
8540  * this is why its safe to utilze the wire_count field in the vm_page_t as the local_id...
8541  * 'wired' and local are ALWAYS mutually exclusive conditions.
8542  */
8543 
8544 #if CONFIG_BACKGROUND_QUEUE
8545 void
vm_page_queues_remove(vm_page_t mem,boolean_t remove_from_backgroundq)8546 vm_page_queues_remove(vm_page_t mem, boolean_t remove_from_backgroundq)
8547 #else
8548 void
8549 vm_page_queues_remove(vm_page_t mem, boolean_t __unused remove_from_backgroundq)
8550 #endif
8551 {
8552 	boolean_t       was_pageable = TRUE;
8553 	vm_object_t     m_object;
8554 
8555 	m_object = VM_PAGE_OBJECT(mem);
8556 
8557 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
8558 
8559 	if (mem->vmp_q_state == VM_PAGE_NOT_ON_Q) {
8560 		assert(mem->vmp_pageq.next == 0 && mem->vmp_pageq.prev == 0);
8561 #if CONFIG_BACKGROUND_QUEUE
8562 		if (remove_from_backgroundq == TRUE) {
8563 			vm_page_remove_from_backgroundq(mem);
8564 		}
8565 		if (mem->vmp_on_backgroundq) {
8566 			assert(mem->vmp_backgroundq.next != 0);
8567 			assert(mem->vmp_backgroundq.prev != 0);
8568 		} else {
8569 			assert(mem->vmp_backgroundq.next == 0);
8570 			assert(mem->vmp_backgroundq.prev == 0);
8571 		}
8572 #endif /* CONFIG_BACKGROUND_QUEUE */
8573 		return;
8574 	}
8575 
8576 	if (mem->vmp_q_state == VM_PAGE_USED_BY_COMPRESSOR) {
8577 		assert(mem->vmp_pageq.next == 0 && mem->vmp_pageq.prev == 0);
8578 #if CONFIG_BACKGROUND_QUEUE
8579 		assert(mem->vmp_backgroundq.next == 0 &&
8580 		    mem->vmp_backgroundq.prev == 0 &&
8581 		    mem->vmp_on_backgroundq == FALSE);
8582 #endif
8583 		return;
8584 	}
8585 	if (mem->vmp_q_state == VM_PAGE_IS_WIRED) {
8586 		/*
8587 		 * might put these guys on a list for debugging purposes
8588 		 * if we do, we'll need to remove this assert
8589 		 */
8590 		assert(mem->vmp_pageq.next == 0 && mem->vmp_pageq.prev == 0);
8591 #if CONFIG_BACKGROUND_QUEUE
8592 		assert(mem->vmp_backgroundq.next == 0 &&
8593 		    mem->vmp_backgroundq.prev == 0 &&
8594 		    mem->vmp_on_backgroundq == FALSE);
8595 #endif
8596 		return;
8597 	}
8598 
8599 	assert(m_object != compressor_object);
8600 	assert(m_object != kernel_object);
8601 	assert(m_object != vm_submap_object);
8602 	assert(!mem->vmp_fictitious);
8603 
8604 	switch (mem->vmp_q_state) {
8605 	case VM_PAGE_ON_ACTIVE_LOCAL_Q:
8606 	{
8607 		struct vpl      *lq;
8608 
8609 		lq = zpercpu_get_cpu(vm_page_local_q, mem->vmp_local_id);
8610 		VPL_LOCK(&lq->vpl_lock);
8611 		vm_page_queue_remove(&lq->vpl_queue, mem, vmp_pageq);
8612 		mem->vmp_local_id = 0;
8613 		lq->vpl_count--;
8614 		if (m_object->internal) {
8615 			lq->vpl_internal_count--;
8616 		} else {
8617 			lq->vpl_external_count--;
8618 		}
8619 		VPL_UNLOCK(&lq->vpl_lock);
8620 		was_pageable = FALSE;
8621 		break;
8622 	}
8623 	case VM_PAGE_ON_ACTIVE_Q:
8624 	{
8625 		vm_page_queue_remove(&vm_page_queue_active, mem, vmp_pageq);
8626 		vm_page_active_count--;
8627 		break;
8628 	}
8629 
8630 	case VM_PAGE_ON_INACTIVE_INTERNAL_Q:
8631 	{
8632 		assert(m_object->internal == TRUE);
8633 
8634 		vm_page_inactive_count--;
8635 		vm_page_queue_remove(&vm_page_queue_anonymous, mem, vmp_pageq);
8636 		vm_page_anonymous_count--;
8637 
8638 		vm_purgeable_q_advance_all();
8639 		vm_page_balance_inactive(3);
8640 		break;
8641 	}
8642 
8643 	case VM_PAGE_ON_INACTIVE_EXTERNAL_Q:
8644 	{
8645 		assert(m_object->internal == FALSE);
8646 
8647 		vm_page_inactive_count--;
8648 		vm_page_queue_remove(&vm_page_queue_inactive, mem, vmp_pageq);
8649 		vm_purgeable_q_advance_all();
8650 		vm_page_balance_inactive(3);
8651 		break;
8652 	}
8653 
8654 	case VM_PAGE_ON_INACTIVE_CLEANED_Q:
8655 	{
8656 		assert(m_object->internal == FALSE);
8657 
8658 		vm_page_inactive_count--;
8659 		vm_page_queue_remove(&vm_page_queue_cleaned, mem, vmp_pageq);
8660 		vm_page_cleaned_count--;
8661 		vm_page_balance_inactive(3);
8662 		break;
8663 	}
8664 
8665 	case VM_PAGE_ON_THROTTLED_Q:
8666 	{
8667 		assert(m_object->internal == TRUE);
8668 
8669 		vm_page_queue_remove(&vm_page_queue_throttled, mem, vmp_pageq);
8670 		vm_page_throttled_count--;
8671 		was_pageable = FALSE;
8672 		break;
8673 	}
8674 
8675 	case VM_PAGE_ON_SPECULATIVE_Q:
8676 	{
8677 		assert(m_object->internal == FALSE);
8678 
8679 		vm_page_remque(&mem->vmp_pageq);
8680 		vm_page_speculative_count--;
8681 		vm_page_balance_inactive(3);
8682 		break;
8683 	}
8684 
8685 #if CONFIG_SECLUDED_MEMORY
8686 	case VM_PAGE_ON_SECLUDED_Q:
8687 	{
8688 		vm_page_queue_remove(&vm_page_queue_secluded, mem, vmp_pageq);
8689 		vm_page_secluded_count--;
8690 		VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE();
8691 		if (m_object == VM_OBJECT_NULL) {
8692 			vm_page_secluded_count_free--;
8693 			was_pageable = FALSE;
8694 		} else {
8695 			assert(!m_object->internal);
8696 			vm_page_secluded_count_inuse--;
8697 			was_pageable = FALSE;
8698 //			was_pageable = TRUE;
8699 		}
8700 		break;
8701 	}
8702 #endif /* CONFIG_SECLUDED_MEMORY */
8703 
8704 	default:
8705 	{
8706 		/*
8707 		 *	if (mem->vmp_q_state == VM_PAGE_ON_PAGEOUT_Q)
8708 		 *              NOTE: vm_page_queues_remove does not deal with removing pages from the pageout queue...
8709 		 *              the caller is responsible for determing if the page is on that queue, and if so, must
8710 		 *              either first remove it (it needs both the page queues lock and the object lock to do
8711 		 *              this via vm_pageout_steal_laundry), or avoid the call to vm_page_queues_remove
8712 		 *
8713 		 *	we also don't expect to encounter VM_PAGE_ON_FREE_Q, VM_PAGE_ON_FREE_LOCAL_Q, VM_PAGE_ON_FREE_LOPAGE_Q
8714 		 *	or any of the undefined states
8715 		 */
8716 		panic("vm_page_queues_remove - bad page q_state (%p, %d)", mem, mem->vmp_q_state);
8717 		break;
8718 	}
8719 	}
8720 	VM_PAGE_ZERO_PAGEQ_ENTRY(mem);
8721 	mem->vmp_q_state = VM_PAGE_NOT_ON_Q;
8722 
8723 #if CONFIG_BACKGROUND_QUEUE
8724 	if (remove_from_backgroundq == TRUE) {
8725 		vm_page_remove_from_backgroundq(mem);
8726 	}
8727 #endif
8728 	if (was_pageable) {
8729 		if (m_object->internal) {
8730 			vm_page_pageable_internal_count--;
8731 		} else {
8732 			vm_page_pageable_external_count--;
8733 		}
8734 	}
8735 }
8736 
8737 void
vm_page_remove_internal(vm_page_t page)8738 vm_page_remove_internal(vm_page_t page)
8739 {
8740 	vm_object_t __object = VM_PAGE_OBJECT(page);
8741 	if (page == __object->memq_hint) {
8742 		vm_page_t       __new_hint;
8743 		vm_page_queue_entry_t   __qe;
8744 		__qe = (vm_page_queue_entry_t)vm_page_queue_next(&page->vmp_listq);
8745 		if (vm_page_queue_end(&__object->memq, __qe)) {
8746 			__qe = (vm_page_queue_entry_t)vm_page_queue_prev(&page->vmp_listq);
8747 			if (vm_page_queue_end(&__object->memq, __qe)) {
8748 				__qe = NULL;
8749 			}
8750 		}
8751 		__new_hint = (vm_page_t)((uintptr_t) __qe);
8752 		__object->memq_hint = __new_hint;
8753 	}
8754 	vm_page_queue_remove(&__object->memq, page, vmp_listq);
8755 #if CONFIG_SECLUDED_MEMORY
8756 	if (__object->eligible_for_secluded) {
8757 		vm_page_secluded.eligible_for_secluded--;
8758 	}
8759 #endif /* CONFIG_SECLUDED_MEMORY */
8760 }
8761 
8762 void
vm_page_enqueue_inactive(vm_page_t mem,boolean_t first)8763 vm_page_enqueue_inactive(vm_page_t mem, boolean_t first)
8764 {
8765 	vm_object_t     m_object;
8766 
8767 	m_object = VM_PAGE_OBJECT(mem);
8768 
8769 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
8770 	assert(!mem->vmp_fictitious);
8771 	assert(!mem->vmp_laundry);
8772 	assert(mem->vmp_q_state == VM_PAGE_NOT_ON_Q);
8773 	vm_page_check_pageable_safe(mem);
8774 
8775 	if (m_object->internal) {
8776 		mem->vmp_q_state = VM_PAGE_ON_INACTIVE_INTERNAL_Q;
8777 
8778 		if (first == TRUE) {
8779 			vm_page_queue_enter_first(&vm_page_queue_anonymous, mem, vmp_pageq);
8780 		} else {
8781 			vm_page_queue_enter(&vm_page_queue_anonymous, mem, vmp_pageq);
8782 		}
8783 
8784 		vm_page_anonymous_count++;
8785 		vm_page_pageable_internal_count++;
8786 	} else {
8787 		mem->vmp_q_state = VM_PAGE_ON_INACTIVE_EXTERNAL_Q;
8788 
8789 		if (first == TRUE) {
8790 			vm_page_queue_enter_first(&vm_page_queue_inactive, mem, vmp_pageq);
8791 		} else {
8792 			vm_page_queue_enter(&vm_page_queue_inactive, mem, vmp_pageq);
8793 		}
8794 
8795 		vm_page_pageable_external_count++;
8796 	}
8797 	vm_page_inactive_count++;
8798 	token_new_pagecount++;
8799 
8800 #if CONFIG_BACKGROUND_QUEUE
8801 	if (mem->vmp_in_background) {
8802 		vm_page_add_to_backgroundq(mem, FALSE);
8803 	}
8804 #endif
8805 }
8806 
8807 void
vm_page_enqueue_active(vm_page_t mem,boolean_t first)8808 vm_page_enqueue_active(vm_page_t mem, boolean_t first)
8809 {
8810 	vm_object_t     m_object;
8811 
8812 	m_object = VM_PAGE_OBJECT(mem);
8813 
8814 	LCK_MTX_ASSERT(&vm_page_queue_lock, LCK_MTX_ASSERT_OWNED);
8815 	assert(!mem->vmp_fictitious);
8816 	assert(!mem->vmp_laundry);
8817 	assert(mem->vmp_q_state == VM_PAGE_NOT_ON_Q);
8818 	vm_page_check_pageable_safe(mem);
8819 
8820 	mem->vmp_q_state = VM_PAGE_ON_ACTIVE_Q;
8821 	if (first == TRUE) {
8822 		vm_page_queue_enter_first(&vm_page_queue_active, mem, vmp_pageq);
8823 	} else {
8824 		vm_page_queue_enter(&vm_page_queue_active, mem, vmp_pageq);
8825 	}
8826 	vm_page_active_count++;
8827 
8828 	if (m_object->internal) {
8829 		vm_page_pageable_internal_count++;
8830 	} else {
8831 		vm_page_pageable_external_count++;
8832 	}
8833 
8834 #if CONFIG_BACKGROUND_QUEUE
8835 	if (mem->vmp_in_background) {
8836 		vm_page_add_to_backgroundq(mem, FALSE);
8837 	}
8838 #endif
8839 	vm_page_balance_inactive(3);
8840 }
8841 
8842 /*
8843  * Pages from special kernel objects shouldn't
8844  * be placed on pageable queues.
8845  */
8846 void
vm_page_check_pageable_safe(vm_page_t page)8847 vm_page_check_pageable_safe(vm_page_t page)
8848 {
8849 	vm_object_t     page_object;
8850 
8851 	page_object = VM_PAGE_OBJECT(page);
8852 
8853 	if (page_object == kernel_object) {
8854 		panic("vm_page_check_pageable_safe: trying to add page" \
8855 		    "from kernel object (%p) to pageable queue", kernel_object);
8856 	}
8857 
8858 	if (page_object == compressor_object) {
8859 		panic("vm_page_check_pageable_safe: trying to add page" \
8860 		    "from compressor object (%p) to pageable queue", compressor_object);
8861 	}
8862 
8863 	if (page_object == vm_submap_object) {
8864 		panic("vm_page_check_pageable_safe: trying to add page" \
8865 		    "from submap object (%p) to pageable queue", vm_submap_object);
8866 	}
8867 }
8868 
8869 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
8870 * wired page diagnose
8871 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
8872 
8873 #include <libkern/OSKextLibPrivate.h>
8874 
8875 #define KA_SIZE(namelen, subtotalscount)        \
8876 	(sizeof(struct vm_allocation_site) + (namelen) + 1 + ((subtotalscount) * sizeof(struct vm_allocation_total)))
8877 
8878 #define KA_NAME(alloc)  \
8879 	((char *)(&(alloc)->subtotals[(alloc->subtotalscount)]))
8880 
8881 #define KA_NAME_LEN(alloc)      \
8882     (VM_TAG_NAME_LEN_MAX & (alloc->flags >> VM_TAG_NAME_LEN_SHIFT))
8883 
8884 vm_tag_t
vm_tag_bt(void)8885 vm_tag_bt(void)
8886 {
8887 	uintptr_t* frameptr;
8888 	uintptr_t* frameptr_next;
8889 	uintptr_t retaddr;
8890 	uintptr_t kstackb, kstackt;
8891 	const vm_allocation_site_t * site;
8892 	thread_t cthread;
8893 	kern_allocation_name_t name;
8894 
8895 	cthread = current_thread();
8896 	if (__improbable(cthread == NULL)) {
8897 		return VM_KERN_MEMORY_OSFMK;
8898 	}
8899 
8900 	if ((name = thread_get_kernel_state(cthread)->allocation_name)) {
8901 		if (!name->tag) {
8902 			vm_tag_alloc(name);
8903 		}
8904 		return name->tag;
8905 	}
8906 
8907 	kstackb = cthread->kernel_stack;
8908 	kstackt = kstackb + kernel_stack_size;
8909 
8910 	/* Load stack frame pointer (EBP on x86) into frameptr */
8911 	frameptr = __builtin_frame_address(0);
8912 	site = NULL;
8913 	while (frameptr != NULL) {
8914 		/* Verify thread stack bounds */
8915 		if (((uintptr_t)(frameptr + 2) > kstackt) || ((uintptr_t)frameptr < kstackb)) {
8916 			break;
8917 		}
8918 
8919 		/* Next frame pointer is pointed to by the previous one */
8920 		frameptr_next = (uintptr_t*) *frameptr;
8921 
8922 		/* Pull return address from one spot above the frame pointer */
8923 		retaddr = *(frameptr + 1);
8924 
8925 #if defined(HAS_APPLE_PAC)
8926 		retaddr = (uintptr_t) ptrauth_strip((void *)retaddr, ptrauth_key_return_address);
8927 #endif
8928 
8929 		if (((retaddr < vm_kernel_builtinkmod_text_end) && (retaddr >= vm_kernel_builtinkmod_text))
8930 		    || (retaddr < vm_kernel_stext) || (retaddr > vm_kernel_top)) {
8931 			site = OSKextGetAllocationSiteForCaller(retaddr);
8932 			break;
8933 		}
8934 		frameptr = frameptr_next;
8935 	}
8936 
8937 	return site ? site->tag : VM_KERN_MEMORY_NONE;
8938 }
8939 
8940 static uint64_t free_tag_bits[VM_MAX_TAG_VALUE / 64];
8941 
8942 void
vm_tag_alloc_locked(vm_allocation_site_t * site,vm_allocation_site_t ** releasesiteP)8943 vm_tag_alloc_locked(vm_allocation_site_t * site, vm_allocation_site_t ** releasesiteP)
8944 {
8945 	vm_tag_t tag;
8946 	uint64_t avail;
8947 	uint32_t idx;
8948 	vm_allocation_site_t * prev;
8949 
8950 	if (site->tag) {
8951 		return;
8952 	}
8953 
8954 	idx = 0;
8955 	while (TRUE) {
8956 		avail = free_tag_bits[idx];
8957 		if (avail) {
8958 			tag = (vm_tag_t)__builtin_clzll(avail);
8959 			avail &= ~(1ULL << (63 - tag));
8960 			free_tag_bits[idx] = avail;
8961 			tag += (idx << 6);
8962 			break;
8963 		}
8964 		idx++;
8965 		if (idx >= ARRAY_COUNT(free_tag_bits)) {
8966 			for (idx = 0; idx < ARRAY_COUNT(vm_allocation_sites); idx++) {
8967 				prev = vm_allocation_sites[idx];
8968 				if (!prev) {
8969 					continue;
8970 				}
8971 				if (!KA_NAME_LEN(prev)) {
8972 					continue;
8973 				}
8974 				if (!prev->tag) {
8975 					continue;
8976 				}
8977 				if (prev->total) {
8978 					continue;
8979 				}
8980 				if (1 != prev->refcount) {
8981 					continue;
8982 				}
8983 
8984 				assert(idx == prev->tag);
8985 				tag = (vm_tag_t)idx;
8986 				prev->tag = VM_KERN_MEMORY_NONE;
8987 				*releasesiteP = prev;
8988 				break;
8989 			}
8990 			if (idx >= ARRAY_COUNT(vm_allocation_sites)) {
8991 				tag = VM_KERN_MEMORY_ANY;
8992 			}
8993 			break;
8994 		}
8995 	}
8996 	site->tag = tag;
8997 
8998 	OSAddAtomic16(1, &site->refcount);
8999 
9000 	if (VM_KERN_MEMORY_ANY != tag) {
9001 		vm_allocation_sites[tag] = site;
9002 	}
9003 
9004 	if (tag > vm_allocation_tag_highest) {
9005 		vm_allocation_tag_highest = tag;
9006 	}
9007 }
9008 
9009 static void
vm_tag_free_locked(vm_tag_t tag)9010 vm_tag_free_locked(vm_tag_t tag)
9011 {
9012 	uint64_t avail;
9013 	uint32_t idx;
9014 	uint64_t bit;
9015 
9016 	if (VM_KERN_MEMORY_ANY == tag) {
9017 		return;
9018 	}
9019 
9020 	idx = (tag >> 6);
9021 	avail = free_tag_bits[idx];
9022 	tag &= 63;
9023 	bit = (1ULL << (63 - tag));
9024 	assert(!(avail & bit));
9025 	free_tag_bits[idx] = (avail | bit);
9026 }
9027 
9028 static void
vm_tag_init(void)9029 vm_tag_init(void)
9030 {
9031 	vm_tag_t tag;
9032 	for (tag = VM_KERN_MEMORY_FIRST_DYNAMIC; tag < VM_KERN_MEMORY_ANY; tag++) {
9033 		vm_tag_free_locked(tag);
9034 	}
9035 
9036 	for (tag = VM_KERN_MEMORY_ANY + 1; tag < VM_MAX_TAG_VALUE; tag++) {
9037 		vm_tag_free_locked(tag);
9038 	}
9039 }
9040 
9041 vm_tag_t
vm_tag_alloc(vm_allocation_site_t * site)9042 vm_tag_alloc(vm_allocation_site_t * site)
9043 {
9044 	vm_allocation_site_t * releasesite;
9045 
9046 	if (!site->tag) {
9047 		releasesite = NULL;
9048 		lck_spin_lock(&vm_allocation_sites_lock);
9049 		vm_tag_alloc_locked(site, &releasesite);
9050 		lck_spin_unlock(&vm_allocation_sites_lock);
9051 		if (releasesite) {
9052 			kern_allocation_name_release(releasesite);
9053 		}
9054 	}
9055 
9056 	return site->tag;
9057 }
9058 
9059 void
vm_tag_update_size(vm_tag_t tag,int64_t delta)9060 vm_tag_update_size(vm_tag_t tag, int64_t delta)
9061 {
9062 	vm_allocation_site_t * allocation;
9063 	uint64_t prior;
9064 
9065 	assert(VM_KERN_MEMORY_NONE != tag);
9066 	assert(tag < VM_MAX_TAG_VALUE);
9067 
9068 	allocation = vm_allocation_sites[tag];
9069 	assert(allocation);
9070 
9071 	if (delta < 0) {
9072 		assertf(allocation->total >= ((uint64_t)-delta), "tag %d, site %p", tag, allocation);
9073 	}
9074 	prior = OSAddAtomic64(delta, &allocation->total);
9075 
9076 #if DEBUG || DEVELOPMENT
9077 
9078 	uint64_t new, peak;
9079 	new = prior + delta;
9080 	do{
9081 		peak = allocation->peak;
9082 		if (new <= peak) {
9083 			break;
9084 		}
9085 	}while (!OSCompareAndSwap64(peak, new, &allocation->peak));
9086 
9087 #endif /* DEBUG || DEVELOPMENT */
9088 
9089 	if (tag < VM_KERN_MEMORY_FIRST_DYNAMIC) {
9090 		return;
9091 	}
9092 
9093 	if (!prior && !allocation->tag) {
9094 		vm_tag_alloc(allocation);
9095 	}
9096 }
9097 
9098 void
kern_allocation_update_size(kern_allocation_name_t allocation,int64_t delta)9099 kern_allocation_update_size(kern_allocation_name_t allocation, int64_t delta)
9100 {
9101 	uint64_t prior;
9102 
9103 	if (delta < 0) {
9104 		assertf(allocation->total >= ((uint64_t)-delta), "name %p", allocation);
9105 	}
9106 	prior = OSAddAtomic64(delta, &allocation->total);
9107 
9108 #if DEBUG || DEVELOPMENT
9109 
9110 	uint64_t new, peak;
9111 	new = prior + delta;
9112 	do{
9113 		peak = allocation->peak;
9114 		if (new <= peak) {
9115 			break;
9116 		}
9117 	}while (!OSCompareAndSwap64(peak, new, &allocation->peak));
9118 
9119 #endif /* DEBUG || DEVELOPMENT */
9120 
9121 	if (!prior && !allocation->tag) {
9122 		vm_tag_alloc(allocation);
9123 	}
9124 }
9125 
9126 #if VM_TAG_SIZECLASSES
9127 
9128 void
vm_allocation_zones_init(void)9129 vm_allocation_zones_init(void)
9130 {
9131 	kern_return_t ret;
9132 	vm_offset_t   addr;
9133 	vm_size_t     size;
9134 
9135 	const vm_tag_t early_tags[] = {
9136 		VM_KERN_MEMORY_DIAG,
9137 		VM_KERN_MEMORY_KALLOC,
9138 		VM_KERN_MEMORY_KALLOC_DATA,
9139 		VM_KERN_MEMORY_KALLOC_TYPE,
9140 		VM_KERN_MEMORY_LIBKERN,
9141 		VM_KERN_MEMORY_OSFMK,
9142 	};
9143 
9144 	size = VM_MAX_TAG_VALUE * sizeof(vm_allocation_zone_total_t * *)
9145 	    + ARRAY_COUNT(early_tags) * VM_TAG_SIZECLASSES * sizeof(vm_allocation_zone_total_t);
9146 
9147 	ret = kernel_memory_allocate(kernel_map,
9148 	    &addr, round_page(size), 0,
9149 	    KMA_ZERO, VM_KERN_MEMORY_DIAG);
9150 	assert(KERN_SUCCESS == ret);
9151 
9152 	vm_allocation_zone_totals = (vm_allocation_zone_total_t **) addr;
9153 	addr += VM_MAX_TAG_VALUE * sizeof(vm_allocation_zone_total_t * *);
9154 
9155 	// prepopulate early tag ranges so allocations
9156 	// in vm_tag_update_zone_size() and early boot won't recurse
9157 	for (size_t i = 0; i < ARRAY_COUNT(early_tags); i++) {
9158 		vm_allocation_zone_totals[early_tags[i]] = (vm_allocation_zone_total_t *)addr;
9159 		addr += VM_TAG_SIZECLASSES * sizeof(vm_allocation_zone_total_t);
9160 	}
9161 }
9162 
9163 __attribute__((noinline))
9164 static vm_tag_t
vm_tag_zone_stats_alloc(vm_tag_t tag,zalloc_flags_t flags)9165 vm_tag_zone_stats_alloc(vm_tag_t tag, zalloc_flags_t flags)
9166 {
9167 	vm_allocation_zone_total_t *stats;
9168 	vm_size_t size = sizeof(*stats) * VM_TAG_SIZECLASSES;
9169 
9170 	flags = Z_VM_TAG(Z_ZERO | flags, VM_KERN_MEMORY_DIAG);
9171 	stats = kalloc_data(size, flags);
9172 	if (!stats) {
9173 		return VM_KERN_MEMORY_NONE;
9174 	}
9175 	if (!os_atomic_cmpxchg(&vm_allocation_zone_totals[tag], NULL, stats, release)) {
9176 		kfree_data(stats, size);
9177 	}
9178 	return tag;
9179 }
9180 
9181 vm_tag_t
vm_tag_will_update_zone(vm_tag_t tag,uint32_t zidx,uint32_t zflags)9182 vm_tag_will_update_zone(vm_tag_t tag, uint32_t zidx, uint32_t zflags)
9183 {
9184 	assert(VM_KERN_MEMORY_NONE != tag);
9185 	assert(tag < VM_MAX_TAG_VALUE);
9186 
9187 	if (zidx >= VM_TAG_SIZECLASSES) {
9188 		return VM_KERN_MEMORY_NONE;
9189 	}
9190 
9191 	if (__probable(vm_allocation_zone_totals[tag])) {
9192 		return tag;
9193 	}
9194 	return vm_tag_zone_stats_alloc(tag, zflags);
9195 }
9196 
9197 void
vm_tag_update_zone_size(vm_tag_t tag,uint32_t zidx,long delta)9198 vm_tag_update_zone_size(vm_tag_t tag, uint32_t zidx, long delta)
9199 {
9200 	vm_allocation_zone_total_t *stats;
9201 	vm_size_t value;
9202 
9203 	assert(VM_KERN_MEMORY_NONE != tag);
9204 	assert(tag < VM_MAX_TAG_VALUE);
9205 
9206 	if (zidx >= VM_TAG_SIZECLASSES) {
9207 		return;
9208 	}
9209 
9210 	stats = vm_allocation_zone_totals[tag];
9211 	assert(stats);
9212 	stats += zidx;
9213 
9214 	value = os_atomic_add(&stats->vazt_total, delta, relaxed);
9215 	if (delta < 0) {
9216 		assertf((long)value >= 0, "zidx %d, tag %d, %p", zidx, tag, stats);
9217 		return;
9218 	} else if (os_atomic_load(&stats->vazt_peak, relaxed) < value) {
9219 		os_atomic_max(&stats->vazt_peak, value, relaxed);
9220 	}
9221 }
9222 
9223 #endif /* VM_TAG_SIZECLASSES */
9224 
9225 void
kern_allocation_update_subtotal(kern_allocation_name_t allocation,uint32_t subtag,int64_t delta)9226 kern_allocation_update_subtotal(kern_allocation_name_t allocation, uint32_t subtag, int64_t delta)
9227 {
9228 	kern_allocation_name_t other;
9229 	struct vm_allocation_total * total;
9230 	uint32_t subidx;
9231 
9232 	subidx = 0;
9233 	assert(VM_KERN_MEMORY_NONE != subtag);
9234 	lck_spin_lock(&vm_allocation_sites_lock);
9235 	for (; subidx < allocation->subtotalscount; subidx++) {
9236 		if (VM_KERN_MEMORY_NONE == allocation->subtotals[subidx].tag) {
9237 			allocation->subtotals[subidx].tag = (vm_tag_t)subtag;
9238 			break;
9239 		}
9240 		if (subtag == allocation->subtotals[subidx].tag) {
9241 			break;
9242 		}
9243 	}
9244 	lck_spin_unlock(&vm_allocation_sites_lock);
9245 	assert(subidx < allocation->subtotalscount);
9246 	if (subidx >= allocation->subtotalscount) {
9247 		return;
9248 	}
9249 
9250 	total = &allocation->subtotals[subidx];
9251 	other = vm_allocation_sites[subtag];
9252 	assert(other);
9253 
9254 	if (delta < 0) {
9255 		assertf(total->total >= ((uint64_t)-delta), "name %p", allocation);
9256 		assertf(other->mapped >= ((uint64_t)-delta), "other %p", other);
9257 	}
9258 	OSAddAtomic64(delta, &other->mapped);
9259 	OSAddAtomic64(delta, &total->total);
9260 }
9261 
9262 const char *
kern_allocation_get_name(kern_allocation_name_t allocation)9263 kern_allocation_get_name(kern_allocation_name_t allocation)
9264 {
9265 	return KA_NAME(allocation);
9266 }
9267 
9268 kern_allocation_name_t
kern_allocation_name_allocate(const char * name,uint16_t subtotalscount)9269 kern_allocation_name_allocate(const char * name, uint16_t subtotalscount)
9270 {
9271 	kern_allocation_name_t allocation;
9272 	uint16_t namelen;
9273 
9274 	namelen = (uint16_t)strnlen(name, MACH_MEMORY_INFO_NAME_MAX_LEN - 1);
9275 
9276 	allocation = kalloc_data(KA_SIZE(namelen, subtotalscount), Z_WAITOK | Z_ZERO);
9277 	allocation->refcount       = 1;
9278 	allocation->subtotalscount = subtotalscount;
9279 	allocation->flags          = (uint16_t)(namelen << VM_TAG_NAME_LEN_SHIFT);
9280 	strlcpy(KA_NAME(allocation), name, namelen + 1);
9281 
9282 	return allocation;
9283 }
9284 
9285 void
kern_allocation_name_release(kern_allocation_name_t allocation)9286 kern_allocation_name_release(kern_allocation_name_t allocation)
9287 {
9288 	assert(allocation->refcount > 0);
9289 	if (1 == OSAddAtomic16(-1, &allocation->refcount)) {
9290 		kfree_data(allocation,
9291 		    KA_SIZE(KA_NAME_LEN(allocation), allocation->subtotalscount));
9292 	}
9293 }
9294 
9295 vm_tag_t
kern_allocation_name_get_vm_tag(kern_allocation_name_t allocation)9296 kern_allocation_name_get_vm_tag(kern_allocation_name_t allocation)
9297 {
9298 	return vm_tag_alloc(allocation);
9299 }
9300 
9301 #if !VM_TAG_ACTIVE_UPDATE
9302 static void
vm_page_count_object(mach_memory_info_t * info,unsigned int __unused num_info,vm_object_t object)9303 vm_page_count_object(mach_memory_info_t * info, unsigned int __unused num_info, vm_object_t object)
9304 {
9305 	if (!object->wired_page_count) {
9306 		return;
9307 	}
9308 	if (object != kernel_object) {
9309 		assert(object->wire_tag < num_info);
9310 		info[object->wire_tag].size += ptoa_64(object->wired_page_count);
9311 	}
9312 }
9313 
9314 typedef void (*vm_page_iterate_proc)(mach_memory_info_t * info,
9315     unsigned int num_info, vm_object_t object);
9316 
9317 static void
vm_page_iterate_purgeable_objects(mach_memory_info_t * info,unsigned int num_info,vm_page_iterate_proc proc,purgeable_q_t queue,int group)9318 vm_page_iterate_purgeable_objects(mach_memory_info_t * info, unsigned int num_info,
9319     vm_page_iterate_proc proc, purgeable_q_t queue,
9320     int group)
9321 {
9322 	vm_object_t object;
9323 
9324 	for (object = (vm_object_t) queue_first(&queue->objq[group]);
9325 	    !queue_end(&queue->objq[group], (queue_entry_t) object);
9326 	    object = (vm_object_t) queue_next(&object->objq)) {
9327 		proc(info, num_info, object);
9328 	}
9329 }
9330 
9331 static void
vm_page_iterate_objects(mach_memory_info_t * info,unsigned int num_info,vm_page_iterate_proc proc)9332 vm_page_iterate_objects(mach_memory_info_t * info, unsigned int num_info,
9333     vm_page_iterate_proc proc)
9334 {
9335 	vm_object_t     object;
9336 
9337 	lck_spin_lock_grp(&vm_objects_wired_lock, &vm_page_lck_grp_bucket);
9338 	queue_iterate(&vm_objects_wired,
9339 	    object,
9340 	    vm_object_t,
9341 	    wired_objq)
9342 	{
9343 		proc(info, num_info, object);
9344 	}
9345 	lck_spin_unlock(&vm_objects_wired_lock);
9346 }
9347 #endif /* ! VM_TAG_ACTIVE_UPDATE */
9348 
9349 static uint64_t
process_account(mach_memory_info_t * info,unsigned int num_info,uint64_t zones_collectable_bytes,boolean_t iterated)9350 process_account(mach_memory_info_t * info, unsigned int num_info,
9351     uint64_t zones_collectable_bytes, boolean_t iterated)
9352 {
9353 	size_t                 namelen;
9354 	unsigned int           idx, count, nextinfo;
9355 	vm_allocation_site_t * site;
9356 	lck_spin_lock(&vm_allocation_sites_lock);
9357 
9358 	for (idx = 0; idx <= vm_allocation_tag_highest; idx++) {
9359 		site = vm_allocation_sites[idx];
9360 		if (!site) {
9361 			continue;
9362 		}
9363 		info[idx].mapped = site->mapped;
9364 		info[idx].tag    = site->tag;
9365 		if (!iterated) {
9366 			info[idx].size = site->total;
9367 #if DEBUG || DEVELOPMENT
9368 			info[idx].peak = site->peak;
9369 #endif /* DEBUG || DEVELOPMENT */
9370 		} else {
9371 			if (!site->subtotalscount && (site->total != info[idx].size)) {
9372 				printf("tag mismatch[%d] 0x%qx, iter 0x%qx\n", idx, site->total, info[idx].size);
9373 				info[idx].size = site->total;
9374 			}
9375 		}
9376 		info[idx].flags |= VM_KERN_SITE_WIRED;
9377 		if (idx < VM_KERN_MEMORY_FIRST_DYNAMIC) {
9378 			info[idx].site   = idx;
9379 			info[idx].flags |= VM_KERN_SITE_TAG;
9380 			if (VM_KERN_MEMORY_ZONE == idx) {
9381 				info[idx].flags |= VM_KERN_SITE_HIDE;
9382 				info[idx].flags &= ~VM_KERN_SITE_WIRED;
9383 				info[idx].collectable_bytes = zones_collectable_bytes;
9384 			}
9385 		} else if ((namelen = (VM_TAG_NAME_LEN_MAX & (site->flags >> VM_TAG_NAME_LEN_SHIFT)))) {
9386 			info[idx].site   = 0;
9387 			info[idx].flags |= VM_KERN_SITE_NAMED;
9388 			if (namelen > sizeof(info[idx].name)) {
9389 				namelen = sizeof(info[idx].name);
9390 			}
9391 			strncpy(&info[idx].name[0], KA_NAME(site), namelen);
9392 		} else if (VM_TAG_KMOD & site->flags) {
9393 			info[idx].site   = OSKextGetKmodIDForSite(site, NULL, 0);
9394 			info[idx].flags |= VM_KERN_SITE_KMOD;
9395 		} else {
9396 			info[idx].site   = VM_KERNEL_UNSLIDE(site);
9397 			info[idx].flags |= VM_KERN_SITE_KERNEL;
9398 		}
9399 	}
9400 
9401 	nextinfo = (vm_allocation_tag_highest + 1);
9402 	count    = nextinfo;
9403 	if (count >= num_info) {
9404 		count = num_info;
9405 	}
9406 
9407 	for (idx = 0; idx < count; idx++) {
9408 		site = vm_allocation_sites[idx];
9409 		if (!site) {
9410 			continue;
9411 		}
9412 #if VM_TAG_SIZECLASSES
9413 		vm_allocation_zone_total_t * zone;
9414 		unsigned int                 zidx;
9415 
9416 		if (vm_allocation_zone_totals
9417 		    && (zone = vm_allocation_zone_totals[idx])
9418 		    && (nextinfo < num_info)) {
9419 			for (zidx = 0; zidx < VM_TAG_SIZECLASSES; zidx++) {
9420 				if (!zone[zidx].vazt_peak) {
9421 					continue;
9422 				}
9423 				info[nextinfo]        = info[idx];
9424 				info[nextinfo].zone   = (uint16_t)zone_index_from_tag_index(zidx);
9425 				info[nextinfo].flags  &= ~VM_KERN_SITE_WIRED;
9426 				info[nextinfo].flags  |= VM_KERN_SITE_ZONE;
9427 				info[nextinfo].flags  |= VM_KERN_SITE_KALLOC;
9428 				info[nextinfo].size   = zone[zidx].vazt_total;
9429 				info[nextinfo].peak   = zone[zidx].vazt_peak;
9430 				info[nextinfo].mapped = 0;
9431 				nextinfo++;
9432 			}
9433 		}
9434 #endif /* VM_TAG_SIZECLASSES */
9435 		if (site->subtotalscount) {
9436 			uint64_t mapped, mapcost, take;
9437 			uint32_t sub;
9438 			vm_tag_t alloctag;
9439 
9440 			info[idx].size = site->total;
9441 			mapped = info[idx].size;
9442 			info[idx].mapped = mapped;
9443 			mapcost = 0;
9444 			for (sub = 0; sub < site->subtotalscount; sub++) {
9445 				alloctag = site->subtotals[sub].tag;
9446 				assert(alloctag < num_info);
9447 				if (info[alloctag].name[0]) {
9448 					continue;
9449 				}
9450 				take = site->subtotals[sub].total;
9451 				if (take > info[alloctag].size) {
9452 					take = info[alloctag].size;
9453 				}
9454 				if (take > mapped) {
9455 					take = mapped;
9456 				}
9457 				info[alloctag].mapped  -= take;
9458 				info[alloctag].size    -= take;
9459 				mapped                 -= take;
9460 				mapcost                += take;
9461 			}
9462 			info[idx].size = mapcost;
9463 		}
9464 	}
9465 	lck_spin_unlock(&vm_allocation_sites_lock);
9466 
9467 	return 0;
9468 }
9469 
9470 uint32_t
vm_page_diagnose_estimate(void)9471 vm_page_diagnose_estimate(void)
9472 {
9473 	vm_allocation_site_t * site;
9474 	uint32_t               count = zone_view_count;
9475 	uint32_t               idx;
9476 
9477 	lck_spin_lock(&vm_allocation_sites_lock);
9478 	for (idx = 0; idx < VM_MAX_TAG_VALUE; idx++) {
9479 		site = vm_allocation_sites[idx];
9480 		if (!site) {
9481 			continue;
9482 		}
9483 		count++;
9484 #if VM_TAG_SIZECLASSES
9485 		if (vm_allocation_zone_totals) {
9486 			vm_allocation_zone_total_t * zone;
9487 			zone = vm_allocation_zone_totals[idx];
9488 			if (!zone) {
9489 				continue;
9490 			}
9491 			for (uint32_t zidx = 0; zidx < VM_TAG_SIZECLASSES; zidx++) {
9492 				count += (zone[zidx].vazt_peak != 0);
9493 			}
9494 		}
9495 #endif
9496 	}
9497 	lck_spin_unlock(&vm_allocation_sites_lock);
9498 
9499 	/* some slop for new tags created */
9500 	count += 8;
9501 	count += VM_KERN_COUNTER_COUNT;
9502 
9503 	return count;
9504 }
9505 
9506 static void
vm_page_diagnose_zone_stats(mach_memory_info_t * info,zone_stats_t zstats,bool percpu)9507 vm_page_diagnose_zone_stats(mach_memory_info_t *info, zone_stats_t zstats,
9508     bool percpu)
9509 {
9510 	zpercpu_foreach(zs, zstats) {
9511 		info->size += zs->zs_mem_allocated - zs->zs_mem_freed;
9512 	}
9513 	if (percpu) {
9514 		info->size *= zpercpu_count();
9515 	}
9516 	info->flags |= VM_KERN_SITE_NAMED | VM_KERN_SITE_ZONE_VIEW;
9517 }
9518 
9519 static void
vm_page_diagnose_zone(mach_memory_info_t * info,zone_t z)9520 vm_page_diagnose_zone(mach_memory_info_t *info, zone_t z)
9521 {
9522 	vm_page_diagnose_zone_stats(info, z->z_stats, z->z_percpu);
9523 	snprintf(info->name, sizeof(info->name),
9524 	    "%s%s[raw]", zone_heap_name(z), z->z_name);
9525 }
9526 
9527 static int
vm_page_diagnose_heap(mach_memory_info_t * info,kalloc_heap_t kheap)9528 vm_page_diagnose_heap(mach_memory_info_t *info, kalloc_heap_t kheap)
9529 {
9530 	struct kheap_zones *zones = kheap->kh_zones;
9531 	int i = 0;
9532 
9533 	for (; i < zones->max_k_zone; i++) {
9534 		vm_page_diagnose_zone(info + i, zones->k_zone[i]);
9535 	}
9536 
9537 	for (kalloc_heap_t kh = zones->views; kh; kh = kh->kh_next, i++) {
9538 		vm_page_diagnose_zone_stats(info + i, kh->kh_stats, false);
9539 		snprintf(info[i].name, sizeof(info[i].name),
9540 		    "%skalloc[%s]", kheap->kh_name, kh->kh_name);
9541 	}
9542 
9543 	return i;
9544 }
9545 
9546 static int
vm_page_diagnose_kt_heaps(mach_memory_info_t * info)9547 vm_page_diagnose_kt_heaps(mach_memory_info_t *info)
9548 {
9549 	uint32_t idx = 0;
9550 	vm_page_diagnose_zone_stats(info + idx, KHEAP_KT_VAR->kh_stats, false);
9551 	snprintf(info[idx].name, sizeof(info[idx].name),
9552 	    "%s[raw]", KHEAP_KT_VAR->kh_name);
9553 	idx++;
9554 
9555 	for (uint32_t i = 0; i < KT_VAR_MAX_HEAPS; i++) {
9556 		struct kt_heap_zones heap = kalloc_type_heap_array[i];
9557 
9558 		for (kalloc_type_var_view_t ktv = heap.views; ktv;
9559 		    ktv = (kalloc_type_var_view_t) ktv->kt_next) {
9560 			if (ktv->kt_stats) {
9561 				vm_page_diagnose_zone_stats(info + idx, ktv->kt_stats, false);
9562 				snprintf(info[i].name, sizeof(info[i].name),
9563 				    "%s[%s]", KHEAP_KT_VAR->kh_name, ktv->kt_name);
9564 				idx++;
9565 			}
9566 		}
9567 	}
9568 
9569 	return idx;
9570 }
9571 
9572 kern_return_t
vm_page_diagnose(mach_memory_info_t * info,unsigned int num_info,uint64_t zones_collectable_bytes)9573 vm_page_diagnose(mach_memory_info_t * info, unsigned int num_info, uint64_t zones_collectable_bytes)
9574 {
9575 	uint64_t                 wired_size;
9576 	uint64_t                 wired_managed_size;
9577 	uint64_t                 wired_reserved_size;
9578 	boolean_t                iterate;
9579 	mach_memory_info_t     * counts;
9580 	uint32_t                 i;
9581 
9582 	bzero(info, num_info * sizeof(mach_memory_info_t));
9583 
9584 	if (!vm_page_wire_count_initial) {
9585 		return KERN_ABORTED;
9586 	}
9587 
9588 #if !XNU_TARGET_OS_OSX
9589 	wired_size          = ptoa_64(vm_page_wire_count);
9590 	wired_reserved_size = ptoa_64(vm_page_wire_count_initial - vm_page_stolen_count);
9591 #else /* !XNU_TARGET_OS_OSX */
9592 	wired_size          = ptoa_64(vm_page_wire_count + vm_lopage_free_count + vm_page_throttled_count);
9593 	wired_reserved_size = ptoa_64(vm_page_wire_count_initial - vm_page_stolen_count + vm_page_throttled_count);
9594 #endif /* !XNU_TARGET_OS_OSX */
9595 	wired_managed_size  = ptoa_64(vm_page_wire_count - vm_page_wire_count_initial);
9596 
9597 	wired_size += booter_size;
9598 
9599 	assert(num_info >= VM_KERN_COUNTER_COUNT);
9600 	num_info -= VM_KERN_COUNTER_COUNT;
9601 	counts = &info[num_info];
9602 
9603 #define SET_COUNT(xcount, xsize, xflags)                        \
9604     counts[xcount].tag   = VM_MAX_TAG_VALUE + xcount;   \
9605     counts[xcount].site  = (xcount);                            \
9606     counts[xcount].size  = (xsize);                                 \
9607     counts[xcount].mapped  = (xsize);                           \
9608     counts[xcount].flags = VM_KERN_SITE_COUNTER | xflags;
9609 
9610 	SET_COUNT(VM_KERN_COUNT_MANAGED, ptoa_64(vm_page_pages), 0);
9611 	SET_COUNT(VM_KERN_COUNT_WIRED, wired_size, 0);
9612 	SET_COUNT(VM_KERN_COUNT_WIRED_MANAGED, wired_managed_size, 0);
9613 	SET_COUNT(VM_KERN_COUNT_RESERVED, wired_reserved_size, VM_KERN_SITE_WIRED);
9614 	SET_COUNT(VM_KERN_COUNT_STOLEN, ptoa_64(vm_page_stolen_count), VM_KERN_SITE_WIRED);
9615 	SET_COUNT(VM_KERN_COUNT_LOPAGE, ptoa_64(vm_lopage_free_count), VM_KERN_SITE_WIRED);
9616 	SET_COUNT(VM_KERN_COUNT_WIRED_BOOT, ptoa_64(vm_page_wire_count_on_boot), 0);
9617 	SET_COUNT(VM_KERN_COUNT_BOOT_STOLEN, booter_size, VM_KERN_SITE_WIRED);
9618 	SET_COUNT(VM_KERN_COUNT_WIRED_STATIC_KERNELCACHE, ptoa_64(vm_page_kernelcache_count), 0);
9619 
9620 #define SET_MAP(xcount, xsize, xfree, xlargest) \
9621     counts[xcount].site    = (xcount);                  \
9622     counts[xcount].size    = (xsize);                   \
9623     counts[xcount].mapped  = (xsize);                   \
9624     counts[xcount].free    = (xfree);                   \
9625     counts[xcount].largest = (xlargest);                \
9626     counts[xcount].flags   = VM_KERN_SITE_COUNTER;
9627 
9628 	vm_map_size_t map_size, map_free, map_largest;
9629 
9630 	vm_map_sizes(kernel_map, &map_size, &map_free, &map_largest);
9631 	SET_MAP(VM_KERN_COUNT_MAP_KERNEL, map_size, map_free, map_largest);
9632 
9633 	vm_map_sizes(kalloc_large_map_get(), &map_size, &map_free, &map_largest);
9634 	SET_MAP(VM_KERN_COUNT_MAP_KALLOC_LARGE, map_size, map_free, map_largest);
9635 
9636 	vm_map_sizes(kernel_data_map_get(), &map_size, &map_free, &map_largest);
9637 	SET_MAP(VM_KERN_COUNT_MAP_KERNEL_DATA, map_size, map_free, map_largest);
9638 
9639 	vm_map_sizes(kalloc_large_data_map_get(), &map_size, &map_free, &map_largest);
9640 	SET_MAP(VM_KERN_COUNT_MAP_KALLOC_LARGE_DATA, map_size, map_free, map_largest);
9641 
9642 	zone_map_sizes(&map_size, &map_free, &map_largest);
9643 	SET_MAP(VM_KERN_COUNT_MAP_ZONE, map_size, map_free, map_largest);
9644 
9645 	assert(num_info >= zone_view_count);
9646 	num_info -= zone_view_count;
9647 	counts = &info[num_info];
9648 	i = 0;
9649 
9650 	i += vm_page_diagnose_heap(counts + i, KHEAP_DEFAULT);
9651 	if (KHEAP_DATA_BUFFERS->kh_heap_id == KHEAP_ID_DATA_BUFFERS) {
9652 		i += vm_page_diagnose_heap(counts + i, KHEAP_DATA_BUFFERS);
9653 	}
9654 	if (KHEAP_KEXT->kh_heap_id == KHEAP_ID_KEXT) {
9655 		i += vm_page_diagnose_heap(counts + i, KHEAP_KEXT);
9656 	}
9657 	if (KHEAP_KT_VAR->kh_heap_id == KHEAP_ID_KT_VAR) {
9658 		i += vm_page_diagnose_kt_heaps(counts + i);
9659 	}
9660 	assert(i <= zone_view_count);
9661 
9662 	zone_index_foreach(zidx) {
9663 		zone_t z = &zone_array[zidx];
9664 		zone_security_flags_t zsflags = zone_security_array[zidx];
9665 		zone_view_t zv = z->z_views;
9666 
9667 		if (zv == NULL) {
9668 			continue;
9669 		}
9670 
9671 		zone_stats_t zv_stats_head = z->z_stats;
9672 		bool has_raw_view = false;
9673 
9674 		for (; zv; zv = zv->zv_next) {
9675 			/*
9676 			 * kalloc_types that allocate from the same zone are linked
9677 			 * as views. Only print the ones that have their own stats.
9678 			 */
9679 			if (zv->zv_stats == zv_stats_head) {
9680 				continue;
9681 			}
9682 			has_raw_view = true;
9683 			vm_page_diagnose_zone_stats(counts + i, zv->zv_stats,
9684 			    z->z_percpu);
9685 			snprintf(counts[i].name, sizeof(counts[i].name), "%s%s[%s]",
9686 			    zone_heap_name(z), z->z_name, zv->zv_name);
9687 			i++;
9688 			assert(i <= zone_view_count);
9689 		}
9690 
9691 		/*
9692 		 * Print raw views for non kalloc or kalloc_type zones
9693 		 */
9694 		bool kalloc_type = zsflags.z_kalloc_type;
9695 		if ((zsflags.z_kheap_id == KHEAP_ID_NONE && !kalloc_type) ||
9696 		    (kalloc_type && has_raw_view)) {
9697 			vm_page_diagnose_zone(counts + i, z);
9698 			i++;
9699 			assert(i <= zone_view_count);
9700 		}
9701 	}
9702 
9703 	iterate = !VM_TAG_ACTIVE_UPDATE;
9704 	if (iterate) {
9705 		enum                       { kMaxKernelDepth = 1 };
9706 		vm_map_t                     maps[kMaxKernelDepth];
9707 		vm_map_entry_t               entries[kMaxKernelDepth];
9708 		vm_map_t                     map;
9709 		vm_map_entry_t               entry;
9710 		vm_object_offset_t           offset;
9711 		vm_page_t                    page;
9712 		int                          stackIdx, count;
9713 
9714 #if !VM_TAG_ACTIVE_UPDATE
9715 		vm_page_iterate_objects(info, num_info, &vm_page_count_object);
9716 #endif /* ! VM_TAG_ACTIVE_UPDATE */
9717 
9718 		map = kernel_map;
9719 		stackIdx = 0;
9720 		while (map) {
9721 			vm_map_lock(map);
9722 			for (entry = map->hdr.links.next; map; entry = entry->links.next) {
9723 				if (entry->is_sub_map) {
9724 					assert(stackIdx < kMaxKernelDepth);
9725 					maps[stackIdx] = map;
9726 					entries[stackIdx] = entry;
9727 					stackIdx++;
9728 					map = VME_SUBMAP(entry);
9729 					entry = NULL;
9730 					break;
9731 				}
9732 				if (VME_OBJECT(entry) == kernel_object) {
9733 					count = 0;
9734 					vm_object_lock(VME_OBJECT(entry));
9735 					for (offset = entry->links.start; offset < entry->links.end; offset += page_size) {
9736 						page = vm_page_lookup(VME_OBJECT(entry), offset);
9737 						if (page && VM_PAGE_WIRED(page)) {
9738 							count++;
9739 						}
9740 					}
9741 					vm_object_unlock(VME_OBJECT(entry));
9742 
9743 					if (count) {
9744 						assert(VME_ALIAS(entry) != VM_KERN_MEMORY_NONE);
9745 						assert(VME_ALIAS(entry) < num_info);
9746 						info[VME_ALIAS(entry)].size += ptoa_64(count);
9747 					}
9748 				}
9749 				while (map && (entry == vm_map_last_entry(map))) {
9750 					vm_map_unlock(map);
9751 					if (!stackIdx) {
9752 						map = NULL;
9753 					} else {
9754 						--stackIdx;
9755 						map = maps[stackIdx];
9756 						entry = entries[stackIdx];
9757 					}
9758 				}
9759 			}
9760 		}
9761 	}
9762 
9763 	process_account(info, num_info, zones_collectable_bytes, iterate);
9764 
9765 	return KERN_SUCCESS;
9766 }
9767 
9768 #if DEBUG || DEVELOPMENT
9769 
9770 kern_return_t
vm_kern_allocation_info(uintptr_t addr,vm_size_t * size,vm_tag_t * tag,vm_size_t * zone_size)9771 vm_kern_allocation_info(uintptr_t addr, vm_size_t * size, vm_tag_t * tag, vm_size_t * zone_size)
9772 {
9773 	kern_return_t  ret;
9774 	vm_size_t      zsize;
9775 	vm_map_t       map;
9776 	vm_map_entry_t entry;
9777 
9778 	zsize = zone_element_info((void *) addr, tag);
9779 	if (zsize) {
9780 		*zone_size = *size = zsize;
9781 		return KERN_SUCCESS;
9782 	}
9783 
9784 	*zone_size = 0;
9785 	ret = KERN_INVALID_ADDRESS;
9786 	for (map = kernel_map; map;) {
9787 		vm_map_lock(map);
9788 		if (!vm_map_lookup_entry_allow_pgz(map, addr, &entry)) {
9789 			break;
9790 		}
9791 		if (entry->is_sub_map) {
9792 			if (map != kernel_map) {
9793 				break;
9794 			}
9795 			map = VME_SUBMAP(entry);
9796 			continue;
9797 		}
9798 		if (entry->vme_start != addr) {
9799 			break;
9800 		}
9801 		*tag = (vm_tag_t)VME_ALIAS(entry);
9802 		*size = (entry->vme_end - addr);
9803 		ret = KERN_SUCCESS;
9804 		break;
9805 	}
9806 	if (map != kernel_map) {
9807 		vm_map_unlock(map);
9808 	}
9809 	vm_map_unlock(kernel_map);
9810 
9811 	return ret;
9812 }
9813 
9814 #endif /* DEBUG || DEVELOPMENT */
9815 
9816 uint32_t
vm_tag_get_kext(vm_tag_t tag,char * name,vm_size_t namelen)9817 vm_tag_get_kext(vm_tag_t tag, char * name, vm_size_t namelen)
9818 {
9819 	vm_allocation_site_t * site;
9820 	uint32_t               kmodId;
9821 
9822 	kmodId = 0;
9823 	lck_spin_lock(&vm_allocation_sites_lock);
9824 	if ((site = vm_allocation_sites[tag])) {
9825 		if (VM_TAG_KMOD & site->flags) {
9826 			kmodId = OSKextGetKmodIDForSite(site, name, namelen);
9827 		}
9828 	}
9829 	lck_spin_unlock(&vm_allocation_sites_lock);
9830 
9831 	return kmodId;
9832 }
9833 
9834 
9835 #if CONFIG_SECLUDED_MEMORY
9836 /*
9837  * Note that there's no locking around other accesses to vm_page_secluded_target.
9838  * That should be OK, since these are the only place where it can be changed after
9839  * initialization. Other users (like vm_pageout) may see the wrong value briefly,
9840  * but will eventually get the correct value. This brief mismatch is OK as pageout
9841  * and page freeing will auto-adjust the vm_page_secluded_count to match the target
9842  * over time.
9843  */
9844 unsigned int vm_page_secluded_suppress_cnt = 0;
9845 unsigned int vm_page_secluded_save_target;
9846 
9847 LCK_GRP_DECLARE(secluded_suppress_slock_grp, "secluded_suppress_slock");
9848 LCK_SPIN_DECLARE(secluded_suppress_slock, &secluded_suppress_slock_grp);
9849 
9850 void
start_secluded_suppression(task_t task)9851 start_secluded_suppression(task_t task)
9852 {
9853 	if (task->task_suppressed_secluded) {
9854 		return;
9855 	}
9856 	lck_spin_lock(&secluded_suppress_slock);
9857 	if (!task->task_suppressed_secluded && vm_page_secluded_suppress_cnt++ == 0) {
9858 		task->task_suppressed_secluded = TRUE;
9859 		vm_page_secluded_save_target = vm_page_secluded_target;
9860 		vm_page_secluded_target = 0;
9861 		VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE();
9862 	}
9863 	lck_spin_unlock(&secluded_suppress_slock);
9864 }
9865 
9866 void
stop_secluded_suppression(task_t task)9867 stop_secluded_suppression(task_t task)
9868 {
9869 	lck_spin_lock(&secluded_suppress_slock);
9870 	if (task->task_suppressed_secluded && --vm_page_secluded_suppress_cnt == 0) {
9871 		task->task_suppressed_secluded = FALSE;
9872 		vm_page_secluded_target = vm_page_secluded_save_target;
9873 		VM_PAGE_SECLUDED_COUNT_OVER_TARGET_UPDATE();
9874 	}
9875 	lck_spin_unlock(&secluded_suppress_slock);
9876 }
9877 
9878 #endif /* CONFIG_SECLUDED_MEMORY */
9879 
9880 /*
9881  * Move the list of retired pages on the vm_page_queue_retired to
9882  * their final resting place on retired_pages_object.
9883  */
9884 void
vm_retire_boot_pages(void)9885 vm_retire_boot_pages(void)
9886 {
9887 #if defined(__arm64__)
9888 	vm_page_t p;
9889 
9890 	vm_object_lock(retired_pages_object);
9891 	while (!vm_page_queue_empty(&vm_page_queue_retired)) {
9892 		vm_page_queue_remove_first(&vm_page_queue_retired, p, vmp_pageq);
9893 		assert(p != NULL);
9894 		vm_page_lock_queues();
9895 		p->vmp_q_state = VM_PAGE_IS_WIRED;
9896 		p->vmp_wire_count++;
9897 		vm_page_unlock_queues();
9898 		vm_page_insert_wired(p, retired_pages_object, ptoa(VM_PAGE_GET_PHYS_PAGE(p)), VM_KERN_MEMORY_RETIRED);
9899 		vm_object_unlock(retired_pages_object);
9900 		pmap_retire_page(VM_PAGE_GET_PHYS_PAGE(p));
9901 		vm_object_lock(retired_pages_object);
9902 	}
9903 	vm_object_unlock(retired_pages_object);
9904 #endif /* defined(__arm64__) */
9905 }
9906 
9907 /*
9908  * Returns the current number of retired pages, used for sysctl.
9909  */
9910 uint32_t
vm_retired_pages_count(void)9911 vm_retired_pages_count(void)
9912 {
9913 	return retired_pages_object->resident_page_count;
9914 }
9915 
9916