1 /*-
2 * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
3 *
4 * Copyright (c) 1991 Regents of the University of California.
5 * All rights reserved.
6 * Copyright (c) 1998 Matthew Dillon. All Rights Reserved.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * The Mach Operating System project at Carnegie-Mellon University.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36 /*-
37 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38 * All rights reserved.
39 *
40 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41 *
42 * Permission to use, copy, modify and distribute this software and
43 * its documentation is hereby granted, provided that both the copyright
44 * notice and this permission notice appear in all copies of the
45 * software, derivative works or modified versions, and any portions
46 * thereof, and that both notices appear in supporting documentation.
47 *
48 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51 *
52 * Carnegie Mellon requests users of this software to return to
53 *
54 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
55 * School of Computer Science
56 * Carnegie Mellon University
57 * Pittsburgh PA 15213-3890
58 *
59 * any improvements or extensions that they make and grant Carnegie the
60 * rights to redistribute these changes.
61 */
62
63 /*
64 * Resident memory management module.
65 */
66
67 #include <sys/cdefs.h>
68 #include "opt_vm.h"
69
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/counter.h>
73 #include <sys/domainset.h>
74 #include <sys/kernel.h>
75 #include <sys/limits.h>
76 #include <sys/linker.h>
77 #include <sys/lock.h>
78 #include <sys/malloc.h>
79 #include <sys/mman.h>
80 #include <sys/msgbuf.h>
81 #include <sys/mutex.h>
82 #include <sys/proc.h>
83 #include <sys/rwlock.h>
84 #include <sys/sleepqueue.h>
85 #include <sys/sbuf.h>
86 #include <sys/sched.h>
87 #include <sys/sf_buf.h>
88 #include <sys/smp.h>
89 #include <sys/sysctl.h>
90 #include <sys/vmmeter.h>
91 #include <sys/vnode.h>
92
93 #include <vm/vm.h>
94 #include <vm/pmap.h>
95 #include <vm/vm_param.h>
96 #include <vm/vm_domainset.h>
97 #include <vm/vm_kern.h>
98 #include <vm/vm_map.h>
99 #include <vm/vm_object.h>
100 #include <vm/vm_page.h>
101 #include <vm/vm_pageout.h>
102 #include <vm/vm_phys.h>
103 #include <vm/vm_pagequeue.h>
104 #include <vm/vm_pager.h>
105 #include <vm/vm_radix.h>
106 #include <vm/vm_reserv.h>
107 #include <vm/vm_extern.h>
108 #include <vm/vm_dumpset.h>
109 #include <vm/uma.h>
110 #include <vm/uma_int.h>
111
112 #include <machine/md_var.h>
113 #if defined(__aarch64__)
114 #include <machine/pmap.h>
115 #include <machine/rsi.h>
116 #endif
117
118 struct vm_domain vm_dom[MAXMEMDOM];
119
120 DPCPU_DEFINE_STATIC(struct vm_batchqueue, pqbatch[MAXMEMDOM][PQ_COUNT]);
121
122 struct mtx_padalign __exclusive_cache_line vm_domainset_lock;
123 /* The following fields are protected by the domainset lock. */
124 domainset_t __exclusive_cache_line vm_min_domains;
125 domainset_t __exclusive_cache_line vm_severe_domains;
126 static int vm_min_waiters;
127 static int vm_severe_waiters;
128 static int vm_pageproc_waiters;
129
130 static SYSCTL_NODE(_vm_stats, OID_AUTO, page, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
131 "VM page statistics");
132
133 static COUNTER_U64_DEFINE_EARLY(pqstate_commit_retries);
134 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, pqstate_commit_retries,
135 CTLFLAG_RD, &pqstate_commit_retries,
136 "Number of failed per-page atomic queue state updates");
137
138 static COUNTER_U64_DEFINE_EARLY(queue_ops);
139 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_ops,
140 CTLFLAG_RD, &queue_ops,
141 "Number of batched queue operations");
142
143 static COUNTER_U64_DEFINE_EARLY(queue_nops);
144 SYSCTL_COUNTER_U64(_vm_stats_page, OID_AUTO, queue_nops,
145 CTLFLAG_RD, &queue_nops,
146 "Number of batched queue operations with no effects");
147
148 static unsigned long nofreeq_size;
149 SYSCTL_ULONG(_vm_stats_page, OID_AUTO, nofreeq_size, CTLFLAG_RD,
150 &nofreeq_size, 0,
151 "Size of the nofree queue");
152
153 #ifdef INVARIANTS
154 bool vm_check_pg_zero = false;
155 SYSCTL_BOOL(_debug, OID_AUTO, vm_check_pg_zero, CTLFLAG_RWTUN,
156 &vm_check_pg_zero, 0,
157 "verify content of freed zero-filled pages");
158 #endif
159
160 /*
161 * bogus page -- for I/O to/from partially complete buffers,
162 * or for paging into sparsely invalid regions.
163 */
164 vm_page_t bogus_page;
165
166 vm_page_t vm_page_array;
167 long vm_page_array_size;
168 long first_page;
169
170 struct bitset *vm_page_dump;
171 long vm_page_dump_pages;
172
173 static TAILQ_HEAD(, vm_page) blacklist_head;
174 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
175 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
176 CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
177
178 static uma_zone_t fakepg_zone;
179
180 static void vm_page_alloc_check(vm_page_t m);
181 static vm_page_t vm_page_alloc_nofree_domain(int domain, int req);
182 static bool _vm_page_busy_sleep(vm_object_t obj, vm_page_t m,
183 vm_pindex_t pindex, const char *wmesg, int allocflags, bool locked);
184 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
185 static void vm_page_enqueue(vm_page_t m, uint8_t queue);
186 static bool vm_page_free_prep(vm_page_t m);
187 static void vm_page_free_toq(vm_page_t m);
188 static void vm_page_init(void *dummy);
189 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object);
190 static void vm_page_mvqueue(vm_page_t m, const uint8_t queue,
191 const uint16_t nflag);
192 static int vm_page_reclaim_run(int req_class, int domain, u_long npages,
193 vm_page_t m_run, vm_paddr_t high);
194 static void vm_page_release_toq(vm_page_t m, uint8_t nqueue, bool noreuse);
195 static int vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object,
196 int req);
197 static int vm_page_zone_import(void *arg, void **store, int cnt, int domain,
198 int flags);
199 static void vm_page_zone_release(void *arg, void **store, int cnt);
200
201 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init, NULL);
202
203 static void
vm_page_init(void * dummy)204 vm_page_init(void *dummy)
205 {
206
207 fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
208 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
209 bogus_page = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_NOFREE);
210 }
211
212 static int pgcache_zone_max_pcpu;
213 SYSCTL_INT(_vm, OID_AUTO, pgcache_zone_max_pcpu,
214 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pgcache_zone_max_pcpu, 0,
215 "Per-CPU page cache size");
216
217 /*
218 * The cache page zone is initialized later since we need to be able to allocate
219 * pages before UMA is fully initialized.
220 */
221 static void
vm_page_init_cache_zones(void * dummy __unused)222 vm_page_init_cache_zones(void *dummy __unused)
223 {
224 struct vm_domain *vmd;
225 struct vm_pgcache *pgcache;
226 int cache, domain, maxcache, pool;
227
228 TUNABLE_INT_FETCH("vm.pgcache_zone_max_pcpu", &pgcache_zone_max_pcpu);
229 maxcache = pgcache_zone_max_pcpu * mp_ncpus;
230 for (domain = 0; domain < vm_ndomains; domain++) {
231 vmd = VM_DOMAIN(domain);
232 for (pool = 0; pool < VM_NFREEPOOL; pool++) {
233 #ifdef VM_FREEPOOL_LAZYINIT
234 if (pool == VM_FREEPOOL_LAZYINIT)
235 continue;
236 #endif
237 pgcache = &vmd->vmd_pgcache[pool];
238 pgcache->domain = domain;
239 pgcache->pool = pool;
240 pgcache->zone = uma_zcache_create("vm pgcache",
241 PAGE_SIZE, NULL, NULL, NULL, NULL,
242 vm_page_zone_import, vm_page_zone_release, pgcache,
243 UMA_ZONE_VM);
244
245 /*
246 * Limit each pool's zone to 0.1% of the pages in the
247 * domain.
248 */
249 cache = maxcache != 0 ? maxcache :
250 vmd->vmd_page_count / 1000;
251 uma_zone_set_maxcache(pgcache->zone, cache);
252 }
253 }
254 }
255 SYSINIT(vm_page2, SI_SUB_VM_CONF, SI_ORDER_ANY, vm_page_init_cache_zones, NULL);
256
257 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
258 #if PAGE_SIZE == 32768
259 #ifdef CTASSERT
260 CTASSERT(sizeof(u_long) >= 8);
261 #endif
262 #endif
263
264 /*
265 * vm_set_page_size:
266 *
267 * Sets the page size, perhaps based upon the memory
268 * size. Must be called before any use of page-size
269 * dependent functions.
270 */
271 void
vm_set_page_size(void)272 vm_set_page_size(void)
273 {
274 if (vm_cnt.v_page_size == 0)
275 vm_cnt.v_page_size = PAGE_SIZE;
276 if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
277 panic("vm_set_page_size: page size not a power of two");
278 }
279
280 /*
281 * vm_page_blacklist_next:
282 *
283 * Find the next entry in the provided string of blacklist
284 * addresses. Entries are separated by space, comma, or newline.
285 * If an invalid integer is encountered then the rest of the
286 * string is skipped. Updates the list pointer to the next
287 * character, or NULL if the string is exhausted or invalid.
288 */
289 static vm_paddr_t
vm_page_blacklist_next(char ** list,char * end)290 vm_page_blacklist_next(char **list, char *end)
291 {
292 vm_paddr_t bad;
293 char *cp, *pos;
294
295 if (list == NULL || *list == NULL)
296 return (0);
297 if (**list =='\0') {
298 *list = NULL;
299 return (0);
300 }
301
302 /*
303 * If there's no end pointer then the buffer is coming from
304 * the kenv and we know it's null-terminated.
305 */
306 if (end == NULL)
307 end = *list + strlen(*list);
308
309 /* Ensure that strtoq() won't walk off the end */
310 if (*end != '\0') {
311 if (*end == '\n' || *end == ' ' || *end == ',')
312 *end = '\0';
313 else {
314 printf("Blacklist not terminated, skipping\n");
315 *list = NULL;
316 return (0);
317 }
318 }
319
320 for (pos = *list; *pos != '\0'; pos = cp) {
321 bad = strtoq(pos, &cp, 0);
322 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
323 if (bad == 0) {
324 if (++cp < end)
325 continue;
326 else
327 break;
328 }
329 } else
330 break;
331 if (*cp == '\0' || ++cp >= end)
332 *list = NULL;
333 else
334 *list = cp;
335 return (trunc_page(bad));
336 }
337 printf("Garbage in RAM blacklist, skipping\n");
338 *list = NULL;
339 return (0);
340 }
341
342 bool
vm_page_blacklist_add(vm_paddr_t pa,bool verbose)343 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
344 {
345 struct vm_domain *vmd;
346 vm_page_t m;
347 bool found;
348
349 m = vm_phys_paddr_to_vm_page(pa);
350 if (m == NULL)
351 return (true); /* page does not exist, no failure */
352
353 vmd = VM_DOMAIN(vm_phys_domain(pa));
354 vm_domain_free_lock(vmd);
355 found = vm_phys_unfree_page(pa);
356 vm_domain_free_unlock(vmd);
357 if (found) {
358 vm_domain_freecnt_inc(vmd, -1);
359 TAILQ_INSERT_TAIL(&blacklist_head, m, plinks.q);
360 if (verbose)
361 printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
362 }
363 return (found);
364 }
365
366 /*
367 * vm_page_blacklist_check:
368 *
369 * Iterate through the provided string of blacklist addresses, pulling
370 * each entry out of the physical allocator free list and putting it
371 * onto a list for reporting via the vm.page_blacklist sysctl.
372 */
373 static void
vm_page_blacklist_check(char * list,char * end)374 vm_page_blacklist_check(char *list, char *end)
375 {
376 vm_paddr_t pa;
377 char *next;
378
379 next = list;
380 while (next != NULL) {
381 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
382 continue;
383 vm_page_blacklist_add(pa, bootverbose);
384 }
385 }
386
387 /*
388 * vm_page_blacklist_load:
389 *
390 * Search for a special module named "ram_blacklist". It'll be a
391 * plain text file provided by the user via the loader directive
392 * of the same name.
393 */
394 static void
vm_page_blacklist_load(char ** list,char ** end)395 vm_page_blacklist_load(char **list, char **end)
396 {
397 void *mod;
398 u_char *ptr;
399 u_int len;
400
401 mod = NULL;
402 ptr = NULL;
403
404 mod = preload_search_by_type("ram_blacklist");
405 if (mod != NULL) {
406 ptr = preload_fetch_addr(mod);
407 len = preload_fetch_size(mod);
408 }
409
410 if (ptr != NULL && len > 0) {
411 *list = ptr;
412 *end = ptr + len - 1;
413 } else {
414 *list = NULL;
415 *end = NULL;
416 }
417
418 return;
419 }
420
421 static int
sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)422 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
423 {
424 vm_page_t m;
425 struct sbuf sbuf;
426 int error, first;
427
428 first = 1;
429 error = sysctl_wire_old_buffer(req, 0);
430 if (error != 0)
431 return (error);
432 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
433 TAILQ_FOREACH(m, &blacklist_head, plinks.q) {
434 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
435 (uintmax_t)m->phys_addr);
436 first = 0;
437 }
438 error = sbuf_finish(&sbuf);
439 sbuf_delete(&sbuf);
440 return (error);
441 }
442
443 /*
444 * Initialize a dummy page for use in scans of the specified paging queue.
445 * In principle, this function only needs to set the flag PG_MARKER.
446 * Nonetheless, it write busies the page as a safety precaution.
447 */
448 void
vm_page_init_marker(vm_page_t marker,int queue,uint16_t aflags)449 vm_page_init_marker(vm_page_t marker, int queue, uint16_t aflags)
450 {
451
452 bzero(marker, sizeof(*marker));
453 marker->flags = PG_MARKER;
454 marker->a.flags = aflags;
455 marker->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
456 marker->a.queue = queue;
457 }
458
459 static void
vm_page_domain_init(int domain)460 vm_page_domain_init(int domain)
461 {
462 struct vm_domain *vmd;
463 struct vm_pagequeue *pq;
464 int i;
465
466 vmd = VM_DOMAIN(domain);
467 bzero(vmd, sizeof(*vmd));
468 *__DECONST(const char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
469 "vm inactive pagequeue";
470 *__DECONST(const char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
471 "vm active pagequeue";
472 *__DECONST(const char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
473 "vm laundry pagequeue";
474 *__DECONST(const char **,
475 &vmd->vmd_pagequeues[PQ_UNSWAPPABLE].pq_name) =
476 "vm unswappable pagequeue";
477 vmd->vmd_domain = domain;
478 vmd->vmd_page_count = 0;
479 vmd->vmd_free_count = 0;
480 vmd->vmd_segs = 0;
481 vmd->vmd_oom = false;
482 vmd->vmd_helper_threads_enabled = true;
483 for (i = 0; i < PQ_COUNT; i++) {
484 pq = &vmd->vmd_pagequeues[i];
485 TAILQ_INIT(&pq->pq_pl);
486 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
487 MTX_DEF | MTX_DUPOK);
488 pq->pq_pdpages = 0;
489 vm_page_init_marker(&vmd->vmd_markers[i], i, 0);
490 }
491 mtx_init(&vmd->vmd_free_mtx, "vm page free queue", NULL, MTX_DEF);
492 mtx_init(&vmd->vmd_pageout_mtx, "vm pageout lock", NULL, MTX_DEF);
493 snprintf(vmd->vmd_name, sizeof(vmd->vmd_name), "%d", domain);
494
495 /*
496 * inacthead is used to provide FIFO ordering for LRU-bypassing
497 * insertions.
498 */
499 vm_page_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE, PGA_ENQUEUED);
500 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
501 &vmd->vmd_inacthead, plinks.q);
502
503 /*
504 * The clock pages are used to implement active queue scanning without
505 * requeues. Scans start at clock[0], which is advanced after the scan
506 * ends. When the two clock hands meet, they are reset and scanning
507 * resumes from the head of the queue.
508 */
509 vm_page_init_marker(&vmd->vmd_clock[0], PQ_ACTIVE, PGA_ENQUEUED);
510 vm_page_init_marker(&vmd->vmd_clock[1], PQ_ACTIVE, PGA_ENQUEUED);
511 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
512 &vmd->vmd_clock[0], plinks.q);
513 TAILQ_INSERT_TAIL(&vmd->vmd_pagequeues[PQ_ACTIVE].pq_pl,
514 &vmd->vmd_clock[1], plinks.q);
515 }
516
517 /*
518 * Initialize a physical page in preparation for adding it to the free
519 * lists.
520 */
521 void
vm_page_init_page(vm_page_t m,vm_paddr_t pa,int segind,int pool)522 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind, int pool)
523 {
524 m->object = NULL;
525 m->ref_count = 0;
526 m->busy_lock = VPB_FREED;
527 m->flags = m->a.flags = 0;
528 m->phys_addr = pa;
529 m->a.queue = PQ_NONE;
530 m->psind = 0;
531 m->segind = segind;
532 m->order = VM_NFREEORDER;
533 m->pool = pool;
534 m->valid = m->dirty = 0;
535 pmap_page_init(m);
536 }
537
538 #ifndef PMAP_HAS_PAGE_ARRAY
539 static vm_paddr_t
vm_page_array_alloc(vm_offset_t * vaddr,vm_paddr_t end,vm_paddr_t page_range)540 vm_page_array_alloc(vm_offset_t *vaddr, vm_paddr_t end, vm_paddr_t page_range)
541 {
542 vm_paddr_t new_end;
543
544 /*
545 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
546 * However, because this page is allocated from KVM, out-of-bounds
547 * accesses using the direct map will not be trapped.
548 */
549 *vaddr += PAGE_SIZE;
550
551 /*
552 * Allocate physical memory for the page structures, and map it.
553 */
554 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
555 vm_page_array = (vm_page_t)pmap_map(vaddr, new_end, end,
556 VM_PROT_READ | VM_PROT_WRITE);
557 vm_page_array_size = page_range;
558
559 return (new_end);
560 }
561 #endif
562
563 /*
564 * vm_page_startup:
565 *
566 * Initializes the resident memory module. Allocates physical memory for
567 * bootstrapping UMA and some data structures that are used to manage
568 * physical pages. Initializes these structures, and populates the free
569 * page queues.
570 */
571 vm_offset_t
vm_page_startup(vm_offset_t vaddr)572 vm_page_startup(vm_offset_t vaddr)
573 {
574 struct vm_phys_seg *seg;
575 struct vm_domain *vmd;
576 vm_page_t m;
577 char *list, *listend;
578 vm_paddr_t end, high_avail, low_avail, new_end, size;
579 vm_paddr_t page_range __unused;
580 vm_paddr_t last_pa, pa, startp, endp;
581 u_long pagecount;
582 #if MINIDUMP_PAGE_TRACKING
583 u_long vm_page_dump_size;
584 #endif
585 int biggestone, i, segind;
586 #ifdef WITNESS
587 void *mapped;
588 u_long witness_size;
589 #endif
590 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
591 long ii;
592 #endif
593 int pool;
594 #ifdef VM_FREEPOOL_LAZYINIT
595 int lazyinit;
596 #endif
597
598 vaddr = round_page(vaddr);
599
600 vm_phys_early_startup();
601 biggestone = vm_phys_avail_largest();
602 end = phys_avail[biggestone+1];
603
604 /*
605 * Initialize the page and queue locks.
606 */
607 mtx_init(&vm_domainset_lock, "vm domainset lock", NULL, MTX_DEF);
608 for (i = 0; i < vm_ndomains; i++)
609 vm_page_domain_init(i);
610
611 new_end = end;
612 #ifdef WITNESS
613 /*
614 * witness(4) support. Allocate and map memory and initialize.
615 * Advertised available memory is limited in order to avoid witness
616 * misconfiguration consuming memory needed for subsequent essential
617 * allocations.
618 */
619 witness_size = round_page(witness_startup_count(
620 trunc_page((new_end - phys_avail[biggestone]) / 2)));
621 new_end -= witness_size;
622 mapped = pmap_map(&vaddr, new_end, new_end + witness_size,
623 VM_PROT_READ | VM_PROT_WRITE);
624 bzero(mapped, witness_size);
625 witness_startup(mapped);
626 #endif
627
628 #if MINIDUMP_PAGE_TRACKING
629 /*
630 * Allocate a bitmap to indicate that a random physical page
631 * needs to be included in a minidump.
632 *
633 * The amd64 port needs this to indicate which direct map pages
634 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
635 *
636 * However, i386 still needs this workspace internally within the
637 * minidump code. In theory, they are not needed on i386, but are
638 * included should the sf_buf code decide to use them.
639 */
640 last_pa = 0;
641 vm_page_dump_pages = 0;
642 for (i = 0; dump_avail[i + 1] != 0; i += 2) {
643 vm_page_dump_pages += howmany(dump_avail[i + 1], PAGE_SIZE) -
644 dump_avail[i] / PAGE_SIZE;
645 if (dump_avail[i + 1] > last_pa)
646 last_pa = dump_avail[i + 1];
647 }
648 vm_page_dump_size = round_page(BITSET_SIZE(vm_page_dump_pages));
649 new_end -= vm_page_dump_size;
650 vm_page_dump = pmap_map(&vaddr, new_end,
651 new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
652 bzero((void *)vm_page_dump, vm_page_dump_size);
653 #if MINIDUMP_STARTUP_PAGE_TRACKING
654 /*
655 * Include the UMA bootstrap pages, witness pages and vm_page_dump
656 * in a crash dump. When pmap_map() uses the direct map, they are
657 * not automatically included.
658 */
659 for (pa = new_end; pa < end; pa += PAGE_SIZE)
660 dump_add_page(pa);
661 #endif
662 #else
663 (void)last_pa;
664 #endif
665 phys_avail[biggestone + 1] = new_end;
666 #ifdef __amd64__
667 /*
668 * Request that the physical pages underlying the message buffer be
669 * included in a crash dump. Since the message buffer is accessed
670 * through the direct map, they are not automatically included.
671 */
672 pa = DMAP_TO_PHYS(msgbufp->msg_ptr);
673 last_pa = pa + round_page(msgbufsize);
674 while (pa < last_pa) {
675 dump_add_page(pa);
676 pa += PAGE_SIZE;
677 }
678 #else
679 (void)pa;
680 #endif
681
682 /*
683 * Determine the lowest and highest physical addresses and, in the case
684 * of VM_PHYSSEG_SPARSE, the exact size of the available physical
685 * memory. vm_phys_early_startup() already checked that phys_avail[]
686 * has at least one element.
687 */
688 #ifdef VM_PHYSSEG_SPARSE
689 size = phys_avail[1] - phys_avail[0];
690 #endif
691 low_avail = phys_avail[0];
692 high_avail = phys_avail[1];
693 for (i = 2; phys_avail[i + 1] != 0; i += 2) {
694 #ifdef VM_PHYSSEG_SPARSE
695 size += phys_avail[i + 1] - phys_avail[i];
696 #endif
697 if (phys_avail[i] < low_avail)
698 low_avail = phys_avail[i];
699 if (phys_avail[i + 1] > high_avail)
700 high_avail = phys_avail[i + 1];
701 }
702 for (i = 0; i < vm_phys_nsegs; i++) {
703 #ifdef VM_PHYSSEG_SPARSE
704 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
705 #endif
706 if (vm_phys_segs[i].start < low_avail)
707 low_avail = vm_phys_segs[i].start;
708 if (vm_phys_segs[i].end > high_avail)
709 high_avail = vm_phys_segs[i].end;
710 }
711 first_page = low_avail / PAGE_SIZE;
712 #ifdef VM_PHYSSEG_DENSE
713 size = high_avail - low_avail;
714 #endif
715
716 #ifdef PMAP_HAS_PAGE_ARRAY
717 pmap_page_array_startup(size / PAGE_SIZE);
718 biggestone = vm_phys_avail_largest();
719 end = new_end = phys_avail[biggestone + 1];
720 #else
721 #ifdef VM_PHYSSEG_DENSE
722 /*
723 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
724 * the overhead of a page structure per page only if vm_page_array is
725 * allocated from the last physical memory chunk. Otherwise, we must
726 * allocate page structures representing the physical memory
727 * underlying vm_page_array, even though they will not be used.
728 */
729 if (new_end != high_avail)
730 page_range = size / PAGE_SIZE;
731 else
732 #endif
733 {
734 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
735
736 /*
737 * If the partial bytes remaining are large enough for
738 * a page (PAGE_SIZE) without a corresponding
739 * 'struct vm_page', then new_end will contain an
740 * extra page after subtracting the length of the VM
741 * page array. Compensate by subtracting an extra
742 * page from new_end.
743 */
744 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
745 if (new_end == high_avail)
746 high_avail -= PAGE_SIZE;
747 new_end -= PAGE_SIZE;
748 }
749 }
750 end = new_end;
751 new_end = vm_page_array_alloc(&vaddr, end, page_range);
752 #endif
753
754 #if VM_NRESERVLEVEL > 0
755 /*
756 * Allocate physical memory for the reservation management system's
757 * data structures, and map it.
758 */
759 new_end = vm_reserv_startup(&vaddr, new_end);
760 #endif
761 #if MINIDUMP_PAGE_TRACKING && MINIDUMP_STARTUP_PAGE_TRACKING
762 /*
763 * Include vm_page_array and vm_reserv_array in a crash dump.
764 */
765 for (pa = new_end; pa < end; pa += PAGE_SIZE)
766 dump_add_page(pa);
767 #endif
768 phys_avail[biggestone + 1] = new_end;
769
770 /*
771 * Add physical memory segments corresponding to the available
772 * physical pages.
773 */
774 for (i = 0; phys_avail[i + 1] != 0; i += 2)
775 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
776
777 /*
778 * Initialize the physical memory allocator.
779 */
780 vm_phys_init();
781
782 pool = VM_FREEPOOL_DEFAULT;
783 #ifdef VM_FREEPOOL_LAZYINIT
784 lazyinit = 1;
785 TUNABLE_INT_FETCH("debug.vm.lazy_page_init", &lazyinit);
786 if (lazyinit)
787 pool = VM_FREEPOOL_LAZYINIT;
788 #endif
789
790 /*
791 * Initialize the page structures and add every available page to the
792 * physical memory allocator's free lists.
793 */
794 #if defined(__i386__) && defined(VM_PHYSSEG_DENSE)
795 for (ii = 0; ii < vm_page_array_size; ii++) {
796 m = &vm_page_array[ii];
797 vm_page_init_page(m, (first_page + ii) << PAGE_SHIFT, 0,
798 VM_FREEPOOL_DEFAULT);
799 m->flags = PG_FICTITIOUS;
800 }
801 #endif
802 vm_cnt.v_page_count = 0;
803 for (segind = 0; segind < vm_phys_nsegs; segind++) {
804 seg = &vm_phys_segs[segind];
805
806 /*
807 * Initialize pages not covered by phys_avail[], since they
808 * might be freed to the allocator at some future point, e.g.,
809 * by kmem_bootstrap_free().
810 */
811 startp = seg->start;
812 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
813 if (startp >= seg->end)
814 break;
815 if (phys_avail[i + 1] < startp)
816 continue;
817 if (phys_avail[i] <= startp) {
818 startp = phys_avail[i + 1];
819 continue;
820 }
821 m = vm_phys_seg_paddr_to_vm_page(seg, startp);
822 for (endp = MIN(phys_avail[i], seg->end);
823 startp < endp; startp += PAGE_SIZE, m++) {
824 vm_page_init_page(m, startp, segind,
825 VM_FREEPOOL_DEFAULT);
826 }
827 }
828
829 /*
830 * Add the segment's pages that are covered by one of
831 * phys_avail's ranges to the free lists.
832 */
833 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
834 if (seg->end <= phys_avail[i] ||
835 seg->start >= phys_avail[i + 1])
836 continue;
837
838 startp = MAX(seg->start, phys_avail[i]);
839 endp = MIN(seg->end, phys_avail[i + 1]);
840 pagecount = (u_long)atop(endp - startp);
841 if (pagecount == 0)
842 continue;
843
844 /*
845 * If lazy vm_page initialization is not enabled, simply
846 * initialize all of the pages in the segment covered by
847 * phys_avail. Otherwise, initialize only the first
848 * page of each run of free pages handed to the vm_phys
849 * allocator, which in turn defers initialization of
850 * pages until they are needed.
851 *
852 * This avoids blocking the boot process for long
853 * periods, which may be relevant for VMs (which ought
854 * to boot as quickly as possible) and/or systems with
855 * large amounts of physical memory.
856 */
857 m = vm_phys_seg_paddr_to_vm_page(seg, startp);
858 vm_page_init_page(m, startp, segind, pool);
859 if (pool == VM_FREEPOOL_DEFAULT) {
860 for (u_long j = 1; j < pagecount; j++) {
861 vm_page_init_page(&m[j],
862 startp + ptoa((vm_paddr_t)j),
863 segind, pool);
864 }
865 }
866 vmd = VM_DOMAIN(seg->domain);
867 vm_domain_free_lock(vmd);
868 vm_phys_enqueue_contig(m, pool, pagecount);
869 vm_domain_free_unlock(vmd);
870 vm_domain_freecnt_inc(vmd, pagecount);
871 vm_cnt.v_page_count += (u_int)pagecount;
872 vmd->vmd_page_count += (u_int)pagecount;
873 vmd->vmd_segs |= 1UL << segind;
874 }
875 }
876
877 /*
878 * Remove blacklisted pages from the physical memory allocator.
879 */
880 TAILQ_INIT(&blacklist_head);
881 vm_page_blacklist_load(&list, &listend);
882 vm_page_blacklist_check(list, listend);
883
884 list = kern_getenv("vm.blacklist");
885 vm_page_blacklist_check(list, NULL);
886
887 freeenv(list);
888 #if VM_NRESERVLEVEL > 0
889 /*
890 * Initialize the reservation management system.
891 */
892 vm_reserv_init();
893 #endif
894
895 return (vaddr);
896 }
897
898 void
vm_page_reference(vm_page_t m)899 vm_page_reference(vm_page_t m)
900 {
901
902 vm_page_aflag_set(m, PGA_REFERENCED);
903 }
904
905 /*
906 * vm_page_trybusy
907 *
908 * Helper routine for grab functions to trylock busy.
909 *
910 * Returns true on success and false on failure.
911 */
912 static bool
vm_page_trybusy(vm_page_t m,int allocflags)913 vm_page_trybusy(vm_page_t m, int allocflags)
914 {
915
916 if ((allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0)
917 return (vm_page_trysbusy(m));
918 else
919 return (vm_page_tryxbusy(m));
920 }
921
922 /*
923 * vm_page_tryacquire
924 *
925 * Helper routine for grab functions to trylock busy and wire.
926 *
927 * Returns true on success and false on failure.
928 */
929 static inline bool
vm_page_tryacquire(vm_page_t m,int allocflags)930 vm_page_tryacquire(vm_page_t m, int allocflags)
931 {
932 bool locked;
933
934 locked = vm_page_trybusy(m, allocflags);
935 if (locked && (allocflags & VM_ALLOC_WIRED) != 0)
936 vm_page_wire(m);
937 return (locked);
938 }
939
940 /*
941 * vm_page_busy_acquire:
942 *
943 * Acquire the busy lock as described by VM_ALLOC_* flags. Will loop
944 * and drop the object lock if necessary.
945 */
946 bool
vm_page_busy_acquire(vm_page_t m,int allocflags)947 vm_page_busy_acquire(vm_page_t m, int allocflags)
948 {
949 vm_object_t obj;
950 bool locked;
951
952 /*
953 * The page-specific object must be cached because page
954 * identity can change during the sleep, causing the
955 * re-lock of a different object.
956 * It is assumed that a reference to the object is already
957 * held by the callers.
958 */
959 obj = atomic_load_ptr(&m->object);
960 for (;;) {
961 if (vm_page_tryacquire(m, allocflags))
962 return (true);
963 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
964 return (false);
965 if (obj != NULL)
966 locked = VM_OBJECT_WOWNED(obj);
967 else
968 locked = false;
969 MPASS(locked || vm_page_wired(m));
970 if (_vm_page_busy_sleep(obj, m, m->pindex, "vmpba", allocflags,
971 locked) && locked)
972 VM_OBJECT_WLOCK(obj);
973 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
974 return (false);
975 KASSERT(m->object == obj || m->object == NULL,
976 ("vm_page_busy_acquire: page %p does not belong to %p",
977 m, obj));
978 }
979 }
980
981 /*
982 * vm_page_busy_downgrade:
983 *
984 * Downgrade an exclusive busy page into a single shared busy page.
985 */
986 void
vm_page_busy_downgrade(vm_page_t m)987 vm_page_busy_downgrade(vm_page_t m)
988 {
989 u_int x;
990
991 vm_page_assert_xbusied(m);
992
993 x = vm_page_busy_fetch(m);
994 for (;;) {
995 if (atomic_fcmpset_rel_int(&m->busy_lock,
996 &x, VPB_SHARERS_WORD(1)))
997 break;
998 }
999 if ((x & VPB_BIT_WAITERS) != 0)
1000 wakeup(m);
1001 }
1002
1003 /*
1004 *
1005 * vm_page_busy_tryupgrade:
1006 *
1007 * Attempt to upgrade a single shared busy into an exclusive busy.
1008 */
1009 int
vm_page_busy_tryupgrade(vm_page_t m)1010 vm_page_busy_tryupgrade(vm_page_t m)
1011 {
1012 u_int ce, x;
1013
1014 vm_page_assert_sbusied(m);
1015
1016 x = vm_page_busy_fetch(m);
1017 ce = VPB_CURTHREAD_EXCLUSIVE;
1018 for (;;) {
1019 if (VPB_SHARERS(x) > 1)
1020 return (0);
1021 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
1022 ("vm_page_busy_tryupgrade: invalid lock state"));
1023 if (!atomic_fcmpset_acq_int(&m->busy_lock, &x,
1024 ce | (x & VPB_BIT_WAITERS)))
1025 continue;
1026 return (1);
1027 }
1028 }
1029
1030 /*
1031 * vm_page_sbusied:
1032 *
1033 * Return a positive value if the page is shared busied, 0 otherwise.
1034 */
1035 int
vm_page_sbusied(vm_page_t m)1036 vm_page_sbusied(vm_page_t m)
1037 {
1038 u_int x;
1039
1040 x = vm_page_busy_fetch(m);
1041 return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
1042 }
1043
1044 /*
1045 * vm_page_sunbusy:
1046 *
1047 * Shared unbusy a page.
1048 */
1049 void
vm_page_sunbusy(vm_page_t m)1050 vm_page_sunbusy(vm_page_t m)
1051 {
1052 u_int x;
1053
1054 vm_page_assert_sbusied(m);
1055
1056 x = vm_page_busy_fetch(m);
1057 for (;;) {
1058 KASSERT(x != VPB_FREED,
1059 ("vm_page_sunbusy: Unlocking freed page."));
1060 if (VPB_SHARERS(x) > 1) {
1061 if (atomic_fcmpset_int(&m->busy_lock, &x,
1062 x - VPB_ONE_SHARER))
1063 break;
1064 continue;
1065 }
1066 KASSERT((x & ~VPB_BIT_WAITERS) == VPB_SHARERS_WORD(1),
1067 ("vm_page_sunbusy: invalid lock state"));
1068 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1069 continue;
1070 if ((x & VPB_BIT_WAITERS) == 0)
1071 break;
1072 wakeup(m);
1073 break;
1074 }
1075 }
1076
1077 /*
1078 * vm_page_busy_sleep:
1079 *
1080 * Sleep if the page is busy, using the page pointer as wchan.
1081 * This is used to implement the hard-path of the busying mechanism.
1082 *
1083 * If VM_ALLOC_IGN_SBUSY is specified in allocflags, the function
1084 * will not sleep if the page is shared-busy.
1085 *
1086 * The object lock must be held on entry.
1087 *
1088 * Returns true if it slept and dropped the object lock, or false
1089 * if there was no sleep and the lock is still held.
1090 */
1091 bool
vm_page_busy_sleep(vm_page_t m,const char * wmesg,int allocflags)1092 vm_page_busy_sleep(vm_page_t m, const char *wmesg, int allocflags)
1093 {
1094 vm_object_t obj;
1095
1096 obj = m->object;
1097 VM_OBJECT_ASSERT_LOCKED(obj);
1098
1099 return (_vm_page_busy_sleep(obj, m, m->pindex, wmesg, allocflags,
1100 true));
1101 }
1102
1103 /*
1104 * vm_page_busy_sleep_unlocked:
1105 *
1106 * Sleep if the page is busy, using the page pointer as wchan.
1107 * This is used to implement the hard-path of busying mechanism.
1108 *
1109 * If VM_ALLOC_IGN_SBUSY is specified in allocflags, the function
1110 * will not sleep if the page is shared-busy.
1111 *
1112 * The object lock must not be held on entry. The operation will
1113 * return if the page changes identity.
1114 */
1115 void
vm_page_busy_sleep_unlocked(vm_object_t obj,vm_page_t m,vm_pindex_t pindex,const char * wmesg,int allocflags)1116 vm_page_busy_sleep_unlocked(vm_object_t obj, vm_page_t m, vm_pindex_t pindex,
1117 const char *wmesg, int allocflags)
1118 {
1119 VM_OBJECT_ASSERT_UNLOCKED(obj);
1120
1121 (void)_vm_page_busy_sleep(obj, m, pindex, wmesg, allocflags, false);
1122 }
1123
1124 /*
1125 * _vm_page_busy_sleep:
1126 *
1127 * Internal busy sleep function. Verifies the page identity and
1128 * lockstate against parameters. Returns true if it sleeps and
1129 * false otherwise.
1130 *
1131 * allocflags uses VM_ALLOC_* flags to specify the lock required.
1132 *
1133 * If locked is true the lock will be dropped for any true returns
1134 * and held for any false returns.
1135 */
1136 static bool
_vm_page_busy_sleep(vm_object_t obj,vm_page_t m,vm_pindex_t pindex,const char * wmesg,int allocflags,bool locked)1137 _vm_page_busy_sleep(vm_object_t obj, vm_page_t m, vm_pindex_t pindex,
1138 const char *wmesg, int allocflags, bool locked)
1139 {
1140 bool xsleep;
1141 u_int x;
1142
1143 /*
1144 * If the object is busy we must wait for that to drain to zero
1145 * before trying the page again.
1146 */
1147 if (obj != NULL && vm_object_busied(obj)) {
1148 if (locked)
1149 VM_OBJECT_DROP(obj);
1150 vm_object_busy_wait(obj, wmesg);
1151 return (true);
1152 }
1153
1154 if (!vm_page_busied(m))
1155 return (false);
1156
1157 xsleep = (allocflags & (VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY)) != 0;
1158 sleepq_lock(m);
1159 x = vm_page_busy_fetch(m);
1160 do {
1161 /*
1162 * If the page changes objects or becomes unlocked we can
1163 * simply return.
1164 */
1165 if (x == VPB_UNBUSIED ||
1166 (xsleep && (x & VPB_BIT_SHARED) != 0) ||
1167 m->object != obj || m->pindex != pindex) {
1168 sleepq_release(m);
1169 return (false);
1170 }
1171 if ((x & VPB_BIT_WAITERS) != 0)
1172 break;
1173 } while (!atomic_fcmpset_int(&m->busy_lock, &x, x | VPB_BIT_WAITERS));
1174 if (locked)
1175 VM_OBJECT_DROP(obj);
1176 DROP_GIANT();
1177 sleepq_add(m, NULL, wmesg, 0, 0);
1178 sleepq_wait(m, PVM);
1179 PICKUP_GIANT();
1180 return (true);
1181 }
1182
1183 /*
1184 * vm_page_trysbusy:
1185 *
1186 * Try to shared busy a page.
1187 * If the operation succeeds 1 is returned otherwise 0.
1188 * The operation never sleeps.
1189 */
1190 int
vm_page_trysbusy(vm_page_t m)1191 vm_page_trysbusy(vm_page_t m)
1192 {
1193 vm_object_t obj;
1194 u_int x;
1195
1196 obj = m->object;
1197 x = vm_page_busy_fetch(m);
1198 for (;;) {
1199 if ((x & VPB_BIT_SHARED) == 0)
1200 return (0);
1201 /*
1202 * Reduce the window for transient busies that will trigger
1203 * false negatives in vm_page_ps_test().
1204 */
1205 if (obj != NULL && vm_object_busied(obj))
1206 return (0);
1207 if (atomic_fcmpset_acq_int(&m->busy_lock, &x,
1208 x + VPB_ONE_SHARER))
1209 break;
1210 }
1211
1212 /* Refetch the object now that we're guaranteed that it is stable. */
1213 obj = m->object;
1214 if (obj != NULL && vm_object_busied(obj)) {
1215 vm_page_sunbusy(m);
1216 return (0);
1217 }
1218 return (1);
1219 }
1220
1221 /*
1222 * vm_page_tryxbusy:
1223 *
1224 * Try to exclusive busy a page.
1225 * If the operation succeeds 1 is returned otherwise 0.
1226 * The operation never sleeps.
1227 */
1228 int
vm_page_tryxbusy(vm_page_t m)1229 vm_page_tryxbusy(vm_page_t m)
1230 {
1231 vm_object_t obj;
1232
1233 if (atomic_cmpset_acq_int(&m->busy_lock, VPB_UNBUSIED,
1234 VPB_CURTHREAD_EXCLUSIVE) == 0)
1235 return (0);
1236
1237 obj = m->object;
1238 if (obj != NULL && vm_object_busied(obj)) {
1239 vm_page_xunbusy(m);
1240 return (0);
1241 }
1242 return (1);
1243 }
1244
1245 static void
vm_page_xunbusy_hard_tail(vm_page_t m)1246 vm_page_xunbusy_hard_tail(vm_page_t m)
1247 {
1248 atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1249 /* Wake the waiter. */
1250 wakeup(m);
1251 }
1252
1253 /*
1254 * vm_page_xunbusy_hard:
1255 *
1256 * Called when unbusy has failed because there is a waiter.
1257 */
1258 void
vm_page_xunbusy_hard(vm_page_t m)1259 vm_page_xunbusy_hard(vm_page_t m)
1260 {
1261 vm_page_assert_xbusied(m);
1262 vm_page_xunbusy_hard_tail(m);
1263 }
1264
1265 void
vm_page_xunbusy_hard_unchecked(vm_page_t m)1266 vm_page_xunbusy_hard_unchecked(vm_page_t m)
1267 {
1268 vm_page_assert_xbusied_unchecked(m);
1269 vm_page_xunbusy_hard_tail(m);
1270 }
1271
1272 static void
vm_page_busy_free(vm_page_t m)1273 vm_page_busy_free(vm_page_t m)
1274 {
1275 u_int x;
1276
1277 atomic_thread_fence_rel();
1278 x = atomic_swap_int(&m->busy_lock, VPB_FREED);
1279 if ((x & VPB_BIT_WAITERS) != 0)
1280 wakeup(m);
1281 }
1282
1283 /*
1284 * vm_page_unhold_pages:
1285 *
1286 * Unhold each of the pages that is referenced by the given array.
1287 */
1288 void
vm_page_unhold_pages(vm_page_t * ma,int count)1289 vm_page_unhold_pages(vm_page_t *ma, int count)
1290 {
1291
1292 for (; count != 0; count--) {
1293 vm_page_unwire(*ma, PQ_ACTIVE);
1294 ma++;
1295 }
1296 }
1297
1298 vm_page_t
PHYS_TO_VM_PAGE(vm_paddr_t pa)1299 PHYS_TO_VM_PAGE(vm_paddr_t pa)
1300 {
1301 vm_page_t m;
1302
1303 #ifdef VM_PHYSSEG_SPARSE
1304 #if defined(__aarch64__)
1305 if (in_realm())
1306 pa &= ~prot_ns_shared_pa; /* Mask off secure bit */
1307 #endif
1308 m = vm_phys_paddr_to_vm_page(pa);
1309 if (m == NULL)
1310 m = vm_phys_fictitious_to_vm_page(pa);
1311 return (m);
1312 #elif defined(VM_PHYSSEG_DENSE)
1313 long pi;
1314
1315 pi = atop(pa);
1316 if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
1317 m = &vm_page_array[pi - first_page];
1318 return (m);
1319 }
1320 return (vm_phys_fictitious_to_vm_page(pa));
1321 #else
1322 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
1323 #endif
1324 }
1325
1326 /*
1327 * vm_page_getfake:
1328 *
1329 * Create a fictitious page with the specified physical address and
1330 * memory attribute. The memory attribute is the only the machine-
1331 * dependent aspect of a fictitious page that must be initialized.
1332 */
1333 vm_page_t
vm_page_getfake(vm_paddr_t paddr,vm_memattr_t memattr)1334 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
1335 {
1336 vm_page_t m;
1337
1338 m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
1339 vm_page_initfake(m, paddr, memattr);
1340 return (m);
1341 }
1342
1343 void
vm_page_initfake(vm_page_t m,vm_paddr_t paddr,vm_memattr_t memattr)1344 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1345 {
1346
1347 if ((m->flags & PG_FICTITIOUS) != 0) {
1348 /*
1349 * The page's memattr might have changed since the
1350 * previous initialization. Update the pmap to the
1351 * new memattr.
1352 */
1353 goto memattr;
1354 }
1355 m->phys_addr = paddr;
1356 m->a.queue = PQ_NONE;
1357 /* Fictitious pages don't use "segind". */
1358 m->flags = PG_FICTITIOUS;
1359 /* Fictitious pages don't use "order" or "pool". */
1360 m->oflags = VPO_UNMANAGED;
1361 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
1362 /* Fictitious pages are unevictable. */
1363 m->ref_count = 1;
1364 pmap_page_init(m);
1365 memattr:
1366 pmap_page_set_memattr(m, memattr);
1367 }
1368
1369 /*
1370 * vm_page_putfake:
1371 *
1372 * Release a fictitious page.
1373 */
1374 void
vm_page_putfake(vm_page_t m)1375 vm_page_putfake(vm_page_t m)
1376 {
1377
1378 KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1379 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1380 ("vm_page_putfake: bad page %p", m));
1381 if (m->object != NULL) {
1382 vm_page_assert_xbusied(m);
1383 vm_page_busy_free(m);
1384 }
1385 uma_zfree(fakepg_zone, m);
1386 }
1387
1388 /*
1389 * vm_page_updatefake:
1390 *
1391 * Update the given fictitious page to the specified physical address and
1392 * memory attribute.
1393 */
1394 void
vm_page_updatefake(vm_page_t m,vm_paddr_t paddr,vm_memattr_t memattr)1395 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1396 {
1397
1398 KASSERT((m->flags & PG_FICTITIOUS) != 0,
1399 ("vm_page_updatefake: bad page %p", m));
1400 m->phys_addr = paddr;
1401 pmap_page_set_memattr(m, memattr);
1402 }
1403
1404 /*
1405 * vm_page_free:
1406 *
1407 * Free a page.
1408 */
1409 void
vm_page_free(vm_page_t m)1410 vm_page_free(vm_page_t m)
1411 {
1412
1413 m->flags &= ~PG_ZERO;
1414 vm_page_free_toq(m);
1415 }
1416
1417 /*
1418 * vm_page_free_zero:
1419 *
1420 * Free a page to the zerod-pages queue
1421 */
1422 void
vm_page_free_zero(vm_page_t m)1423 vm_page_free_zero(vm_page_t m)
1424 {
1425
1426 m->flags |= PG_ZERO;
1427 vm_page_free_toq(m);
1428 }
1429
1430 /*
1431 * Unbusy and handle the page queueing for a page from a getpages request that
1432 * was optionally read ahead or behind.
1433 */
1434 void
vm_page_readahead_finish(vm_page_t m)1435 vm_page_readahead_finish(vm_page_t m)
1436 {
1437
1438 /* We shouldn't put invalid pages on queues. */
1439 KASSERT(!vm_page_none_valid(m), ("%s: %p is invalid", __func__, m));
1440
1441 /*
1442 * Since the page is not the actually needed one, whether it should
1443 * be activated or deactivated is not obvious. Empirical results
1444 * have shown that deactivating the page is usually the best choice,
1445 * unless the page is wanted by another thread.
1446 */
1447 if ((vm_page_busy_fetch(m) & VPB_BIT_WAITERS) != 0)
1448 vm_page_activate(m);
1449 else
1450 vm_page_deactivate(m);
1451 vm_page_xunbusy_unchecked(m);
1452 }
1453
1454 /*
1455 * Destroy the identity of an invalid page and free it if possible.
1456 * This is intended to be used when reading a page from backing store fails.
1457 */
1458 void
vm_page_free_invalid(vm_page_t m)1459 vm_page_free_invalid(vm_page_t m)
1460 {
1461
1462 KASSERT(vm_page_none_valid(m), ("page %p is valid", m));
1463 KASSERT(!pmap_page_is_mapped(m), ("page %p is mapped", m));
1464 KASSERT(m->object != NULL, ("page %p has no object", m));
1465 VM_OBJECT_ASSERT_WLOCKED(m->object);
1466
1467 /*
1468 * We may be attempting to free the page as part of the handling for an
1469 * I/O error, in which case the page was xbusied by a different thread.
1470 */
1471 vm_page_xbusy_claim(m);
1472
1473 /*
1474 * If someone has wired this page while the object lock
1475 * was not held, then the thread that unwires is responsible
1476 * for freeing the page. Otherwise just free the page now.
1477 * The wire count of this unmapped page cannot change while
1478 * we have the page xbusy and the page's object wlocked.
1479 */
1480 if (vm_page_remove(m))
1481 vm_page_free(m);
1482 }
1483
1484 /*
1485 * vm_page_dirty_KBI: [ internal use only ]
1486 *
1487 * Set all bits in the page's dirty field.
1488 *
1489 * The object containing the specified page must be locked if the
1490 * call is made from the machine-independent layer.
1491 *
1492 * See vm_page_clear_dirty_mask().
1493 *
1494 * This function should only be called by vm_page_dirty().
1495 */
1496 void
vm_page_dirty_KBI(vm_page_t m)1497 vm_page_dirty_KBI(vm_page_t m)
1498 {
1499
1500 /* Refer to this operation by its public name. */
1501 KASSERT(vm_page_all_valid(m), ("vm_page_dirty: page is invalid!"));
1502 m->dirty = VM_PAGE_BITS_ALL;
1503 }
1504
1505 /*
1506 * Insert the given page into the given object at the given pindex.
1507 *
1508 * The procedure is marked __always_inline to suggest to the compiler to
1509 * eliminate the iter parameter and the associated alternate branch.
1510 */
1511 static __always_inline int
vm_page_insert_lookup(vm_page_t m,vm_object_t object,vm_pindex_t pindex,bool iter,struct pctrie_iter * pages)1512 vm_page_insert_lookup(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1513 bool iter, struct pctrie_iter *pages)
1514 {
1515 int error;
1516
1517 VM_OBJECT_ASSERT_WLOCKED(object);
1518 KASSERT(m->object == NULL,
1519 ("vm_page_insert: page %p already inserted", m));
1520
1521 /*
1522 * Record the object/offset pair in this page.
1523 */
1524 m->object = object;
1525 m->pindex = pindex;
1526 m->ref_count |= VPRC_OBJREF;
1527
1528 /*
1529 * Add this page to the object's radix tree.
1530 */
1531 if (iter)
1532 error = vm_radix_iter_insert(pages, m);
1533 else
1534 error = vm_radix_insert(&object->rtree, m);
1535 if (__predict_false(error != 0)) {
1536 m->object = NULL;
1537 m->pindex = 0;
1538 m->ref_count &= ~VPRC_OBJREF;
1539 return (1);
1540 }
1541
1542 vm_page_insert_radixdone(m, object);
1543 vm_pager_page_inserted(object, m);
1544 return (0);
1545 }
1546
1547 /*
1548 * vm_page_insert: [ internal use only ]
1549 *
1550 * Inserts the given mem entry into the object and object list.
1551 *
1552 * The object must be locked.
1553 */
1554 int
vm_page_insert(vm_page_t m,vm_object_t object,vm_pindex_t pindex)1555 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1556 {
1557 return (vm_page_insert_lookup(m, object, pindex, false, NULL));
1558 }
1559
1560 /*
1561 * vm_page_iter_insert:
1562 *
1563 * Tries to insert the page "m" into the specified object at offset
1564 * "pindex" using the iterator "pages". Returns 0 if the insertion was
1565 * successful.
1566 *
1567 * The object must be locked.
1568 */
1569 int
vm_page_iter_insert(vm_page_t m,vm_object_t object,vm_pindex_t pindex,struct pctrie_iter * pages)1570 vm_page_iter_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1571 struct pctrie_iter *pages)
1572 {
1573 return (vm_page_insert_lookup(m, object, pindex, true, pages));
1574 }
1575
1576 /*
1577 * vm_page_insert_radixdone:
1578 *
1579 * Complete page "m" insertion into the specified object after the
1580 * radix trie hooking.
1581 *
1582 * The object must be locked.
1583 */
1584 static void
vm_page_insert_radixdone(vm_page_t m,vm_object_t object)1585 vm_page_insert_radixdone(vm_page_t m, vm_object_t object)
1586 {
1587
1588 VM_OBJECT_ASSERT_WLOCKED(object);
1589 KASSERT(object != NULL && m->object == object,
1590 ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1591 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1592 ("vm_page_insert_radixdone: page %p is missing object ref", m));
1593
1594 /*
1595 * Show that the object has one more resident page.
1596 */
1597 object->resident_page_count++;
1598
1599 /*
1600 * Hold the vnode until the last page is released.
1601 */
1602 if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1603 vhold(object->handle);
1604
1605 /*
1606 * Since we are inserting a new and possibly dirty page,
1607 * update the object's generation count.
1608 */
1609 if (pmap_page_is_write_mapped(m))
1610 vm_object_set_writeable_dirty(object);
1611 }
1612
1613 /*
1614 * vm_page_remove_radixdone
1615 *
1616 * Complete page "m" removal from the specified object after the radix trie
1617 * unhooking.
1618 *
1619 * The caller is responsible for updating the page's fields to reflect this
1620 * removal.
1621 */
1622 static void
vm_page_remove_radixdone(vm_page_t m)1623 vm_page_remove_radixdone(vm_page_t m)
1624 {
1625 vm_object_t object;
1626
1627 vm_page_assert_xbusied(m);
1628 object = m->object;
1629 VM_OBJECT_ASSERT_WLOCKED(object);
1630 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1631 ("page %p is missing its object ref", m));
1632
1633 /* Deferred free of swap space. */
1634 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1635 vm_pager_page_unswapped(m);
1636
1637 vm_pager_page_removed(object, m);
1638 m->object = NULL;
1639
1640 /*
1641 * And show that the object has one fewer resident page.
1642 */
1643 object->resident_page_count--;
1644
1645 /*
1646 * The vnode may now be recycled.
1647 */
1648 if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1649 vdrop(object->handle);
1650 }
1651
1652 /*
1653 * vm_page_free_object_prep:
1654 *
1655 * Disassociates the given page from its VM object.
1656 *
1657 * The object must be locked, and the page must be xbusy.
1658 */
1659 static void
vm_page_free_object_prep(vm_page_t m)1660 vm_page_free_object_prep(vm_page_t m)
1661 {
1662 KASSERT(((m->oflags & VPO_UNMANAGED) != 0) ==
1663 ((m->object->flags & OBJ_UNMANAGED) != 0),
1664 ("%s: managed flag mismatch for page %p",
1665 __func__, m));
1666 vm_page_assert_xbusied(m);
1667
1668 /*
1669 * The object reference can be released without an atomic
1670 * operation.
1671 */
1672 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
1673 m->ref_count == VPRC_OBJREF,
1674 ("%s: page %p has unexpected ref_count %u",
1675 __func__, m, m->ref_count));
1676 vm_page_remove_radixdone(m);
1677 m->ref_count -= VPRC_OBJREF;
1678 }
1679
1680 /*
1681 * vm_page_iter_free:
1682 *
1683 * Free the given page, and use the iterator to remove it from the radix
1684 * tree.
1685 */
1686 void
vm_page_iter_free(struct pctrie_iter * pages,vm_page_t m)1687 vm_page_iter_free(struct pctrie_iter *pages, vm_page_t m)
1688 {
1689 vm_radix_iter_remove(pages);
1690 vm_page_free_object_prep(m);
1691 vm_page_xunbusy(m);
1692 m->flags &= ~PG_ZERO;
1693 vm_page_free_toq(m);
1694 }
1695
1696 /*
1697 * vm_page_remove:
1698 *
1699 * Removes the specified page from its containing object, but does not
1700 * invalidate any backing storage. Returns true if the object's reference
1701 * was the last reference to the page, and false otherwise.
1702 *
1703 * The object must be locked and the page must be exclusively busied.
1704 * The exclusive busy will be released on return. If this is not the
1705 * final ref and the caller does not hold a wire reference it may not
1706 * continue to access the page.
1707 */
1708 bool
vm_page_remove(vm_page_t m)1709 vm_page_remove(vm_page_t m)
1710 {
1711 bool dropped;
1712
1713 dropped = vm_page_remove_xbusy(m);
1714 vm_page_xunbusy(m);
1715
1716 return (dropped);
1717 }
1718
1719 /*
1720 * vm_page_iter_remove:
1721 *
1722 * Remove the current page, and use the iterator to remove it from the
1723 * radix tree.
1724 */
1725 bool
vm_page_iter_remove(struct pctrie_iter * pages,vm_page_t m)1726 vm_page_iter_remove(struct pctrie_iter *pages, vm_page_t m)
1727 {
1728 bool dropped;
1729
1730 vm_radix_iter_remove(pages);
1731 vm_page_remove_radixdone(m);
1732 dropped = (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1733 vm_page_xunbusy(m);
1734
1735 return (dropped);
1736 }
1737
1738 /*
1739 * vm_page_radix_remove
1740 *
1741 * Removes the specified page from the radix tree.
1742 */
1743 static void
vm_page_radix_remove(vm_page_t m)1744 vm_page_radix_remove(vm_page_t m)
1745 {
1746 vm_page_t mrem __diagused;
1747
1748 mrem = vm_radix_remove(&m->object->rtree, m->pindex);
1749 KASSERT(mrem == m,
1750 ("removed page %p, expected page %p", mrem, m));
1751 }
1752
1753 /*
1754 * vm_page_remove_xbusy
1755 *
1756 * Removes the page but leaves the xbusy held. Returns true if this
1757 * removed the final ref and false otherwise.
1758 */
1759 bool
vm_page_remove_xbusy(vm_page_t m)1760 vm_page_remove_xbusy(vm_page_t m)
1761 {
1762
1763 vm_page_radix_remove(m);
1764 vm_page_remove_radixdone(m);
1765 return (vm_page_drop(m, VPRC_OBJREF) == VPRC_OBJREF);
1766 }
1767
1768 /*
1769 * vm_page_lookup:
1770 *
1771 * Returns the page associated with the object/offset
1772 * pair specified; if none is found, NULL is returned.
1773 *
1774 * The object must be locked.
1775 */
1776 vm_page_t
vm_page_lookup(vm_object_t object,vm_pindex_t pindex)1777 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1778 {
1779
1780 VM_OBJECT_ASSERT_LOCKED(object);
1781 return (vm_radix_lookup(&object->rtree, pindex));
1782 }
1783
1784 /*
1785 * vm_page_iter_init:
1786 *
1787 * Initialize iterator for vm pages.
1788 */
1789 void
vm_page_iter_init(struct pctrie_iter * pages,vm_object_t object)1790 vm_page_iter_init(struct pctrie_iter *pages, vm_object_t object)
1791 {
1792
1793 vm_radix_iter_init(pages, &object->rtree);
1794 }
1795
1796 /*
1797 * vm_page_iter_init:
1798 *
1799 * Initialize iterator for vm pages.
1800 */
1801 void
vm_page_iter_limit_init(struct pctrie_iter * pages,vm_object_t object,vm_pindex_t limit)1802 vm_page_iter_limit_init(struct pctrie_iter *pages, vm_object_t object,
1803 vm_pindex_t limit)
1804 {
1805
1806 vm_radix_iter_limit_init(pages, &object->rtree, limit);
1807 }
1808
1809 /*
1810 * vm_page_lookup_unlocked:
1811 *
1812 * Returns the page associated with the object/offset pair specified;
1813 * if none is found, NULL is returned. The page may be no longer be
1814 * present in the object at the time that this function returns. Only
1815 * useful for opportunistic checks such as inmem().
1816 */
1817 vm_page_t
vm_page_lookup_unlocked(vm_object_t object,vm_pindex_t pindex)1818 vm_page_lookup_unlocked(vm_object_t object, vm_pindex_t pindex)
1819 {
1820
1821 return (vm_radix_lookup_unlocked(&object->rtree, pindex));
1822 }
1823
1824 /*
1825 * vm_page_relookup:
1826 *
1827 * Returns a page that must already have been busied by
1828 * the caller. Used for bogus page replacement.
1829 */
1830 vm_page_t
vm_page_relookup(vm_object_t object,vm_pindex_t pindex)1831 vm_page_relookup(vm_object_t object, vm_pindex_t pindex)
1832 {
1833 vm_page_t m;
1834
1835 m = vm_page_lookup_unlocked(object, pindex);
1836 KASSERT(m != NULL && (vm_page_busied(m) || vm_page_wired(m)) &&
1837 m->object == object && m->pindex == pindex,
1838 ("vm_page_relookup: Invalid page %p", m));
1839 return (m);
1840 }
1841
1842 /*
1843 * This should only be used by lockless functions for releasing transient
1844 * incorrect acquires. The page may have been freed after we acquired a
1845 * busy lock. In this case busy_lock == VPB_FREED and we have nothing
1846 * further to do.
1847 */
1848 static void
vm_page_busy_release(vm_page_t m)1849 vm_page_busy_release(vm_page_t m)
1850 {
1851 u_int x;
1852
1853 x = vm_page_busy_fetch(m);
1854 for (;;) {
1855 if (x == VPB_FREED)
1856 break;
1857 if ((x & VPB_BIT_SHARED) != 0 && VPB_SHARERS(x) > 1) {
1858 if (atomic_fcmpset_int(&m->busy_lock, &x,
1859 x - VPB_ONE_SHARER))
1860 break;
1861 continue;
1862 }
1863 KASSERT((x & VPB_BIT_SHARED) != 0 ||
1864 (x & ~VPB_BIT_WAITERS) == VPB_CURTHREAD_EXCLUSIVE,
1865 ("vm_page_busy_release: %p xbusy not owned.", m));
1866 if (!atomic_fcmpset_rel_int(&m->busy_lock, &x, VPB_UNBUSIED))
1867 continue;
1868 if ((x & VPB_BIT_WAITERS) != 0)
1869 wakeup(m);
1870 break;
1871 }
1872 }
1873
1874 /*
1875 * Uses the page mnew as a replacement for an existing page at index
1876 * pindex which must be already present in the object.
1877 *
1878 * Both pages must be exclusively busied on enter. The old page is
1879 * unbusied on exit.
1880 *
1881 * A return value of true means mold is now free. If this is not the
1882 * final ref and the caller does not hold a wire reference it may not
1883 * continue to access the page.
1884 */
1885 static bool
vm_page_replace_hold(vm_page_t mnew,vm_object_t object,vm_pindex_t pindex,vm_page_t mold)1886 vm_page_replace_hold(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1887 vm_page_t mold)
1888 {
1889 vm_page_t mret __diagused;
1890 bool dropped;
1891
1892 VM_OBJECT_ASSERT_WLOCKED(object);
1893 vm_page_assert_xbusied(mold);
1894 KASSERT(mnew->object == NULL && (mnew->ref_count & VPRC_OBJREF) == 0,
1895 ("vm_page_replace: page %p already in object", mnew));
1896
1897 /*
1898 * This function mostly follows vm_page_insert() and
1899 * vm_page_remove() without the radix, object count and vnode
1900 * dance. Double check such functions for more comments.
1901 */
1902
1903 mnew->object = object;
1904 mnew->pindex = pindex;
1905 atomic_set_int(&mnew->ref_count, VPRC_OBJREF);
1906 mret = vm_radix_replace(&object->rtree, mnew);
1907 KASSERT(mret == mold,
1908 ("invalid page replacement, mold=%p, mret=%p", mold, mret));
1909 KASSERT((mold->oflags & VPO_UNMANAGED) ==
1910 (mnew->oflags & VPO_UNMANAGED),
1911 ("vm_page_replace: mismatched VPO_UNMANAGED"));
1912
1913 mold->object = NULL;
1914
1915 /*
1916 * The object's resident_page_count does not change because we have
1917 * swapped one page for another, but the generation count should
1918 * change if the page is dirty.
1919 */
1920 if (pmap_page_is_write_mapped(mnew))
1921 vm_object_set_writeable_dirty(object);
1922 dropped = vm_page_drop(mold, VPRC_OBJREF) == VPRC_OBJREF;
1923 vm_page_xunbusy(mold);
1924
1925 return (dropped);
1926 }
1927
1928 void
vm_page_replace(vm_page_t mnew,vm_object_t object,vm_pindex_t pindex,vm_page_t mold)1929 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
1930 vm_page_t mold)
1931 {
1932
1933 vm_page_assert_xbusied(mnew);
1934
1935 if (vm_page_replace_hold(mnew, object, pindex, mold))
1936 vm_page_free(mold);
1937 }
1938
1939 /*
1940 * vm_page_iter_rename:
1941 *
1942 * Tries to move the specified page from its current object to a new object
1943 * and pindex, using the given iterator to remove the page from its current
1944 * object. Returns true if the move was successful, and false if the move
1945 * was aborted due to a failed memory allocation.
1946 *
1947 * Panics if a page already resides in the new object at the new pindex.
1948 *
1949 * This routine dirties the page if it is valid, as callers are expected to
1950 * transfer backing storage only after moving the page. Dirtying the page
1951 * ensures that the destination object retains the most recent copy of the
1952 * page.
1953 *
1954 * The objects must be locked.
1955 */
1956 bool
vm_page_iter_rename(struct pctrie_iter * old_pages,vm_page_t m,vm_object_t new_object,vm_pindex_t new_pindex)1957 vm_page_iter_rename(struct pctrie_iter *old_pages, vm_page_t m,
1958 vm_object_t new_object, vm_pindex_t new_pindex)
1959 {
1960 vm_pindex_t opidx;
1961
1962 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
1963 ("%s: page %p is missing object ref", __func__, m));
1964 VM_OBJECT_ASSERT_WLOCKED(m->object);
1965 VM_OBJECT_ASSERT_WLOCKED(new_object);
1966
1967 /*
1968 * Create a custom version of vm_page_insert() which does not depend
1969 * by m_prev and can cheat on the implementation aspects of the
1970 * function.
1971 */
1972 opidx = m->pindex;
1973 m->pindex = new_pindex;
1974 if (vm_radix_insert(&new_object->rtree, m) != 0) {
1975 m->pindex = opidx;
1976 return (false);
1977 }
1978
1979 /*
1980 * The operation cannot fail anymore.
1981 */
1982 m->pindex = opidx;
1983 vm_radix_iter_remove(old_pages);
1984 vm_page_remove_radixdone(m);
1985
1986 /* Return back to the new pindex to complete vm_page_insert(). */
1987 m->pindex = new_pindex;
1988 m->object = new_object;
1989
1990 vm_page_insert_radixdone(m, new_object);
1991 if (vm_page_any_valid(m))
1992 vm_page_dirty(m);
1993 vm_pager_page_inserted(new_object, m);
1994 return (true);
1995 }
1996
1997 /*
1998 * vm_page_alloc:
1999 *
2000 * Allocate and return a page that is associated with the specified
2001 * object and offset pair. By default, this page is exclusive busied.
2002 *
2003 * The caller must always specify an allocation class.
2004 *
2005 * allocation classes:
2006 * VM_ALLOC_NORMAL normal process request
2007 * VM_ALLOC_SYSTEM system *really* needs a page
2008 * VM_ALLOC_INTERRUPT interrupt time request
2009 *
2010 * optional allocation flags:
2011 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2012 * intends to allocate
2013 * VM_ALLOC_NOBUSY do not exclusive busy the page
2014 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
2015 * VM_ALLOC_NOFREE page will never be freed
2016 * VM_ALLOC_NOWAIT ignored (default behavior)
2017 * VM_ALLOC_SBUSY shared busy the allocated page
2018 * VM_ALLOC_WAITFAIL in case of failure, sleep before returning
2019 * VM_ALLOC_WIRED wire the allocated page
2020 * VM_ALLOC_ZERO prefer a zeroed page
2021 */
2022 vm_page_t
vm_page_alloc(vm_object_t object,vm_pindex_t pindex,int req)2023 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
2024 {
2025 struct pctrie_iter pages;
2026
2027 vm_page_iter_init(&pages, object);
2028 return (vm_page_alloc_iter(object, pindex, req, &pages));
2029 }
2030
2031 /*
2032 * Allocate a page in the specified object with the given page index. If the
2033 * object lock is dropped and regained, the pages iter is reset.
2034 */
2035 vm_page_t
vm_page_alloc_iter(vm_object_t object,vm_pindex_t pindex,int req,struct pctrie_iter * pages)2036 vm_page_alloc_iter(vm_object_t object, vm_pindex_t pindex, int req,
2037 struct pctrie_iter *pages)
2038 {
2039 struct vm_domainset_iter di;
2040 vm_page_t m;
2041 int domain;
2042
2043 if (vm_domainset_iter_page_init(&di, object, pindex, &domain, &req) != 0)
2044 return (NULL);
2045
2046 do {
2047 m = vm_page_alloc_domain_iter(object, pindex, domain, req,
2048 pages);
2049 if (m != NULL)
2050 break;
2051 } while (vm_domainset_iter_page(&di, object, &domain, pages) == 0);
2052
2053 return (m);
2054 }
2055
2056 /*
2057 * Returns true if the number of free pages exceeds the minimum
2058 * for the request class and false otherwise.
2059 */
2060 static int
_vm_domain_allocate(struct vm_domain * vmd,int req_class,int npages)2061 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
2062 {
2063 u_int limit, old, new;
2064
2065 if (req_class == VM_ALLOC_INTERRUPT)
2066 limit = 0;
2067 else if (req_class == VM_ALLOC_SYSTEM)
2068 limit = vmd->vmd_interrupt_free_min;
2069 else
2070 limit = vmd->vmd_free_reserved;
2071
2072 /*
2073 * Attempt to reserve the pages. Fail if we're below the limit.
2074 */
2075 limit += npages;
2076 old = atomic_load_int(&vmd->vmd_free_count);
2077 do {
2078 if (old < limit)
2079 return (0);
2080 new = old - npages;
2081 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
2082
2083 /* Wake the page daemon if we've crossed the threshold. */
2084 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
2085 pagedaemon_wakeup(vmd->vmd_domain);
2086
2087 /* Only update bitsets on transitions. */
2088 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
2089 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
2090 vm_domain_set(vmd);
2091
2092 return (1);
2093 }
2094
2095 int
vm_domain_allocate(struct vm_domain * vmd,int req,int npages)2096 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
2097 {
2098 int req_class;
2099
2100 /*
2101 * The page daemon is allowed to dig deeper into the free page list.
2102 */
2103 req_class = req & VM_ALLOC_CLASS_MASK;
2104 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2105 req_class = VM_ALLOC_SYSTEM;
2106 return (_vm_domain_allocate(vmd, req_class, npages));
2107 }
2108
2109 vm_page_t
vm_page_alloc_domain_iter(vm_object_t object,vm_pindex_t pindex,int domain,int req,struct pctrie_iter * pages)2110 vm_page_alloc_domain_iter(vm_object_t object, vm_pindex_t pindex, int domain,
2111 int req, struct pctrie_iter *pages)
2112 {
2113 struct vm_domain *vmd;
2114 vm_page_t m;
2115 int flags;
2116
2117 #define VM_ALLOC_COMMON (VM_ALLOC_CLASS_MASK | VM_ALLOC_NODUMP | \
2118 VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | \
2119 VM_ALLOC_WIRED | VM_ALLOC_ZERO)
2120 #define VPA_FLAGS (VM_ALLOC_COMMON | VM_ALLOC_COUNT_MASK | \
2121 VM_ALLOC_NOBUSY | VM_ALLOC_NOFREE | \
2122 VM_ALLOC_SBUSY)
2123 KASSERT((req & ~VPA_FLAGS) == 0,
2124 ("invalid request %#x", req));
2125 KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2126 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2127 ("invalid request %#x", req));
2128 VM_OBJECT_ASSERT_WLOCKED(object);
2129
2130 flags = 0;
2131 m = NULL;
2132 if (!vm_pager_can_alloc_page(object, pindex))
2133 return (NULL);
2134 #if VM_NRESERVLEVEL > 0
2135 again:
2136 #endif
2137 if (__predict_false((req & VM_ALLOC_NOFREE) != 0)) {
2138 m = vm_page_alloc_nofree_domain(domain, req);
2139 if (m != NULL)
2140 goto found;
2141 }
2142 #if VM_NRESERVLEVEL > 0
2143 /*
2144 * Can we allocate the page from a reservation?
2145 */
2146 if (vm_object_reserv(object) &&
2147 (m = vm_reserv_alloc_page(object, pindex, domain, req, pages)) !=
2148 NULL) {
2149 goto found;
2150 }
2151 #endif
2152 vmd = VM_DOMAIN(domain);
2153 if (vmd->vmd_pgcache[VM_FREEPOOL_DEFAULT].zone != NULL) {
2154 m = uma_zalloc(vmd->vmd_pgcache[VM_FREEPOOL_DEFAULT].zone,
2155 M_NOWAIT | M_NOVM);
2156 if (m != NULL) {
2157 flags |= PG_PCPU_CACHE;
2158 goto found;
2159 }
2160 }
2161 if (vm_domain_allocate(vmd, req, 1)) {
2162 /*
2163 * If not, allocate it from the free page queues.
2164 */
2165 vm_domain_free_lock(vmd);
2166 m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DEFAULT, 0);
2167 vm_domain_free_unlock(vmd);
2168 if (m == NULL) {
2169 vm_domain_freecnt_inc(vmd, 1);
2170 #if VM_NRESERVLEVEL > 0
2171 if (vm_reserv_reclaim_inactive(domain))
2172 goto again;
2173 #endif
2174 }
2175 }
2176 if (m == NULL) {
2177 /*
2178 * Not allocatable, give up.
2179 */
2180 (void)vm_domain_alloc_fail(vmd, object, req);
2181 if ((req & VM_ALLOC_WAITFAIL) != 0)
2182 pctrie_iter_reset(pages);
2183 return (NULL);
2184 }
2185
2186 /*
2187 * At this point we had better have found a good page.
2188 */
2189 found:
2190 vm_page_dequeue(m);
2191 vm_page_alloc_check(m);
2192
2193 /*
2194 * Initialize the page. Only the PG_ZERO flag is inherited.
2195 */
2196 flags |= m->flags & PG_ZERO;
2197 if ((req & VM_ALLOC_NODUMP) != 0)
2198 flags |= PG_NODUMP;
2199 if ((req & VM_ALLOC_NOFREE) != 0)
2200 flags |= PG_NOFREE;
2201 m->flags = flags;
2202 m->a.flags = 0;
2203 m->oflags = (object->flags & OBJ_UNMANAGED) != 0 ? VPO_UNMANAGED : 0;
2204 m->pool = VM_FREEPOOL_DEFAULT;
2205 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2206 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2207 else if ((req & VM_ALLOC_SBUSY) != 0)
2208 m->busy_lock = VPB_SHARERS_WORD(1);
2209 else
2210 m->busy_lock = VPB_UNBUSIED;
2211 if (req & VM_ALLOC_WIRED) {
2212 vm_wire_add(1);
2213 m->ref_count = 1;
2214 }
2215 m->a.act_count = 0;
2216
2217 if (vm_page_iter_insert(m, object, pindex, pages)) {
2218 if (req & VM_ALLOC_WIRED) {
2219 vm_wire_sub(1);
2220 m->ref_count = 0;
2221 }
2222 KASSERT(m->object == NULL, ("page %p has object", m));
2223 m->oflags = VPO_UNMANAGED;
2224 m->busy_lock = VPB_UNBUSIED;
2225 /* Don't change PG_ZERO. */
2226 vm_page_free_toq(m);
2227 if (req & VM_ALLOC_WAITFAIL) {
2228 VM_OBJECT_WUNLOCK(object);
2229 vm_radix_wait();
2230 pctrie_iter_reset(pages);
2231 VM_OBJECT_WLOCK(object);
2232 }
2233 return (NULL);
2234 }
2235
2236 /* Ignore device objects; the pager sets "memattr" for them. */
2237 if (object->memattr != VM_MEMATTR_DEFAULT &&
2238 (object->flags & OBJ_FICTITIOUS) == 0)
2239 pmap_page_set_memattr(m, object->memattr);
2240
2241 return (m);
2242 }
2243
2244 /*
2245 * vm_page_alloc_contig:
2246 *
2247 * Allocate a contiguous set of physical pages of the given size "npages"
2248 * from the free lists. All of the physical pages must be at or above
2249 * the given physical address "low" and below the given physical address
2250 * "high". The given value "alignment" determines the alignment of the
2251 * first physical page in the set. If the given value "boundary" is
2252 * non-zero, then the set of physical pages cannot cross any physical
2253 * address boundary that is a multiple of that value. Both "alignment"
2254 * and "boundary" must be a power of two.
2255 *
2256 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2257 * then the memory attribute setting for the physical pages is configured
2258 * to the object's memory attribute setting. Otherwise, the memory
2259 * attribute setting for the physical pages is configured to "memattr",
2260 * overriding the object's memory attribute setting. However, if the
2261 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2262 * memory attribute setting for the physical pages cannot be configured
2263 * to VM_MEMATTR_DEFAULT.
2264 *
2265 * The specified object may not contain fictitious pages.
2266 *
2267 * The caller must always specify an allocation class.
2268 *
2269 * allocation classes:
2270 * VM_ALLOC_NORMAL normal process request
2271 * VM_ALLOC_SYSTEM system *really* needs the pages
2272 * VM_ALLOC_INTERRUPT interrupt time request
2273 *
2274 * optional allocation flags:
2275 * VM_ALLOC_NOBUSY do not exclusive busy the pages
2276 * VM_ALLOC_NODUMP do not include the pages in a kernel core dump
2277 * VM_ALLOC_NORECLAIM do not reclaim after initial failure
2278 * VM_ALLOC_NOWAIT ignored (default behavior)
2279 * VM_ALLOC_SBUSY shared busy the allocated pages
2280 * VM_ALLOC_WAITFAIL in case of failure, sleep before returning
2281 * VM_ALLOC_WIRED wire the allocated pages
2282 * VM_ALLOC_ZERO prefer zeroed pages
2283 */
2284 vm_page_t
vm_page_alloc_contig(vm_object_t object,vm_pindex_t pindex,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary,vm_memattr_t memattr)2285 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2286 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2287 vm_paddr_t boundary, vm_memattr_t memattr)
2288 {
2289 struct vm_domainset_iter di;
2290 vm_page_t bounds[2];
2291 vm_page_t m;
2292 int domain;
2293 int start_segind;
2294
2295 start_segind = -1;
2296
2297 if (vm_domainset_iter_page_init(&di, object, pindex, &domain, &req) != 0)
2298 return (NULL);
2299
2300 do {
2301 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2302 npages, low, high, alignment, boundary, memattr);
2303 if (m != NULL)
2304 break;
2305 if (start_segind == -1)
2306 start_segind = vm_phys_lookup_segind(low);
2307 if (vm_phys_find_range(bounds, start_segind, domain,
2308 npages, low, high) == -1) {
2309 vm_domainset_iter_ignore(&di, domain);
2310 }
2311 } while (vm_domainset_iter_page(&di, object, &domain, NULL) == 0);
2312
2313 return (m);
2314 }
2315
2316 static vm_page_t
vm_page_find_contig_domain(int domain,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary)2317 vm_page_find_contig_domain(int domain, int req, u_long npages, vm_paddr_t low,
2318 vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2319 {
2320 struct vm_domain *vmd;
2321 vm_page_t m_ret;
2322
2323 /*
2324 * Can we allocate the pages without the number of free pages falling
2325 * below the lower bound for the allocation class?
2326 */
2327 vmd = VM_DOMAIN(domain);
2328 if (!vm_domain_allocate(vmd, req, npages))
2329 return (NULL);
2330 /*
2331 * Try to allocate the pages from the free page queues.
2332 */
2333 vm_domain_free_lock(vmd);
2334 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2335 alignment, boundary);
2336 vm_domain_free_unlock(vmd);
2337 if (m_ret != NULL)
2338 return (m_ret);
2339 #if VM_NRESERVLEVEL > 0
2340 /*
2341 * Try to break a reservation to allocate the pages.
2342 */
2343 if ((req & VM_ALLOC_NORECLAIM) == 0) {
2344 m_ret = vm_reserv_reclaim_contig(domain, npages, low,
2345 high, alignment, boundary);
2346 if (m_ret != NULL)
2347 return (m_ret);
2348 }
2349 #endif
2350 vm_domain_freecnt_inc(vmd, npages);
2351 return (NULL);
2352 }
2353
2354 vm_page_t
vm_page_alloc_contig_domain(vm_object_t object,vm_pindex_t pindex,int domain,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary,vm_memattr_t memattr)2355 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2356 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2357 vm_paddr_t boundary, vm_memattr_t memattr)
2358 {
2359 struct pctrie_iter pages;
2360 vm_page_t m, m_ret, mpred;
2361 u_int busy_lock, flags, oflags;
2362
2363 #define VPAC_FLAGS (VM_ALLOC_COMMON | VM_ALLOC_COUNT_MASK | \
2364 VM_ALLOC_NOBUSY | VM_ALLOC_NORECLAIM | \
2365 VM_ALLOC_SBUSY)
2366 KASSERT((req & ~VPAC_FLAGS) == 0,
2367 ("invalid request %#x", req));
2368 KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2369 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2370 ("invalid request %#x", req));
2371 VM_OBJECT_ASSERT_WLOCKED(object);
2372 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2373 ("vm_page_alloc_contig: object %p has fictitious pages",
2374 object));
2375 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2376
2377 vm_page_iter_init(&pages, object);
2378 m_ret = NULL;
2379 #if VM_NRESERVLEVEL > 0
2380 /*
2381 * Can we allocate the pages from a reservation?
2382 */
2383 if (vm_object_reserv(object)) {
2384 m_ret = vm_reserv_alloc_contig(object, pindex, domain,
2385 req, npages, low, high, alignment, boundary, &pages);
2386 }
2387 #endif
2388 if (m_ret == NULL) {
2389 m_ret = vm_page_find_contig_domain(domain, req, npages,
2390 low, high, alignment, boundary);
2391 }
2392 if (m_ret == NULL) {
2393 (void)vm_domain_alloc_fail(VM_DOMAIN(domain), object, req);
2394 return (NULL);
2395 }
2396
2397 /*
2398 * Initialize the pages. Only the PG_ZERO flag is inherited.
2399 */
2400 flags = PG_ZERO;
2401 if ((req & VM_ALLOC_NODUMP) != 0)
2402 flags |= PG_NODUMP;
2403 oflags = (object->flags & OBJ_UNMANAGED) != 0 ? VPO_UNMANAGED : 0;
2404 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2405 busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2406 else if ((req & VM_ALLOC_SBUSY) != 0)
2407 busy_lock = VPB_SHARERS_WORD(1);
2408 else
2409 busy_lock = VPB_UNBUSIED;
2410 if ((req & VM_ALLOC_WIRED) != 0)
2411 vm_wire_add(npages);
2412 if (object->memattr != VM_MEMATTR_DEFAULT &&
2413 memattr == VM_MEMATTR_DEFAULT)
2414 memattr = object->memattr;
2415 for (m = m_ret; m < &m_ret[npages]; m++) {
2416 vm_page_dequeue(m);
2417 vm_page_alloc_check(m);
2418 m->a.flags = 0;
2419 m->flags = (m->flags | PG_NODUMP) & flags;
2420 m->busy_lock = busy_lock;
2421 if ((req & VM_ALLOC_WIRED) != 0)
2422 m->ref_count = 1;
2423 m->a.act_count = 0;
2424 m->oflags = oflags;
2425 m->pool = VM_FREEPOOL_DEFAULT;
2426 if (vm_page_iter_insert(m, object, pindex, &pages)) {
2427 if ((req & VM_ALLOC_WIRED) != 0)
2428 vm_wire_sub(npages);
2429 KASSERT(m->object == NULL,
2430 ("page %p has object", m));
2431 mpred = m;
2432 for (m = m_ret; m < &m_ret[npages]; m++) {
2433 if (m <= mpred &&
2434 (req & VM_ALLOC_WIRED) != 0)
2435 m->ref_count = 0;
2436 m->oflags = VPO_UNMANAGED;
2437 m->busy_lock = VPB_UNBUSIED;
2438 /* Don't change PG_ZERO. */
2439 vm_page_free_toq(m);
2440 }
2441 if (req & VM_ALLOC_WAITFAIL) {
2442 VM_OBJECT_WUNLOCK(object);
2443 vm_radix_wait();
2444 VM_OBJECT_WLOCK(object);
2445 }
2446 return (NULL);
2447 }
2448 if (memattr != VM_MEMATTR_DEFAULT)
2449 pmap_page_set_memattr(m, memattr);
2450 pindex++;
2451 }
2452 return (m_ret);
2453 }
2454
2455 /*
2456 * Allocate a physical page that is not intended to be inserted into a VM
2457 * object.
2458 */
2459 vm_page_t
vm_page_alloc_noobj_domain(int domain,int req)2460 vm_page_alloc_noobj_domain(int domain, int req)
2461 {
2462 struct vm_domain *vmd;
2463 vm_page_t m;
2464 int flags;
2465
2466 #define VPAN_FLAGS (VM_ALLOC_COMMON | VM_ALLOC_COUNT_MASK | \
2467 VM_ALLOC_NOFREE | VM_ALLOC_WAITOK)
2468 KASSERT((req & ~VPAN_FLAGS) == 0,
2469 ("invalid request %#x", req));
2470
2471 flags = ((req & VM_ALLOC_NODUMP) != 0 ? PG_NODUMP : 0) |
2472 ((req & VM_ALLOC_NOFREE) != 0 ? PG_NOFREE : 0);
2473 vmd = VM_DOMAIN(domain);
2474 again:
2475 if (__predict_false((req & VM_ALLOC_NOFREE) != 0)) {
2476 m = vm_page_alloc_nofree_domain(domain, req);
2477 if (m != NULL)
2478 goto found;
2479 }
2480
2481 if (vmd->vmd_pgcache[VM_FREEPOOL_DIRECT].zone != NULL) {
2482 m = uma_zalloc(vmd->vmd_pgcache[VM_FREEPOOL_DIRECT].zone,
2483 M_NOWAIT | M_NOVM);
2484 if (m != NULL) {
2485 flags |= PG_PCPU_CACHE;
2486 goto found;
2487 }
2488 }
2489
2490 if (vm_domain_allocate(vmd, req, 1)) {
2491 vm_domain_free_lock(vmd);
2492 m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DIRECT, 0);
2493 vm_domain_free_unlock(vmd);
2494 if (m == NULL) {
2495 vm_domain_freecnt_inc(vmd, 1);
2496 #if VM_NRESERVLEVEL > 0
2497 if (vm_reserv_reclaim_inactive(domain))
2498 goto again;
2499 #endif
2500 }
2501 }
2502 if (m == NULL) {
2503 if (!vm_domain_alloc_fail(vmd, NULL, req))
2504 return (NULL);
2505 goto again;
2506 }
2507
2508 found:
2509 /*
2510 * If the page comes from the free page cache, then it might still
2511 * have a pending deferred dequeue. Specifically, when the page is
2512 * imported from a different pool by vm_phys_alloc_npages(), the
2513 * second, third, etc. pages in a non-zero order set could have
2514 * pending deferred dequeues.
2515 */
2516 vm_page_dequeue(m);
2517 vm_page_alloc_check(m);
2518
2519 /*
2520 * Consumers should not rely on a useful default pindex value.
2521 */
2522 m->pindex = 0xdeadc0dedeadc0de;
2523 m->flags = (m->flags & PG_ZERO) | flags;
2524 m->a.flags = 0;
2525 m->oflags = VPO_UNMANAGED;
2526 m->pool = VM_FREEPOOL_DIRECT;
2527 m->busy_lock = VPB_UNBUSIED;
2528 if ((req & VM_ALLOC_WIRED) != 0) {
2529 vm_wire_add(1);
2530 m->ref_count = 1;
2531 }
2532
2533 if ((req & VM_ALLOC_ZERO) != 0 && (m->flags & PG_ZERO) == 0)
2534 pmap_zero_page(m);
2535
2536 return (m);
2537 }
2538
2539 #if VM_NRESERVLEVEL > 1
2540 #define VM_NOFREE_IMPORT_ORDER (VM_LEVEL_1_ORDER + VM_LEVEL_0_ORDER)
2541 #elif VM_NRESERVLEVEL > 0
2542 #define VM_NOFREE_IMPORT_ORDER VM_LEVEL_0_ORDER
2543 #else
2544 #define VM_NOFREE_IMPORT_ORDER 8
2545 #endif
2546
2547 /*
2548 * Allocate a single NOFREE page.
2549 *
2550 * This routine hands out NOFREE pages from higher-order
2551 * physical memory blocks in order to reduce memory fragmentation.
2552 * When a NOFREE for a given domain chunk is used up,
2553 * the routine will try to fetch a new one from the freelists
2554 * and discard the old one.
2555 */
2556 static vm_page_t __noinline
vm_page_alloc_nofree_domain(int domain,int req)2557 vm_page_alloc_nofree_domain(int domain, int req)
2558 {
2559 vm_page_t m;
2560 struct vm_domain *vmd;
2561
2562 KASSERT((req & VM_ALLOC_NOFREE) != 0, ("invalid request %#x", req));
2563
2564 vmd = VM_DOMAIN(domain);
2565 vm_domain_free_lock(vmd);
2566 if (TAILQ_EMPTY(&vmd->vmd_nofreeq)) {
2567 int count;
2568
2569 count = 1 << VM_NOFREE_IMPORT_ORDER;
2570 if (!vm_domain_allocate(vmd, req, count)) {
2571 vm_domain_free_unlock(vmd);
2572 return (NULL);
2573 }
2574 m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DEFAULT,
2575 VM_NOFREE_IMPORT_ORDER);
2576 if (m == NULL) {
2577 vm_domain_freecnt_inc(vmd, count);
2578 vm_domain_free_unlock(vmd);
2579 return (NULL);
2580 }
2581 m->ref_count = count - 1;
2582 TAILQ_INSERT_HEAD(&vmd->vmd_nofreeq, m, plinks.q);
2583 atomic_add_long(&nofreeq_size, count);
2584 }
2585 m = TAILQ_FIRST(&vmd->vmd_nofreeq);
2586 TAILQ_REMOVE(&vmd->vmd_nofreeq, m, plinks.q);
2587 if (m->ref_count > 0) {
2588 vm_page_t m_next;
2589
2590 m_next = &m[1];
2591 vm_page_dequeue(m_next);
2592 m_next->ref_count = m->ref_count - 1;
2593 TAILQ_INSERT_HEAD(&vmd->vmd_nofreeq, m_next, plinks.q);
2594 m->ref_count = 0;
2595 }
2596 vm_domain_free_unlock(vmd);
2597 atomic_add_long(&nofreeq_size, -1);
2598 VM_CNT_INC(v_nofree_count);
2599
2600 return (m);
2601 }
2602
2603 /*
2604 * Though a NOFREE page by definition should not be freed, we support putting
2605 * them aside for future NOFREE allocations. This enables code which allocates
2606 * NOFREE pages for some purpose but then encounters an error and releases
2607 * resources.
2608 */
2609 static void __noinline
vm_page_free_nofree(struct vm_domain * vmd,vm_page_t m)2610 vm_page_free_nofree(struct vm_domain *vmd, vm_page_t m)
2611 {
2612 VM_CNT_ADD(v_nofree_count, -1);
2613 atomic_add_long(&nofreeq_size, 1);
2614 vm_domain_free_lock(vmd);
2615 MPASS(m->ref_count == 0);
2616 TAILQ_INSERT_HEAD(&vmd->vmd_nofreeq, m, plinks.q);
2617 vm_domain_free_unlock(vmd);
2618 }
2619
2620 vm_page_t
vm_page_alloc_noobj(int req)2621 vm_page_alloc_noobj(int req)
2622 {
2623 struct vm_domainset_iter di;
2624 vm_page_t m;
2625 int domain;
2626
2627 if (vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req) != 0)
2628 return (NULL);
2629
2630 do {
2631 m = vm_page_alloc_noobj_domain(domain, req);
2632 if (m != NULL)
2633 break;
2634 } while (vm_domainset_iter_page(&di, NULL, &domain, NULL) == 0);
2635
2636 return (m);
2637 }
2638
2639 vm_page_t
vm_page_alloc_noobj_contig(int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary,vm_memattr_t memattr)2640 vm_page_alloc_noobj_contig(int req, u_long npages, vm_paddr_t low,
2641 vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
2642 vm_memattr_t memattr)
2643 {
2644 struct vm_domainset_iter di;
2645 vm_page_t m;
2646 int domain;
2647
2648 if (vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req) != 0)
2649 return (NULL);
2650
2651 do {
2652 m = vm_page_alloc_noobj_contig_domain(domain, req, npages, low,
2653 high, alignment, boundary, memattr);
2654 if (m != NULL)
2655 break;
2656 } while (vm_domainset_iter_page(&di, NULL, &domain, NULL) == 0);
2657
2658 return (m);
2659 }
2660
2661 vm_page_t
vm_page_alloc_noobj_contig_domain(int domain,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary,vm_memattr_t memattr)2662 vm_page_alloc_noobj_contig_domain(int domain, int req, u_long npages,
2663 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
2664 vm_memattr_t memattr)
2665 {
2666 vm_page_t m, m_ret;
2667 u_int flags;
2668
2669 #define VPANC_FLAGS (VM_ALLOC_COMMON | VM_ALLOC_COUNT_MASK | \
2670 VM_ALLOC_NORECLAIM | VM_ALLOC_WAITOK)
2671 KASSERT((req & ~VPANC_FLAGS) == 0,
2672 ("invalid request %#x", req));
2673 KASSERT((req & (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM)) !=
2674 (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM),
2675 ("invalid request %#x", req));
2676 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2677
2678 while ((m_ret = vm_page_find_contig_domain(domain, req, npages,
2679 low, high, alignment, boundary)) == NULL) {
2680 if (!vm_domain_alloc_fail(VM_DOMAIN(domain), NULL, req))
2681 return (NULL);
2682 }
2683
2684 /*
2685 * Initialize the pages. Only the PG_ZERO flag is inherited.
2686 */
2687 flags = PG_ZERO;
2688 if ((req & VM_ALLOC_NODUMP) != 0)
2689 flags |= PG_NODUMP;
2690 if ((req & VM_ALLOC_WIRED) != 0)
2691 vm_wire_add(npages);
2692 for (m = m_ret; m < &m_ret[npages]; m++) {
2693 vm_page_dequeue(m);
2694 vm_page_alloc_check(m);
2695
2696 /*
2697 * Consumers should not rely on a useful default pindex value.
2698 */
2699 m->pindex = 0xdeadc0dedeadc0de;
2700 m->a.flags = 0;
2701 m->flags = (m->flags | PG_NODUMP) & flags;
2702 m->busy_lock = VPB_UNBUSIED;
2703 if ((req & VM_ALLOC_WIRED) != 0)
2704 m->ref_count = 1;
2705 m->a.act_count = 0;
2706 m->oflags = VPO_UNMANAGED;
2707 m->pool = VM_FREEPOOL_DIRECT;
2708
2709 /*
2710 * Zero the page before updating any mappings since the page is
2711 * not yet shared with any devices which might require the
2712 * non-default memory attribute. pmap_page_set_memattr()
2713 * flushes data caches before returning.
2714 */
2715 if ((req & VM_ALLOC_ZERO) != 0 && (m->flags & PG_ZERO) == 0)
2716 pmap_zero_page(m);
2717 if (memattr != VM_MEMATTR_DEFAULT)
2718 pmap_page_set_memattr(m, memattr);
2719 }
2720 return (m_ret);
2721 }
2722
2723 /*
2724 * Check a page that has been freshly dequeued from a freelist.
2725 */
2726 static void
vm_page_alloc_check(vm_page_t m)2727 vm_page_alloc_check(vm_page_t m)
2728 {
2729
2730 KASSERT(m->object == NULL, ("page %p has object", m));
2731 KASSERT(m->a.queue == PQ_NONE &&
2732 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
2733 ("page %p has unexpected queue %d, flags %#x",
2734 m, m->a.queue, (m->a.flags & PGA_QUEUE_STATE_MASK)));
2735 KASSERT(m->ref_count == 0, ("page %p has references", m));
2736 KASSERT(vm_page_busy_freed(m), ("page %p is not freed", m));
2737 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2738 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2739 ("page %p has unexpected memattr %d",
2740 m, pmap_page_get_memattr(m)));
2741 KASSERT(vm_page_none_valid(m), ("free page %p is valid", m));
2742 pmap_vm_page_alloc_check(m);
2743 }
2744
2745 static int
vm_page_zone_import(void * arg,void ** store,int cnt,int domain,int flags)2746 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2747 {
2748 struct vm_domain *vmd;
2749 struct vm_pgcache *pgcache;
2750 int i;
2751
2752 pgcache = arg;
2753 vmd = VM_DOMAIN(pgcache->domain);
2754
2755 /*
2756 * The page daemon should avoid creating extra memory pressure since its
2757 * main purpose is to replenish the store of free pages.
2758 */
2759 if (vmd->vmd_severeset || curproc == pageproc ||
2760 !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2761 return (0);
2762 domain = vmd->vmd_domain;
2763 vm_domain_free_lock(vmd);
2764 i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2765 (vm_page_t *)store);
2766 vm_domain_free_unlock(vmd);
2767 if (cnt != i)
2768 vm_domain_freecnt_inc(vmd, cnt - i);
2769
2770 return (i);
2771 }
2772
2773 static void
vm_page_zone_release(void * arg,void ** store,int cnt)2774 vm_page_zone_release(void *arg, void **store, int cnt)
2775 {
2776 struct vm_domain *vmd;
2777 struct vm_pgcache *pgcache;
2778 vm_page_t m;
2779 int i;
2780
2781 pgcache = arg;
2782 vmd = VM_DOMAIN(pgcache->domain);
2783 vm_domain_free_lock(vmd);
2784 for (i = 0; i < cnt; i++) {
2785 m = (vm_page_t)store[i];
2786 vm_phys_free_pages(m, pgcache->pool, 0);
2787 }
2788 vm_domain_free_unlock(vmd);
2789 vm_domain_freecnt_inc(vmd, cnt);
2790 }
2791
2792 #define VPSC_ANY 0 /* No restrictions. */
2793 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2794 #define VPSC_NOSUPER 2 /* Skip superpages. */
2795
2796 /*
2797 * vm_page_scan_contig:
2798 *
2799 * Scan vm_page_array[] between the specified entries "m_start" and
2800 * "m_end" for a run of contiguous physical pages that satisfy the
2801 * specified conditions, and return the lowest page in the run. The
2802 * specified "alignment" determines the alignment of the lowest physical
2803 * page in the run. If the specified "boundary" is non-zero, then the
2804 * run of physical pages cannot span a physical address that is a
2805 * multiple of "boundary".
2806 *
2807 * "m_end" is never dereferenced, so it need not point to a vm_page
2808 * structure within vm_page_array[].
2809 *
2810 * "npages" must be greater than zero. "m_start" and "m_end" must not
2811 * span a hole (or discontiguity) in the physical address space. Both
2812 * "alignment" and "boundary" must be a power of two.
2813 */
2814 static vm_page_t
vm_page_scan_contig(u_long npages,vm_page_t m_start,vm_page_t m_end,u_long alignment,vm_paddr_t boundary,int options)2815 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2816 u_long alignment, vm_paddr_t boundary, int options)
2817 {
2818 vm_object_t object;
2819 vm_paddr_t pa;
2820 vm_page_t m, m_run;
2821 #if VM_NRESERVLEVEL > 0
2822 int level;
2823 #endif
2824 int m_inc, order, run_ext, run_len;
2825
2826 KASSERT(npages > 0, ("npages is 0"));
2827 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2828 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2829 m_run = NULL;
2830 run_len = 0;
2831 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2832 KASSERT((m->flags & PG_MARKER) == 0,
2833 ("page %p is PG_MARKER", m));
2834 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2835 ("fictitious page %p has invalid ref count", m));
2836
2837 /*
2838 * If the current page would be the start of a run, check its
2839 * physical address against the end, alignment, and boundary
2840 * conditions. If it doesn't satisfy these conditions, either
2841 * terminate the scan or advance to the next page that
2842 * satisfies the failed condition.
2843 */
2844 if (run_len == 0) {
2845 KASSERT(m_run == NULL, ("m_run != NULL"));
2846 if (m + npages > m_end)
2847 break;
2848 pa = VM_PAGE_TO_PHYS(m);
2849 if (!vm_addr_align_ok(pa, alignment)) {
2850 m_inc = atop(roundup2(pa, alignment) - pa);
2851 continue;
2852 }
2853 if (!vm_addr_bound_ok(pa, ptoa(npages), boundary)) {
2854 m_inc = atop(roundup2(pa, boundary) - pa);
2855 continue;
2856 }
2857 } else
2858 KASSERT(m_run != NULL, ("m_run == NULL"));
2859
2860 retry:
2861 m_inc = 1;
2862 if (vm_page_wired(m))
2863 run_ext = 0;
2864 #if VM_NRESERVLEVEL > 0
2865 else if ((level = vm_reserv_level(m)) >= 0 &&
2866 (options & VPSC_NORESERV) != 0) {
2867 run_ext = 0;
2868 /* Advance to the end of the reservation. */
2869 pa = VM_PAGE_TO_PHYS(m);
2870 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2871 pa);
2872 }
2873 #endif
2874 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2875 /*
2876 * The page is considered eligible for relocation if
2877 * and only if it could be laundered or reclaimed by
2878 * the page daemon.
2879 */
2880 VM_OBJECT_RLOCK(object);
2881 if (object != m->object) {
2882 VM_OBJECT_RUNLOCK(object);
2883 goto retry;
2884 }
2885 /* Don't care: PG_NODUMP, PG_ZERO. */
2886 if ((object->flags & OBJ_SWAP) == 0 &&
2887 object->type != OBJT_VNODE) {
2888 run_ext = 0;
2889 #if VM_NRESERVLEVEL > 0
2890 } else if ((options & VPSC_NOSUPER) != 0 &&
2891 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2892 run_ext = 0;
2893 /* Advance to the end of the superpage. */
2894 pa = VM_PAGE_TO_PHYS(m);
2895 m_inc = atop(roundup2(pa + 1,
2896 vm_reserv_size(level)) - pa);
2897 #endif
2898 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2899 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2900 /*
2901 * The page is allocated but eligible for
2902 * relocation. Extend the current run by one
2903 * page.
2904 */
2905 KASSERT(pmap_page_get_memattr(m) ==
2906 VM_MEMATTR_DEFAULT,
2907 ("page %p has an unexpected memattr", m));
2908 KASSERT((m->oflags & (VPO_SWAPINPROG |
2909 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2910 ("page %p has unexpected oflags", m));
2911 /* Don't care: PGA_NOSYNC. */
2912 run_ext = 1;
2913 } else
2914 run_ext = 0;
2915 VM_OBJECT_RUNLOCK(object);
2916 #if VM_NRESERVLEVEL > 0
2917 } else if (level >= 0) {
2918 /*
2919 * The page is reserved but not yet allocated. In
2920 * other words, it is still free. Extend the current
2921 * run by one page.
2922 */
2923 run_ext = 1;
2924 #endif
2925 } else if ((order = m->order) < VM_NFREEORDER) {
2926 /*
2927 * The page is enqueued in the physical memory
2928 * allocator's free page queues. Moreover, it is the
2929 * first page in a power-of-two-sized run of
2930 * contiguous free pages. Add these pages to the end
2931 * of the current run, and jump ahead.
2932 */
2933 run_ext = 1 << order;
2934 m_inc = 1 << order;
2935 } else {
2936 /*
2937 * Skip the page for one of the following reasons: (1)
2938 * It is enqueued in the physical memory allocator's
2939 * free page queues. However, it is not the first
2940 * page in a run of contiguous free pages. (This case
2941 * rarely occurs because the scan is performed in
2942 * ascending order.) (2) It is not reserved, and it is
2943 * transitioning from free to allocated. (Conversely,
2944 * the transition from allocated to free for managed
2945 * pages is blocked by the page busy lock.) (3) It is
2946 * allocated but not contained by an object and not
2947 * wired, e.g., allocated by Xen's balloon driver.
2948 */
2949 run_ext = 0;
2950 }
2951
2952 /*
2953 * Extend or reset the current run of pages.
2954 */
2955 if (run_ext > 0) {
2956 if (run_len == 0)
2957 m_run = m;
2958 run_len += run_ext;
2959 } else {
2960 if (run_len > 0) {
2961 m_run = NULL;
2962 run_len = 0;
2963 }
2964 }
2965 }
2966 if (run_len >= npages)
2967 return (m_run);
2968 return (NULL);
2969 }
2970
2971 /*
2972 * vm_page_reclaim_run:
2973 *
2974 * Try to relocate each of the allocated virtual pages within the
2975 * specified run of physical pages to a new physical address. Free the
2976 * physical pages underlying the relocated virtual pages. A virtual page
2977 * is relocatable if and only if it could be laundered or reclaimed by
2978 * the page daemon. Whenever possible, a virtual page is relocated to a
2979 * physical address above "high".
2980 *
2981 * Returns 0 if every physical page within the run was already free or
2982 * just freed by a successful relocation. Otherwise, returns a non-zero
2983 * value indicating why the last attempt to relocate a virtual page was
2984 * unsuccessful.
2985 *
2986 * "req_class" must be an allocation class.
2987 */
2988 static int
vm_page_reclaim_run(int req_class,int domain,u_long npages,vm_page_t m_run,vm_paddr_t high)2989 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
2990 vm_paddr_t high)
2991 {
2992 struct vm_domain *vmd;
2993 struct spglist free;
2994 vm_object_t object;
2995 vm_paddr_t pa;
2996 vm_page_t m, m_end, m_new;
2997 int error, order, req;
2998
2999 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
3000 ("req_class is not an allocation class"));
3001 SLIST_INIT(&free);
3002 error = 0;
3003 m = m_run;
3004 m_end = m_run + npages;
3005 for (; error == 0 && m < m_end; m++) {
3006 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
3007 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
3008
3009 /*
3010 * Racily check for wirings. Races are handled once the object
3011 * lock is held and the page is unmapped.
3012 */
3013 if (vm_page_wired(m))
3014 error = EBUSY;
3015 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
3016 /*
3017 * The page is relocated if and only if it could be
3018 * laundered or reclaimed by the page daemon.
3019 */
3020 VM_OBJECT_WLOCK(object);
3021 /* Don't care: PG_NODUMP, PG_ZERO. */
3022 if (m->object != object ||
3023 ((object->flags & OBJ_SWAP) == 0 &&
3024 object->type != OBJT_VNODE))
3025 error = EINVAL;
3026 else if (object->memattr != VM_MEMATTR_DEFAULT)
3027 error = EINVAL;
3028 else if (vm_page_queue(m) != PQ_NONE &&
3029 vm_page_tryxbusy(m) != 0) {
3030 if (vm_page_wired(m)) {
3031 vm_page_xunbusy(m);
3032 error = EBUSY;
3033 goto unlock;
3034 }
3035 KASSERT(pmap_page_get_memattr(m) ==
3036 VM_MEMATTR_DEFAULT,
3037 ("page %p has an unexpected memattr", m));
3038 KASSERT(m->oflags == 0,
3039 ("page %p has unexpected oflags", m));
3040 /* Don't care: PGA_NOSYNC. */
3041 if (!vm_page_none_valid(m)) {
3042 /*
3043 * First, try to allocate a new page
3044 * that is above "high". Failing
3045 * that, try to allocate a new page
3046 * that is below "m_run". Allocate
3047 * the new page between the end of
3048 * "m_run" and "high" only as a last
3049 * resort.
3050 */
3051 req = req_class;
3052 if ((m->flags & PG_NODUMP) != 0)
3053 req |= VM_ALLOC_NODUMP;
3054 if (trunc_page(high) !=
3055 ~(vm_paddr_t)PAGE_MASK) {
3056 m_new =
3057 vm_page_alloc_noobj_contig(
3058 req, 1, round_page(high),
3059 ~(vm_paddr_t)0, PAGE_SIZE,
3060 0, VM_MEMATTR_DEFAULT);
3061 } else
3062 m_new = NULL;
3063 if (m_new == NULL) {
3064 pa = VM_PAGE_TO_PHYS(m_run);
3065 m_new =
3066 vm_page_alloc_noobj_contig(
3067 req, 1, 0, pa - 1,
3068 PAGE_SIZE, 0,
3069 VM_MEMATTR_DEFAULT);
3070 }
3071 if (m_new == NULL) {
3072 pa += ptoa(npages);
3073 m_new =
3074 vm_page_alloc_noobj_contig(
3075 req, 1, pa, high, PAGE_SIZE,
3076 0, VM_MEMATTR_DEFAULT);
3077 }
3078 if (m_new == NULL) {
3079 vm_page_xunbusy(m);
3080 error = ENOMEM;
3081 goto unlock;
3082 }
3083
3084 /*
3085 * Unmap the page and check for new
3086 * wirings that may have been acquired
3087 * through a pmap lookup.
3088 */
3089 if (object->ref_count != 0 &&
3090 !vm_page_try_remove_all(m)) {
3091 vm_page_xunbusy(m);
3092 vm_page_free(m_new);
3093 error = EBUSY;
3094 goto unlock;
3095 }
3096
3097 /*
3098 * Replace "m" with the new page. For
3099 * vm_page_replace(), "m" must be busy
3100 * and dequeued. Finally, change "m"
3101 * as if vm_page_free() was called.
3102 */
3103 m_new->a.flags = m->a.flags &
3104 ~PGA_QUEUE_STATE_MASK;
3105 KASSERT(m_new->oflags == VPO_UNMANAGED,
3106 ("page %p is managed", m_new));
3107 m_new->oflags = 0;
3108 pmap_copy_page(m, m_new);
3109 m_new->valid = m->valid;
3110 m_new->dirty = m->dirty;
3111 m->flags &= ~PG_ZERO;
3112 vm_page_dequeue(m);
3113 if (vm_page_replace_hold(m_new, object,
3114 m->pindex, m) &&
3115 vm_page_free_prep(m))
3116 SLIST_INSERT_HEAD(&free, m,
3117 plinks.s.ss);
3118
3119 /*
3120 * The new page must be deactivated
3121 * before the object is unlocked.
3122 */
3123 vm_page_deactivate(m_new);
3124 } else {
3125 m->flags &= ~PG_ZERO;
3126 vm_page_dequeue(m);
3127 if (vm_page_free_prep(m))
3128 SLIST_INSERT_HEAD(&free, m,
3129 plinks.s.ss);
3130 KASSERT(m->dirty == 0,
3131 ("page %p is dirty", m));
3132 }
3133 } else
3134 error = EBUSY;
3135 unlock:
3136 VM_OBJECT_WUNLOCK(object);
3137 } else {
3138 MPASS(vm_page_domain(m) == domain);
3139 vmd = VM_DOMAIN(domain);
3140 vm_domain_free_lock(vmd);
3141 order = m->order;
3142 if (order < VM_NFREEORDER) {
3143 /*
3144 * The page is enqueued in the physical memory
3145 * allocator's free page queues. Moreover, it
3146 * is the first page in a power-of-two-sized
3147 * run of contiguous free pages. Jump ahead
3148 * to the last page within that run, and
3149 * continue from there.
3150 */
3151 m += (1 << order) - 1;
3152 }
3153 #if VM_NRESERVLEVEL > 0
3154 else if (vm_reserv_is_page_free(m))
3155 order = 0;
3156 #endif
3157 vm_domain_free_unlock(vmd);
3158 if (order == VM_NFREEORDER)
3159 error = EINVAL;
3160 }
3161 }
3162 if ((m = SLIST_FIRST(&free)) != NULL) {
3163 int cnt;
3164
3165 vmd = VM_DOMAIN(domain);
3166 cnt = 0;
3167 vm_domain_free_lock(vmd);
3168 do {
3169 MPASS(vm_page_domain(m) == domain);
3170 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3171 vm_phys_free_pages(m, m->pool, 0);
3172 cnt++;
3173 } while ((m = SLIST_FIRST(&free)) != NULL);
3174 vm_domain_free_unlock(vmd);
3175 vm_domain_freecnt_inc(vmd, cnt);
3176 }
3177 return (error);
3178 }
3179
3180 #define NRUNS 16
3181
3182 #define RUN_INDEX(count, nruns) ((count) % (nruns))
3183
3184 #define MIN_RECLAIM 8
3185
3186 /*
3187 * vm_page_reclaim_contig:
3188 *
3189 * Reclaim allocated, contiguous physical memory satisfying the specified
3190 * conditions by relocating the virtual pages using that physical memory.
3191 * Returns 0 if reclamation is successful, ERANGE if the specified domain
3192 * can't possibly satisfy the reclamation request, or ENOMEM if not
3193 * currently able to reclaim the requested number of pages. Since
3194 * relocation requires the allocation of physical pages, reclamation may
3195 * fail with ENOMEM due to a shortage of free pages. When reclamation
3196 * fails in this manner, callers are expected to perform vm_wait() before
3197 * retrying a failed allocation operation, e.g., vm_page_alloc_contig().
3198 *
3199 * The caller must always specify an allocation class through "req".
3200 *
3201 * allocation classes:
3202 * VM_ALLOC_NORMAL normal process request
3203 * VM_ALLOC_SYSTEM system *really* needs a page
3204 * VM_ALLOC_INTERRUPT interrupt time request
3205 *
3206 * The optional allocation flags are ignored.
3207 *
3208 * "npages" must be greater than zero. Both "alignment" and "boundary"
3209 * must be a power of two.
3210 */
3211 int
vm_page_reclaim_contig_domain_ext(int domain,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary,int desired_runs)3212 vm_page_reclaim_contig_domain_ext(int domain, int req, u_long npages,
3213 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
3214 int desired_runs)
3215 {
3216 struct vm_domain *vmd;
3217 vm_page_t bounds[2], m_run, _m_runs[NRUNS], *m_runs;
3218 u_long count, minalign, reclaimed;
3219 int error, i, min_reclaim, nruns, options, req_class;
3220 int segind, start_segind;
3221 int ret;
3222
3223 KASSERT(npages > 0, ("npages is 0"));
3224 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
3225 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
3226
3227 ret = ENOMEM;
3228
3229 /*
3230 * If the caller wants to reclaim multiple runs, try to allocate
3231 * space to store the runs. If that fails, fall back to the old
3232 * behavior of just reclaiming MIN_RECLAIM pages.
3233 */
3234 if (desired_runs > 1)
3235 m_runs = malloc((NRUNS + desired_runs) * sizeof(*m_runs),
3236 M_TEMP, M_NOWAIT);
3237 else
3238 m_runs = NULL;
3239
3240 if (m_runs == NULL) {
3241 m_runs = _m_runs;
3242 nruns = NRUNS;
3243 } else {
3244 nruns = NRUNS + desired_runs - 1;
3245 }
3246 min_reclaim = MAX(desired_runs * npages, MIN_RECLAIM);
3247
3248 /*
3249 * The caller will attempt an allocation after some runs have been
3250 * reclaimed and added to the vm_phys buddy lists. Due to limitations
3251 * of vm_phys_alloc_contig(), round up the requested length to the next
3252 * power of two or maximum chunk size, and ensure that each run is
3253 * suitably aligned.
3254 */
3255 minalign = 1ul << imin(flsl(npages - 1), VM_NFREEORDER - 1);
3256 npages = roundup2(npages, minalign);
3257 if (alignment < ptoa(minalign))
3258 alignment = ptoa(minalign);
3259
3260 /*
3261 * The page daemon is allowed to dig deeper into the free page list.
3262 */
3263 req_class = req & VM_ALLOC_CLASS_MASK;
3264 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
3265 req_class = VM_ALLOC_SYSTEM;
3266
3267 start_segind = vm_phys_lookup_segind(low);
3268
3269 /*
3270 * Return if the number of free pages cannot satisfy the requested
3271 * allocation.
3272 */
3273 vmd = VM_DOMAIN(domain);
3274 count = vmd->vmd_free_count;
3275 if (count < npages + vmd->vmd_free_reserved || (count < npages +
3276 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
3277 (count < npages && req_class == VM_ALLOC_INTERRUPT))
3278 goto done;
3279
3280 /*
3281 * Scan up to three times, relaxing the restrictions ("options") on
3282 * the reclamation of reservations and superpages each time.
3283 */
3284 for (options = VPSC_NORESERV;;) {
3285 bool phys_range_exists = false;
3286
3287 /*
3288 * Find the highest runs that satisfy the given constraints
3289 * and restrictions, and record them in "m_runs".
3290 */
3291 count = 0;
3292 segind = start_segind;
3293 while ((segind = vm_phys_find_range(bounds, segind, domain,
3294 npages, low, high)) != -1) {
3295 phys_range_exists = true;
3296 while ((m_run = vm_page_scan_contig(npages, bounds[0],
3297 bounds[1], alignment, boundary, options))) {
3298 bounds[0] = m_run + npages;
3299 m_runs[RUN_INDEX(count, nruns)] = m_run;
3300 count++;
3301 }
3302 segind++;
3303 }
3304
3305 if (!phys_range_exists) {
3306 ret = ERANGE;
3307 goto done;
3308 }
3309
3310 /*
3311 * Reclaim the highest runs in LIFO (descending) order until
3312 * the number of reclaimed pages, "reclaimed", is at least
3313 * "min_reclaim". Reset "reclaimed" each time because each
3314 * reclamation is idempotent, and runs will (likely) recur
3315 * from one scan to the next as restrictions are relaxed.
3316 */
3317 reclaimed = 0;
3318 for (i = 0; count > 0 && i < nruns; i++) {
3319 count--;
3320 m_run = m_runs[RUN_INDEX(count, nruns)];
3321 error = vm_page_reclaim_run(req_class, domain, npages,
3322 m_run, high);
3323 if (error == 0) {
3324 reclaimed += npages;
3325 if (reclaimed >= min_reclaim) {
3326 ret = 0;
3327 goto done;
3328 }
3329 }
3330 }
3331
3332 /*
3333 * Either relax the restrictions on the next scan or return if
3334 * the last scan had no restrictions.
3335 */
3336 if (options == VPSC_NORESERV)
3337 options = VPSC_NOSUPER;
3338 else if (options == VPSC_NOSUPER)
3339 options = VPSC_ANY;
3340 else if (options == VPSC_ANY) {
3341 if (reclaimed != 0)
3342 ret = 0;
3343 goto done;
3344 }
3345 }
3346 done:
3347 if (m_runs != _m_runs)
3348 free(m_runs, M_TEMP);
3349 return (ret);
3350 }
3351
3352 int
vm_page_reclaim_contig_domain(int domain,int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary)3353 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
3354 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
3355 {
3356 return (vm_page_reclaim_contig_domain_ext(domain, req, npages, low,
3357 high, alignment, boundary, 1));
3358 }
3359
3360 int
vm_page_reclaim_contig(int req,u_long npages,vm_paddr_t low,vm_paddr_t high,u_long alignment,vm_paddr_t boundary)3361 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
3362 u_long alignment, vm_paddr_t boundary)
3363 {
3364 struct vm_domainset_iter di;
3365 int domain, ret, status;
3366
3367 ret = ERANGE;
3368
3369 if (vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req) != 0)
3370 return (ret);
3371
3372 do {
3373 status = vm_page_reclaim_contig_domain(domain, req, npages, low,
3374 high, alignment, boundary);
3375 if (status == 0)
3376 return (0);
3377 else if (status == ERANGE)
3378 vm_domainset_iter_ignore(&di, domain);
3379 else {
3380 KASSERT(status == ENOMEM, ("Unrecognized error %d "
3381 "from vm_page_reclaim_contig_domain()", status));
3382 ret = ENOMEM;
3383 }
3384 } while (vm_domainset_iter_page(&di, NULL, &domain, NULL) == 0);
3385
3386 return (ret);
3387 }
3388
3389 /*
3390 * Set the domain in the appropriate page level domainset.
3391 */
3392 void
vm_domain_set(struct vm_domain * vmd)3393 vm_domain_set(struct vm_domain *vmd)
3394 {
3395
3396 mtx_lock(&vm_domainset_lock);
3397 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
3398 vmd->vmd_minset = 1;
3399 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
3400 }
3401 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
3402 vmd->vmd_severeset = 1;
3403 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
3404 }
3405 mtx_unlock(&vm_domainset_lock);
3406 }
3407
3408 /*
3409 * Clear the domain from the appropriate page level domainset.
3410 */
3411 void
vm_domain_clear(struct vm_domain * vmd)3412 vm_domain_clear(struct vm_domain *vmd)
3413 {
3414
3415 mtx_lock(&vm_domainset_lock);
3416 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
3417 vmd->vmd_minset = 0;
3418 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
3419 if (vm_min_waiters != 0) {
3420 vm_min_waiters = 0;
3421 wakeup(&vm_min_domains);
3422 }
3423 }
3424 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
3425 vmd->vmd_severeset = 0;
3426 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
3427 if (vm_severe_waiters != 0) {
3428 vm_severe_waiters = 0;
3429 wakeup(&vm_severe_domains);
3430 }
3431 }
3432
3433 /*
3434 * If pageout daemon needs pages, then tell it that there are
3435 * some free.
3436 */
3437 if (vmd->vmd_pageout_pages_needed &&
3438 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
3439 wakeup(&vmd->vmd_pageout_pages_needed);
3440 vmd->vmd_pageout_pages_needed = 0;
3441 }
3442
3443 /* See comments in vm_wait_doms(). */
3444 if (vm_pageproc_waiters) {
3445 vm_pageproc_waiters = 0;
3446 wakeup(&vm_pageproc_waiters);
3447 }
3448 mtx_unlock(&vm_domainset_lock);
3449 }
3450
3451 /*
3452 * Wait for free pages to exceed the min threshold globally.
3453 */
3454 void
vm_wait_min(void)3455 vm_wait_min(void)
3456 {
3457
3458 mtx_lock(&vm_domainset_lock);
3459 while (vm_page_count_min()) {
3460 vm_min_waiters++;
3461 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3462 }
3463 mtx_unlock(&vm_domainset_lock);
3464 }
3465
3466 /*
3467 * Wait for free pages to exceed the severe threshold globally.
3468 */
3469 void
vm_wait_severe(void)3470 vm_wait_severe(void)
3471 {
3472
3473 mtx_lock(&vm_domainset_lock);
3474 while (vm_page_count_severe()) {
3475 vm_severe_waiters++;
3476 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3477 "vmwait", 0);
3478 }
3479 mtx_unlock(&vm_domainset_lock);
3480 }
3481
3482 u_int
vm_wait_count(void)3483 vm_wait_count(void)
3484 {
3485
3486 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3487 }
3488
3489 int
vm_wait_doms(const domainset_t * wdoms,int mflags)3490 vm_wait_doms(const domainset_t *wdoms, int mflags)
3491 {
3492 int error;
3493
3494 error = 0;
3495
3496 /*
3497 * We use racey wakeup synchronization to avoid expensive global
3498 * locking for the pageproc when sleeping with a non-specific vm_wait.
3499 * To handle this, we only sleep for one tick in this instance. It
3500 * is expected that most allocations for the pageproc will come from
3501 * kmem or vm_page_grab* which will use the more specific and
3502 * race-free vm_wait_domain().
3503 */
3504 if (curproc == pageproc) {
3505 mtx_lock(&vm_domainset_lock);
3506 vm_pageproc_waiters++;
3507 error = msleep(&vm_pageproc_waiters, &vm_domainset_lock,
3508 PVM | PDROP | mflags, "pageprocwait", 1);
3509 } else {
3510 /*
3511 * XXX Ideally we would wait only until the allocation could
3512 * be satisfied. This condition can cause new allocators to
3513 * consume all freed pages while old allocators wait.
3514 */
3515 mtx_lock(&vm_domainset_lock);
3516 if (vm_page_count_min_set(wdoms)) {
3517 if (pageproc == NULL)
3518 panic("vm_wait in early boot");
3519 vm_min_waiters++;
3520 error = msleep(&vm_min_domains, &vm_domainset_lock,
3521 PVM | PDROP | mflags, "vmwait", 0);
3522 } else
3523 mtx_unlock(&vm_domainset_lock);
3524 }
3525 return (error);
3526 }
3527
3528 /*
3529 * vm_wait_domain:
3530 *
3531 * Sleep until free pages are available for allocation.
3532 * - Called in various places after failed memory allocations.
3533 */
3534 void
vm_wait_domain(int domain)3535 vm_wait_domain(int domain)
3536 {
3537 struct vm_domain *vmd;
3538 domainset_t wdom;
3539
3540 vmd = VM_DOMAIN(domain);
3541 vm_domain_free_assert_unlocked(vmd);
3542
3543 if (curproc == pageproc) {
3544 mtx_lock(&vm_domainset_lock);
3545 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3546 vmd->vmd_pageout_pages_needed = 1;
3547 msleep(&vmd->vmd_pageout_pages_needed,
3548 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3549 } else
3550 mtx_unlock(&vm_domainset_lock);
3551 } else {
3552 DOMAINSET_ZERO(&wdom);
3553 DOMAINSET_SET(vmd->vmd_domain, &wdom);
3554 vm_wait_doms(&wdom, 0);
3555 }
3556 }
3557
3558 static int
vm_wait_flags(vm_object_t obj,int mflags)3559 vm_wait_flags(vm_object_t obj, int mflags)
3560 {
3561 struct domainset *d;
3562
3563 d = NULL;
3564
3565 /*
3566 * Carefully fetch pointers only once: the struct domainset
3567 * itself is ummutable but the pointer might change.
3568 */
3569 if (obj != NULL)
3570 d = obj->domain.dr_policy;
3571 if (d == NULL)
3572 d = curthread->td_domain.dr_policy;
3573
3574 return (vm_wait_doms(&d->ds_mask, mflags));
3575 }
3576
3577 /*
3578 * vm_wait:
3579 *
3580 * Sleep until free pages are available for allocation in the
3581 * affinity domains of the obj. If obj is NULL, the domain set
3582 * for the calling thread is used.
3583 * Called in various places after failed memory allocations.
3584 */
3585 void
vm_wait(vm_object_t obj)3586 vm_wait(vm_object_t obj)
3587 {
3588 (void)vm_wait_flags(obj, 0);
3589 }
3590
3591 int
vm_wait_intr(vm_object_t obj)3592 vm_wait_intr(vm_object_t obj)
3593 {
3594 return (vm_wait_flags(obj, PCATCH));
3595 }
3596
3597 /*
3598 * vm_domain_alloc_fail:
3599 *
3600 * Called when a page allocation function fails. Informs the
3601 * pagedaemon and performs the requested wait. Requires the
3602 * domain_free and object lock on entry. Returns with the
3603 * object lock held and free lock released. Returns an error when
3604 * retry is necessary.
3605 *
3606 */
3607 static int
vm_domain_alloc_fail(struct vm_domain * vmd,vm_object_t object,int req)3608 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3609 {
3610
3611 vm_domain_free_assert_unlocked(vmd);
3612
3613 atomic_add_int(&vmd->vmd_pageout_deficit,
3614 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3615 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3616 if (object != NULL)
3617 VM_OBJECT_WUNLOCK(object);
3618 vm_wait_domain(vmd->vmd_domain);
3619 if (object != NULL)
3620 VM_OBJECT_WLOCK(object);
3621 if (req & VM_ALLOC_WAITOK)
3622 return (EAGAIN);
3623 }
3624
3625 return (0);
3626 }
3627
3628 /*
3629 * vm_waitpfault:
3630 *
3631 * Sleep until free pages are available for allocation.
3632 * - Called only in vm_fault so that processes page faulting
3633 * can be easily tracked.
3634 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3635 * processes will be able to grab memory first. Do not change
3636 * this balance without careful testing first.
3637 */
3638 void
vm_waitpfault(struct domainset * dset,int timo)3639 vm_waitpfault(struct domainset *dset, int timo)
3640 {
3641
3642 /*
3643 * XXX Ideally we would wait only until the allocation could
3644 * be satisfied. This condition can cause new allocators to
3645 * consume all freed pages while old allocators wait.
3646 */
3647 mtx_lock(&vm_domainset_lock);
3648 if (vm_page_count_min_set(&dset->ds_mask)) {
3649 vm_min_waiters++;
3650 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3651 "pfault", timo);
3652 } else
3653 mtx_unlock(&vm_domainset_lock);
3654 }
3655
3656 static struct vm_pagequeue *
_vm_page_pagequeue(vm_page_t m,uint8_t queue)3657 _vm_page_pagequeue(vm_page_t m, uint8_t queue)
3658 {
3659
3660 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3661 }
3662
3663 #ifdef INVARIANTS
3664 static struct vm_pagequeue *
vm_page_pagequeue(vm_page_t m)3665 vm_page_pagequeue(vm_page_t m)
3666 {
3667
3668 return (_vm_page_pagequeue(m, vm_page_astate_load(m).queue));
3669 }
3670 #endif
3671
3672 static __always_inline bool
vm_page_pqstate_fcmpset(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3673 vm_page_pqstate_fcmpset(vm_page_t m, vm_page_astate_t *old,
3674 vm_page_astate_t new)
3675 {
3676 vm_page_astate_t tmp;
3677
3678 tmp = *old;
3679 do {
3680 if (__predict_true(vm_page_astate_fcmpset(m, old, new)))
3681 return (true);
3682 counter_u64_add(pqstate_commit_retries, 1);
3683 } while (old->_bits == tmp._bits);
3684
3685 return (false);
3686 }
3687
3688 static __always_inline bool
vm_page_pqstate_fcmpset_rel(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3689 vm_page_pqstate_fcmpset_rel(vm_page_t m, vm_page_astate_t *old,
3690 vm_page_astate_t new)
3691 {
3692 vm_page_astate_t tmp;
3693
3694 tmp = *old;
3695 do {
3696 if (__predict_true(vm_page_astate_fcmpset_rel(m, old, new)))
3697 return (true);
3698 counter_u64_add(pqstate_commit_retries, 1);
3699 } while (old->_bits == tmp._bits);
3700
3701 return (false);
3702 }
3703
3704 /*
3705 * Do the work of committing a queue state update that moves the page out of
3706 * its current queue.
3707 */
3708 static bool
_vm_page_pqstate_commit_dequeue(struct vm_pagequeue * pq,vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3709 _vm_page_pqstate_commit_dequeue(struct vm_pagequeue *pq, vm_page_t m,
3710 vm_page_astate_t *old, vm_page_astate_t new)
3711 {
3712 vm_page_t next;
3713
3714 vm_pagequeue_assert_locked(pq);
3715 KASSERT(vm_page_pagequeue(m) == pq,
3716 ("%s: queue %p does not match page %p", __func__, pq, m));
3717 KASSERT(old->queue != PQ_NONE && new.queue != old->queue,
3718 ("%s: invalid queue indices %d %d",
3719 __func__, old->queue, new.queue));
3720
3721 /*
3722 * Once the queue index of the page changes there is nothing
3723 * synchronizing with further updates to the page's physical
3724 * queue state. Therefore we must speculatively remove the page
3725 * from the queue now and be prepared to roll back if the queue
3726 * state update fails. If the page is not physically enqueued then
3727 * we just update its queue index.
3728 */
3729 if ((old->flags & PGA_ENQUEUED) != 0) {
3730 new.flags &= ~PGA_ENQUEUED;
3731 next = TAILQ_NEXT(m, plinks.q);
3732 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3733 vm_pagequeue_cnt_dec(pq);
3734 /* See vm_page_dequeue(). */
3735 if (!vm_page_pqstate_fcmpset_rel(m, old, new)) {
3736 if (next == NULL)
3737 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3738 else
3739 TAILQ_INSERT_BEFORE(next, m, plinks.q);
3740 vm_pagequeue_cnt_inc(pq);
3741 return (false);
3742 } else {
3743 return (true);
3744 }
3745 } else {
3746 return (vm_page_pqstate_fcmpset(m, old, new));
3747 }
3748 }
3749
3750 static bool
vm_page_pqstate_commit_dequeue(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3751 vm_page_pqstate_commit_dequeue(vm_page_t m, vm_page_astate_t *old,
3752 vm_page_astate_t new)
3753 {
3754 struct vm_pagequeue *pq;
3755 vm_page_astate_t as;
3756 bool ret;
3757
3758 pq = _vm_page_pagequeue(m, old->queue);
3759
3760 /*
3761 * The queue field and PGA_ENQUEUED flag are stable only so long as the
3762 * corresponding page queue lock is held.
3763 */
3764 vm_pagequeue_lock(pq);
3765 as = vm_page_astate_load(m);
3766 if (__predict_false(as._bits != old->_bits)) {
3767 *old = as;
3768 ret = false;
3769 } else {
3770 ret = _vm_page_pqstate_commit_dequeue(pq, m, old, new);
3771 }
3772 vm_pagequeue_unlock(pq);
3773 return (ret);
3774 }
3775
3776 /*
3777 * Commit a queue state update that enqueues or requeues a page.
3778 */
3779 static bool
_vm_page_pqstate_commit_requeue(struct vm_pagequeue * pq,vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3780 _vm_page_pqstate_commit_requeue(struct vm_pagequeue *pq, vm_page_t m,
3781 vm_page_astate_t *old, vm_page_astate_t new)
3782 {
3783 struct vm_domain *vmd;
3784
3785 vm_pagequeue_assert_locked(pq);
3786 KASSERT(old->queue != PQ_NONE && new.queue == old->queue,
3787 ("%s: invalid queue indices %d %d",
3788 __func__, old->queue, new.queue));
3789
3790 new.flags |= PGA_ENQUEUED;
3791 if (!vm_page_pqstate_fcmpset(m, old, new))
3792 return (false);
3793
3794 if ((old->flags & PGA_ENQUEUED) != 0)
3795 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3796 else
3797 vm_pagequeue_cnt_inc(pq);
3798
3799 /*
3800 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE. In particular, if
3801 * both flags are set in close succession, only PGA_REQUEUE_HEAD will be
3802 * applied, even if it was set first.
3803 */
3804 if ((old->flags & PGA_REQUEUE_HEAD) != 0) {
3805 vmd = vm_pagequeue_domain(m);
3806 KASSERT(pq == &vmd->vmd_pagequeues[PQ_INACTIVE],
3807 ("%s: invalid page queue for page %p", __func__, m));
3808 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3809 } else {
3810 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3811 }
3812 return (true);
3813 }
3814
3815 /*
3816 * Commit a queue state update that encodes a request for a deferred queue
3817 * operation.
3818 */
3819 static bool
vm_page_pqstate_commit_request(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3820 vm_page_pqstate_commit_request(vm_page_t m, vm_page_astate_t *old,
3821 vm_page_astate_t new)
3822 {
3823
3824 KASSERT(old->queue == new.queue || new.queue != PQ_NONE,
3825 ("%s: invalid state, queue %d flags %x",
3826 __func__, new.queue, new.flags));
3827
3828 if (old->_bits != new._bits &&
3829 !vm_page_pqstate_fcmpset(m, old, new))
3830 return (false);
3831 vm_page_pqbatch_submit(m, new.queue);
3832 return (true);
3833 }
3834
3835 /*
3836 * A generic queue state update function. This handles more cases than the
3837 * specialized functions above.
3838 */
3839 bool
vm_page_pqstate_commit(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3840 vm_page_pqstate_commit(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3841 {
3842
3843 if (old->_bits == new._bits)
3844 return (true);
3845
3846 if (old->queue != PQ_NONE && new.queue != old->queue) {
3847 if (!vm_page_pqstate_commit_dequeue(m, old, new))
3848 return (false);
3849 if (new.queue != PQ_NONE)
3850 vm_page_pqbatch_submit(m, new.queue);
3851 } else {
3852 if (!vm_page_pqstate_fcmpset(m, old, new))
3853 return (false);
3854 if (new.queue != PQ_NONE &&
3855 ((new.flags & ~old->flags) & PGA_QUEUE_OP_MASK) != 0)
3856 vm_page_pqbatch_submit(m, new.queue);
3857 }
3858 return (true);
3859 }
3860
3861 /*
3862 * Apply deferred queue state updates to a page.
3863 */
3864 static inline void
vm_pqbatch_process_page(struct vm_pagequeue * pq,vm_page_t m,uint8_t queue)3865 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m, uint8_t queue)
3866 {
3867 vm_page_astate_t new, old;
3868
3869 CRITICAL_ASSERT(curthread);
3870 vm_pagequeue_assert_locked(pq);
3871 KASSERT(queue < PQ_COUNT,
3872 ("%s: invalid queue index %d", __func__, queue));
3873 KASSERT(pq == _vm_page_pagequeue(m, queue),
3874 ("%s: page %p does not belong to queue %p", __func__, m, pq));
3875
3876 for (old = vm_page_astate_load(m);;) {
3877 if (__predict_false(old.queue != queue ||
3878 (old.flags & PGA_QUEUE_OP_MASK) == 0)) {
3879 counter_u64_add(queue_nops, 1);
3880 break;
3881 }
3882 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3883 ("%s: page %p is unmanaged", __func__, m));
3884
3885 new = old;
3886 if ((old.flags & PGA_DEQUEUE) != 0) {
3887 new.flags &= ~PGA_QUEUE_OP_MASK;
3888 new.queue = PQ_NONE;
3889 if (__predict_true(_vm_page_pqstate_commit_dequeue(pq,
3890 m, &old, new))) {
3891 counter_u64_add(queue_ops, 1);
3892 break;
3893 }
3894 } else {
3895 new.flags &= ~(PGA_REQUEUE | PGA_REQUEUE_HEAD);
3896 if (__predict_true(_vm_page_pqstate_commit_requeue(pq,
3897 m, &old, new))) {
3898 counter_u64_add(queue_ops, 1);
3899 break;
3900 }
3901 }
3902 }
3903 }
3904
3905 static void
vm_pqbatch_process(struct vm_pagequeue * pq,struct vm_batchqueue * bq,uint8_t queue)3906 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3907 uint8_t queue)
3908 {
3909 int i;
3910
3911 for (i = 0; i < bq->bq_cnt; i++)
3912 vm_pqbatch_process_page(pq, bq->bq_pa[i], queue);
3913 vm_batchqueue_init(bq);
3914 }
3915
3916 /*
3917 * vm_page_pqbatch_submit: [ internal use only ]
3918 *
3919 * Enqueue a page in the specified page queue's batched work queue.
3920 * The caller must have encoded the requested operation in the page
3921 * structure's a.flags field.
3922 */
3923 void
vm_page_pqbatch_submit(vm_page_t m,uint8_t queue)3924 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3925 {
3926 struct vm_batchqueue *bq;
3927 struct vm_pagequeue *pq;
3928 int domain, slots_remaining;
3929
3930 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3931
3932 domain = vm_page_domain(m);
3933 critical_enter();
3934 bq = DPCPU_PTR(pqbatch[domain][queue]);
3935 slots_remaining = vm_batchqueue_insert(bq, m);
3936 if (slots_remaining > (VM_BATCHQUEUE_SIZE >> 1)) {
3937 /* keep building the bq */
3938 critical_exit();
3939 return;
3940 } else if (slots_remaining > 0 ) {
3941 /* Try to process the bq if we can get the lock */
3942 pq = &VM_DOMAIN(domain)->vmd_pagequeues[queue];
3943 if (vm_pagequeue_trylock(pq)) {
3944 vm_pqbatch_process(pq, bq, queue);
3945 vm_pagequeue_unlock(pq);
3946 }
3947 critical_exit();
3948 return;
3949 }
3950 critical_exit();
3951
3952 /* if we make it here, the bq is full so wait for the lock */
3953
3954 pq = &VM_DOMAIN(domain)->vmd_pagequeues[queue];
3955 vm_pagequeue_lock(pq);
3956 critical_enter();
3957 bq = DPCPU_PTR(pqbatch[domain][queue]);
3958 vm_pqbatch_process(pq, bq, queue);
3959 vm_pqbatch_process_page(pq, m, queue);
3960 vm_pagequeue_unlock(pq);
3961 critical_exit();
3962 }
3963
3964 /*
3965 * vm_page_pqbatch_drain: [ internal use only ]
3966 *
3967 * Force all per-CPU page queue batch queues to be drained. This is
3968 * intended for use in severe memory shortages, to ensure that pages
3969 * do not remain stuck in the batch queues.
3970 */
3971 void
vm_page_pqbatch_drain(void)3972 vm_page_pqbatch_drain(void)
3973 {
3974 struct thread *td;
3975 struct vm_domain *vmd;
3976 struct vm_pagequeue *pq;
3977 int cpu, domain, queue;
3978
3979 td = curthread;
3980 CPU_FOREACH(cpu) {
3981 thread_lock(td);
3982 sched_bind(td, cpu);
3983 thread_unlock(td);
3984
3985 for (domain = 0; domain < vm_ndomains; domain++) {
3986 vmd = VM_DOMAIN(domain);
3987 for (queue = 0; queue < PQ_COUNT; queue++) {
3988 pq = &vmd->vmd_pagequeues[queue];
3989 vm_pagequeue_lock(pq);
3990 critical_enter();
3991 vm_pqbatch_process(pq,
3992 DPCPU_PTR(pqbatch[domain][queue]), queue);
3993 critical_exit();
3994 vm_pagequeue_unlock(pq);
3995 }
3996 }
3997 }
3998 thread_lock(td);
3999 sched_unbind(td);
4000 thread_unlock(td);
4001 }
4002
4003 /*
4004 * vm_page_dequeue_deferred: [ internal use only ]
4005 *
4006 * Request removal of the given page from its current page
4007 * queue. Physical removal from the queue may be deferred
4008 * indefinitely.
4009 */
4010 void
vm_page_dequeue_deferred(vm_page_t m)4011 vm_page_dequeue_deferred(vm_page_t m)
4012 {
4013 vm_page_astate_t new, old;
4014
4015 old = vm_page_astate_load(m);
4016 do {
4017 if (old.queue == PQ_NONE) {
4018 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
4019 ("%s: page %p has unexpected queue state",
4020 __func__, m));
4021 break;
4022 }
4023 new = old;
4024 new.flags |= PGA_DEQUEUE;
4025 } while (!vm_page_pqstate_commit_request(m, &old, new));
4026 }
4027
4028 /*
4029 * vm_page_dequeue:
4030 *
4031 * Remove the page from whichever page queue it's in, if any, before
4032 * returning.
4033 */
4034 void
vm_page_dequeue(vm_page_t m)4035 vm_page_dequeue(vm_page_t m)
4036 {
4037 vm_page_astate_t new, old;
4038
4039 /*
4040 * Synchronize with _vm_page_pqstate_commit_dequeue(): make sure
4041 * that the page's queue linkage field updates are visible before
4042 * returning.
4043 */
4044 old = vm_page_astate_load_acq(m);
4045 do {
4046 if (__predict_true(old.queue == PQ_NONE)) {
4047 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
4048 ("%s: page %p has unexpected queue state",
4049 __func__, m));
4050 break;
4051 }
4052 new = old;
4053 new.flags &= ~PGA_QUEUE_OP_MASK;
4054 new.queue = PQ_NONE;
4055 } while (!vm_page_pqstate_commit_dequeue(m, &old, new));
4056
4057 }
4058
4059 /*
4060 * Schedule the given page for insertion into the specified page queue.
4061 * Physical insertion of the page may be deferred indefinitely.
4062 */
4063 static void
vm_page_enqueue(vm_page_t m,uint8_t queue)4064 vm_page_enqueue(vm_page_t m, uint8_t queue)
4065 {
4066
4067 KASSERT(m->a.queue == PQ_NONE &&
4068 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
4069 ("%s: page %p is already enqueued", __func__, m));
4070 KASSERT(m->ref_count > 0,
4071 ("%s: page %p does not carry any references", __func__, m));
4072
4073 m->a.queue = queue;
4074 if ((m->a.flags & PGA_REQUEUE) == 0)
4075 vm_page_aflag_set(m, PGA_REQUEUE);
4076 vm_page_pqbatch_submit(m, queue);
4077 }
4078
4079 /*
4080 * vm_page_free_prep:
4081 *
4082 * Prepares the given page to be put on the free list,
4083 * disassociating it from any VM object. The caller may return
4084 * the page to the free list only if this function returns true.
4085 *
4086 * The object, if it exists, must be locked, and then the page must
4087 * be xbusy. Otherwise the page must be not busied. A managed
4088 * page must be unmapped.
4089 */
4090 static bool
vm_page_free_prep(vm_page_t m)4091 vm_page_free_prep(vm_page_t m)
4092 {
4093
4094 /*
4095 * Synchronize with threads that have dropped a reference to this
4096 * page.
4097 */
4098 atomic_thread_fence_acq();
4099
4100 #ifdef INVARIANTS
4101 if (vm_check_pg_zero && (m->flags & PG_ZERO) != 0) {
4102 struct sf_buf *sf;
4103 unsigned long *p;
4104 int i;
4105
4106 sched_pin();
4107 sf = sf_buf_alloc(m, SFB_CPUPRIVATE | SFB_NOWAIT);
4108 if (sf != NULL) {
4109 p = (unsigned long *)sf_buf_kva(sf);
4110 for (i = 0; i < PAGE_SIZE / sizeof(*p); i++, p++) {
4111 KASSERT(*p == 0,
4112 ("zerocheck failed page %p PG_ZERO %d %jx",
4113 m, i, (uintmax_t)*p));
4114 }
4115 sf_buf_free(sf);
4116 }
4117 sched_unpin();
4118 }
4119 #endif
4120 if ((m->oflags & VPO_UNMANAGED) == 0) {
4121 KASSERT(!pmap_page_is_mapped(m),
4122 ("vm_page_free_prep: freeing mapped page %p", m));
4123 KASSERT((m->a.flags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
4124 ("vm_page_free_prep: mapping flags set in page %p", m));
4125 } else {
4126 KASSERT(m->a.queue == PQ_NONE,
4127 ("vm_page_free_prep: unmanaged page %p is queued", m));
4128 }
4129 VM_CNT_INC(v_tfree);
4130
4131 if (m->object != NULL) {
4132 vm_page_radix_remove(m);
4133 vm_page_free_object_prep(m);
4134 } else
4135 vm_page_assert_unbusied(m);
4136
4137 vm_page_busy_free(m);
4138
4139 /*
4140 * If fictitious remove object association and
4141 * return.
4142 */
4143 if ((m->flags & PG_FICTITIOUS) != 0) {
4144 KASSERT(m->ref_count == 1,
4145 ("fictitious page %p is referenced", m));
4146 KASSERT(m->a.queue == PQ_NONE,
4147 ("fictitious page %p is queued", m));
4148 return (false);
4149 }
4150
4151 /*
4152 * Pages need not be dequeued before they are returned to the physical
4153 * memory allocator, but they must at least be marked for a deferred
4154 * dequeue.
4155 */
4156 if ((m->oflags & VPO_UNMANAGED) == 0)
4157 vm_page_dequeue_deferred(m);
4158
4159 m->valid = 0;
4160 vm_page_undirty(m);
4161
4162 if (m->ref_count != 0)
4163 panic("vm_page_free_prep: page %p has references", m);
4164
4165 /*
4166 * Restore the default memory attribute to the page.
4167 */
4168 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
4169 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
4170
4171 #if VM_NRESERVLEVEL > 0
4172 /*
4173 * Determine whether the page belongs to a reservation. If the page was
4174 * allocated from a per-CPU cache, it cannot belong to a reservation, so
4175 * as an optimization, we avoid the check in that case.
4176 */
4177 if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
4178 return (false);
4179 #endif
4180
4181 return (true);
4182 }
4183
4184 /*
4185 * vm_page_free_toq:
4186 *
4187 * Returns the given page to the free list, disassociating it
4188 * from any VM object.
4189 *
4190 * The object must be locked. The page must be exclusively busied if it
4191 * belongs to an object.
4192 */
4193 static void
vm_page_free_toq(vm_page_t m)4194 vm_page_free_toq(vm_page_t m)
4195 {
4196 struct vm_domain *vmd;
4197 uma_zone_t zone;
4198
4199 if (!vm_page_free_prep(m))
4200 return;
4201
4202 vmd = vm_pagequeue_domain(m);
4203 if (__predict_false((m->flags & PG_NOFREE) != 0)) {
4204 vm_page_free_nofree(vmd, m);
4205 return;
4206 }
4207 zone = vmd->vmd_pgcache[m->pool].zone;
4208 if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
4209 uma_zfree(zone, m);
4210 return;
4211 }
4212 vm_domain_free_lock(vmd);
4213 vm_phys_free_pages(m, m->pool, 0);
4214 vm_domain_free_unlock(vmd);
4215 vm_domain_freecnt_inc(vmd, 1);
4216 }
4217
4218 /*
4219 * vm_page_free_pages_toq:
4220 *
4221 * Returns a list of pages to the free list, disassociating it
4222 * from any VM object. In other words, this is equivalent to
4223 * calling vm_page_free_toq() for each page of a list of VM objects.
4224 */
4225 int
vm_page_free_pages_toq(struct spglist * free,bool update_wire_count)4226 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
4227 {
4228 vm_page_t m;
4229 int count;
4230
4231 if (SLIST_EMPTY(free))
4232 return (0);
4233
4234 count = 0;
4235 while ((m = SLIST_FIRST(free)) != NULL) {
4236 count++;
4237 SLIST_REMOVE_HEAD(free, plinks.s.ss);
4238 vm_page_free_toq(m);
4239 }
4240
4241 if (update_wire_count)
4242 vm_wire_sub(count);
4243 return (count);
4244 }
4245
4246 /*
4247 * Mark this page as wired down. For managed pages, this prevents reclamation
4248 * by the page daemon, or when the containing object, if any, is destroyed.
4249 */
4250 void
vm_page_wire(vm_page_t m)4251 vm_page_wire(vm_page_t m)
4252 {
4253 u_int old;
4254
4255 #ifdef INVARIANTS
4256 if (m->object != NULL && !vm_page_busied(m) &&
4257 !vm_object_busied(m->object))
4258 VM_OBJECT_ASSERT_LOCKED(m->object);
4259 #endif
4260 KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
4261 VPRC_WIRE_COUNT(m->ref_count) >= 1,
4262 ("vm_page_wire: fictitious page %p has zero wirings", m));
4263
4264 old = atomic_fetchadd_int(&m->ref_count, 1);
4265 KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
4266 ("vm_page_wire: counter overflow for page %p", m));
4267 if (VPRC_WIRE_COUNT(old) == 0) {
4268 if ((m->oflags & VPO_UNMANAGED) == 0)
4269 vm_page_aflag_set(m, PGA_DEQUEUE);
4270 vm_wire_add(1);
4271 }
4272 }
4273
4274 /*
4275 * Attempt to wire a mapped page following a pmap lookup of that page.
4276 * This may fail if a thread is concurrently tearing down mappings of the page.
4277 * The transient failure is acceptable because it translates to the
4278 * failure of the caller pmap_extract_and_hold(), which should be then
4279 * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
4280 */
4281 bool
vm_page_wire_mapped(vm_page_t m)4282 vm_page_wire_mapped(vm_page_t m)
4283 {
4284 u_int old;
4285
4286 old = atomic_load_int(&m->ref_count);
4287 do {
4288 KASSERT(old > 0,
4289 ("vm_page_wire_mapped: wiring unreferenced page %p", m));
4290 if ((old & VPRC_BLOCKED) != 0)
4291 return (false);
4292 } while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
4293
4294 if (VPRC_WIRE_COUNT(old) == 0) {
4295 if ((m->oflags & VPO_UNMANAGED) == 0)
4296 vm_page_aflag_set(m, PGA_DEQUEUE);
4297 vm_wire_add(1);
4298 }
4299 return (true);
4300 }
4301
4302 /*
4303 * Release a wiring reference to a managed page. If the page still belongs to
4304 * an object, update its position in the page queues to reflect the reference.
4305 * If the wiring was the last reference to the page, free the page.
4306 */
4307 static void
vm_page_unwire_managed(vm_page_t m,uint8_t nqueue,bool noreuse)4308 vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
4309 {
4310 u_int old;
4311
4312 KASSERT(nqueue < PQ_COUNT,
4313 ("vm_page_unwire: invalid queue %u request for page %p",
4314 nqueue, m));
4315 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4316 ("%s: page %p is unmanaged", __func__, m));
4317
4318 /*
4319 * Update LRU state before releasing the wiring reference.
4320 * Use a release store when updating the reference count to
4321 * synchronize with vm_page_free_prep().
4322 */
4323 old = atomic_load_int(&m->ref_count);
4324 do {
4325 u_int count;
4326
4327 KASSERT(VPRC_WIRE_COUNT(old) > 0,
4328 ("vm_page_unwire: wire count underflow for page %p", m));
4329
4330 count = old & ~VPRC_BLOCKED;
4331 if (count > VPRC_OBJREF + 1) {
4332 /*
4333 * The page has at least one other wiring reference. An
4334 * earlier iteration of this loop may have called
4335 * vm_page_release_toq() and cleared PGA_DEQUEUE, so
4336 * re-set it if necessary.
4337 */
4338 if ((vm_page_astate_load(m).flags & PGA_DEQUEUE) == 0)
4339 vm_page_aflag_set(m, PGA_DEQUEUE);
4340 } else if (count == VPRC_OBJREF + 1) {
4341 /*
4342 * This is the last wiring. Clear PGA_DEQUEUE and
4343 * update the page's queue state to reflect the
4344 * reference. If the page does not belong to an object
4345 * (i.e., the VPRC_OBJREF bit is clear), we only need to
4346 * clear leftover queue state.
4347 */
4348 vm_page_release_toq(m, nqueue, noreuse);
4349 } else if (count == 1) {
4350 vm_page_aflag_clear(m, PGA_DEQUEUE);
4351 }
4352 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
4353
4354 if (VPRC_WIRE_COUNT(old) == 1) {
4355 vm_wire_sub(1);
4356 if (old == 1)
4357 vm_page_free(m);
4358 }
4359 }
4360
4361 /*
4362 * Release one wiring of the specified page, potentially allowing it to be
4363 * paged out.
4364 *
4365 * Only managed pages belonging to an object can be paged out. If the number
4366 * of wirings transitions to zero and the page is eligible for page out, then
4367 * the page is added to the specified paging queue. If the released wiring
4368 * represented the last reference to the page, the page is freed.
4369 */
4370 void
vm_page_unwire(vm_page_t m,uint8_t nqueue)4371 vm_page_unwire(vm_page_t m, uint8_t nqueue)
4372 {
4373 KASSERT(nqueue < PQ_COUNT || nqueue == PQ_NONE,
4374 ("%s: invalid queue %u request for page %p", __func__, nqueue, m));
4375
4376 if ((m->oflags & VPO_UNMANAGED) != 0) {
4377 if (vm_page_unwire_noq(m) && m->ref_count == 0)
4378 vm_page_free(m);
4379 } else {
4380 vm_page_unwire_managed(m, nqueue, false);
4381 }
4382 }
4383
4384 /*
4385 * Unwire a page without (re-)inserting it into a page queue. It is up
4386 * to the caller to enqueue, requeue, or free the page as appropriate.
4387 * In most cases involving managed pages, vm_page_unwire() should be used
4388 * instead.
4389 */
4390 bool
vm_page_unwire_noq(vm_page_t m)4391 vm_page_unwire_noq(vm_page_t m)
4392 {
4393 u_int old;
4394
4395 old = vm_page_drop(m, 1);
4396 KASSERT(VPRC_WIRE_COUNT(old) != 0,
4397 ("%s: counter underflow for page %p", __func__, m));
4398 KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
4399 ("%s: missing ref on fictitious page %p", __func__, m));
4400
4401 if (VPRC_WIRE_COUNT(old) > 1)
4402 return (false);
4403 if ((m->oflags & VPO_UNMANAGED) == 0)
4404 vm_page_aflag_clear(m, PGA_DEQUEUE);
4405 vm_wire_sub(1);
4406 return (true);
4407 }
4408
4409 /*
4410 * Ensure that the page ends up in the specified page queue. If the page is
4411 * active or being moved to the active queue, ensure that its act_count is
4412 * at least ACT_INIT but do not otherwise mess with it.
4413 */
4414 static __always_inline void
vm_page_mvqueue(vm_page_t m,const uint8_t nqueue,const uint16_t nflag)4415 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue, const uint16_t nflag)
4416 {
4417 vm_page_astate_t old, new;
4418
4419 KASSERT(m->ref_count > 0,
4420 ("%s: page %p does not carry any references", __func__, m));
4421 KASSERT(nflag == PGA_REQUEUE || nflag == PGA_REQUEUE_HEAD,
4422 ("%s: invalid flags %x", __func__, nflag));
4423
4424 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
4425 return;
4426
4427 old = vm_page_astate_load(m);
4428 do {
4429 if ((old.flags & PGA_DEQUEUE) != 0)
4430 break;
4431 new = old;
4432 new.flags &= ~PGA_QUEUE_OP_MASK;
4433 if (nqueue == PQ_ACTIVE)
4434 new.act_count = max(old.act_count, ACT_INIT);
4435 if (old.queue == nqueue) {
4436 /*
4437 * There is no need to requeue pages already in the
4438 * active queue.
4439 */
4440 if (nqueue != PQ_ACTIVE ||
4441 (old.flags & PGA_ENQUEUED) == 0)
4442 new.flags |= nflag;
4443 } else {
4444 new.flags |= nflag;
4445 new.queue = nqueue;
4446 }
4447 } while (!vm_page_pqstate_commit(m, &old, new));
4448 }
4449
4450 /*
4451 * Put the specified page on the active list (if appropriate).
4452 */
4453 void
vm_page_activate(vm_page_t m)4454 vm_page_activate(vm_page_t m)
4455 {
4456
4457 vm_page_mvqueue(m, PQ_ACTIVE, PGA_REQUEUE);
4458 }
4459
4460 /*
4461 * Move the specified page to the tail of the inactive queue, or requeue
4462 * the page if it is already in the inactive queue.
4463 */
4464 void
vm_page_deactivate(vm_page_t m)4465 vm_page_deactivate(vm_page_t m)
4466 {
4467
4468 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE);
4469 }
4470
4471 void
vm_page_deactivate_noreuse(vm_page_t m)4472 vm_page_deactivate_noreuse(vm_page_t m)
4473 {
4474
4475 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE_HEAD);
4476 }
4477
4478 /*
4479 * Put a page in the laundry, or requeue it if it is already there.
4480 */
4481 void
vm_page_launder(vm_page_t m)4482 vm_page_launder(vm_page_t m)
4483 {
4484
4485 vm_page_mvqueue(m, PQ_LAUNDRY, PGA_REQUEUE);
4486 }
4487
4488 /*
4489 * Put a page in the PQ_UNSWAPPABLE holding queue.
4490 */
4491 void
vm_page_unswappable(vm_page_t m)4492 vm_page_unswappable(vm_page_t m)
4493 {
4494
4495 VM_OBJECT_ASSERT_LOCKED(m->object);
4496 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4497 ("page %p already unswappable", m));
4498
4499 vm_page_dequeue(m);
4500 vm_page_enqueue(m, PQ_UNSWAPPABLE);
4501 }
4502
4503 /*
4504 * Release a page back to the page queues in preparation for unwiring.
4505 */
4506 static void
vm_page_release_toq(vm_page_t m,uint8_t nqueue,const bool noreuse)4507 vm_page_release_toq(vm_page_t m, uint8_t nqueue, const bool noreuse)
4508 {
4509 vm_page_astate_t old, new;
4510 uint16_t nflag;
4511
4512 /*
4513 * Use a check of the valid bits to determine whether we should
4514 * accelerate reclamation of the page. The object lock might not be
4515 * held here, in which case the check is racy. At worst we will either
4516 * accelerate reclamation of a valid page and violate LRU, or
4517 * unnecessarily defer reclamation of an invalid page.
4518 *
4519 * If we were asked to not cache the page, place it near the head of the
4520 * inactive queue so that is reclaimed sooner.
4521 */
4522 if (noreuse || vm_page_none_valid(m)) {
4523 nqueue = PQ_INACTIVE;
4524 nflag = PGA_REQUEUE_HEAD;
4525 } else {
4526 nflag = PGA_REQUEUE;
4527 }
4528
4529 old = vm_page_astate_load(m);
4530 do {
4531 new = old;
4532
4533 /*
4534 * If the page is already in the active queue and we are not
4535 * trying to accelerate reclamation, simply mark it as
4536 * referenced and avoid any queue operations.
4537 */
4538 new.flags &= ~PGA_QUEUE_OP_MASK;
4539 if (nflag != PGA_REQUEUE_HEAD && old.queue == PQ_ACTIVE &&
4540 (old.flags & PGA_ENQUEUED) != 0)
4541 new.flags |= PGA_REFERENCED;
4542 else {
4543 new.flags |= nflag;
4544 new.queue = nqueue;
4545 }
4546 } while (!vm_page_pqstate_commit(m, &old, new));
4547 }
4548
4549 /*
4550 * Unwire a page and either attempt to free it or re-add it to the page queues.
4551 */
4552 void
vm_page_release(vm_page_t m,int flags)4553 vm_page_release(vm_page_t m, int flags)
4554 {
4555 if ((m->oflags & VPO_UNMANAGED) != 0) {
4556 vm_page_unwire(m, PQ_NONE);
4557 return;
4558 }
4559
4560 if ((flags & VPR_TRYFREE) != 0) {
4561 for (;;) {
4562 vm_object_t object;
4563
4564 object = atomic_load_ptr(&m->object);
4565 if (object == NULL)
4566 break;
4567 /* Depends on type-stability. */
4568 if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object))
4569 break;
4570 if (object == m->object) {
4571 vm_page_release_locked(m, flags);
4572 VM_OBJECT_WUNLOCK(object);
4573 return;
4574 }
4575 VM_OBJECT_WUNLOCK(object);
4576 }
4577 }
4578 vm_page_unwire_managed(m, PQ_INACTIVE, flags != 0);
4579 }
4580
4581 /* See vm_page_release(). */
4582 void
vm_page_release_locked(vm_page_t m,int flags)4583 vm_page_release_locked(vm_page_t m, int flags)
4584 {
4585
4586 VM_OBJECT_ASSERT_WLOCKED(m->object);
4587 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4588 ("vm_page_release_locked: page %p is unmanaged", m));
4589
4590 if (vm_page_unwire_noq(m)) {
4591 if ((flags & VPR_TRYFREE) != 0 &&
4592 (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4593 m->dirty == 0 && vm_page_tryxbusy(m)) {
4594 /*
4595 * An unlocked lookup may have wired the page before the
4596 * busy lock was acquired, in which case the page must
4597 * not be freed.
4598 */
4599 if (__predict_true(!vm_page_wired(m))) {
4600 vm_page_free(m);
4601 return;
4602 }
4603 vm_page_xunbusy(m);
4604 } else {
4605 vm_page_release_toq(m, PQ_INACTIVE, flags != 0);
4606 }
4607 }
4608 }
4609
4610 static bool
vm_page_try_blocked_op(vm_page_t m,void (* op)(vm_page_t))4611 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4612 {
4613 u_int old;
4614
4615 KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4616 ("vm_page_try_blocked_op: page %p has no object", m));
4617 KASSERT(vm_page_busied(m),
4618 ("vm_page_try_blocked_op: page %p is not busy", m));
4619 VM_OBJECT_ASSERT_LOCKED(m->object);
4620
4621 old = atomic_load_int(&m->ref_count);
4622 do {
4623 KASSERT(old != 0,
4624 ("vm_page_try_blocked_op: page %p has no references", m));
4625 KASSERT((old & VPRC_BLOCKED) == 0,
4626 ("vm_page_try_blocked_op: page %p blocks wirings", m));
4627 if (VPRC_WIRE_COUNT(old) != 0)
4628 return (false);
4629 } while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4630
4631 (op)(m);
4632
4633 /*
4634 * If the object is read-locked, new wirings may be created via an
4635 * object lookup.
4636 */
4637 old = vm_page_drop(m, VPRC_BLOCKED);
4638 KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4639 old == (VPRC_BLOCKED | VPRC_OBJREF),
4640 ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4641 old, m));
4642 return (true);
4643 }
4644
4645 /*
4646 * Atomically check for wirings and remove all mappings of the page.
4647 */
4648 bool
vm_page_try_remove_all(vm_page_t m)4649 vm_page_try_remove_all(vm_page_t m)
4650 {
4651
4652 return (vm_page_try_blocked_op(m, pmap_remove_all));
4653 }
4654
4655 /*
4656 * Atomically check for wirings and remove all writeable mappings of the page.
4657 */
4658 bool
vm_page_try_remove_write(vm_page_t m)4659 vm_page_try_remove_write(vm_page_t m)
4660 {
4661
4662 return (vm_page_try_blocked_op(m, pmap_remove_write));
4663 }
4664
4665 /*
4666 * vm_page_advise
4667 *
4668 * Apply the specified advice to the given page.
4669 */
4670 void
vm_page_advise(vm_page_t m,int advice)4671 vm_page_advise(vm_page_t m, int advice)
4672 {
4673
4674 VM_OBJECT_ASSERT_WLOCKED(m->object);
4675 vm_page_assert_xbusied(m);
4676
4677 if (advice == MADV_FREE)
4678 /*
4679 * Mark the page clean. This will allow the page to be freed
4680 * without first paging it out. MADV_FREE pages are often
4681 * quickly reused by malloc(3), so we do not do anything that
4682 * would result in a page fault on a later access.
4683 */
4684 vm_page_undirty(m);
4685 else if (advice != MADV_DONTNEED) {
4686 if (advice == MADV_WILLNEED)
4687 vm_page_activate(m);
4688 return;
4689 }
4690
4691 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4692 vm_page_dirty(m);
4693
4694 /*
4695 * Clear any references to the page. Otherwise, the page daemon will
4696 * immediately reactivate the page.
4697 */
4698 vm_page_aflag_clear(m, PGA_REFERENCED);
4699
4700 /*
4701 * Place clean pages near the head of the inactive queue rather than
4702 * the tail, thus defeating the queue's LRU operation and ensuring that
4703 * the page will be reused quickly. Dirty pages not already in the
4704 * laundry are moved there.
4705 */
4706 if (m->dirty == 0)
4707 vm_page_deactivate_noreuse(m);
4708 else if (!vm_page_in_laundry(m))
4709 vm_page_launder(m);
4710 }
4711
4712 /*
4713 * vm_page_grab_release
4714 *
4715 * Helper routine for grab functions to release busy on return.
4716 */
4717 static inline void
vm_page_grab_release(vm_page_t m,int allocflags)4718 vm_page_grab_release(vm_page_t m, int allocflags)
4719 {
4720
4721 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4722 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4723 vm_page_sunbusy(m);
4724 else
4725 vm_page_xunbusy(m);
4726 }
4727 }
4728
4729 /*
4730 * vm_page_grab_sleep
4731 *
4732 * Sleep for busy according to VM_ALLOC_ parameters. Returns true
4733 * if the caller should retry and false otherwise.
4734 *
4735 * If the object is locked on entry the object will be unlocked with
4736 * false returns and still locked but possibly having been dropped
4737 * with true returns.
4738 */
4739 static bool
vm_page_grab_sleep(vm_object_t object,vm_page_t m,vm_pindex_t pindex,const char * wmesg,int allocflags,bool locked)4740 vm_page_grab_sleep(vm_object_t object, vm_page_t m, vm_pindex_t pindex,
4741 const char *wmesg, int allocflags, bool locked)
4742 {
4743
4744 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4745 return (false);
4746
4747 /*
4748 * Reference the page before unlocking and sleeping so that
4749 * the page daemon is less likely to reclaim it.
4750 */
4751 if (locked && (allocflags & VM_ALLOC_NOCREAT) == 0)
4752 vm_page_reference(m);
4753
4754 if (_vm_page_busy_sleep(object, m, pindex, wmesg, allocflags, locked) &&
4755 locked)
4756 VM_OBJECT_WLOCK(object);
4757 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
4758 return (false);
4759
4760 return (true);
4761 }
4762
4763 /*
4764 * Assert that the grab flags are valid.
4765 */
4766 static inline void
vm_page_grab_check(int allocflags)4767 vm_page_grab_check(int allocflags)
4768 {
4769
4770 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4771 (allocflags & VM_ALLOC_WIRED) != 0,
4772 ("vm_page_grab*: the pages must be busied or wired"));
4773
4774 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4775 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4776 ("vm_page_grab*: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4777 }
4778
4779 /*
4780 * Calculate the page allocation flags for grab.
4781 */
4782 static inline int
vm_page_grab_pflags(int allocflags)4783 vm_page_grab_pflags(int allocflags)
4784 {
4785 int pflags;
4786
4787 pflags = allocflags &
4788 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4789 VM_ALLOC_NOBUSY | VM_ALLOC_IGN_SBUSY | VM_ALLOC_NOCREAT);
4790 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4791 pflags |= VM_ALLOC_WAITFAIL;
4792 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4793 pflags |= VM_ALLOC_SBUSY;
4794
4795 return (pflags);
4796 }
4797
4798 /*
4799 * Grab a page, waiting until we are woken up due to the page changing state.
4800 * We keep on waiting, if the page continues to be in the object, unless
4801 * allocflags forbid waiting.
4802 *
4803 * The object must be locked on entry. This routine may sleep. The lock will,
4804 * however, be released and reacquired if the routine sleeps.
4805 *
4806 * Return a grabbed page, or NULL. Set *found if a page was found, whether or
4807 * not it was grabbed.
4808 */
4809 static inline vm_page_t
vm_page_grab_lookup(vm_object_t object,vm_pindex_t pindex,int allocflags,bool * found,struct pctrie_iter * pages)4810 vm_page_grab_lookup(vm_object_t object, vm_pindex_t pindex, int allocflags,
4811 bool *found, struct pctrie_iter *pages)
4812 {
4813 vm_page_t m;
4814
4815 while ((*found = (m = vm_radix_iter_lookup(pages, pindex)) != NULL) &&
4816 !vm_page_tryacquire(m, allocflags)) {
4817 if (!vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4818 allocflags, true))
4819 return (NULL);
4820 pctrie_iter_reset(pages);
4821 }
4822 return (m);
4823 }
4824
4825 /*
4826 * Grab a page. Use an iterator parameter. Keep on waiting, as long as the page
4827 * exists in the object. If the page doesn't exist, first allocate it and then
4828 * conditionally zero it.
4829 *
4830 * The object must be locked on entry. This routine may sleep. The lock will,
4831 * however, be released and reacquired if the routine sleeps.
4832 */
4833 vm_page_t
vm_page_grab_iter(vm_object_t object,vm_pindex_t pindex,int allocflags,struct pctrie_iter * pages)4834 vm_page_grab_iter(vm_object_t object, vm_pindex_t pindex, int allocflags,
4835 struct pctrie_iter *pages)
4836 {
4837 vm_page_t m;
4838 bool found;
4839
4840 VM_OBJECT_ASSERT_WLOCKED(object);
4841 vm_page_grab_check(allocflags);
4842
4843 while ((m = vm_page_grab_lookup(
4844 object, pindex, allocflags, &found, pages)) == NULL) {
4845 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4846 return (NULL);
4847 if (found &&
4848 (allocflags & (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL)) != 0)
4849 return (NULL);
4850 m = vm_page_alloc_iter(object, pindex,
4851 vm_page_grab_pflags(allocflags), pages);
4852 if (m != NULL) {
4853 if ((allocflags & VM_ALLOC_ZERO) != 0 &&
4854 (m->flags & PG_ZERO) == 0)
4855 pmap_zero_page(m);
4856 break;
4857 }
4858 if ((allocflags &
4859 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL)) != 0)
4860 return (NULL);
4861 }
4862 vm_page_grab_release(m, allocflags);
4863
4864 return (m);
4865 }
4866
4867 /*
4868 * Grab a page. Keep on waiting, as long as the page exists in the object. If
4869 * the page doesn't exist, first allocate it and then conditionally zero it.
4870 *
4871 * The object must be locked on entry. This routine may sleep. The lock will,
4872 * however, be released and reacquired if the routine sleeps.
4873 */
4874 vm_page_t
vm_page_grab(vm_object_t object,vm_pindex_t pindex,int allocflags)4875 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4876 {
4877 struct pctrie_iter pages;
4878
4879 VM_OBJECT_ASSERT_WLOCKED(object);
4880 vm_page_iter_init(&pages, object);
4881 return (vm_page_grab_iter(object, pindex, allocflags, &pages));
4882 }
4883
4884 /*
4885 * Attempt to validate a page, locklessly acquiring it if necessary, given a
4886 * (object, pindex) tuple and either an invalided page or NULL. The resulting
4887 * page will be validated against the identity tuple, and busied or wired as
4888 * requested. A NULL page returned guarantees that the page was not in radix at
4889 * the time of the call but callers must perform higher level synchronization or
4890 * retry the operation under a lock if they require an atomic answer. This is
4891 * the only lock free validation routine, other routines can depend on the
4892 * resulting page state.
4893 *
4894 * The return value PAGE_NOT_ACQUIRED indicates that the operation failed due to
4895 * caller flags.
4896 */
4897 #define PAGE_NOT_ACQUIRED ((vm_page_t)1)
4898 static vm_page_t
vm_page_acquire_unlocked(vm_object_t object,vm_pindex_t pindex,vm_page_t m,int allocflags)4899 vm_page_acquire_unlocked(vm_object_t object, vm_pindex_t pindex, vm_page_t m,
4900 int allocflags)
4901 {
4902 if (m == NULL)
4903 m = vm_page_lookup_unlocked(object, pindex);
4904 for (; m != NULL; m = vm_page_lookup_unlocked(object, pindex)) {
4905 if (vm_page_trybusy(m, allocflags)) {
4906 if (m->object == object && m->pindex == pindex) {
4907 if ((allocflags & VM_ALLOC_WIRED) != 0)
4908 vm_page_wire(m);
4909 vm_page_grab_release(m, allocflags);
4910 break;
4911 }
4912 /* relookup. */
4913 vm_page_busy_release(m);
4914 cpu_spinwait();
4915 continue;
4916 }
4917 if (!vm_page_grab_sleep(object, m, pindex, "pgnslp",
4918 allocflags, false))
4919 return (PAGE_NOT_ACQUIRED);
4920 }
4921 return (m);
4922 }
4923
4924 /*
4925 * Try to locklessly grab a page and fall back to the object lock if NOCREAT
4926 * is not set.
4927 */
4928 vm_page_t
vm_page_grab_unlocked(vm_object_t object,vm_pindex_t pindex,int allocflags)4929 vm_page_grab_unlocked(vm_object_t object, vm_pindex_t pindex, int allocflags)
4930 {
4931 vm_page_t m;
4932
4933 vm_page_grab_check(allocflags);
4934 m = vm_page_acquire_unlocked(object, pindex, NULL, allocflags);
4935 if (m == PAGE_NOT_ACQUIRED)
4936 return (NULL);
4937 if (m != NULL)
4938 return (m);
4939
4940 /*
4941 * The radix lockless lookup should never return a false negative
4942 * errors. If the user specifies NOCREAT they are guaranteed there
4943 * was no page present at the instant of the call. A NOCREAT caller
4944 * must handle create races gracefully.
4945 */
4946 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4947 return (NULL);
4948
4949 VM_OBJECT_WLOCK(object);
4950 m = vm_page_grab(object, pindex, allocflags);
4951 VM_OBJECT_WUNLOCK(object);
4952
4953 return (m);
4954 }
4955
4956 /*
4957 * Grab a page and make it valid, paging in if necessary. Use an iterator
4958 * parameter. Pages missing from their pager are zero filled and validated. If
4959 * a VM_ALLOC_COUNT is supplied and the page is not valid as many as
4960 * VM_INITIAL_PAGEIN pages can be brought in simultaneously. Additional pages
4961 * will be left on a paging queue but will neither be wired nor busy regardless
4962 * of allocflags.
4963 */
4964 int
vm_page_grab_valid_iter(vm_page_t * mp,vm_object_t object,vm_pindex_t pindex,int allocflags,struct pctrie_iter * pages)4965 vm_page_grab_valid_iter(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex,
4966 int allocflags, struct pctrie_iter *pages)
4967 {
4968 vm_page_t m;
4969 vm_page_t ma[VM_INITIAL_PAGEIN];
4970 int after, ahead, i, pflags, rv;
4971
4972 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4973 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4974 ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4975 KASSERT((allocflags &
4976 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4977 ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4978 VM_OBJECT_ASSERT_WLOCKED(object);
4979 pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY |
4980 VM_ALLOC_WIRED | VM_ALLOC_IGN_SBUSY);
4981 pflags |= VM_ALLOC_WAITFAIL;
4982
4983 retrylookup:
4984 if ((m = vm_radix_iter_lookup(pages, pindex)) != NULL) {
4985 /*
4986 * If the page is fully valid it can only become invalid
4987 * with the object lock held. If it is not valid it can
4988 * become valid with the busy lock held. Therefore, we
4989 * may unnecessarily lock the exclusive busy here if we
4990 * race with I/O completion not using the object lock.
4991 * However, we will not end up with an invalid page and a
4992 * shared lock.
4993 */
4994 if (!vm_page_trybusy(m,
4995 vm_page_all_valid(m) ? allocflags : 0)) {
4996 (void)vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4997 allocflags, true);
4998 pctrie_iter_reset(pages);
4999 goto retrylookup;
5000 }
5001 if (vm_page_all_valid(m))
5002 goto out;
5003 if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
5004 vm_page_busy_release(m);
5005 *mp = NULL;
5006 return (VM_PAGER_FAIL);
5007 }
5008 } else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
5009 *mp = NULL;
5010 return (VM_PAGER_FAIL);
5011 } else {
5012 m = vm_page_alloc_iter(object, pindex, pflags, pages);
5013 if (m == NULL) {
5014 if (!vm_pager_can_alloc_page(object, pindex)) {
5015 *mp = NULL;
5016 return (VM_PAGER_AGAIN);
5017 }
5018 goto retrylookup;
5019 }
5020 }
5021
5022 vm_page_assert_xbusied(m);
5023 if (vm_pager_has_page(object, pindex, NULL, &after)) {
5024 after = MIN(after, VM_INITIAL_PAGEIN);
5025 after = MIN(after, allocflags >> VM_ALLOC_COUNT_SHIFT);
5026 after = MAX(after, 1);
5027 ma[0] = m;
5028 pctrie_iter_reset(pages);
5029 for (i = 1; i < after; i++) {
5030 m = vm_radix_iter_lookup_ge(pages, pindex + i);
5031 ahead = after;
5032 if (m != NULL)
5033 ahead = MIN(ahead, m->pindex - pindex);
5034 for (; i < ahead; i++) {
5035 ma[i] = vm_page_alloc_iter(object, pindex + i,
5036 VM_ALLOC_NORMAL, pages);
5037 if (ma[i] == NULL)
5038 break;
5039 }
5040 if (m == NULL || m->pindex != pindex + i ||
5041 vm_page_any_valid(m) || !vm_page_tryxbusy(m))
5042 break;
5043 ma[i] = m;
5044 }
5045 after = i;
5046 vm_object_pip_add(object, after);
5047 VM_OBJECT_WUNLOCK(object);
5048 rv = vm_pager_get_pages(object, ma, after, NULL, NULL);
5049 pctrie_iter_reset(pages);
5050 VM_OBJECT_WLOCK(object);
5051 vm_object_pip_wakeupn(object, after);
5052 /* Pager may have replaced a page. */
5053 m = ma[0];
5054 if (rv != VM_PAGER_OK) {
5055 for (i = 0; i < after; i++) {
5056 if (!vm_page_wired(ma[i]))
5057 vm_page_free(ma[i]);
5058 else
5059 vm_page_xunbusy(ma[i]);
5060 }
5061 *mp = NULL;
5062 return (rv);
5063 }
5064 for (i = 1; i < after; i++)
5065 vm_page_readahead_finish(ma[i]);
5066 MPASS(vm_page_all_valid(m));
5067 } else {
5068 vm_page_zero_invalid(m, TRUE);
5069 pctrie_iter_reset(pages);
5070 }
5071 out:
5072 if ((allocflags & VM_ALLOC_WIRED) != 0)
5073 vm_page_wire(m);
5074 if ((allocflags & VM_ALLOC_SBUSY) != 0 && vm_page_xbusied(m))
5075 vm_page_busy_downgrade(m);
5076 else if ((allocflags & VM_ALLOC_NOBUSY) != 0)
5077 vm_page_busy_release(m);
5078 *mp = m;
5079 return (VM_PAGER_OK);
5080 }
5081
5082 /*
5083 * Grab a page and make it valid, paging in if necessary. Pages missing from
5084 * their pager are zero filled and validated. If a VM_ALLOC_COUNT is supplied
5085 * and the page is not valid as many as VM_INITIAL_PAGEIN pages can be brought
5086 * in simultaneously. Additional pages will be left on a paging queue but
5087 * will neither be wired nor busy regardless of allocflags.
5088 */
5089 int
vm_page_grab_valid(vm_page_t * mp,vm_object_t object,vm_pindex_t pindex,int allocflags)5090 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex,
5091 int allocflags)
5092 {
5093 struct pctrie_iter pages;
5094
5095 VM_OBJECT_ASSERT_WLOCKED(object);
5096 vm_page_iter_init(&pages, object);
5097 return (vm_page_grab_valid_iter(mp, object, pindex, allocflags,
5098 &pages));
5099 }
5100
5101 /*
5102 * Grab a page. Keep on waiting, as long as the page exists in the object. If
5103 * the page doesn't exist, and the pager has it, allocate it and zero part of
5104 * it.
5105 *
5106 * The object must be locked on entry. This routine may sleep. The lock will,
5107 * however, be released and reacquired if the routine sleeps.
5108 */
5109 int
vm_page_grab_zero_partial(vm_object_t object,vm_pindex_t pindex,int base,int end)5110 vm_page_grab_zero_partial(vm_object_t object, vm_pindex_t pindex, int base,
5111 int end)
5112 {
5113 struct pctrie_iter pages;
5114 vm_page_t m;
5115 int allocflags, rv;
5116 bool found;
5117
5118 VM_OBJECT_ASSERT_WLOCKED(object);
5119 KASSERT(base >= 0, ("%s: base %d", __func__, base));
5120 KASSERT(end - base <= PAGE_SIZE, ("%s: base %d end %d", __func__, base,
5121 end));
5122
5123 allocflags = VM_ALLOC_NOCREAT | VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL;
5124 vm_page_iter_init(&pages, object);
5125 while ((m = vm_page_grab_lookup(
5126 object, pindex, allocflags, &found, &pages)) == NULL) {
5127 if (!vm_pager_has_page(object, pindex, NULL, NULL))
5128 return (0);
5129 m = vm_page_alloc_iter(object, pindex,
5130 vm_page_grab_pflags(allocflags), &pages);
5131 if (m != NULL) {
5132 vm_object_pip_add(object, 1);
5133 VM_OBJECT_WUNLOCK(object);
5134 rv = vm_pager_get_pages(object, &m, 1, NULL, NULL);
5135 VM_OBJECT_WLOCK(object);
5136 vm_object_pip_wakeup(object);
5137 if (rv != VM_PAGER_OK) {
5138 vm_page_free(m);
5139 return (EIO);
5140 }
5141
5142 /*
5143 * Since the page was not resident, and therefore not
5144 * recently accessed, immediately enqueue it for
5145 * asynchronous laundering. The current operation is
5146 * not regarded as an access.
5147 */
5148 vm_page_launder(m);
5149 break;
5150 }
5151 }
5152
5153 pmap_zero_page_area(m, base, end - base);
5154 KASSERT(vm_page_all_valid(m), ("%s: page %p is invalid", __func__, m));
5155 vm_page_set_dirty(m);
5156 vm_page_xunbusy(m);
5157 return (0);
5158 }
5159
5160 /*
5161 * Locklessly grab a valid page. If the page is not valid or not yet
5162 * allocated this will fall back to the object lock method.
5163 */
5164 int
vm_page_grab_valid_unlocked(vm_page_t * mp,vm_object_t object,vm_pindex_t pindex,int allocflags)5165 vm_page_grab_valid_unlocked(vm_page_t *mp, vm_object_t object,
5166 vm_pindex_t pindex, int allocflags)
5167 {
5168 vm_page_t m;
5169 int flags;
5170 int error;
5171
5172 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
5173 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
5174 ("vm_page_grab_valid_unlocked: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY "
5175 "mismatch"));
5176 KASSERT((allocflags &
5177 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
5178 ("vm_page_grab_valid_unlocked: Invalid flags 0x%X", allocflags));
5179
5180 /*
5181 * Attempt a lockless lookup and busy. We need at least an sbusy
5182 * before we can inspect the valid field and return a wired page.
5183 */
5184 flags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
5185 vm_page_grab_check(flags);
5186 m = vm_page_acquire_unlocked(object, pindex, NULL, flags);
5187 if (m == PAGE_NOT_ACQUIRED)
5188 return (VM_PAGER_FAIL);
5189 if (m != NULL) {
5190 if (vm_page_all_valid(m)) {
5191 if ((allocflags & VM_ALLOC_WIRED) != 0)
5192 vm_page_wire(m);
5193 vm_page_grab_release(m, allocflags);
5194 *mp = m;
5195 return (VM_PAGER_OK);
5196 }
5197 vm_page_busy_release(m);
5198 }
5199 if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
5200 *mp = NULL;
5201 return (VM_PAGER_FAIL);
5202 }
5203 VM_OBJECT_WLOCK(object);
5204 error = vm_page_grab_valid(mp, object, pindex, allocflags);
5205 VM_OBJECT_WUNLOCK(object);
5206
5207 return (error);
5208 }
5209
5210 /*
5211 * Return the specified range of pages from the given object. For each
5212 * page offset within the range, if a page already exists within the object
5213 * at that offset and it is busy, then wait for it to change state. If,
5214 * instead, the page doesn't exist, then allocate it.
5215 *
5216 * The caller must always specify an allocation class.
5217 *
5218 * allocation classes:
5219 * VM_ALLOC_NORMAL normal process request
5220 * VM_ALLOC_SYSTEM system *really* needs the pages
5221 * VM_ALLOC_INTERRUPT interrupt time request
5222 *
5223 * The caller must always specify that the pages are to be busied and/or
5224 * wired.
5225 *
5226 * optional allocation flags:
5227 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
5228 * VM_ALLOC_NOBUSY do not exclusive busy the pages
5229 * VM_ALLOC_NODUMP do not include the pages in a kernel core dump
5230 * VM_ALLOC_NOFREE pages will never be freed
5231 * VM_ALLOC_NOWAIT do not sleep
5232 * VM_ALLOC_SBUSY set pages to sbusy state
5233 * VM_ALLOC_WAITFAIL in case of failure, sleep before returning
5234 * VM_ALLOC_WAITOK ignored (default behavior)
5235 * VM_ALLOC_WIRED wire the pages
5236 * VM_ALLOC_ZERO zero and validate any invalid pages
5237 *
5238 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
5239 * may return a partial prefix of the requested range.
5240 */
5241 int
vm_page_grab_pages(vm_object_t object,vm_pindex_t pindex,int allocflags,vm_page_t * ma,int count)5242 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
5243 vm_page_t *ma, int count)
5244 {
5245 struct pctrie_iter pages;
5246 vm_page_t m;
5247 int pflags;
5248 int ahead, i;
5249
5250 VM_OBJECT_ASSERT_WLOCKED(object);
5251 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
5252 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
5253 KASSERT(count > 0,
5254 ("vm_page_grab_pages: invalid page count %d", count));
5255 vm_page_grab_check(allocflags);
5256
5257 pflags = vm_page_grab_pflags(allocflags);
5258 i = 0;
5259 vm_page_iter_init(&pages, object);
5260 retrylookup:
5261 ahead = -1;
5262 for (; i < count; i++) {
5263 if (ahead < 0) {
5264 ahead = vm_radix_iter_lookup_range(
5265 &pages, pindex + i, &ma[i], count - i);
5266 }
5267 if (ahead-- > 0) {
5268 m = ma[i];
5269 if (!vm_page_tryacquire(m, allocflags)) {
5270 if (vm_page_grab_sleep(object, m, pindex + i,
5271 "grbmaw", allocflags, true)) {
5272 pctrie_iter_reset(&pages);
5273 goto retrylookup;
5274 }
5275 break;
5276 }
5277 } else {
5278 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
5279 break;
5280 m = vm_page_alloc_iter(object, pindex + i,
5281 pflags | VM_ALLOC_COUNT(count - i), &pages);
5282 /* pages was reset if alloc_iter lost the lock. */
5283 if (m == NULL) {
5284 if ((allocflags & (VM_ALLOC_NOWAIT |
5285 VM_ALLOC_WAITFAIL)) != 0)
5286 break;
5287 goto retrylookup;
5288 }
5289 ma[i] = m;
5290 }
5291 if (vm_page_none_valid(m) &&
5292 (allocflags & VM_ALLOC_ZERO) != 0) {
5293 if ((m->flags & PG_ZERO) == 0)
5294 pmap_zero_page(m);
5295 vm_page_valid(m);
5296 }
5297 vm_page_grab_release(m, allocflags);
5298 }
5299 return (i);
5300 }
5301
5302 /*
5303 * Unlocked variant of vm_page_grab_pages(). This accepts the same flags
5304 * and will fall back to the locked variant to handle allocation.
5305 */
5306 int
vm_page_grab_pages_unlocked(vm_object_t object,vm_pindex_t pindex,int allocflags,vm_page_t * ma,int count)5307 vm_page_grab_pages_unlocked(vm_object_t object, vm_pindex_t pindex,
5308 int allocflags, vm_page_t *ma, int count)
5309 {
5310 vm_page_t m;
5311 int flags;
5312 int i, num_fetched;
5313
5314 KASSERT(count > 0,
5315 ("vm_page_grab_pages_unlocked: invalid page count %d", count));
5316 vm_page_grab_check(allocflags);
5317
5318 /*
5319 * Modify flags for lockless acquire to hold the page until we
5320 * set it valid if necessary.
5321 */
5322 flags = allocflags & ~VM_ALLOC_NOBUSY;
5323 vm_page_grab_check(flags);
5324 num_fetched = vm_radix_lookup_range_unlocked(&object->rtree, pindex,
5325 ma, count);
5326 for (i = 0; i < num_fetched; i++, pindex++) {
5327 m = vm_page_acquire_unlocked(object, pindex, ma[i], flags);
5328 if (m == PAGE_NOT_ACQUIRED)
5329 return (i);
5330 if (m == NULL)
5331 break;
5332 if ((flags & VM_ALLOC_ZERO) != 0 && vm_page_none_valid(m)) {
5333 if ((m->flags & PG_ZERO) == 0)
5334 pmap_zero_page(m);
5335 vm_page_valid(m);
5336 }
5337 /* m will still be wired or busy according to flags. */
5338 vm_page_grab_release(m, allocflags);
5339 /* vm_page_acquire_unlocked() may not return ma[i]. */
5340 ma[i] = m;
5341 }
5342 if (i == count || (allocflags & VM_ALLOC_NOCREAT) != 0)
5343 return (i);
5344 count -= i;
5345 VM_OBJECT_WLOCK(object);
5346 i += vm_page_grab_pages(object, pindex, allocflags, &ma[i], count);
5347 VM_OBJECT_WUNLOCK(object);
5348
5349 return (i);
5350 }
5351
5352 /*
5353 * Mapping function for valid or dirty bits in a page.
5354 *
5355 * Inputs are required to range within a page.
5356 */
5357 vm_page_bits_t
vm_page_bits(int base,int size)5358 vm_page_bits(int base, int size)
5359 {
5360 int first_bit;
5361 int last_bit;
5362
5363 KASSERT(
5364 base + size <= PAGE_SIZE,
5365 ("vm_page_bits: illegal base/size %d/%d", base, size)
5366 );
5367
5368 if (size == 0) /* handle degenerate case */
5369 return (0);
5370
5371 first_bit = base >> DEV_BSHIFT;
5372 last_bit = (base + size - 1) >> DEV_BSHIFT;
5373
5374 return (((vm_page_bits_t)2 << last_bit) -
5375 ((vm_page_bits_t)1 << first_bit));
5376 }
5377
5378 void
vm_page_bits_set(vm_page_t m,vm_page_bits_t * bits,vm_page_bits_t set)5379 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
5380 {
5381 #if PAGE_SIZE == 32768
5382 atomic_set_64((uint64_t *)bits, set);
5383 #elif PAGE_SIZE == 16384
5384 atomic_set_32((uint32_t *)bits, set);
5385 #elif PAGE_SIZE == 8192
5386 atomic_set_16((uint16_t *)bits, set);
5387 #elif PAGE_SIZE == 4096
5388 atomic_set_8((uint8_t *)bits, set);
5389 #else
5390 #error unhandled page size
5391 #endif
5392 }
5393
5394 static inline void
vm_page_bits_clear(vm_page_t m,vm_page_bits_t * bits,vm_page_bits_t clear)5395 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
5396 {
5397 #if PAGE_SIZE == 32768
5398 atomic_clear_64((uint64_t *)bits, clear);
5399 #elif PAGE_SIZE == 16384
5400 atomic_clear_32((uint32_t *)bits, clear);
5401 #elif PAGE_SIZE == 8192
5402 atomic_clear_16((uint16_t *)bits, clear);
5403 #elif PAGE_SIZE == 4096
5404 atomic_clear_8((uint8_t *)bits, clear);
5405 #else
5406 #error unhandled page size
5407 #endif
5408 }
5409
5410 static inline vm_page_bits_t
vm_page_bits_swap(vm_page_t m,vm_page_bits_t * bits,vm_page_bits_t newbits)5411 vm_page_bits_swap(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t newbits)
5412 {
5413 #if PAGE_SIZE == 32768
5414 uint64_t old;
5415
5416 old = *bits;
5417 while (atomic_fcmpset_64(bits, &old, newbits) == 0);
5418 return (old);
5419 #elif PAGE_SIZE == 16384
5420 uint32_t old;
5421
5422 old = *bits;
5423 while (atomic_fcmpset_32(bits, &old, newbits) == 0);
5424 return (old);
5425 #elif PAGE_SIZE == 8192
5426 uint16_t old;
5427
5428 old = *bits;
5429 while (atomic_fcmpset_16(bits, &old, newbits) == 0);
5430 return (old);
5431 #elif PAGE_SIZE == 4096
5432 uint8_t old;
5433
5434 old = *bits;
5435 while (atomic_fcmpset_8(bits, &old, newbits) == 0);
5436 return (old);
5437 #else
5438 #error unhandled page size
5439 #endif
5440 }
5441
5442 /*
5443 * vm_page_set_valid_range:
5444 *
5445 * Sets portions of a page valid. The arguments are expected
5446 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5447 * of any partial chunks touched by the range. The invalid portion of
5448 * such chunks will be zeroed.
5449 *
5450 * (base + size) must be less then or equal to PAGE_SIZE.
5451 */
5452 void
vm_page_set_valid_range(vm_page_t m,int base,int size)5453 vm_page_set_valid_range(vm_page_t m, int base, int size)
5454 {
5455 int endoff, frag;
5456 vm_page_bits_t pagebits;
5457
5458 vm_page_assert_busied(m);
5459 if (size == 0) /* handle degenerate case */
5460 return;
5461
5462 /*
5463 * If the base is not DEV_BSIZE aligned and the valid
5464 * bit is clear, we have to zero out a portion of the
5465 * first block.
5466 */
5467 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5468 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
5469 pmap_zero_page_area(m, frag, base - frag);
5470
5471 /*
5472 * If the ending offset is not DEV_BSIZE aligned and the
5473 * valid bit is clear, we have to zero out a portion of
5474 * the last block.
5475 */
5476 endoff = base + size;
5477 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5478 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
5479 pmap_zero_page_area(m, endoff,
5480 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5481
5482 /*
5483 * Assert that no previously invalid block that is now being validated
5484 * is already dirty.
5485 */
5486 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
5487 ("vm_page_set_valid_range: page %p is dirty", m));
5488
5489 /*
5490 * Set valid bits inclusive of any overlap.
5491 */
5492 pagebits = vm_page_bits(base, size);
5493 if (vm_page_xbusied(m))
5494 m->valid |= pagebits;
5495 else
5496 vm_page_bits_set(m, &m->valid, pagebits);
5497 }
5498
5499 /*
5500 * Set the page dirty bits and free the invalid swap space if
5501 * present. Returns the previous dirty bits.
5502 */
5503 vm_page_bits_t
vm_page_set_dirty(vm_page_t m)5504 vm_page_set_dirty(vm_page_t m)
5505 {
5506 vm_page_bits_t old;
5507
5508 VM_PAGE_OBJECT_BUSY_ASSERT(m);
5509
5510 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m)) {
5511 old = m->dirty;
5512 m->dirty = VM_PAGE_BITS_ALL;
5513 } else
5514 old = vm_page_bits_swap(m, &m->dirty, VM_PAGE_BITS_ALL);
5515 if (old == 0 && (m->a.flags & PGA_SWAP_SPACE) != 0)
5516 vm_pager_page_unswapped(m);
5517
5518 return (old);
5519 }
5520
5521 /*
5522 * Clear the given bits from the specified page's dirty field.
5523 */
5524 static __inline void
vm_page_clear_dirty_mask(vm_page_t m,vm_page_bits_t pagebits)5525 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
5526 {
5527
5528 vm_page_assert_busied(m);
5529
5530 /*
5531 * If the page is xbusied and not write mapped we are the
5532 * only thread that can modify dirty bits. Otherwise, The pmap
5533 * layer can call vm_page_dirty() without holding a distinguished
5534 * lock. The combination of page busy and atomic operations
5535 * suffice to guarantee consistency of the page dirty field.
5536 */
5537 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
5538 m->dirty &= ~pagebits;
5539 else
5540 vm_page_bits_clear(m, &m->dirty, pagebits);
5541 }
5542
5543 /*
5544 * vm_page_set_validclean:
5545 *
5546 * Sets portions of a page valid and clean. The arguments are expected
5547 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5548 * of any partial chunks touched by the range. The invalid portion of
5549 * such chunks will be zero'd.
5550 *
5551 * (base + size) must be less then or equal to PAGE_SIZE.
5552 */
5553 void
vm_page_set_validclean(vm_page_t m,int base,int size)5554 vm_page_set_validclean(vm_page_t m, int base, int size)
5555 {
5556 vm_page_bits_t oldvalid, pagebits;
5557 int endoff, frag;
5558
5559 vm_page_assert_busied(m);
5560 if (size == 0) /* handle degenerate case */
5561 return;
5562
5563 /*
5564 * If the base is not DEV_BSIZE aligned and the valid
5565 * bit is clear, we have to zero out a portion of the
5566 * first block.
5567 */
5568 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5569 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
5570 pmap_zero_page_area(m, frag, base - frag);
5571
5572 /*
5573 * If the ending offset is not DEV_BSIZE aligned and the
5574 * valid bit is clear, we have to zero out a portion of
5575 * the last block.
5576 */
5577 endoff = base + size;
5578 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5579 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
5580 pmap_zero_page_area(m, endoff,
5581 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5582
5583 /*
5584 * Set valid, clear dirty bits. If validating the entire
5585 * page we can safely clear the pmap modify bit. We also
5586 * use this opportunity to clear the PGA_NOSYNC flag. If a process
5587 * takes a write fault on a MAP_NOSYNC memory area the flag will
5588 * be set again.
5589 *
5590 * We set valid bits inclusive of any overlap, but we can only
5591 * clear dirty bits for DEV_BSIZE chunks that are fully within
5592 * the range.
5593 */
5594 oldvalid = m->valid;
5595 pagebits = vm_page_bits(base, size);
5596 if (vm_page_xbusied(m))
5597 m->valid |= pagebits;
5598 else
5599 vm_page_bits_set(m, &m->valid, pagebits);
5600 #if 0 /* NOT YET */
5601 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
5602 frag = DEV_BSIZE - frag;
5603 base += frag;
5604 size -= frag;
5605 if (size < 0)
5606 size = 0;
5607 }
5608 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
5609 #endif
5610 if (base == 0 && size == PAGE_SIZE) {
5611 /*
5612 * The page can only be modified within the pmap if it is
5613 * mapped, and it can only be mapped if it was previously
5614 * fully valid.
5615 */
5616 if (oldvalid == VM_PAGE_BITS_ALL)
5617 /*
5618 * Perform the pmap_clear_modify() first. Otherwise,
5619 * a concurrent pmap operation, such as
5620 * pmap_protect(), could clear a modification in the
5621 * pmap and set the dirty field on the page before
5622 * pmap_clear_modify() had begun and after the dirty
5623 * field was cleared here.
5624 */
5625 pmap_clear_modify(m);
5626 m->dirty = 0;
5627 vm_page_aflag_clear(m, PGA_NOSYNC);
5628 } else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
5629 m->dirty &= ~pagebits;
5630 else
5631 vm_page_clear_dirty_mask(m, pagebits);
5632 }
5633
5634 void
vm_page_clear_dirty(vm_page_t m,int base,int size)5635 vm_page_clear_dirty(vm_page_t m, int base, int size)
5636 {
5637
5638 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
5639 }
5640
5641 /*
5642 * vm_page_set_invalid:
5643 *
5644 * Invalidates DEV_BSIZE'd chunks within a page. Both the
5645 * valid and dirty bits for the effected areas are cleared.
5646 */
5647 void
vm_page_set_invalid(vm_page_t m,int base,int size)5648 vm_page_set_invalid(vm_page_t m, int base, int size)
5649 {
5650 vm_page_bits_t bits;
5651 vm_object_t object;
5652
5653 /*
5654 * The object lock is required so that pages can't be mapped
5655 * read-only while we're in the process of invalidating them.
5656 */
5657 object = m->object;
5658 VM_OBJECT_ASSERT_WLOCKED(object);
5659 vm_page_assert_busied(m);
5660
5661 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
5662 size >= object->un_pager.vnp.vnp_size)
5663 bits = VM_PAGE_BITS_ALL;
5664 else
5665 bits = vm_page_bits(base, size);
5666 if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
5667 pmap_remove_all(m);
5668 KASSERT((bits == 0 && vm_page_all_valid(m)) ||
5669 !pmap_page_is_mapped(m),
5670 ("vm_page_set_invalid: page %p is mapped", m));
5671 if (vm_page_xbusied(m)) {
5672 m->valid &= ~bits;
5673 m->dirty &= ~bits;
5674 } else {
5675 vm_page_bits_clear(m, &m->valid, bits);
5676 vm_page_bits_clear(m, &m->dirty, bits);
5677 }
5678 }
5679
5680 /*
5681 * vm_page_invalid:
5682 *
5683 * Invalidates the entire page. The page must be busy, unmapped, and
5684 * the enclosing object must be locked. The object locks protects
5685 * against concurrent read-only pmap enter which is done without
5686 * busy.
5687 */
5688 void
vm_page_invalid(vm_page_t m)5689 vm_page_invalid(vm_page_t m)
5690 {
5691
5692 vm_page_assert_busied(m);
5693 VM_OBJECT_ASSERT_WLOCKED(m->object);
5694 MPASS(!pmap_page_is_mapped(m));
5695
5696 if (vm_page_xbusied(m))
5697 m->valid = 0;
5698 else
5699 vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
5700 }
5701
5702 /*
5703 * vm_page_zero_invalid()
5704 *
5705 * The kernel assumes that the invalid portions of a page contain
5706 * garbage, but such pages can be mapped into memory by user code.
5707 * When this occurs, we must zero out the non-valid portions of the
5708 * page so user code sees what it expects.
5709 *
5710 * Pages are most often semi-valid when the end of a file is mapped
5711 * into memory and the file's size is not page aligned.
5712 */
5713 void
vm_page_zero_invalid(vm_page_t m,boolean_t setvalid)5714 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
5715 {
5716 int b;
5717 int i;
5718
5719 /*
5720 * Scan the valid bits looking for invalid sections that
5721 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
5722 * valid bit may be set ) have already been zeroed by
5723 * vm_page_set_validclean().
5724 */
5725 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
5726 if (i == (PAGE_SIZE / DEV_BSIZE) ||
5727 (m->valid & ((vm_page_bits_t)1 << i))) {
5728 if (i > b) {
5729 pmap_zero_page_area(m,
5730 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
5731 }
5732 b = i + 1;
5733 }
5734 }
5735
5736 /*
5737 * setvalid is TRUE when we can safely set the zero'd areas
5738 * as being valid. We can do this if there are no cache consistency
5739 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
5740 */
5741 if (setvalid)
5742 vm_page_valid(m);
5743 }
5744
5745 /*
5746 * vm_page_is_valid:
5747 *
5748 * Is (partial) page valid? Note that the case where size == 0
5749 * will return FALSE in the degenerate case where the page is
5750 * entirely invalid, and TRUE otherwise.
5751 *
5752 * Some callers envoke this routine without the busy lock held and
5753 * handle races via higher level locks. Typical callers should
5754 * hold a busy lock to prevent invalidation.
5755 */
5756 int
vm_page_is_valid(vm_page_t m,int base,int size)5757 vm_page_is_valid(vm_page_t m, int base, int size)
5758 {
5759 vm_page_bits_t bits;
5760
5761 bits = vm_page_bits(base, size);
5762 return (vm_page_any_valid(m) && (m->valid & bits) == bits);
5763 }
5764
5765 /*
5766 * Returns true if all of the specified predicates are true for the entire
5767 * (super)page and false otherwise.
5768 */
5769 bool
vm_page_ps_test(vm_page_t m,int psind,int flags,vm_page_t skip_m)5770 vm_page_ps_test(vm_page_t m, int psind, int flags, vm_page_t skip_m)
5771 {
5772 vm_object_t object;
5773 int i, npages;
5774
5775 object = m->object;
5776 if (skip_m != NULL && skip_m->object != object)
5777 return (false);
5778 VM_OBJECT_ASSERT_LOCKED(object);
5779 KASSERT(psind <= m->psind,
5780 ("psind %d > psind %d of m %p", psind, m->psind, m));
5781 npages = atop(pagesizes[psind]);
5782
5783 /*
5784 * The physically contiguous pages that make up a superpage, i.e., a
5785 * page with a page size index ("psind") greater than zero, will
5786 * occupy adjacent entries in vm_page_array[].
5787 */
5788 for (i = 0; i < npages; i++) {
5789 /* Always test object consistency, including "skip_m". */
5790 if (m[i].object != object)
5791 return (false);
5792 if (&m[i] == skip_m)
5793 continue;
5794 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
5795 return (false);
5796 if ((flags & PS_ALL_DIRTY) != 0) {
5797 /*
5798 * Calling vm_page_test_dirty() or pmap_is_modified()
5799 * might stop this case from spuriously returning
5800 * "false". However, that would require a write lock
5801 * on the object containing "m[i]".
5802 */
5803 if (m[i].dirty != VM_PAGE_BITS_ALL)
5804 return (false);
5805 }
5806 if ((flags & PS_ALL_VALID) != 0 &&
5807 m[i].valid != VM_PAGE_BITS_ALL)
5808 return (false);
5809 }
5810 return (true);
5811 }
5812
5813 /*
5814 * Set the page's dirty bits if the page is modified.
5815 */
5816 void
vm_page_test_dirty(vm_page_t m)5817 vm_page_test_dirty(vm_page_t m)
5818 {
5819
5820 vm_page_assert_busied(m);
5821 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
5822 vm_page_dirty(m);
5823 }
5824
5825 void
vm_page_valid(vm_page_t m)5826 vm_page_valid(vm_page_t m)
5827 {
5828
5829 vm_page_assert_busied(m);
5830 if (vm_page_xbusied(m))
5831 m->valid = VM_PAGE_BITS_ALL;
5832 else
5833 vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
5834 }
5835
5836 #ifdef INVARIANTS
5837 void
vm_page_object_busy_assert(vm_page_t m)5838 vm_page_object_busy_assert(vm_page_t m)
5839 {
5840
5841 /*
5842 * Certain of the page's fields may only be modified by the
5843 * holder of a page or object busy.
5844 */
5845 if (m->object != NULL && !vm_page_busied(m))
5846 VM_OBJECT_ASSERT_BUSY(m->object);
5847 }
5848
5849 void
vm_page_assert_pga_writeable(vm_page_t m,uint16_t bits)5850 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5851 {
5852
5853 if ((bits & PGA_WRITEABLE) == 0)
5854 return;
5855
5856 /*
5857 * The PGA_WRITEABLE flag can only be set if the page is
5858 * managed, is exclusively busied or the object is locked.
5859 * Currently, this flag is only set by pmap_enter().
5860 */
5861 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5862 ("PGA_WRITEABLE on unmanaged page"));
5863 if (!vm_page_xbusied(m))
5864 VM_OBJECT_ASSERT_BUSY(m->object);
5865 }
5866 #endif
5867
5868 #include "opt_ddb.h"
5869 #ifdef DDB
5870 #include <sys/kernel.h>
5871
5872 #include <ddb/ddb.h>
5873
DB_SHOW_COMMAND_FLAGS(page,vm_page_print_page_info,DB_CMD_MEMSAFE)5874 DB_SHOW_COMMAND_FLAGS(page, vm_page_print_page_info, DB_CMD_MEMSAFE)
5875 {
5876
5877 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5878 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5879 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5880 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5881 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5882 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5883 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5884 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5885 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5886 }
5887
DB_SHOW_COMMAND_FLAGS(pageq,vm_page_print_pageq_info,DB_CMD_MEMSAFE)5888 DB_SHOW_COMMAND_FLAGS(pageq, vm_page_print_pageq_info, DB_CMD_MEMSAFE)
5889 {
5890 int dom;
5891
5892 db_printf("pq_free %d\n", vm_free_count());
5893 for (dom = 0; dom < vm_ndomains; dom++) {
5894 db_printf(
5895 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5896 dom,
5897 vm_dom[dom].vmd_page_count,
5898 vm_dom[dom].vmd_free_count,
5899 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5900 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5901 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5902 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5903 }
5904 }
5905
DB_SHOW_COMMAND(pginfo,vm_page_print_pginfo)5906 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5907 {
5908 vm_page_t m;
5909 boolean_t phys, virt;
5910
5911 if (!have_addr) {
5912 db_printf("show pginfo addr\n");
5913 return;
5914 }
5915
5916 phys = strchr(modif, 'p') != NULL;
5917 virt = strchr(modif, 'v') != NULL;
5918 if (virt)
5919 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5920 else if (phys)
5921 m = PHYS_TO_VM_PAGE(addr);
5922 else
5923 m = (vm_page_t)addr;
5924 db_printf(
5925 "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref 0x%x\n"
5926 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5927 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5928 m->a.queue, m->ref_count, m->a.flags, m->oflags,
5929 m->flags, m->a.act_count, m->busy_lock, m->valid, m->dirty);
5930 }
5931 #endif /* DDB */
5932