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