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