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 * Note: swap associated with the page must be invalidated by the move. We
2042 * have to do this for several reasons: (1) we aren't freeing the
2043 * page, (2) we are dirtying the page, (3) the VM system is probably
2044 * moving the page from object A to B, and will then later move
2045 * the backing store from A to B and we can't have a conflict.
2046 *
2047 * Note: we *always* dirty the page. It is necessary both for the
2048 * fact that we moved it, and because we may be invalidating
2049 * swap.
2050 *
2051 * The objects must be locked.
2052 */
2053 bool
vm_page_iter_rename(struct pctrie_iter * old_pages,vm_page_t m,vm_object_t new_object,vm_pindex_t new_pindex)2054 vm_page_iter_rename(struct pctrie_iter *old_pages, vm_page_t m,
2055 vm_object_t new_object, vm_pindex_t new_pindex)
2056 {
2057 vm_page_t mpred;
2058 vm_pindex_t opidx;
2059
2060 KASSERT((m->ref_count & VPRC_OBJREF) != 0,
2061 ("%s: page %p is missing object ref", __func__, m));
2062 VM_OBJECT_ASSERT_WLOCKED(m->object);
2063 VM_OBJECT_ASSERT_WLOCKED(new_object);
2064
2065 /*
2066 * Create a custom version of vm_page_insert() which does not depend
2067 * by m_prev and can cheat on the implementation aspects of the
2068 * function.
2069 */
2070 opidx = m->pindex;
2071 m->pindex = new_pindex;
2072 if (vm_radix_insert_lookup_lt(&new_object->rtree, m, &mpred) != 0) {
2073 m->pindex = opidx;
2074 return (false);
2075 }
2076
2077 /*
2078 * The operation cannot fail anymore. The removal must happen before
2079 * the listq iterator is tainted.
2080 */
2081 m->pindex = opidx;
2082 vm_radix_iter_remove(old_pages);
2083 vm_page_remove_radixdone(m);
2084
2085 /* Return back to the new pindex to complete vm_page_insert(). */
2086 m->pindex = new_pindex;
2087 m->object = new_object;
2088
2089 vm_page_insert_radixdone(m, new_object, mpred);
2090 vm_page_dirty(m);
2091 vm_pager_page_inserted(new_object, m);
2092 return (true);
2093 }
2094
2095 /*
2096 * vm_page_mpred:
2097 *
2098 * Return the greatest page of the object with index <= pindex,
2099 * or NULL, if there is none. Assumes object lock is held.
2100 */
2101 vm_page_t
vm_page_mpred(vm_object_t object,vm_pindex_t pindex)2102 vm_page_mpred(vm_object_t object, vm_pindex_t pindex)
2103 {
2104 return (vm_radix_lookup_le(&object->rtree, pindex));
2105 }
2106
2107 /*
2108 * vm_page_alloc:
2109 *
2110 * Allocate and return a page that is associated with the specified
2111 * object and offset pair. By default, this page is exclusive busied.
2112 *
2113 * The caller must always specify an allocation class.
2114 *
2115 * allocation classes:
2116 * VM_ALLOC_NORMAL normal process request
2117 * VM_ALLOC_SYSTEM system *really* needs a page
2118 * VM_ALLOC_INTERRUPT interrupt time request
2119 *
2120 * optional allocation flags:
2121 * VM_ALLOC_COUNT(number) the number of additional pages that the caller
2122 * intends to allocate
2123 * VM_ALLOC_NOBUSY do not exclusive busy the page
2124 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
2125 * VM_ALLOC_SBUSY shared busy the allocated page
2126 * VM_ALLOC_WIRED wire the allocated page
2127 * VM_ALLOC_ZERO prefer a zeroed page
2128 */
2129 vm_page_t
vm_page_alloc(vm_object_t object,vm_pindex_t pindex,int req)2130 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
2131 {
2132
2133 return (vm_page_alloc_after(object, pindex, req,
2134 vm_page_mpred(object, pindex)));
2135 }
2136
2137 /*
2138 * Allocate a page in the specified object with the given page index. To
2139 * optimize insertion of the page into the object, the caller must also specify
2140 * the resident page in the object with largest index smaller than the given
2141 * page index, or NULL if no such page exists.
2142 */
2143 vm_page_t
vm_page_alloc_after(vm_object_t object,vm_pindex_t pindex,int req,vm_page_t mpred)2144 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex,
2145 int req, vm_page_t mpred)
2146 {
2147 struct vm_domainset_iter di;
2148 vm_page_t m;
2149 int domain;
2150
2151 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2152 do {
2153 m = vm_page_alloc_domain_after(object, pindex, domain, req,
2154 mpred);
2155 if (m != NULL)
2156 break;
2157 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
2158
2159 return (m);
2160 }
2161
2162 /*
2163 * Returns true if the number of free pages exceeds the minimum
2164 * for the request class and false otherwise.
2165 */
2166 static int
_vm_domain_allocate(struct vm_domain * vmd,int req_class,int npages)2167 _vm_domain_allocate(struct vm_domain *vmd, int req_class, int npages)
2168 {
2169 u_int limit, old, new;
2170
2171 if (req_class == VM_ALLOC_INTERRUPT)
2172 limit = 0;
2173 else if (req_class == VM_ALLOC_SYSTEM)
2174 limit = vmd->vmd_interrupt_free_min;
2175 else
2176 limit = vmd->vmd_free_reserved;
2177
2178 /*
2179 * Attempt to reserve the pages. Fail if we're below the limit.
2180 */
2181 limit += npages;
2182 old = atomic_load_int(&vmd->vmd_free_count);
2183 do {
2184 if (old < limit)
2185 return (0);
2186 new = old - npages;
2187 } while (atomic_fcmpset_int(&vmd->vmd_free_count, &old, new) == 0);
2188
2189 /* Wake the page daemon if we've crossed the threshold. */
2190 if (vm_paging_needed(vmd, new) && !vm_paging_needed(vmd, old))
2191 pagedaemon_wakeup(vmd->vmd_domain);
2192
2193 /* Only update bitsets on transitions. */
2194 if ((old >= vmd->vmd_free_min && new < vmd->vmd_free_min) ||
2195 (old >= vmd->vmd_free_severe && new < vmd->vmd_free_severe))
2196 vm_domain_set(vmd);
2197
2198 return (1);
2199 }
2200
2201 int
vm_domain_allocate(struct vm_domain * vmd,int req,int npages)2202 vm_domain_allocate(struct vm_domain *vmd, int req, int npages)
2203 {
2204 int req_class;
2205
2206 /*
2207 * The page daemon is allowed to dig deeper into the free page list.
2208 */
2209 req_class = req & VM_ALLOC_CLASS_MASK;
2210 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2211 req_class = VM_ALLOC_SYSTEM;
2212 return (_vm_domain_allocate(vmd, req_class, npages));
2213 }
2214
2215 vm_page_t
vm_page_alloc_domain_after(vm_object_t object,vm_pindex_t pindex,int domain,int req,vm_page_t mpred)2216 vm_page_alloc_domain_after(vm_object_t object, vm_pindex_t pindex, int domain,
2217 int req, vm_page_t mpred)
2218 {
2219 struct vm_domain *vmd;
2220 vm_page_t m;
2221 int flags;
2222
2223 #define VPA_FLAGS (VM_ALLOC_CLASS_MASK | VM_ALLOC_WAITFAIL | \
2224 VM_ALLOC_NOWAIT | VM_ALLOC_NOBUSY | \
2225 VM_ALLOC_SBUSY | VM_ALLOC_WIRED | \
2226 VM_ALLOC_NODUMP | VM_ALLOC_ZERO | \
2227 VM_ALLOC_NOFREE | VM_ALLOC_COUNT_MASK)
2228 KASSERT((req & ~VPA_FLAGS) == 0,
2229 ("invalid request %#x", req));
2230 KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2231 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2232 ("invalid request %#x", req));
2233 KASSERT(mpred == NULL || mpred->pindex < pindex,
2234 ("mpred %p doesn't precede pindex 0x%jx", mpred,
2235 (uintmax_t)pindex));
2236 VM_OBJECT_ASSERT_WLOCKED(object);
2237
2238 flags = 0;
2239 m = NULL;
2240 if (!vm_pager_can_alloc_page(object, pindex))
2241 return (NULL);
2242 again:
2243 if (__predict_false((req & VM_ALLOC_NOFREE) != 0)) {
2244 m = vm_page_alloc_nofree_domain(domain, req);
2245 if (m != NULL)
2246 goto found;
2247 }
2248 #if VM_NRESERVLEVEL > 0
2249 /*
2250 * Can we allocate the page from a reservation?
2251 */
2252 if (vm_object_reserv(object) &&
2253 (m = vm_reserv_alloc_page(object, pindex, domain, req, mpred)) !=
2254 NULL) {
2255 goto found;
2256 }
2257 #endif
2258 vmd = VM_DOMAIN(domain);
2259 if (vmd->vmd_pgcache[VM_FREEPOOL_DEFAULT].zone != NULL) {
2260 m = uma_zalloc(vmd->vmd_pgcache[VM_FREEPOOL_DEFAULT].zone,
2261 M_NOWAIT | M_NOVM);
2262 if (m != NULL) {
2263 flags |= PG_PCPU_CACHE;
2264 goto found;
2265 }
2266 }
2267 if (vm_domain_allocate(vmd, req, 1)) {
2268 /*
2269 * If not, allocate it from the free page queues.
2270 */
2271 vm_domain_free_lock(vmd);
2272 m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DEFAULT, 0);
2273 vm_domain_free_unlock(vmd);
2274 if (m == NULL) {
2275 vm_domain_freecnt_inc(vmd, 1);
2276 #if VM_NRESERVLEVEL > 0
2277 if (vm_reserv_reclaim_inactive(domain))
2278 goto again;
2279 #endif
2280 }
2281 }
2282 if (m == NULL) {
2283 /*
2284 * Not allocatable, give up.
2285 */
2286 if (vm_domain_alloc_fail(vmd, object, req))
2287 goto again;
2288 return (NULL);
2289 }
2290
2291 /*
2292 * At this point we had better have found a good page.
2293 */
2294 found:
2295 vm_page_dequeue(m);
2296 vm_page_alloc_check(m);
2297
2298 /*
2299 * Initialize the page. Only the PG_ZERO flag is inherited.
2300 */
2301 flags |= m->flags & PG_ZERO;
2302 if ((req & VM_ALLOC_NODUMP) != 0)
2303 flags |= PG_NODUMP;
2304 if ((req & VM_ALLOC_NOFREE) != 0)
2305 flags |= PG_NOFREE;
2306 m->flags = flags;
2307 m->a.flags = 0;
2308 m->oflags = (object->flags & OBJ_UNMANAGED) != 0 ? VPO_UNMANAGED : 0;
2309 m->pool = VM_FREEPOOL_DEFAULT;
2310 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2311 m->busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2312 else if ((req & VM_ALLOC_SBUSY) != 0)
2313 m->busy_lock = VPB_SHARERS_WORD(1);
2314 else
2315 m->busy_lock = VPB_UNBUSIED;
2316 if (req & VM_ALLOC_WIRED) {
2317 vm_wire_add(1);
2318 m->ref_count = 1;
2319 }
2320 m->a.act_count = 0;
2321
2322 if (vm_page_insert_after(m, object, pindex, mpred)) {
2323 if (req & VM_ALLOC_WIRED) {
2324 vm_wire_sub(1);
2325 m->ref_count = 0;
2326 }
2327 KASSERT(m->object == NULL, ("page %p has object", m));
2328 m->oflags = VPO_UNMANAGED;
2329 m->busy_lock = VPB_UNBUSIED;
2330 /* Don't change PG_ZERO. */
2331 vm_page_free_toq(m);
2332 if (req & VM_ALLOC_WAITFAIL) {
2333 VM_OBJECT_WUNLOCK(object);
2334 vm_radix_wait();
2335 VM_OBJECT_WLOCK(object);
2336 }
2337 return (NULL);
2338 }
2339
2340 /* Ignore device objects; the pager sets "memattr" for them. */
2341 if (object->memattr != VM_MEMATTR_DEFAULT &&
2342 (object->flags & OBJ_FICTITIOUS) == 0)
2343 pmap_page_set_memattr(m, object->memattr);
2344
2345 return (m);
2346 }
2347
2348 /*
2349 * vm_page_alloc_contig:
2350 *
2351 * Allocate a contiguous set of physical pages of the given size "npages"
2352 * from the free lists. All of the physical pages must be at or above
2353 * the given physical address "low" and below the given physical address
2354 * "high". The given value "alignment" determines the alignment of the
2355 * first physical page in the set. If the given value "boundary" is
2356 * non-zero, then the set of physical pages cannot cross any physical
2357 * address boundary that is a multiple of that value. Both "alignment"
2358 * and "boundary" must be a power of two.
2359 *
2360 * If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
2361 * then the memory attribute setting for the physical pages is configured
2362 * to the object's memory attribute setting. Otherwise, the memory
2363 * attribute setting for the physical pages is configured to "memattr",
2364 * overriding the object's memory attribute setting. However, if the
2365 * object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
2366 * memory attribute setting for the physical pages cannot be configured
2367 * to VM_MEMATTR_DEFAULT.
2368 *
2369 * The specified object may not contain fictitious pages.
2370 *
2371 * The caller must always specify an allocation class.
2372 *
2373 * allocation classes:
2374 * VM_ALLOC_NORMAL normal process request
2375 * VM_ALLOC_SYSTEM system *really* needs a page
2376 * VM_ALLOC_INTERRUPT interrupt time request
2377 *
2378 * optional allocation flags:
2379 * VM_ALLOC_NOBUSY do not exclusive busy the page
2380 * VM_ALLOC_NODUMP do not include the page in a kernel core dump
2381 * VM_ALLOC_SBUSY shared busy the allocated page
2382 * VM_ALLOC_WIRED wire the allocated page
2383 * VM_ALLOC_ZERO prefer a zeroed page
2384 */
2385 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)2386 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
2387 u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2388 vm_paddr_t boundary, vm_memattr_t memattr)
2389 {
2390 struct vm_domainset_iter di;
2391 vm_page_t bounds[2];
2392 vm_page_t m;
2393 int domain;
2394 int start_segind;
2395
2396 start_segind = -1;
2397
2398 vm_domainset_iter_page_init(&di, object, pindex, &domain, &req);
2399 do {
2400 m = vm_page_alloc_contig_domain(object, pindex, domain, req,
2401 npages, low, high, alignment, boundary, memattr);
2402 if (m != NULL)
2403 break;
2404 if (start_segind == -1)
2405 start_segind = vm_phys_lookup_segind(low);
2406 if (vm_phys_find_range(bounds, start_segind, domain,
2407 npages, low, high) == -1) {
2408 vm_domainset_iter_ignore(&di, domain);
2409 }
2410 } while (vm_domainset_iter_page(&di, object, &domain) == 0);
2411
2412 return (m);
2413 }
2414
2415 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)2416 vm_page_find_contig_domain(int domain, int req, u_long npages, vm_paddr_t low,
2417 vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
2418 {
2419 struct vm_domain *vmd;
2420 vm_page_t m_ret;
2421
2422 /*
2423 * Can we allocate the pages without the number of free pages falling
2424 * below the lower bound for the allocation class?
2425 */
2426 vmd = VM_DOMAIN(domain);
2427 if (!vm_domain_allocate(vmd, req, npages))
2428 return (NULL);
2429 /*
2430 * Try to allocate the pages from the free page queues.
2431 */
2432 vm_domain_free_lock(vmd);
2433 m_ret = vm_phys_alloc_contig(domain, npages, low, high,
2434 alignment, boundary);
2435 vm_domain_free_unlock(vmd);
2436 if (m_ret != NULL)
2437 return (m_ret);
2438 #if VM_NRESERVLEVEL > 0
2439 /*
2440 * Try to break a reservation to allocate the pages.
2441 */
2442 if ((req & VM_ALLOC_NORECLAIM) == 0) {
2443 m_ret = vm_reserv_reclaim_contig(domain, npages, low,
2444 high, alignment, boundary);
2445 if (m_ret != NULL)
2446 return (m_ret);
2447 }
2448 #endif
2449 vm_domain_freecnt_inc(vmd, npages);
2450 return (NULL);
2451 }
2452
2453 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)2454 vm_page_alloc_contig_domain(vm_object_t object, vm_pindex_t pindex, int domain,
2455 int req, u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
2456 vm_paddr_t boundary, vm_memattr_t memattr)
2457 {
2458 struct pctrie_iter pages;
2459 vm_page_t m, m_ret, mpred;
2460 u_int busy_lock, flags, oflags;
2461
2462 #define VPAC_FLAGS (VPA_FLAGS | VM_ALLOC_NORECLAIM)
2463 KASSERT((req & ~VPAC_FLAGS) == 0,
2464 ("invalid request %#x", req));
2465 KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2466 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2467 ("invalid request %#x", req));
2468 KASSERT((req & (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM)) !=
2469 (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM),
2470 ("invalid request %#x", req));
2471 VM_OBJECT_ASSERT_WLOCKED(object);
2472 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
2473 ("vm_page_alloc_contig: object %p has fictitious pages",
2474 object));
2475 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2476
2477 vm_page_iter_init(&pages, object);
2478 mpred = vm_radix_iter_lookup_le(&pages, pindex);
2479 KASSERT(mpred == NULL || mpred->pindex != pindex,
2480 ("vm_page_alloc_contig: pindex already allocated"));
2481 for (;;) {
2482 #if VM_NRESERVLEVEL > 0
2483 /*
2484 * Can we allocate the pages from a reservation?
2485 */
2486 if (vm_object_reserv(object) &&
2487 (m_ret = vm_reserv_alloc_contig(object, pindex, domain, req,
2488 mpred, npages, low, high, alignment, boundary)) != NULL) {
2489 break;
2490 }
2491 #endif
2492 if ((m_ret = vm_page_find_contig_domain(domain, req, npages,
2493 low, high, alignment, boundary)) != NULL)
2494 break;
2495 if (!vm_domain_alloc_fail(VM_DOMAIN(domain), object, req))
2496 return (NULL);
2497 }
2498
2499 /*
2500 * Initialize the pages. Only the PG_ZERO flag is inherited.
2501 */
2502 flags = PG_ZERO;
2503 if ((req & VM_ALLOC_NODUMP) != 0)
2504 flags |= PG_NODUMP;
2505 oflags = (object->flags & OBJ_UNMANAGED) != 0 ? VPO_UNMANAGED : 0;
2506 if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2507 busy_lock = VPB_CURTHREAD_EXCLUSIVE;
2508 else if ((req & VM_ALLOC_SBUSY) != 0)
2509 busy_lock = VPB_SHARERS_WORD(1);
2510 else
2511 busy_lock = VPB_UNBUSIED;
2512 if ((req & VM_ALLOC_WIRED) != 0)
2513 vm_wire_add(npages);
2514 if (object->memattr != VM_MEMATTR_DEFAULT &&
2515 memattr == VM_MEMATTR_DEFAULT)
2516 memattr = object->memattr;
2517 for (m = m_ret; m < &m_ret[npages]; m++) {
2518 vm_page_dequeue(m);
2519 vm_page_alloc_check(m);
2520 m->a.flags = 0;
2521 m->flags = (m->flags | PG_NODUMP) & flags;
2522 m->busy_lock = busy_lock;
2523 if ((req & VM_ALLOC_WIRED) != 0)
2524 m->ref_count = 1;
2525 m->a.act_count = 0;
2526 m->oflags = oflags;
2527 m->pool = VM_FREEPOOL_DEFAULT;
2528 if (vm_page_iter_insert(&pages, m, object, pindex, mpred)) {
2529 if ((req & VM_ALLOC_WIRED) != 0)
2530 vm_wire_sub(npages);
2531 KASSERT(m->object == NULL,
2532 ("page %p has object", m));
2533 mpred = m;
2534 for (m = m_ret; m < &m_ret[npages]; m++) {
2535 if (m <= mpred &&
2536 (req & VM_ALLOC_WIRED) != 0)
2537 m->ref_count = 0;
2538 m->oflags = VPO_UNMANAGED;
2539 m->busy_lock = VPB_UNBUSIED;
2540 /* Don't change PG_ZERO. */
2541 vm_page_free_toq(m);
2542 }
2543 if (req & VM_ALLOC_WAITFAIL) {
2544 VM_OBJECT_WUNLOCK(object);
2545 vm_radix_wait();
2546 VM_OBJECT_WLOCK(object);
2547 }
2548 return (NULL);
2549 }
2550 mpred = m;
2551 if (memattr != VM_MEMATTR_DEFAULT)
2552 pmap_page_set_memattr(m, memattr);
2553 pindex++;
2554 }
2555 return (m_ret);
2556 }
2557
2558 /*
2559 * Allocate a physical page that is not intended to be inserted into a VM
2560 * object.
2561 */
2562 vm_page_t
vm_page_alloc_noobj_domain(int domain,int req)2563 vm_page_alloc_noobj_domain(int domain, int req)
2564 {
2565 struct vm_domain *vmd;
2566 vm_page_t m;
2567 int flags;
2568
2569 #define VPAN_FLAGS (VM_ALLOC_CLASS_MASK | VM_ALLOC_WAITFAIL | \
2570 VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | \
2571 VM_ALLOC_NOBUSY | VM_ALLOC_WIRED | \
2572 VM_ALLOC_NODUMP | VM_ALLOC_ZERO | \
2573 VM_ALLOC_NOFREE | VM_ALLOC_COUNT_MASK)
2574 KASSERT((req & ~VPAN_FLAGS) == 0,
2575 ("invalid request %#x", req));
2576
2577 flags = ((req & VM_ALLOC_NODUMP) != 0 ? PG_NODUMP : 0) |
2578 ((req & VM_ALLOC_NOFREE) != 0 ? PG_NOFREE : 0);
2579 vmd = VM_DOMAIN(domain);
2580 again:
2581 if (__predict_false((req & VM_ALLOC_NOFREE) != 0)) {
2582 m = vm_page_alloc_nofree_domain(domain, req);
2583 if (m != NULL)
2584 goto found;
2585 }
2586
2587 if (vmd->vmd_pgcache[VM_FREEPOOL_DIRECT].zone != NULL) {
2588 m = uma_zalloc(vmd->vmd_pgcache[VM_FREEPOOL_DIRECT].zone,
2589 M_NOWAIT | M_NOVM);
2590 if (m != NULL) {
2591 flags |= PG_PCPU_CACHE;
2592 goto found;
2593 }
2594 }
2595
2596 if (vm_domain_allocate(vmd, req, 1)) {
2597 vm_domain_free_lock(vmd);
2598 m = vm_phys_alloc_pages(domain, VM_FREEPOOL_DIRECT, 0);
2599 vm_domain_free_unlock(vmd);
2600 if (m == NULL) {
2601 vm_domain_freecnt_inc(vmd, 1);
2602 #if VM_NRESERVLEVEL > 0
2603 if (vm_reserv_reclaim_inactive(domain))
2604 goto again;
2605 #endif
2606 }
2607 }
2608 if (m == NULL) {
2609 if (vm_domain_alloc_fail(vmd, NULL, req))
2610 goto again;
2611 return (NULL);
2612 }
2613
2614 found:
2615 vm_page_dequeue(m);
2616 vm_page_alloc_check(m);
2617
2618 /*
2619 * Consumers should not rely on a useful default pindex value.
2620 */
2621 m->pindex = 0xdeadc0dedeadc0de;
2622 m->flags = (m->flags & PG_ZERO) | flags;
2623 m->a.flags = 0;
2624 m->oflags = VPO_UNMANAGED;
2625 m->pool = VM_FREEPOOL_DIRECT;
2626 m->busy_lock = VPB_UNBUSIED;
2627 if ((req & VM_ALLOC_WIRED) != 0) {
2628 vm_wire_add(1);
2629 m->ref_count = 1;
2630 }
2631
2632 if ((req & VM_ALLOC_ZERO) != 0 && (m->flags & PG_ZERO) == 0)
2633 pmap_zero_page(m);
2634
2635 return (m);
2636 }
2637
2638 #if VM_NRESERVLEVEL > 1
2639 #define VM_NOFREE_IMPORT_ORDER (VM_LEVEL_1_ORDER + VM_LEVEL_0_ORDER)
2640 #elif VM_NRESERVLEVEL > 0
2641 #define VM_NOFREE_IMPORT_ORDER VM_LEVEL_0_ORDER
2642 #else
2643 #define VM_NOFREE_IMPORT_ORDER 8
2644 #endif
2645
2646 /*
2647 * Allocate a single NOFREE page.
2648 *
2649 * This routine hands out NOFREE pages from higher-order
2650 * physical memory blocks in order to reduce memory fragmentation.
2651 * When a NOFREE for a given domain chunk is used up,
2652 * the routine will try to fetch a new one from the freelists
2653 * and discard the old one.
2654 */
2655 static vm_page_t
vm_page_alloc_nofree_domain(int domain,int req)2656 vm_page_alloc_nofree_domain(int domain, int req)
2657 {
2658 vm_page_t m;
2659 struct vm_domain *vmd;
2660 struct vm_nofreeq *nqp;
2661
2662 KASSERT((req & VM_ALLOC_NOFREE) != 0, ("invalid request %#x", req));
2663
2664 vmd = VM_DOMAIN(domain);
2665 nqp = &vmd->vmd_nofreeq;
2666 vm_domain_free_lock(vmd);
2667 if (nqp->offs >= (1 << VM_NOFREE_IMPORT_ORDER) || nqp->ma == NULL) {
2668 if (!vm_domain_allocate(vmd, req,
2669 1 << VM_NOFREE_IMPORT_ORDER)) {
2670 vm_domain_free_unlock(vmd);
2671 return (NULL);
2672 }
2673 nqp->ma = vm_phys_alloc_pages(domain, VM_FREEPOOL_DEFAULT,
2674 VM_NOFREE_IMPORT_ORDER);
2675 if (nqp->ma == NULL) {
2676 vm_domain_freecnt_inc(vmd, 1 << VM_NOFREE_IMPORT_ORDER);
2677 vm_domain_free_unlock(vmd);
2678 return (NULL);
2679 }
2680 nqp->offs = 0;
2681 }
2682 m = &nqp->ma[nqp->offs++];
2683 vm_domain_free_unlock(vmd);
2684 VM_CNT_ADD(v_nofree_count, 1);
2685
2686 return (m);
2687 }
2688
2689 vm_page_t
vm_page_alloc_noobj(int req)2690 vm_page_alloc_noobj(int req)
2691 {
2692 struct vm_domainset_iter di;
2693 vm_page_t m;
2694 int domain;
2695
2696 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2697 do {
2698 m = vm_page_alloc_noobj_domain(domain, req);
2699 if (m != NULL)
2700 break;
2701 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2702
2703 return (m);
2704 }
2705
2706 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)2707 vm_page_alloc_noobj_contig(int req, u_long npages, vm_paddr_t low,
2708 vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
2709 vm_memattr_t memattr)
2710 {
2711 struct vm_domainset_iter di;
2712 vm_page_t m;
2713 int domain;
2714
2715 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
2716 do {
2717 m = vm_page_alloc_noobj_contig_domain(domain, req, npages, low,
2718 high, alignment, boundary, memattr);
2719 if (m != NULL)
2720 break;
2721 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
2722
2723 return (m);
2724 }
2725
2726 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)2727 vm_page_alloc_noobj_contig_domain(int domain, int req, u_long npages,
2728 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
2729 vm_memattr_t memattr)
2730 {
2731 vm_page_t m, m_ret;
2732 u_int flags;
2733
2734 #define VPANC_FLAGS (VPAN_FLAGS | VM_ALLOC_NORECLAIM)
2735 KASSERT((req & ~VPANC_FLAGS) == 0,
2736 ("invalid request %#x", req));
2737 KASSERT((req & (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM)) !=
2738 (VM_ALLOC_WAITOK | VM_ALLOC_NORECLAIM),
2739 ("invalid request %#x", req));
2740 KASSERT(((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
2741 (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
2742 ("invalid request %#x", req));
2743 KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
2744
2745 while ((m_ret = vm_page_find_contig_domain(domain, req, npages,
2746 low, high, alignment, boundary)) == NULL) {
2747 if (!vm_domain_alloc_fail(VM_DOMAIN(domain), NULL, req))
2748 return (NULL);
2749 }
2750
2751 /*
2752 * Initialize the pages. Only the PG_ZERO flag is inherited.
2753 */
2754 flags = PG_ZERO;
2755 if ((req & VM_ALLOC_NODUMP) != 0)
2756 flags |= PG_NODUMP;
2757 if ((req & VM_ALLOC_WIRED) != 0)
2758 vm_wire_add(npages);
2759 for (m = m_ret; m < &m_ret[npages]; m++) {
2760 vm_page_dequeue(m);
2761 vm_page_alloc_check(m);
2762
2763 /*
2764 * Consumers should not rely on a useful default pindex value.
2765 */
2766 m->pindex = 0xdeadc0dedeadc0de;
2767 m->a.flags = 0;
2768 m->flags = (m->flags | PG_NODUMP) & flags;
2769 m->busy_lock = VPB_UNBUSIED;
2770 if ((req & VM_ALLOC_WIRED) != 0)
2771 m->ref_count = 1;
2772 m->a.act_count = 0;
2773 m->oflags = VPO_UNMANAGED;
2774 m->pool = VM_FREEPOOL_DIRECT;
2775
2776 /*
2777 * Zero the page before updating any mappings since the page is
2778 * not yet shared with any devices which might require the
2779 * non-default memory attribute. pmap_page_set_memattr()
2780 * flushes data caches before returning.
2781 */
2782 if ((req & VM_ALLOC_ZERO) != 0 && (m->flags & PG_ZERO) == 0)
2783 pmap_zero_page(m);
2784 if (memattr != VM_MEMATTR_DEFAULT)
2785 pmap_page_set_memattr(m, memattr);
2786 }
2787 return (m_ret);
2788 }
2789
2790 /*
2791 * Check a page that has been freshly dequeued from a freelist.
2792 */
2793 static void
vm_page_alloc_check(vm_page_t m)2794 vm_page_alloc_check(vm_page_t m)
2795 {
2796
2797 KASSERT(m->object == NULL, ("page %p has object", m));
2798 KASSERT(m->a.queue == PQ_NONE &&
2799 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
2800 ("page %p has unexpected queue %d, flags %#x",
2801 m, m->a.queue, (m->a.flags & PGA_QUEUE_STATE_MASK)));
2802 KASSERT(m->ref_count == 0, ("page %p has references", m));
2803 KASSERT(vm_page_busy_freed(m), ("page %p is not freed", m));
2804 KASSERT(m->dirty == 0, ("page %p is dirty", m));
2805 KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
2806 ("page %p has unexpected memattr %d",
2807 m, pmap_page_get_memattr(m)));
2808 KASSERT(vm_page_none_valid(m), ("free page %p is valid", m));
2809 pmap_vm_page_alloc_check(m);
2810 }
2811
2812 static int
vm_page_zone_import(void * arg,void ** store,int cnt,int domain,int flags)2813 vm_page_zone_import(void *arg, void **store, int cnt, int domain, int flags)
2814 {
2815 struct vm_domain *vmd;
2816 struct vm_pgcache *pgcache;
2817 int i;
2818
2819 pgcache = arg;
2820 vmd = VM_DOMAIN(pgcache->domain);
2821
2822 /*
2823 * The page daemon should avoid creating extra memory pressure since its
2824 * main purpose is to replenish the store of free pages.
2825 */
2826 if (vmd->vmd_severeset || curproc == pageproc ||
2827 !_vm_domain_allocate(vmd, VM_ALLOC_NORMAL, cnt))
2828 return (0);
2829 domain = vmd->vmd_domain;
2830 vm_domain_free_lock(vmd);
2831 i = vm_phys_alloc_npages(domain, pgcache->pool, cnt,
2832 (vm_page_t *)store);
2833 vm_domain_free_unlock(vmd);
2834 if (cnt != i)
2835 vm_domain_freecnt_inc(vmd, cnt - i);
2836
2837 return (i);
2838 }
2839
2840 static void
vm_page_zone_release(void * arg,void ** store,int cnt)2841 vm_page_zone_release(void *arg, void **store, int cnt)
2842 {
2843 struct vm_domain *vmd;
2844 struct vm_pgcache *pgcache;
2845 vm_page_t m;
2846 int i;
2847
2848 pgcache = arg;
2849 vmd = VM_DOMAIN(pgcache->domain);
2850 vm_domain_free_lock(vmd);
2851 for (i = 0; i < cnt; i++) {
2852 m = (vm_page_t)store[i];
2853 vm_phys_free_pages(m, pgcache->pool, 0);
2854 }
2855 vm_domain_free_unlock(vmd);
2856 vm_domain_freecnt_inc(vmd, cnt);
2857 }
2858
2859 #define VPSC_ANY 0 /* No restrictions. */
2860 #define VPSC_NORESERV 1 /* Skip reservations; implies VPSC_NOSUPER. */
2861 #define VPSC_NOSUPER 2 /* Skip superpages. */
2862
2863 /*
2864 * vm_page_scan_contig:
2865 *
2866 * Scan vm_page_array[] between the specified entries "m_start" and
2867 * "m_end" for a run of contiguous physical pages that satisfy the
2868 * specified conditions, and return the lowest page in the run. The
2869 * specified "alignment" determines the alignment of the lowest physical
2870 * page in the run. If the specified "boundary" is non-zero, then the
2871 * run of physical pages cannot span a physical address that is a
2872 * multiple of "boundary".
2873 *
2874 * "m_end" is never dereferenced, so it need not point to a vm_page
2875 * structure within vm_page_array[].
2876 *
2877 * "npages" must be greater than zero. "m_start" and "m_end" must not
2878 * span a hole (or discontiguity) in the physical address space. Both
2879 * "alignment" and "boundary" must be a power of two.
2880 */
2881 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)2882 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
2883 u_long alignment, vm_paddr_t boundary, int options)
2884 {
2885 vm_object_t object;
2886 vm_paddr_t pa;
2887 vm_page_t m, m_run;
2888 #if VM_NRESERVLEVEL > 0
2889 int level;
2890 #endif
2891 int m_inc, order, run_ext, run_len;
2892
2893 KASSERT(npages > 0, ("npages is 0"));
2894 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2895 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2896 m_run = NULL;
2897 run_len = 0;
2898 for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2899 KASSERT((m->flags & PG_MARKER) == 0,
2900 ("page %p is PG_MARKER", m));
2901 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->ref_count >= 1,
2902 ("fictitious page %p has invalid ref count", m));
2903
2904 /*
2905 * If the current page would be the start of a run, check its
2906 * physical address against the end, alignment, and boundary
2907 * conditions. If it doesn't satisfy these conditions, either
2908 * terminate the scan or advance to the next page that
2909 * satisfies the failed condition.
2910 */
2911 if (run_len == 0) {
2912 KASSERT(m_run == NULL, ("m_run != NULL"));
2913 if (m + npages > m_end)
2914 break;
2915 pa = VM_PAGE_TO_PHYS(m);
2916 if (!vm_addr_align_ok(pa, alignment)) {
2917 m_inc = atop(roundup2(pa, alignment) - pa);
2918 continue;
2919 }
2920 if (!vm_addr_bound_ok(pa, ptoa(npages), boundary)) {
2921 m_inc = atop(roundup2(pa, boundary) - pa);
2922 continue;
2923 }
2924 } else
2925 KASSERT(m_run != NULL, ("m_run == NULL"));
2926
2927 retry:
2928 m_inc = 1;
2929 if (vm_page_wired(m))
2930 run_ext = 0;
2931 #if VM_NRESERVLEVEL > 0
2932 else if ((level = vm_reserv_level(m)) >= 0 &&
2933 (options & VPSC_NORESERV) != 0) {
2934 run_ext = 0;
2935 /* Advance to the end of the reservation. */
2936 pa = VM_PAGE_TO_PHYS(m);
2937 m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2938 pa);
2939 }
2940 #endif
2941 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
2942 /*
2943 * The page is considered eligible for relocation if
2944 * and only if it could be laundered or reclaimed by
2945 * the page daemon.
2946 */
2947 VM_OBJECT_RLOCK(object);
2948 if (object != m->object) {
2949 VM_OBJECT_RUNLOCK(object);
2950 goto retry;
2951 }
2952 /* Don't care: PG_NODUMP, PG_ZERO. */
2953 if ((object->flags & OBJ_SWAP) == 0 &&
2954 object->type != OBJT_VNODE) {
2955 run_ext = 0;
2956 #if VM_NRESERVLEVEL > 0
2957 } else if ((options & VPSC_NOSUPER) != 0 &&
2958 (level = vm_reserv_level_iffullpop(m)) >= 0) {
2959 run_ext = 0;
2960 /* Advance to the end of the superpage. */
2961 pa = VM_PAGE_TO_PHYS(m);
2962 m_inc = atop(roundup2(pa + 1,
2963 vm_reserv_size(level)) - pa);
2964 #endif
2965 } else if (object->memattr == VM_MEMATTR_DEFAULT &&
2966 vm_page_queue(m) != PQ_NONE && !vm_page_busied(m)) {
2967 /*
2968 * The page is allocated but eligible for
2969 * relocation. Extend the current run by one
2970 * page.
2971 */
2972 KASSERT(pmap_page_get_memattr(m) ==
2973 VM_MEMATTR_DEFAULT,
2974 ("page %p has an unexpected memattr", m));
2975 KASSERT((m->oflags & (VPO_SWAPINPROG |
2976 VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2977 ("page %p has unexpected oflags", m));
2978 /* Don't care: PGA_NOSYNC. */
2979 run_ext = 1;
2980 } else
2981 run_ext = 0;
2982 VM_OBJECT_RUNLOCK(object);
2983 #if VM_NRESERVLEVEL > 0
2984 } else if (level >= 0) {
2985 /*
2986 * The page is reserved but not yet allocated. In
2987 * other words, it is still free. Extend the current
2988 * run by one page.
2989 */
2990 run_ext = 1;
2991 #endif
2992 } else if ((order = m->order) < VM_NFREEORDER) {
2993 /*
2994 * The page is enqueued in the physical memory
2995 * allocator's free page queues. Moreover, it is the
2996 * first page in a power-of-two-sized run of
2997 * contiguous free pages. Add these pages to the end
2998 * of the current run, and jump ahead.
2999 */
3000 run_ext = 1 << order;
3001 m_inc = 1 << order;
3002 } else {
3003 /*
3004 * Skip the page for one of the following reasons: (1)
3005 * It is enqueued in the physical memory allocator's
3006 * free page queues. However, it is not the first
3007 * page in a run of contiguous free pages. (This case
3008 * rarely occurs because the scan is performed in
3009 * ascending order.) (2) It is not reserved, and it is
3010 * transitioning from free to allocated. (Conversely,
3011 * the transition from allocated to free for managed
3012 * pages is blocked by the page busy lock.) (3) It is
3013 * allocated but not contained by an object and not
3014 * wired, e.g., allocated by Xen's balloon driver.
3015 */
3016 run_ext = 0;
3017 }
3018
3019 /*
3020 * Extend or reset the current run of pages.
3021 */
3022 if (run_ext > 0) {
3023 if (run_len == 0)
3024 m_run = m;
3025 run_len += run_ext;
3026 } else {
3027 if (run_len > 0) {
3028 m_run = NULL;
3029 run_len = 0;
3030 }
3031 }
3032 }
3033 if (run_len >= npages)
3034 return (m_run);
3035 return (NULL);
3036 }
3037
3038 /*
3039 * vm_page_reclaim_run:
3040 *
3041 * Try to relocate each of the allocated virtual pages within the
3042 * specified run of physical pages to a new physical address. Free the
3043 * physical pages underlying the relocated virtual pages. A virtual page
3044 * is relocatable if and only if it could be laundered or reclaimed by
3045 * the page daemon. Whenever possible, a virtual page is relocated to a
3046 * physical address above "high".
3047 *
3048 * Returns 0 if every physical page within the run was already free or
3049 * just freed by a successful relocation. Otherwise, returns a non-zero
3050 * value indicating why the last attempt to relocate a virtual page was
3051 * unsuccessful.
3052 *
3053 * "req_class" must be an allocation class.
3054 */
3055 static int
vm_page_reclaim_run(int req_class,int domain,u_long npages,vm_page_t m_run,vm_paddr_t high)3056 vm_page_reclaim_run(int req_class, int domain, u_long npages, vm_page_t m_run,
3057 vm_paddr_t high)
3058 {
3059 struct vm_domain *vmd;
3060 struct spglist free;
3061 vm_object_t object;
3062 vm_paddr_t pa;
3063 vm_page_t m, m_end, m_new;
3064 int error, order, req;
3065
3066 KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
3067 ("req_class is not an allocation class"));
3068 SLIST_INIT(&free);
3069 error = 0;
3070 m = m_run;
3071 m_end = m_run + npages;
3072 for (; error == 0 && m < m_end; m++) {
3073 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
3074 ("page %p is PG_FICTITIOUS or PG_MARKER", m));
3075
3076 /*
3077 * Racily check for wirings. Races are handled once the object
3078 * lock is held and the page is unmapped.
3079 */
3080 if (vm_page_wired(m))
3081 error = EBUSY;
3082 else if ((object = atomic_load_ptr(&m->object)) != NULL) {
3083 /*
3084 * The page is relocated if and only if it could be
3085 * laundered or reclaimed by the page daemon.
3086 */
3087 VM_OBJECT_WLOCK(object);
3088 /* Don't care: PG_NODUMP, PG_ZERO. */
3089 if (m->object != object ||
3090 ((object->flags & OBJ_SWAP) == 0 &&
3091 object->type != OBJT_VNODE))
3092 error = EINVAL;
3093 else if (object->memattr != VM_MEMATTR_DEFAULT)
3094 error = EINVAL;
3095 else if (vm_page_queue(m) != PQ_NONE &&
3096 vm_page_tryxbusy(m) != 0) {
3097 if (vm_page_wired(m)) {
3098 vm_page_xunbusy(m);
3099 error = EBUSY;
3100 goto unlock;
3101 }
3102 KASSERT(pmap_page_get_memattr(m) ==
3103 VM_MEMATTR_DEFAULT,
3104 ("page %p has an unexpected memattr", m));
3105 KASSERT(m->oflags == 0,
3106 ("page %p has unexpected oflags", m));
3107 /* Don't care: PGA_NOSYNC. */
3108 if (!vm_page_none_valid(m)) {
3109 /*
3110 * First, try to allocate a new page
3111 * that is above "high". Failing
3112 * that, try to allocate a new page
3113 * that is below "m_run". Allocate
3114 * the new page between the end of
3115 * "m_run" and "high" only as a last
3116 * resort.
3117 */
3118 req = req_class;
3119 if ((m->flags & PG_NODUMP) != 0)
3120 req |= VM_ALLOC_NODUMP;
3121 if (trunc_page(high) !=
3122 ~(vm_paddr_t)PAGE_MASK) {
3123 m_new =
3124 vm_page_alloc_noobj_contig(
3125 req, 1, round_page(high),
3126 ~(vm_paddr_t)0, PAGE_SIZE,
3127 0, VM_MEMATTR_DEFAULT);
3128 } else
3129 m_new = NULL;
3130 if (m_new == NULL) {
3131 pa = VM_PAGE_TO_PHYS(m_run);
3132 m_new =
3133 vm_page_alloc_noobj_contig(
3134 req, 1, 0, pa - 1,
3135 PAGE_SIZE, 0,
3136 VM_MEMATTR_DEFAULT);
3137 }
3138 if (m_new == NULL) {
3139 pa += ptoa(npages);
3140 m_new =
3141 vm_page_alloc_noobj_contig(
3142 req, 1, pa, high, PAGE_SIZE,
3143 0, VM_MEMATTR_DEFAULT);
3144 }
3145 if (m_new == NULL) {
3146 vm_page_xunbusy(m);
3147 error = ENOMEM;
3148 goto unlock;
3149 }
3150
3151 /*
3152 * Unmap the page and check for new
3153 * wirings that may have been acquired
3154 * through a pmap lookup.
3155 */
3156 if (object->ref_count != 0 &&
3157 !vm_page_try_remove_all(m)) {
3158 vm_page_xunbusy(m);
3159 vm_page_free(m_new);
3160 error = EBUSY;
3161 goto unlock;
3162 }
3163
3164 /*
3165 * Replace "m" with the new page. For
3166 * vm_page_replace(), "m" must be busy
3167 * and dequeued. Finally, change "m"
3168 * as if vm_page_free() was called.
3169 */
3170 m_new->a.flags = m->a.flags &
3171 ~PGA_QUEUE_STATE_MASK;
3172 KASSERT(m_new->oflags == VPO_UNMANAGED,
3173 ("page %p is managed", m_new));
3174 m_new->oflags = 0;
3175 pmap_copy_page(m, m_new);
3176 m_new->valid = m->valid;
3177 m_new->dirty = m->dirty;
3178 m->flags &= ~PG_ZERO;
3179 vm_page_dequeue(m);
3180 if (vm_page_replace_hold(m_new, object,
3181 m->pindex, m) &&
3182 vm_page_free_prep(m))
3183 SLIST_INSERT_HEAD(&free, m,
3184 plinks.s.ss);
3185
3186 /*
3187 * The new page must be deactivated
3188 * before the object is unlocked.
3189 */
3190 vm_page_deactivate(m_new);
3191 } else {
3192 m->flags &= ~PG_ZERO;
3193 vm_page_dequeue(m);
3194 if (vm_page_free_prep(m))
3195 SLIST_INSERT_HEAD(&free, m,
3196 plinks.s.ss);
3197 KASSERT(m->dirty == 0,
3198 ("page %p is dirty", m));
3199 }
3200 } else
3201 error = EBUSY;
3202 unlock:
3203 VM_OBJECT_WUNLOCK(object);
3204 } else {
3205 MPASS(vm_page_domain(m) == domain);
3206 vmd = VM_DOMAIN(domain);
3207 vm_domain_free_lock(vmd);
3208 order = m->order;
3209 if (order < VM_NFREEORDER) {
3210 /*
3211 * The page is enqueued in the physical memory
3212 * allocator's free page queues. Moreover, it
3213 * is the first page in a power-of-two-sized
3214 * run of contiguous free pages. Jump ahead
3215 * to the last page within that run, and
3216 * continue from there.
3217 */
3218 m += (1 << order) - 1;
3219 }
3220 #if VM_NRESERVLEVEL > 0
3221 else if (vm_reserv_is_page_free(m))
3222 order = 0;
3223 #endif
3224 vm_domain_free_unlock(vmd);
3225 if (order == VM_NFREEORDER)
3226 error = EINVAL;
3227 }
3228 }
3229 if ((m = SLIST_FIRST(&free)) != NULL) {
3230 int cnt;
3231
3232 vmd = VM_DOMAIN(domain);
3233 cnt = 0;
3234 vm_domain_free_lock(vmd);
3235 do {
3236 MPASS(vm_page_domain(m) == domain);
3237 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3238 vm_phys_free_pages(m, m->pool, 0);
3239 cnt++;
3240 } while ((m = SLIST_FIRST(&free)) != NULL);
3241 vm_domain_free_unlock(vmd);
3242 vm_domain_freecnt_inc(vmd, cnt);
3243 }
3244 return (error);
3245 }
3246
3247 #define NRUNS 16
3248
3249 #define RUN_INDEX(count, nruns) ((count) % (nruns))
3250
3251 #define MIN_RECLAIM 8
3252
3253 /*
3254 * vm_page_reclaim_contig:
3255 *
3256 * Reclaim allocated, contiguous physical memory satisfying the specified
3257 * conditions by relocating the virtual pages using that physical memory.
3258 * Returns 0 if reclamation is successful, ERANGE if the specified domain
3259 * can't possibly satisfy the reclamation request, or ENOMEM if not
3260 * currently able to reclaim the requested number of pages. Since
3261 * relocation requires the allocation of physical pages, reclamation may
3262 * fail with ENOMEM due to a shortage of free pages. When reclamation
3263 * fails in this manner, callers are expected to perform vm_wait() before
3264 * retrying a failed allocation operation, e.g., vm_page_alloc_contig().
3265 *
3266 * The caller must always specify an allocation class through "req".
3267 *
3268 * allocation classes:
3269 * VM_ALLOC_NORMAL normal process request
3270 * VM_ALLOC_SYSTEM system *really* needs a page
3271 * VM_ALLOC_INTERRUPT interrupt time request
3272 *
3273 * The optional allocation flags are ignored.
3274 *
3275 * "npages" must be greater than zero. Both "alignment" and "boundary"
3276 * must be a power of two.
3277 */
3278 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)3279 vm_page_reclaim_contig_domain_ext(int domain, int req, u_long npages,
3280 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary,
3281 int desired_runs)
3282 {
3283 struct vm_domain *vmd;
3284 vm_page_t bounds[2], m_run, _m_runs[NRUNS], *m_runs;
3285 u_long count, minalign, reclaimed;
3286 int error, i, min_reclaim, nruns, options, req_class;
3287 int segind, start_segind;
3288 int ret;
3289
3290 KASSERT(npages > 0, ("npages is 0"));
3291 KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
3292 KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
3293
3294 ret = ENOMEM;
3295
3296 /*
3297 * If the caller wants to reclaim multiple runs, try to allocate
3298 * space to store the runs. If that fails, fall back to the old
3299 * behavior of just reclaiming MIN_RECLAIM pages.
3300 */
3301 if (desired_runs > 1)
3302 m_runs = malloc((NRUNS + desired_runs) * sizeof(*m_runs),
3303 M_TEMP, M_NOWAIT);
3304 else
3305 m_runs = NULL;
3306
3307 if (m_runs == NULL) {
3308 m_runs = _m_runs;
3309 nruns = NRUNS;
3310 } else {
3311 nruns = NRUNS + desired_runs - 1;
3312 }
3313 min_reclaim = MAX(desired_runs * npages, MIN_RECLAIM);
3314
3315 /*
3316 * The caller will attempt an allocation after some runs have been
3317 * reclaimed and added to the vm_phys buddy lists. Due to limitations
3318 * of vm_phys_alloc_contig(), round up the requested length to the next
3319 * power of two or maximum chunk size, and ensure that each run is
3320 * suitably aligned.
3321 */
3322 minalign = 1ul << imin(flsl(npages - 1), VM_NFREEORDER - 1);
3323 npages = roundup2(npages, minalign);
3324 if (alignment < ptoa(minalign))
3325 alignment = ptoa(minalign);
3326
3327 /*
3328 * The page daemon is allowed to dig deeper into the free page list.
3329 */
3330 req_class = req & VM_ALLOC_CLASS_MASK;
3331 if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
3332 req_class = VM_ALLOC_SYSTEM;
3333
3334 start_segind = vm_phys_lookup_segind(low);
3335
3336 /*
3337 * Return if the number of free pages cannot satisfy the requested
3338 * allocation.
3339 */
3340 vmd = VM_DOMAIN(domain);
3341 count = vmd->vmd_free_count;
3342 if (count < npages + vmd->vmd_free_reserved || (count < npages +
3343 vmd->vmd_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
3344 (count < npages && req_class == VM_ALLOC_INTERRUPT))
3345 goto done;
3346
3347 /*
3348 * Scan up to three times, relaxing the restrictions ("options") on
3349 * the reclamation of reservations and superpages each time.
3350 */
3351 for (options = VPSC_NORESERV;;) {
3352 bool phys_range_exists = false;
3353
3354 /*
3355 * Find the highest runs that satisfy the given constraints
3356 * and restrictions, and record them in "m_runs".
3357 */
3358 count = 0;
3359 segind = start_segind;
3360 while ((segind = vm_phys_find_range(bounds, segind, domain,
3361 npages, low, high)) != -1) {
3362 phys_range_exists = true;
3363 while ((m_run = vm_page_scan_contig(npages, bounds[0],
3364 bounds[1], alignment, boundary, options))) {
3365 bounds[0] = m_run + npages;
3366 m_runs[RUN_INDEX(count, nruns)] = m_run;
3367 count++;
3368 }
3369 segind++;
3370 }
3371
3372 if (!phys_range_exists) {
3373 ret = ERANGE;
3374 goto done;
3375 }
3376
3377 /*
3378 * Reclaim the highest runs in LIFO (descending) order until
3379 * the number of reclaimed pages, "reclaimed", is at least
3380 * "min_reclaim". Reset "reclaimed" each time because each
3381 * reclamation is idempotent, and runs will (likely) recur
3382 * from one scan to the next as restrictions are relaxed.
3383 */
3384 reclaimed = 0;
3385 for (i = 0; count > 0 && i < nruns; i++) {
3386 count--;
3387 m_run = m_runs[RUN_INDEX(count, nruns)];
3388 error = vm_page_reclaim_run(req_class, domain, npages,
3389 m_run, high);
3390 if (error == 0) {
3391 reclaimed += npages;
3392 if (reclaimed >= min_reclaim) {
3393 ret = 0;
3394 goto done;
3395 }
3396 }
3397 }
3398
3399 /*
3400 * Either relax the restrictions on the next scan or return if
3401 * the last scan had no restrictions.
3402 */
3403 if (options == VPSC_NORESERV)
3404 options = VPSC_NOSUPER;
3405 else if (options == VPSC_NOSUPER)
3406 options = VPSC_ANY;
3407 else if (options == VPSC_ANY) {
3408 if (reclaimed != 0)
3409 ret = 0;
3410 goto done;
3411 }
3412 }
3413 done:
3414 if (m_runs != _m_runs)
3415 free(m_runs, M_TEMP);
3416 return (ret);
3417 }
3418
3419 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)3420 vm_page_reclaim_contig_domain(int domain, int req, u_long npages,
3421 vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
3422 {
3423 return (vm_page_reclaim_contig_domain_ext(domain, req, npages, low, high,
3424 alignment, boundary, 1));
3425 }
3426
3427 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)3428 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
3429 u_long alignment, vm_paddr_t boundary)
3430 {
3431 struct vm_domainset_iter di;
3432 int domain, ret, status;
3433
3434 ret = ERANGE;
3435
3436 vm_domainset_iter_page_init(&di, NULL, 0, &domain, &req);
3437 do {
3438 status = vm_page_reclaim_contig_domain(domain, req, npages, low,
3439 high, alignment, boundary);
3440 if (status == 0)
3441 return (0);
3442 else if (status == ERANGE)
3443 vm_domainset_iter_ignore(&di, domain);
3444 else {
3445 KASSERT(status == ENOMEM, ("Unrecognized error %d "
3446 "from vm_page_reclaim_contig_domain()", status));
3447 ret = ENOMEM;
3448 }
3449 } while (vm_domainset_iter_page(&di, NULL, &domain) == 0);
3450
3451 return (ret);
3452 }
3453
3454 /*
3455 * Set the domain in the appropriate page level domainset.
3456 */
3457 void
vm_domain_set(struct vm_domain * vmd)3458 vm_domain_set(struct vm_domain *vmd)
3459 {
3460
3461 mtx_lock(&vm_domainset_lock);
3462 if (!vmd->vmd_minset && vm_paging_min(vmd)) {
3463 vmd->vmd_minset = 1;
3464 DOMAINSET_SET(vmd->vmd_domain, &vm_min_domains);
3465 }
3466 if (!vmd->vmd_severeset && vm_paging_severe(vmd)) {
3467 vmd->vmd_severeset = 1;
3468 DOMAINSET_SET(vmd->vmd_domain, &vm_severe_domains);
3469 }
3470 mtx_unlock(&vm_domainset_lock);
3471 }
3472
3473 /*
3474 * Clear the domain from the appropriate page level domainset.
3475 */
3476 void
vm_domain_clear(struct vm_domain * vmd)3477 vm_domain_clear(struct vm_domain *vmd)
3478 {
3479
3480 mtx_lock(&vm_domainset_lock);
3481 if (vmd->vmd_minset && !vm_paging_min(vmd)) {
3482 vmd->vmd_minset = 0;
3483 DOMAINSET_CLR(vmd->vmd_domain, &vm_min_domains);
3484 if (vm_min_waiters != 0) {
3485 vm_min_waiters = 0;
3486 wakeup(&vm_min_domains);
3487 }
3488 }
3489 if (vmd->vmd_severeset && !vm_paging_severe(vmd)) {
3490 vmd->vmd_severeset = 0;
3491 DOMAINSET_CLR(vmd->vmd_domain, &vm_severe_domains);
3492 if (vm_severe_waiters != 0) {
3493 vm_severe_waiters = 0;
3494 wakeup(&vm_severe_domains);
3495 }
3496 }
3497
3498 /*
3499 * If pageout daemon needs pages, then tell it that there are
3500 * some free.
3501 */
3502 if (vmd->vmd_pageout_pages_needed &&
3503 vmd->vmd_free_count >= vmd->vmd_pageout_free_min) {
3504 wakeup(&vmd->vmd_pageout_pages_needed);
3505 vmd->vmd_pageout_pages_needed = 0;
3506 }
3507
3508 /* See comments in vm_wait_doms(). */
3509 if (vm_pageproc_waiters) {
3510 vm_pageproc_waiters = 0;
3511 wakeup(&vm_pageproc_waiters);
3512 }
3513 mtx_unlock(&vm_domainset_lock);
3514 }
3515
3516 /*
3517 * Wait for free pages to exceed the min threshold globally.
3518 */
3519 void
vm_wait_min(void)3520 vm_wait_min(void)
3521 {
3522
3523 mtx_lock(&vm_domainset_lock);
3524 while (vm_page_count_min()) {
3525 vm_min_waiters++;
3526 msleep(&vm_min_domains, &vm_domainset_lock, PVM, "vmwait", 0);
3527 }
3528 mtx_unlock(&vm_domainset_lock);
3529 }
3530
3531 /*
3532 * Wait for free pages to exceed the severe threshold globally.
3533 */
3534 void
vm_wait_severe(void)3535 vm_wait_severe(void)
3536 {
3537
3538 mtx_lock(&vm_domainset_lock);
3539 while (vm_page_count_severe()) {
3540 vm_severe_waiters++;
3541 msleep(&vm_severe_domains, &vm_domainset_lock, PVM,
3542 "vmwait", 0);
3543 }
3544 mtx_unlock(&vm_domainset_lock);
3545 }
3546
3547 u_int
vm_wait_count(void)3548 vm_wait_count(void)
3549 {
3550
3551 return (vm_severe_waiters + vm_min_waiters + vm_pageproc_waiters);
3552 }
3553
3554 int
vm_wait_doms(const domainset_t * wdoms,int mflags)3555 vm_wait_doms(const domainset_t *wdoms, int mflags)
3556 {
3557 int error;
3558
3559 error = 0;
3560
3561 /*
3562 * We use racey wakeup synchronization to avoid expensive global
3563 * locking for the pageproc when sleeping with a non-specific vm_wait.
3564 * To handle this, we only sleep for one tick in this instance. It
3565 * is expected that most allocations for the pageproc will come from
3566 * kmem or vm_page_grab* which will use the more specific and
3567 * race-free vm_wait_domain().
3568 */
3569 if (curproc == pageproc) {
3570 mtx_lock(&vm_domainset_lock);
3571 vm_pageproc_waiters++;
3572 error = msleep(&vm_pageproc_waiters, &vm_domainset_lock,
3573 PVM | PDROP | mflags, "pageprocwait", 1);
3574 } else {
3575 /*
3576 * XXX Ideally we would wait only until the allocation could
3577 * be satisfied. This condition can cause new allocators to
3578 * consume all freed pages while old allocators wait.
3579 */
3580 mtx_lock(&vm_domainset_lock);
3581 if (vm_page_count_min_set(wdoms)) {
3582 if (pageproc == NULL)
3583 panic("vm_wait in early boot");
3584 vm_min_waiters++;
3585 error = msleep(&vm_min_domains, &vm_domainset_lock,
3586 PVM | PDROP | mflags, "vmwait", 0);
3587 } else
3588 mtx_unlock(&vm_domainset_lock);
3589 }
3590 return (error);
3591 }
3592
3593 /*
3594 * vm_wait_domain:
3595 *
3596 * Sleep until free pages are available for allocation.
3597 * - Called in various places after failed memory allocations.
3598 */
3599 void
vm_wait_domain(int domain)3600 vm_wait_domain(int domain)
3601 {
3602 struct vm_domain *vmd;
3603 domainset_t wdom;
3604
3605 vmd = VM_DOMAIN(domain);
3606 vm_domain_free_assert_unlocked(vmd);
3607
3608 if (curproc == pageproc) {
3609 mtx_lock(&vm_domainset_lock);
3610 if (vmd->vmd_free_count < vmd->vmd_pageout_free_min) {
3611 vmd->vmd_pageout_pages_needed = 1;
3612 msleep(&vmd->vmd_pageout_pages_needed,
3613 &vm_domainset_lock, PDROP | PSWP, "VMWait", 0);
3614 } else
3615 mtx_unlock(&vm_domainset_lock);
3616 } else {
3617 DOMAINSET_ZERO(&wdom);
3618 DOMAINSET_SET(vmd->vmd_domain, &wdom);
3619 vm_wait_doms(&wdom, 0);
3620 }
3621 }
3622
3623 static int
vm_wait_flags(vm_object_t obj,int mflags)3624 vm_wait_flags(vm_object_t obj, int mflags)
3625 {
3626 struct domainset *d;
3627
3628 d = NULL;
3629
3630 /*
3631 * Carefully fetch pointers only once: the struct domainset
3632 * itself is ummutable but the pointer might change.
3633 */
3634 if (obj != NULL)
3635 d = obj->domain.dr_policy;
3636 if (d == NULL)
3637 d = curthread->td_domain.dr_policy;
3638
3639 return (vm_wait_doms(&d->ds_mask, mflags));
3640 }
3641
3642 /*
3643 * vm_wait:
3644 *
3645 * Sleep until free pages are available for allocation in the
3646 * affinity domains of the obj. If obj is NULL, the domain set
3647 * for the calling thread is used.
3648 * Called in various places after failed memory allocations.
3649 */
3650 void
vm_wait(vm_object_t obj)3651 vm_wait(vm_object_t obj)
3652 {
3653 (void)vm_wait_flags(obj, 0);
3654 }
3655
3656 int
vm_wait_intr(vm_object_t obj)3657 vm_wait_intr(vm_object_t obj)
3658 {
3659 return (vm_wait_flags(obj, PCATCH));
3660 }
3661
3662 /*
3663 * vm_domain_alloc_fail:
3664 *
3665 * Called when a page allocation function fails. Informs the
3666 * pagedaemon and performs the requested wait. Requires the
3667 * domain_free and object lock on entry. Returns with the
3668 * object lock held and free lock released. Returns an error when
3669 * retry is necessary.
3670 *
3671 */
3672 static int
vm_domain_alloc_fail(struct vm_domain * vmd,vm_object_t object,int req)3673 vm_domain_alloc_fail(struct vm_domain *vmd, vm_object_t object, int req)
3674 {
3675
3676 vm_domain_free_assert_unlocked(vmd);
3677
3678 atomic_add_int(&vmd->vmd_pageout_deficit,
3679 max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
3680 if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
3681 if (object != NULL)
3682 VM_OBJECT_WUNLOCK(object);
3683 vm_wait_domain(vmd->vmd_domain);
3684 if (object != NULL)
3685 VM_OBJECT_WLOCK(object);
3686 if (req & VM_ALLOC_WAITOK)
3687 return (EAGAIN);
3688 }
3689
3690 return (0);
3691 }
3692
3693 /*
3694 * vm_waitpfault:
3695 *
3696 * Sleep until free pages are available for allocation.
3697 * - Called only in vm_fault so that processes page faulting
3698 * can be easily tracked.
3699 * - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
3700 * processes will be able to grab memory first. Do not change
3701 * this balance without careful testing first.
3702 */
3703 void
vm_waitpfault(struct domainset * dset,int timo)3704 vm_waitpfault(struct domainset *dset, int timo)
3705 {
3706
3707 /*
3708 * XXX Ideally we would wait only until the allocation could
3709 * be satisfied. This condition can cause new allocators to
3710 * consume all freed pages while old allocators wait.
3711 */
3712 mtx_lock(&vm_domainset_lock);
3713 if (vm_page_count_min_set(&dset->ds_mask)) {
3714 vm_min_waiters++;
3715 msleep(&vm_min_domains, &vm_domainset_lock, PUSER | PDROP,
3716 "pfault", timo);
3717 } else
3718 mtx_unlock(&vm_domainset_lock);
3719 }
3720
3721 static struct vm_pagequeue *
_vm_page_pagequeue(vm_page_t m,uint8_t queue)3722 _vm_page_pagequeue(vm_page_t m, uint8_t queue)
3723 {
3724
3725 return (&vm_pagequeue_domain(m)->vmd_pagequeues[queue]);
3726 }
3727
3728 #ifdef INVARIANTS
3729 static struct vm_pagequeue *
vm_page_pagequeue(vm_page_t m)3730 vm_page_pagequeue(vm_page_t m)
3731 {
3732
3733 return (_vm_page_pagequeue(m, vm_page_astate_load(m).queue));
3734 }
3735 #endif
3736
3737 static __always_inline bool
vm_page_pqstate_fcmpset(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3738 vm_page_pqstate_fcmpset(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3739 {
3740 vm_page_astate_t tmp;
3741
3742 tmp = *old;
3743 do {
3744 if (__predict_true(vm_page_astate_fcmpset(m, old, new)))
3745 return (true);
3746 counter_u64_add(pqstate_commit_retries, 1);
3747 } while (old->_bits == tmp._bits);
3748
3749 return (false);
3750 }
3751
3752 /*
3753 * Do the work of committing a queue state update that moves the page out of
3754 * its current queue.
3755 */
3756 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)3757 _vm_page_pqstate_commit_dequeue(struct vm_pagequeue *pq, vm_page_t m,
3758 vm_page_astate_t *old, vm_page_astate_t new)
3759 {
3760 vm_page_t next;
3761
3762 vm_pagequeue_assert_locked(pq);
3763 KASSERT(vm_page_pagequeue(m) == pq,
3764 ("%s: queue %p does not match page %p", __func__, pq, m));
3765 KASSERT(old->queue != PQ_NONE && new.queue != old->queue,
3766 ("%s: invalid queue indices %d %d",
3767 __func__, old->queue, new.queue));
3768
3769 /*
3770 * Once the queue index of the page changes there is nothing
3771 * synchronizing with further updates to the page's physical
3772 * queue state. Therefore we must speculatively remove the page
3773 * from the queue now and be prepared to roll back if the queue
3774 * state update fails. If the page is not physically enqueued then
3775 * we just update its queue index.
3776 */
3777 if ((old->flags & PGA_ENQUEUED) != 0) {
3778 new.flags &= ~PGA_ENQUEUED;
3779 next = TAILQ_NEXT(m, plinks.q);
3780 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3781 vm_pagequeue_cnt_dec(pq);
3782 if (!vm_page_pqstate_fcmpset(m, old, new)) {
3783 if (next == NULL)
3784 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3785 else
3786 TAILQ_INSERT_BEFORE(next, m, plinks.q);
3787 vm_pagequeue_cnt_inc(pq);
3788 return (false);
3789 } else {
3790 return (true);
3791 }
3792 } else {
3793 return (vm_page_pqstate_fcmpset(m, old, new));
3794 }
3795 }
3796
3797 static bool
vm_page_pqstate_commit_dequeue(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3798 vm_page_pqstate_commit_dequeue(vm_page_t m, vm_page_astate_t *old,
3799 vm_page_astate_t new)
3800 {
3801 struct vm_pagequeue *pq;
3802 vm_page_astate_t as;
3803 bool ret;
3804
3805 pq = _vm_page_pagequeue(m, old->queue);
3806
3807 /*
3808 * The queue field and PGA_ENQUEUED flag are stable only so long as the
3809 * corresponding page queue lock is held.
3810 */
3811 vm_pagequeue_lock(pq);
3812 as = vm_page_astate_load(m);
3813 if (__predict_false(as._bits != old->_bits)) {
3814 *old = as;
3815 ret = false;
3816 } else {
3817 ret = _vm_page_pqstate_commit_dequeue(pq, m, old, new);
3818 }
3819 vm_pagequeue_unlock(pq);
3820 return (ret);
3821 }
3822
3823 /*
3824 * Commit a queue state update that enqueues or requeues a page.
3825 */
3826 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)3827 _vm_page_pqstate_commit_requeue(struct vm_pagequeue *pq, vm_page_t m,
3828 vm_page_astate_t *old, vm_page_astate_t new)
3829 {
3830 struct vm_domain *vmd;
3831
3832 vm_pagequeue_assert_locked(pq);
3833 KASSERT(old->queue != PQ_NONE && new.queue == old->queue,
3834 ("%s: invalid queue indices %d %d",
3835 __func__, old->queue, new.queue));
3836
3837 new.flags |= PGA_ENQUEUED;
3838 if (!vm_page_pqstate_fcmpset(m, old, new))
3839 return (false);
3840
3841 if ((old->flags & PGA_ENQUEUED) != 0)
3842 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
3843 else
3844 vm_pagequeue_cnt_inc(pq);
3845
3846 /*
3847 * Give PGA_REQUEUE_HEAD precedence over PGA_REQUEUE. In particular, if
3848 * both flags are set in close succession, only PGA_REQUEUE_HEAD will be
3849 * applied, even if it was set first.
3850 */
3851 if ((old->flags & PGA_REQUEUE_HEAD) != 0) {
3852 vmd = vm_pagequeue_domain(m);
3853 KASSERT(pq == &vmd->vmd_pagequeues[PQ_INACTIVE],
3854 ("%s: invalid page queue for page %p", __func__, m));
3855 TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
3856 } else {
3857 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
3858 }
3859 return (true);
3860 }
3861
3862 /*
3863 * Commit a queue state update that encodes a request for a deferred queue
3864 * operation.
3865 */
3866 static bool
vm_page_pqstate_commit_request(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3867 vm_page_pqstate_commit_request(vm_page_t m, vm_page_astate_t *old,
3868 vm_page_astate_t new)
3869 {
3870
3871 KASSERT(old->queue == new.queue || new.queue != PQ_NONE,
3872 ("%s: invalid state, queue %d flags %x",
3873 __func__, new.queue, new.flags));
3874
3875 if (old->_bits != new._bits &&
3876 !vm_page_pqstate_fcmpset(m, old, new))
3877 return (false);
3878 vm_page_pqbatch_submit(m, new.queue);
3879 return (true);
3880 }
3881
3882 /*
3883 * A generic queue state update function. This handles more cases than the
3884 * specialized functions above.
3885 */
3886 bool
vm_page_pqstate_commit(vm_page_t m,vm_page_astate_t * old,vm_page_astate_t new)3887 vm_page_pqstate_commit(vm_page_t m, vm_page_astate_t *old, vm_page_astate_t new)
3888 {
3889
3890 if (old->_bits == new._bits)
3891 return (true);
3892
3893 if (old->queue != PQ_NONE && new.queue != old->queue) {
3894 if (!vm_page_pqstate_commit_dequeue(m, old, new))
3895 return (false);
3896 if (new.queue != PQ_NONE)
3897 vm_page_pqbatch_submit(m, new.queue);
3898 } else {
3899 if (!vm_page_pqstate_fcmpset(m, old, new))
3900 return (false);
3901 if (new.queue != PQ_NONE &&
3902 ((new.flags & ~old->flags) & PGA_QUEUE_OP_MASK) != 0)
3903 vm_page_pqbatch_submit(m, new.queue);
3904 }
3905 return (true);
3906 }
3907
3908 /*
3909 * Apply deferred queue state updates to a page.
3910 */
3911 static inline void
vm_pqbatch_process_page(struct vm_pagequeue * pq,vm_page_t m,uint8_t queue)3912 vm_pqbatch_process_page(struct vm_pagequeue *pq, vm_page_t m, uint8_t queue)
3913 {
3914 vm_page_astate_t new, old;
3915
3916 CRITICAL_ASSERT(curthread);
3917 vm_pagequeue_assert_locked(pq);
3918 KASSERT(queue < PQ_COUNT,
3919 ("%s: invalid queue index %d", __func__, queue));
3920 KASSERT(pq == _vm_page_pagequeue(m, queue),
3921 ("%s: page %p does not belong to queue %p", __func__, m, pq));
3922
3923 for (old = vm_page_astate_load(m);;) {
3924 if (__predict_false(old.queue != queue ||
3925 (old.flags & PGA_QUEUE_OP_MASK) == 0)) {
3926 counter_u64_add(queue_nops, 1);
3927 break;
3928 }
3929 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3930 ("%s: page %p is unmanaged", __func__, m));
3931
3932 new = old;
3933 if ((old.flags & PGA_DEQUEUE) != 0) {
3934 new.flags &= ~PGA_QUEUE_OP_MASK;
3935 new.queue = PQ_NONE;
3936 if (__predict_true(_vm_page_pqstate_commit_dequeue(pq,
3937 m, &old, new))) {
3938 counter_u64_add(queue_ops, 1);
3939 break;
3940 }
3941 } else {
3942 new.flags &= ~(PGA_REQUEUE | PGA_REQUEUE_HEAD);
3943 if (__predict_true(_vm_page_pqstate_commit_requeue(pq,
3944 m, &old, new))) {
3945 counter_u64_add(queue_ops, 1);
3946 break;
3947 }
3948 }
3949 }
3950 }
3951
3952 static void
vm_pqbatch_process(struct vm_pagequeue * pq,struct vm_batchqueue * bq,uint8_t queue)3953 vm_pqbatch_process(struct vm_pagequeue *pq, struct vm_batchqueue *bq,
3954 uint8_t queue)
3955 {
3956 int i;
3957
3958 for (i = 0; i < bq->bq_cnt; i++)
3959 vm_pqbatch_process_page(pq, bq->bq_pa[i], queue);
3960 vm_batchqueue_init(bq);
3961 }
3962
3963 /*
3964 * vm_page_pqbatch_submit: [ internal use only ]
3965 *
3966 * Enqueue a page in the specified page queue's batched work queue.
3967 * The caller must have encoded the requested operation in the page
3968 * structure's a.flags field.
3969 */
3970 void
vm_page_pqbatch_submit(vm_page_t m,uint8_t queue)3971 vm_page_pqbatch_submit(vm_page_t m, uint8_t queue)
3972 {
3973 struct vm_batchqueue *bq;
3974 struct vm_pagequeue *pq;
3975 int domain, slots_remaining;
3976
3977 KASSERT(queue < PQ_COUNT, ("invalid queue %d", queue));
3978
3979 domain = vm_page_domain(m);
3980 critical_enter();
3981 bq = DPCPU_PTR(pqbatch[domain][queue]);
3982 slots_remaining = vm_batchqueue_insert(bq, m);
3983 if (slots_remaining > (VM_BATCHQUEUE_SIZE >> 1)) {
3984 /* keep building the bq */
3985 critical_exit();
3986 return;
3987 } else if (slots_remaining > 0 ) {
3988 /* Try to process the bq if we can get the lock */
3989 pq = &VM_DOMAIN(domain)->vmd_pagequeues[queue];
3990 if (vm_pagequeue_trylock(pq)) {
3991 vm_pqbatch_process(pq, bq, queue);
3992 vm_pagequeue_unlock(pq);
3993 }
3994 critical_exit();
3995 return;
3996 }
3997 critical_exit();
3998
3999 /* if we make it here, the bq is full so wait for the lock */
4000
4001 pq = &VM_DOMAIN(domain)->vmd_pagequeues[queue];
4002 vm_pagequeue_lock(pq);
4003 critical_enter();
4004 bq = DPCPU_PTR(pqbatch[domain][queue]);
4005 vm_pqbatch_process(pq, bq, queue);
4006 vm_pqbatch_process_page(pq, m, queue);
4007 vm_pagequeue_unlock(pq);
4008 critical_exit();
4009 }
4010
4011 /*
4012 * vm_page_pqbatch_drain: [ internal use only ]
4013 *
4014 * Force all per-CPU page queue batch queues to be drained. This is
4015 * intended for use in severe memory shortages, to ensure that pages
4016 * do not remain stuck in the batch queues.
4017 */
4018 void
vm_page_pqbatch_drain(void)4019 vm_page_pqbatch_drain(void)
4020 {
4021 struct thread *td;
4022 struct vm_domain *vmd;
4023 struct vm_pagequeue *pq;
4024 int cpu, domain, queue;
4025
4026 td = curthread;
4027 CPU_FOREACH(cpu) {
4028 thread_lock(td);
4029 sched_bind(td, cpu);
4030 thread_unlock(td);
4031
4032 for (domain = 0; domain < vm_ndomains; domain++) {
4033 vmd = VM_DOMAIN(domain);
4034 for (queue = 0; queue < PQ_COUNT; queue++) {
4035 pq = &vmd->vmd_pagequeues[queue];
4036 vm_pagequeue_lock(pq);
4037 critical_enter();
4038 vm_pqbatch_process(pq,
4039 DPCPU_PTR(pqbatch[domain][queue]), queue);
4040 critical_exit();
4041 vm_pagequeue_unlock(pq);
4042 }
4043 }
4044 }
4045 thread_lock(td);
4046 sched_unbind(td);
4047 thread_unlock(td);
4048 }
4049
4050 /*
4051 * vm_page_dequeue_deferred: [ internal use only ]
4052 *
4053 * Request removal of the given page from its current page
4054 * queue. Physical removal from the queue may be deferred
4055 * indefinitely.
4056 */
4057 void
vm_page_dequeue_deferred(vm_page_t m)4058 vm_page_dequeue_deferred(vm_page_t m)
4059 {
4060 vm_page_astate_t new, old;
4061
4062 old = vm_page_astate_load(m);
4063 do {
4064 if (old.queue == PQ_NONE) {
4065 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
4066 ("%s: page %p has unexpected queue state",
4067 __func__, m));
4068 break;
4069 }
4070 new = old;
4071 new.flags |= PGA_DEQUEUE;
4072 } while (!vm_page_pqstate_commit_request(m, &old, new));
4073 }
4074
4075 /*
4076 * vm_page_dequeue:
4077 *
4078 * Remove the page from whichever page queue it's in, if any, before
4079 * returning.
4080 */
4081 void
vm_page_dequeue(vm_page_t m)4082 vm_page_dequeue(vm_page_t m)
4083 {
4084 vm_page_astate_t new, old;
4085
4086 old = vm_page_astate_load(m);
4087 do {
4088 if (old.queue == PQ_NONE) {
4089 KASSERT((old.flags & PGA_QUEUE_STATE_MASK) == 0,
4090 ("%s: page %p has unexpected queue state",
4091 __func__, m));
4092 break;
4093 }
4094 new = old;
4095 new.flags &= ~PGA_QUEUE_OP_MASK;
4096 new.queue = PQ_NONE;
4097 } while (!vm_page_pqstate_commit_dequeue(m, &old, new));
4098
4099 }
4100
4101 /*
4102 * Schedule the given page for insertion into the specified page queue.
4103 * Physical insertion of the page may be deferred indefinitely.
4104 */
4105 static void
vm_page_enqueue(vm_page_t m,uint8_t queue)4106 vm_page_enqueue(vm_page_t m, uint8_t queue)
4107 {
4108
4109 KASSERT(m->a.queue == PQ_NONE &&
4110 (m->a.flags & PGA_QUEUE_STATE_MASK) == 0,
4111 ("%s: page %p is already enqueued", __func__, m));
4112 KASSERT(m->ref_count > 0,
4113 ("%s: page %p does not carry any references", __func__, m));
4114
4115 m->a.queue = queue;
4116 if ((m->a.flags & PGA_REQUEUE) == 0)
4117 vm_page_aflag_set(m, PGA_REQUEUE);
4118 vm_page_pqbatch_submit(m, queue);
4119 }
4120
4121 /*
4122 * vm_page_free_prep:
4123 *
4124 * Prepares the given page to be put on the free list,
4125 * disassociating it from any VM object. The caller may return
4126 * the page to the free list only if this function returns true.
4127 *
4128 * The object, if it exists, must be locked, and then the page must
4129 * be xbusy. Otherwise the page must be not busied. A managed
4130 * page must be unmapped.
4131 */
4132 static bool
vm_page_free_prep(vm_page_t m)4133 vm_page_free_prep(vm_page_t m)
4134 {
4135
4136 /*
4137 * Synchronize with threads that have dropped a reference to this
4138 * page.
4139 */
4140 atomic_thread_fence_acq();
4141
4142 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
4143 if (PMAP_HAS_DMAP && (m->flags & PG_ZERO) != 0) {
4144 uint64_t *p;
4145 int i;
4146 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
4147 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
4148 KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
4149 m, i, (uintmax_t)*p));
4150 }
4151 #endif
4152 KASSERT((m->flags & PG_NOFREE) == 0,
4153 ("%s: attempting to free a PG_NOFREE page", __func__));
4154 if ((m->oflags & VPO_UNMANAGED) == 0) {
4155 KASSERT(!pmap_page_is_mapped(m),
4156 ("vm_page_free_prep: freeing mapped page %p", m));
4157 KASSERT((m->a.flags & (PGA_EXECUTABLE | PGA_WRITEABLE)) == 0,
4158 ("vm_page_free_prep: mapping flags set in page %p", m));
4159 } else {
4160 KASSERT(m->a.queue == PQ_NONE,
4161 ("vm_page_free_prep: unmanaged page %p is queued", m));
4162 }
4163 VM_CNT_INC(v_tfree);
4164
4165 if (m->object != NULL) {
4166 vm_page_radix_remove(m);
4167 vm_page_free_object_prep(m);
4168 } else
4169 vm_page_assert_unbusied(m);
4170
4171 vm_page_busy_free(m);
4172
4173 /*
4174 * If fictitious remove object association and
4175 * return.
4176 */
4177 if ((m->flags & PG_FICTITIOUS) != 0) {
4178 KASSERT(m->ref_count == 1,
4179 ("fictitious page %p is referenced", m));
4180 KASSERT(m->a.queue == PQ_NONE,
4181 ("fictitious page %p is queued", m));
4182 return (false);
4183 }
4184
4185 /*
4186 * Pages need not be dequeued before they are returned to the physical
4187 * memory allocator, but they must at least be marked for a deferred
4188 * dequeue.
4189 */
4190 if ((m->oflags & VPO_UNMANAGED) == 0)
4191 vm_page_dequeue_deferred(m);
4192
4193 m->valid = 0;
4194 vm_page_undirty(m);
4195
4196 if (m->ref_count != 0)
4197 panic("vm_page_free_prep: page %p has references", m);
4198
4199 /*
4200 * Restore the default memory attribute to the page.
4201 */
4202 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
4203 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
4204
4205 #if VM_NRESERVLEVEL > 0
4206 /*
4207 * Determine whether the page belongs to a reservation. If the page was
4208 * allocated from a per-CPU cache, it cannot belong to a reservation, so
4209 * as an optimization, we avoid the check in that case.
4210 */
4211 if ((m->flags & PG_PCPU_CACHE) == 0 && vm_reserv_free_page(m))
4212 return (false);
4213 #endif
4214
4215 return (true);
4216 }
4217
4218 /*
4219 * vm_page_free_toq:
4220 *
4221 * Returns the given page to the free list, disassociating it
4222 * from any VM object.
4223 *
4224 * The object must be locked. The page must be exclusively busied if it
4225 * belongs to an object.
4226 */
4227 static void
vm_page_free_toq(vm_page_t m)4228 vm_page_free_toq(vm_page_t m)
4229 {
4230 struct vm_domain *vmd;
4231 uma_zone_t zone;
4232
4233 if (!vm_page_free_prep(m))
4234 return;
4235
4236 vmd = vm_pagequeue_domain(m);
4237 zone = vmd->vmd_pgcache[m->pool].zone;
4238 if ((m->flags & PG_PCPU_CACHE) != 0 && zone != NULL) {
4239 uma_zfree(zone, m);
4240 return;
4241 }
4242 vm_domain_free_lock(vmd);
4243 vm_phys_free_pages(m, m->pool, 0);
4244 vm_domain_free_unlock(vmd);
4245 vm_domain_freecnt_inc(vmd, 1);
4246 }
4247
4248 /*
4249 * vm_page_free_pages_toq:
4250 *
4251 * Returns a list of pages to the free list, disassociating it
4252 * from any VM object. In other words, this is equivalent to
4253 * calling vm_page_free_toq() for each page of a list of VM objects.
4254 */
4255 int
vm_page_free_pages_toq(struct spglist * free,bool update_wire_count)4256 vm_page_free_pages_toq(struct spglist *free, bool update_wire_count)
4257 {
4258 vm_page_t m;
4259 int count;
4260
4261 if (SLIST_EMPTY(free))
4262 return (0);
4263
4264 count = 0;
4265 while ((m = SLIST_FIRST(free)) != NULL) {
4266 count++;
4267 SLIST_REMOVE_HEAD(free, plinks.s.ss);
4268 vm_page_free_toq(m);
4269 }
4270
4271 if (update_wire_count)
4272 vm_wire_sub(count);
4273 return (count);
4274 }
4275
4276 /*
4277 * Mark this page as wired down. For managed pages, this prevents reclamation
4278 * by the page daemon, or when the containing object, if any, is destroyed.
4279 */
4280 void
vm_page_wire(vm_page_t m)4281 vm_page_wire(vm_page_t m)
4282 {
4283 u_int old;
4284
4285 #ifdef INVARIANTS
4286 if (m->object != NULL && !vm_page_busied(m) &&
4287 !vm_object_busied(m->object))
4288 VM_OBJECT_ASSERT_LOCKED(m->object);
4289 #endif
4290 KASSERT((m->flags & PG_FICTITIOUS) == 0 ||
4291 VPRC_WIRE_COUNT(m->ref_count) >= 1,
4292 ("vm_page_wire: fictitious page %p has zero wirings", m));
4293
4294 old = atomic_fetchadd_int(&m->ref_count, 1);
4295 KASSERT(VPRC_WIRE_COUNT(old) != VPRC_WIRE_COUNT_MAX,
4296 ("vm_page_wire: counter overflow for page %p", m));
4297 if (VPRC_WIRE_COUNT(old) == 0) {
4298 if ((m->oflags & VPO_UNMANAGED) == 0)
4299 vm_page_aflag_set(m, PGA_DEQUEUE);
4300 vm_wire_add(1);
4301 }
4302 }
4303
4304 /*
4305 * Attempt to wire a mapped page following a pmap lookup of that page.
4306 * This may fail if a thread is concurrently tearing down mappings of the page.
4307 * The transient failure is acceptable because it translates to the
4308 * failure of the caller pmap_extract_and_hold(), which should be then
4309 * followed by the vm_fault() fallback, see e.g. vm_fault_quick_hold_pages().
4310 */
4311 bool
vm_page_wire_mapped(vm_page_t m)4312 vm_page_wire_mapped(vm_page_t m)
4313 {
4314 u_int old;
4315
4316 old = atomic_load_int(&m->ref_count);
4317 do {
4318 KASSERT(old > 0,
4319 ("vm_page_wire_mapped: wiring unreferenced page %p", m));
4320 if ((old & VPRC_BLOCKED) != 0)
4321 return (false);
4322 } while (!atomic_fcmpset_int(&m->ref_count, &old, old + 1));
4323
4324 if (VPRC_WIRE_COUNT(old) == 0) {
4325 if ((m->oflags & VPO_UNMANAGED) == 0)
4326 vm_page_aflag_set(m, PGA_DEQUEUE);
4327 vm_wire_add(1);
4328 }
4329 return (true);
4330 }
4331
4332 /*
4333 * Release a wiring reference to a managed page. If the page still belongs to
4334 * an object, update its position in the page queues to reflect the reference.
4335 * If the wiring was the last reference to the page, free the page.
4336 */
4337 static void
vm_page_unwire_managed(vm_page_t m,uint8_t nqueue,bool noreuse)4338 vm_page_unwire_managed(vm_page_t m, uint8_t nqueue, bool noreuse)
4339 {
4340 u_int old;
4341
4342 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4343 ("%s: page %p is unmanaged", __func__, m));
4344
4345 /*
4346 * Update LRU state before releasing the wiring reference.
4347 * Use a release store when updating the reference count to
4348 * synchronize with vm_page_free_prep().
4349 */
4350 old = atomic_load_int(&m->ref_count);
4351 do {
4352 u_int count;
4353
4354 KASSERT(VPRC_WIRE_COUNT(old) > 0,
4355 ("vm_page_unwire: wire count underflow for page %p", m));
4356
4357 count = old & ~VPRC_BLOCKED;
4358 if (count > VPRC_OBJREF + 1) {
4359 /*
4360 * The page has at least one other wiring reference. An
4361 * earlier iteration of this loop may have called
4362 * vm_page_release_toq() and cleared PGA_DEQUEUE, so
4363 * re-set it if necessary.
4364 */
4365 if ((vm_page_astate_load(m).flags & PGA_DEQUEUE) == 0)
4366 vm_page_aflag_set(m, PGA_DEQUEUE);
4367 } else if (count == VPRC_OBJREF + 1) {
4368 /*
4369 * This is the last wiring. Clear PGA_DEQUEUE and
4370 * update the page's queue state to reflect the
4371 * reference. If the page does not belong to an object
4372 * (i.e., the VPRC_OBJREF bit is clear), we only need to
4373 * clear leftover queue state.
4374 */
4375 vm_page_release_toq(m, nqueue, noreuse);
4376 } else if (count == 1) {
4377 vm_page_aflag_clear(m, PGA_DEQUEUE);
4378 }
4379 } while (!atomic_fcmpset_rel_int(&m->ref_count, &old, old - 1));
4380
4381 if (VPRC_WIRE_COUNT(old) == 1) {
4382 vm_wire_sub(1);
4383 if (old == 1)
4384 vm_page_free(m);
4385 }
4386 }
4387
4388 /*
4389 * Release one wiring of the specified page, potentially allowing it to be
4390 * paged out.
4391 *
4392 * Only managed pages belonging to an object can be paged out. If the number
4393 * of wirings transitions to zero and the page is eligible for page out, then
4394 * the page is added to the specified paging queue. If the released wiring
4395 * represented the last reference to the page, the page is freed.
4396 */
4397 void
vm_page_unwire(vm_page_t m,uint8_t nqueue)4398 vm_page_unwire(vm_page_t m, uint8_t nqueue)
4399 {
4400
4401 KASSERT(nqueue < PQ_COUNT,
4402 ("vm_page_unwire: invalid queue %u request for page %p",
4403 nqueue, m));
4404
4405 if ((m->oflags & VPO_UNMANAGED) != 0) {
4406 if (vm_page_unwire_noq(m) && m->ref_count == 0)
4407 vm_page_free(m);
4408 return;
4409 }
4410 vm_page_unwire_managed(m, nqueue, false);
4411 }
4412
4413 /*
4414 * Unwire a page without (re-)inserting it into a page queue. It is up
4415 * to the caller to enqueue, requeue, or free the page as appropriate.
4416 * In most cases involving managed pages, vm_page_unwire() should be used
4417 * instead.
4418 */
4419 bool
vm_page_unwire_noq(vm_page_t m)4420 vm_page_unwire_noq(vm_page_t m)
4421 {
4422 u_int old;
4423
4424 old = vm_page_drop(m, 1);
4425 KASSERT(VPRC_WIRE_COUNT(old) != 0,
4426 ("%s: counter underflow for page %p", __func__, m));
4427 KASSERT((m->flags & PG_FICTITIOUS) == 0 || VPRC_WIRE_COUNT(old) > 1,
4428 ("%s: missing ref on fictitious page %p", __func__, m));
4429
4430 if (VPRC_WIRE_COUNT(old) > 1)
4431 return (false);
4432 if ((m->oflags & VPO_UNMANAGED) == 0)
4433 vm_page_aflag_clear(m, PGA_DEQUEUE);
4434 vm_wire_sub(1);
4435 return (true);
4436 }
4437
4438 /*
4439 * Ensure that the page ends up in the specified page queue. If the page is
4440 * active or being moved to the active queue, ensure that its act_count is
4441 * at least ACT_INIT but do not otherwise mess with it.
4442 */
4443 static __always_inline void
vm_page_mvqueue(vm_page_t m,const uint8_t nqueue,const uint16_t nflag)4444 vm_page_mvqueue(vm_page_t m, const uint8_t nqueue, const uint16_t nflag)
4445 {
4446 vm_page_astate_t old, new;
4447
4448 KASSERT(m->ref_count > 0,
4449 ("%s: page %p does not carry any references", __func__, m));
4450 KASSERT(nflag == PGA_REQUEUE || nflag == PGA_REQUEUE_HEAD,
4451 ("%s: invalid flags %x", __func__, nflag));
4452
4453 if ((m->oflags & VPO_UNMANAGED) != 0 || vm_page_wired(m))
4454 return;
4455
4456 old = vm_page_astate_load(m);
4457 do {
4458 if ((old.flags & PGA_DEQUEUE) != 0)
4459 break;
4460 new = old;
4461 new.flags &= ~PGA_QUEUE_OP_MASK;
4462 if (nqueue == PQ_ACTIVE)
4463 new.act_count = max(old.act_count, ACT_INIT);
4464 if (old.queue == nqueue) {
4465 /*
4466 * There is no need to requeue pages already in the
4467 * active queue.
4468 */
4469 if (nqueue != PQ_ACTIVE ||
4470 (old.flags & PGA_ENQUEUED) == 0)
4471 new.flags |= nflag;
4472 } else {
4473 new.flags |= nflag;
4474 new.queue = nqueue;
4475 }
4476 } while (!vm_page_pqstate_commit(m, &old, new));
4477 }
4478
4479 /*
4480 * Put the specified page on the active list (if appropriate).
4481 */
4482 void
vm_page_activate(vm_page_t m)4483 vm_page_activate(vm_page_t m)
4484 {
4485
4486 vm_page_mvqueue(m, PQ_ACTIVE, PGA_REQUEUE);
4487 }
4488
4489 /*
4490 * Move the specified page to the tail of the inactive queue, or requeue
4491 * the page if it is already in the inactive queue.
4492 */
4493 void
vm_page_deactivate(vm_page_t m)4494 vm_page_deactivate(vm_page_t m)
4495 {
4496
4497 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE);
4498 }
4499
4500 void
vm_page_deactivate_noreuse(vm_page_t m)4501 vm_page_deactivate_noreuse(vm_page_t m)
4502 {
4503
4504 vm_page_mvqueue(m, PQ_INACTIVE, PGA_REQUEUE_HEAD);
4505 }
4506
4507 /*
4508 * Put a page in the laundry, or requeue it if it is already there.
4509 */
4510 void
vm_page_launder(vm_page_t m)4511 vm_page_launder(vm_page_t m)
4512 {
4513
4514 vm_page_mvqueue(m, PQ_LAUNDRY, PGA_REQUEUE);
4515 }
4516
4517 /*
4518 * Put a page in the PQ_UNSWAPPABLE holding queue.
4519 */
4520 void
vm_page_unswappable(vm_page_t m)4521 vm_page_unswappable(vm_page_t m)
4522 {
4523
4524 VM_OBJECT_ASSERT_LOCKED(m->object);
4525 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4526 ("page %p already unswappable", m));
4527
4528 vm_page_dequeue(m);
4529 vm_page_enqueue(m, PQ_UNSWAPPABLE);
4530 }
4531
4532 /*
4533 * Release a page back to the page queues in preparation for unwiring.
4534 */
4535 static void
vm_page_release_toq(vm_page_t m,uint8_t nqueue,const bool noreuse)4536 vm_page_release_toq(vm_page_t m, uint8_t nqueue, const bool noreuse)
4537 {
4538 vm_page_astate_t old, new;
4539 uint16_t nflag;
4540
4541 /*
4542 * Use a check of the valid bits to determine whether we should
4543 * accelerate reclamation of the page. The object lock might not be
4544 * held here, in which case the check is racy. At worst we will either
4545 * accelerate reclamation of a valid page and violate LRU, or
4546 * unnecessarily defer reclamation of an invalid page.
4547 *
4548 * If we were asked to not cache the page, place it near the head of the
4549 * inactive queue so that is reclaimed sooner.
4550 */
4551 if (noreuse || vm_page_none_valid(m)) {
4552 nqueue = PQ_INACTIVE;
4553 nflag = PGA_REQUEUE_HEAD;
4554 } else {
4555 nflag = PGA_REQUEUE;
4556 }
4557
4558 old = vm_page_astate_load(m);
4559 do {
4560 new = old;
4561
4562 /*
4563 * If the page is already in the active queue and we are not
4564 * trying to accelerate reclamation, simply mark it as
4565 * referenced and avoid any queue operations.
4566 */
4567 new.flags &= ~PGA_QUEUE_OP_MASK;
4568 if (nflag != PGA_REQUEUE_HEAD && old.queue == PQ_ACTIVE &&
4569 (old.flags & PGA_ENQUEUED) != 0)
4570 new.flags |= PGA_REFERENCED;
4571 else {
4572 new.flags |= nflag;
4573 new.queue = nqueue;
4574 }
4575 } while (!vm_page_pqstate_commit(m, &old, new));
4576 }
4577
4578 /*
4579 * Unwire a page and either attempt to free it or re-add it to the page queues.
4580 */
4581 void
vm_page_release(vm_page_t m,int flags)4582 vm_page_release(vm_page_t m, int flags)
4583 {
4584 vm_object_t object;
4585
4586 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4587 ("vm_page_release: page %p is unmanaged", m));
4588
4589 if ((flags & VPR_TRYFREE) != 0) {
4590 for (;;) {
4591 object = atomic_load_ptr(&m->object);
4592 if (object == NULL)
4593 break;
4594 /* Depends on type-stability. */
4595 if (vm_page_busied(m) || !VM_OBJECT_TRYWLOCK(object))
4596 break;
4597 if (object == m->object) {
4598 vm_page_release_locked(m, flags);
4599 VM_OBJECT_WUNLOCK(object);
4600 return;
4601 }
4602 VM_OBJECT_WUNLOCK(object);
4603 }
4604 }
4605 vm_page_unwire_managed(m, PQ_INACTIVE, flags != 0);
4606 }
4607
4608 /* See vm_page_release(). */
4609 void
vm_page_release_locked(vm_page_t m,int flags)4610 vm_page_release_locked(vm_page_t m, int flags)
4611 {
4612
4613 VM_OBJECT_ASSERT_WLOCKED(m->object);
4614 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4615 ("vm_page_release_locked: page %p is unmanaged", m));
4616
4617 if (vm_page_unwire_noq(m)) {
4618 if ((flags & VPR_TRYFREE) != 0 &&
4619 (m->object->ref_count == 0 || !pmap_page_is_mapped(m)) &&
4620 m->dirty == 0 && vm_page_tryxbusy(m)) {
4621 /*
4622 * An unlocked lookup may have wired the page before the
4623 * busy lock was acquired, in which case the page must
4624 * not be freed.
4625 */
4626 if (__predict_true(!vm_page_wired(m))) {
4627 vm_page_free(m);
4628 return;
4629 }
4630 vm_page_xunbusy(m);
4631 } else {
4632 vm_page_release_toq(m, PQ_INACTIVE, flags != 0);
4633 }
4634 }
4635 }
4636
4637 static bool
vm_page_try_blocked_op(vm_page_t m,void (* op)(vm_page_t))4638 vm_page_try_blocked_op(vm_page_t m, void (*op)(vm_page_t))
4639 {
4640 u_int old;
4641
4642 KASSERT(m->object != NULL && (m->oflags & VPO_UNMANAGED) == 0,
4643 ("vm_page_try_blocked_op: page %p has no object", m));
4644 KASSERT(vm_page_busied(m),
4645 ("vm_page_try_blocked_op: page %p is not busy", m));
4646 VM_OBJECT_ASSERT_LOCKED(m->object);
4647
4648 old = atomic_load_int(&m->ref_count);
4649 do {
4650 KASSERT(old != 0,
4651 ("vm_page_try_blocked_op: page %p has no references", m));
4652 KASSERT((old & VPRC_BLOCKED) == 0,
4653 ("vm_page_try_blocked_op: page %p blocks wirings", m));
4654 if (VPRC_WIRE_COUNT(old) != 0)
4655 return (false);
4656 } while (!atomic_fcmpset_int(&m->ref_count, &old, old | VPRC_BLOCKED));
4657
4658 (op)(m);
4659
4660 /*
4661 * If the object is read-locked, new wirings may be created via an
4662 * object lookup.
4663 */
4664 old = vm_page_drop(m, VPRC_BLOCKED);
4665 KASSERT(!VM_OBJECT_WOWNED(m->object) ||
4666 old == (VPRC_BLOCKED | VPRC_OBJREF),
4667 ("vm_page_try_blocked_op: unexpected refcount value %u for %p",
4668 old, m));
4669 return (true);
4670 }
4671
4672 /*
4673 * Atomically check for wirings and remove all mappings of the page.
4674 */
4675 bool
vm_page_try_remove_all(vm_page_t m)4676 vm_page_try_remove_all(vm_page_t m)
4677 {
4678
4679 return (vm_page_try_blocked_op(m, pmap_remove_all));
4680 }
4681
4682 /*
4683 * Atomically check for wirings and remove all writeable mappings of the page.
4684 */
4685 bool
vm_page_try_remove_write(vm_page_t m)4686 vm_page_try_remove_write(vm_page_t m)
4687 {
4688
4689 return (vm_page_try_blocked_op(m, pmap_remove_write));
4690 }
4691
4692 /*
4693 * vm_page_advise
4694 *
4695 * Apply the specified advice to the given page.
4696 */
4697 void
vm_page_advise(vm_page_t m,int advice)4698 vm_page_advise(vm_page_t m, int advice)
4699 {
4700
4701 VM_OBJECT_ASSERT_WLOCKED(m->object);
4702 vm_page_assert_xbusied(m);
4703
4704 if (advice == MADV_FREE)
4705 /*
4706 * Mark the page clean. This will allow the page to be freed
4707 * without first paging it out. MADV_FREE pages are often
4708 * quickly reused by malloc(3), so we do not do anything that
4709 * would result in a page fault on a later access.
4710 */
4711 vm_page_undirty(m);
4712 else if (advice != MADV_DONTNEED) {
4713 if (advice == MADV_WILLNEED)
4714 vm_page_activate(m);
4715 return;
4716 }
4717
4718 if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
4719 vm_page_dirty(m);
4720
4721 /*
4722 * Clear any references to the page. Otherwise, the page daemon will
4723 * immediately reactivate the page.
4724 */
4725 vm_page_aflag_clear(m, PGA_REFERENCED);
4726
4727 /*
4728 * Place clean pages near the head of the inactive queue rather than
4729 * the tail, thus defeating the queue's LRU operation and ensuring that
4730 * the page will be reused quickly. Dirty pages not already in the
4731 * laundry are moved there.
4732 */
4733 if (m->dirty == 0)
4734 vm_page_deactivate_noreuse(m);
4735 else if (!vm_page_in_laundry(m))
4736 vm_page_launder(m);
4737 }
4738
4739 /*
4740 * vm_page_grab_release
4741 *
4742 * Helper routine for grab functions to release busy on return.
4743 */
4744 static inline void
vm_page_grab_release(vm_page_t m,int allocflags)4745 vm_page_grab_release(vm_page_t m, int allocflags)
4746 {
4747
4748 if ((allocflags & VM_ALLOC_NOBUSY) != 0) {
4749 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4750 vm_page_sunbusy(m);
4751 else
4752 vm_page_xunbusy(m);
4753 }
4754 }
4755
4756 /*
4757 * vm_page_grab_sleep
4758 *
4759 * Sleep for busy according to VM_ALLOC_ parameters. Returns true
4760 * if the caller should retry and false otherwise.
4761 *
4762 * If the object is locked on entry the object will be unlocked with
4763 * false returns and still locked but possibly having been dropped
4764 * with true returns.
4765 */
4766 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)4767 vm_page_grab_sleep(vm_object_t object, vm_page_t m, vm_pindex_t pindex,
4768 const char *wmesg, int allocflags, bool locked)
4769 {
4770
4771 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
4772 return (false);
4773
4774 /*
4775 * Reference the page before unlocking and sleeping so that
4776 * the page daemon is less likely to reclaim it.
4777 */
4778 if (locked && (allocflags & VM_ALLOC_NOCREAT) == 0)
4779 vm_page_reference(m);
4780
4781 if (_vm_page_busy_sleep(object, m, pindex, wmesg, allocflags, locked) &&
4782 locked)
4783 VM_OBJECT_WLOCK(object);
4784 if ((allocflags & VM_ALLOC_WAITFAIL) != 0)
4785 return (false);
4786
4787 return (true);
4788 }
4789
4790 /*
4791 * Assert that the grab flags are valid.
4792 */
4793 static inline void
vm_page_grab_check(int allocflags)4794 vm_page_grab_check(int allocflags)
4795 {
4796
4797 KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
4798 (allocflags & VM_ALLOC_WIRED) != 0,
4799 ("vm_page_grab*: the pages must be busied or wired"));
4800
4801 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4802 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4803 ("vm_page_grab*: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4804 }
4805
4806 /*
4807 * Calculate the page allocation flags for grab.
4808 */
4809 static inline int
vm_page_grab_pflags(int allocflags)4810 vm_page_grab_pflags(int allocflags)
4811 {
4812 int pflags;
4813
4814 pflags = allocflags &
4815 ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL |
4816 VM_ALLOC_NOBUSY | VM_ALLOC_IGN_SBUSY);
4817 if ((allocflags & VM_ALLOC_NOWAIT) == 0)
4818 pflags |= VM_ALLOC_WAITFAIL;
4819 if ((allocflags & VM_ALLOC_IGN_SBUSY) != 0)
4820 pflags |= VM_ALLOC_SBUSY;
4821
4822 return (pflags);
4823 }
4824
4825 /*
4826 * Grab a page, waiting until we are waken up due to the page
4827 * changing state. We keep on waiting, if the page continues
4828 * to be in the object. If the page doesn't exist, first allocate it
4829 * and then conditionally zero it.
4830 *
4831 * This routine may sleep.
4832 *
4833 * The object must be locked on entry. The lock will, however, be released
4834 * and reacquired if the routine sleeps.
4835 */
4836 vm_page_t
vm_page_grab(vm_object_t object,vm_pindex_t pindex,int allocflags)4837 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
4838 {
4839 vm_page_t m;
4840
4841 VM_OBJECT_ASSERT_WLOCKED(object);
4842 vm_page_grab_check(allocflags);
4843
4844 retrylookup:
4845 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4846 if (!vm_page_tryacquire(m, allocflags)) {
4847 if (vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4848 allocflags, true))
4849 goto retrylookup;
4850 return (NULL);
4851 }
4852 goto out;
4853 }
4854 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4855 return (NULL);
4856 m = vm_page_alloc(object, pindex, vm_page_grab_pflags(allocflags));
4857 if (m == NULL) {
4858 if ((allocflags & (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL)) != 0)
4859 return (NULL);
4860 goto retrylookup;
4861 }
4862 if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
4863 pmap_zero_page(m);
4864
4865 out:
4866 vm_page_grab_release(m, allocflags);
4867
4868 return (m);
4869 }
4870
4871 /*
4872 * Attempt to validate a page, locklessly acquiring it if necessary, given a
4873 * (object, pindex) tuple and either an invalided page or NULL. The resulting
4874 * page will be validated against the identity tuple, and busied or wired as
4875 * requested. A NULL page returned guarantees that the page was not in radix at
4876 * the time of the call but callers must perform higher level synchronization or
4877 * retry the operation under a lock if they require an atomic answer. This is
4878 * the only lock free validation routine, other routines can depend on the
4879 * resulting page state.
4880 *
4881 * The return value PAGE_NOT_ACQUIRED indicates that the operation failed due to
4882 * caller flags.
4883 */
4884 #define PAGE_NOT_ACQUIRED ((vm_page_t)1)
4885 static vm_page_t
vm_page_acquire_unlocked(vm_object_t object,vm_pindex_t pindex,vm_page_t m,int allocflags)4886 vm_page_acquire_unlocked(vm_object_t object, vm_pindex_t pindex, vm_page_t m,
4887 int allocflags)
4888 {
4889 if (m == NULL)
4890 m = vm_page_lookup_unlocked(object, pindex);
4891 for (; m != NULL; m = vm_page_lookup_unlocked(object, pindex)) {
4892 if (vm_page_trybusy(m, allocflags)) {
4893 if (m->object == object && m->pindex == pindex) {
4894 if ((allocflags & VM_ALLOC_WIRED) != 0)
4895 vm_page_wire(m);
4896 vm_page_grab_release(m, allocflags);
4897 break;
4898 }
4899 /* relookup. */
4900 vm_page_busy_release(m);
4901 cpu_spinwait();
4902 continue;
4903 }
4904 if (!vm_page_grab_sleep(object, m, pindex, "pgnslp",
4905 allocflags, false))
4906 return (PAGE_NOT_ACQUIRED);
4907 }
4908 return (m);
4909 }
4910
4911 /*
4912 * Try to locklessly grab a page and fall back to the object lock if NOCREAT
4913 * is not set.
4914 */
4915 vm_page_t
vm_page_grab_unlocked(vm_object_t object,vm_pindex_t pindex,int allocflags)4916 vm_page_grab_unlocked(vm_object_t object, vm_pindex_t pindex, int allocflags)
4917 {
4918 vm_page_t m;
4919
4920 vm_page_grab_check(allocflags);
4921 m = vm_page_acquire_unlocked(object, pindex, NULL, allocflags);
4922 if (m == PAGE_NOT_ACQUIRED)
4923 return (NULL);
4924 if (m != NULL)
4925 return (m);
4926
4927 /*
4928 * The radix lockless lookup should never return a false negative
4929 * errors. If the user specifies NOCREAT they are guaranteed there
4930 * was no page present at the instant of the call. A NOCREAT caller
4931 * must handle create races gracefully.
4932 */
4933 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
4934 return (NULL);
4935
4936 VM_OBJECT_WLOCK(object);
4937 m = vm_page_grab(object, pindex, allocflags);
4938 VM_OBJECT_WUNLOCK(object);
4939
4940 return (m);
4941 }
4942
4943 /*
4944 * Grab a page and make it valid, paging in if necessary. Pages missing from
4945 * their pager are zero filled and validated. If a VM_ALLOC_COUNT is supplied
4946 * and the page is not valid as many as VM_INITIAL_PAGEIN pages can be brought
4947 * in simultaneously. Additional pages will be left on a paging queue but
4948 * will neither be wired nor busy regardless of allocflags.
4949 */
4950 int
vm_page_grab_valid(vm_page_t * mp,vm_object_t object,vm_pindex_t pindex,int allocflags)4951 vm_page_grab_valid(vm_page_t *mp, vm_object_t object, vm_pindex_t pindex, int allocflags)
4952 {
4953 vm_page_t m;
4954 vm_page_t ma[VM_INITIAL_PAGEIN];
4955 int after, i, pflags, rv;
4956
4957 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
4958 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
4959 ("vm_page_grab_valid: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
4960 KASSERT((allocflags &
4961 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
4962 ("vm_page_grab_valid: Invalid flags 0x%X", allocflags));
4963 VM_OBJECT_ASSERT_WLOCKED(object);
4964 pflags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY |
4965 VM_ALLOC_WIRED | VM_ALLOC_IGN_SBUSY);
4966 pflags |= VM_ALLOC_WAITFAIL;
4967
4968 retrylookup:
4969 if ((m = vm_page_lookup(object, pindex)) != NULL) {
4970 /*
4971 * If the page is fully valid it can only become invalid
4972 * with the object lock held. If it is not valid it can
4973 * become valid with the busy lock held. Therefore, we
4974 * may unnecessarily lock the exclusive busy here if we
4975 * race with I/O completion not using the object lock.
4976 * However, we will not end up with an invalid page and a
4977 * shared lock.
4978 */
4979 if (!vm_page_trybusy(m,
4980 vm_page_all_valid(m) ? allocflags : 0)) {
4981 (void)vm_page_grab_sleep(object, m, pindex, "pgrbwt",
4982 allocflags, true);
4983 goto retrylookup;
4984 }
4985 if (vm_page_all_valid(m))
4986 goto out;
4987 if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4988 vm_page_busy_release(m);
4989 *mp = NULL;
4990 return (VM_PAGER_FAIL);
4991 }
4992 } else if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
4993 *mp = NULL;
4994 return (VM_PAGER_FAIL);
4995 } else if ((m = vm_page_alloc(object, pindex, pflags)) == NULL) {
4996 if (!vm_pager_can_alloc_page(object, pindex)) {
4997 *mp = NULL;
4998 return (VM_PAGER_AGAIN);
4999 }
5000 goto retrylookup;
5001 }
5002
5003 vm_page_assert_xbusied(m);
5004 if (vm_pager_has_page(object, pindex, NULL, &after)) {
5005 after = MIN(after, VM_INITIAL_PAGEIN);
5006 after = MIN(after, allocflags >> VM_ALLOC_COUNT_SHIFT);
5007 after = MAX(after, 1);
5008 ma[0] = m;
5009 for (i = 1; i < after; i++) {
5010 if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
5011 if (vm_page_any_valid(ma[i]) ||
5012 !vm_page_tryxbusy(ma[i]))
5013 break;
5014 } else {
5015 ma[i] = vm_page_alloc_after(object,
5016 m->pindex + i, VM_ALLOC_NORMAL, ma[i - 1]);
5017 if (ma[i] == NULL)
5018 break;
5019 }
5020 }
5021 after = i;
5022 vm_object_pip_add(object, after);
5023 VM_OBJECT_WUNLOCK(object);
5024 rv = vm_pager_get_pages(object, ma, after, NULL, NULL);
5025 VM_OBJECT_WLOCK(object);
5026 vm_object_pip_wakeupn(object, after);
5027 /* Pager may have replaced a page. */
5028 m = ma[0];
5029 if (rv != VM_PAGER_OK) {
5030 for (i = 0; i < after; i++) {
5031 if (!vm_page_wired(ma[i]))
5032 vm_page_free(ma[i]);
5033 else
5034 vm_page_xunbusy(ma[i]);
5035 }
5036 *mp = NULL;
5037 return (rv);
5038 }
5039 for (i = 1; i < after; i++)
5040 vm_page_readahead_finish(ma[i]);
5041 MPASS(vm_page_all_valid(m));
5042 } else {
5043 vm_page_zero_invalid(m, TRUE);
5044 }
5045 out:
5046 if ((allocflags & VM_ALLOC_WIRED) != 0)
5047 vm_page_wire(m);
5048 if ((allocflags & VM_ALLOC_SBUSY) != 0 && vm_page_xbusied(m))
5049 vm_page_busy_downgrade(m);
5050 else if ((allocflags & VM_ALLOC_NOBUSY) != 0)
5051 vm_page_busy_release(m);
5052 *mp = m;
5053 return (VM_PAGER_OK);
5054 }
5055
5056 /*
5057 * Fill a partial page with zeroes. The object write lock is held on entry and
5058 * exit, but may be temporarily released.
5059 */
5060 int
vm_page_grab_zero_partial(vm_object_t object,vm_pindex_t pindex,int base,int end)5061 vm_page_grab_zero_partial(vm_object_t object, vm_pindex_t pindex, int base,
5062 int end)
5063 {
5064 vm_page_t m;
5065 int rv;
5066
5067 VM_OBJECT_ASSERT_WLOCKED(object);
5068 KASSERT(base >= 0, ("%s: base %d", __func__, base));
5069 KASSERT(end - base <= PAGE_SIZE, ("%s: base %d end %d", __func__, base,
5070 end));
5071
5072 retry:
5073 m = vm_page_grab(object, pindex, VM_ALLOC_NOCREAT);
5074 if (m != NULL) {
5075 MPASS(vm_page_all_valid(m));
5076 } else if (vm_pager_has_page(object, pindex, NULL, NULL)) {
5077 m = vm_page_alloc(object, pindex,
5078 VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
5079 if (m == NULL)
5080 goto retry;
5081 vm_object_pip_add(object, 1);
5082 VM_OBJECT_WUNLOCK(object);
5083 rv = vm_pager_get_pages(object, &m, 1, NULL, NULL);
5084 VM_OBJECT_WLOCK(object);
5085 vm_object_pip_wakeup(object);
5086 if (rv != VM_PAGER_OK) {
5087 vm_page_free(m);
5088 return (EIO);
5089 }
5090
5091 /*
5092 * Since the page was not resident, and therefore not recently
5093 * accessed, immediately enqueue it for asynchronous laundering.
5094 * The current operation is not regarded as an access.
5095 */
5096 vm_page_launder(m);
5097 } else
5098 return (0);
5099
5100 pmap_zero_page_area(m, base, end - base);
5101 KASSERT(vm_page_all_valid(m), ("%s: page %p is invalid", __func__, m));
5102 vm_page_set_dirty(m);
5103 vm_page_xunbusy(m);
5104 return (0);
5105 }
5106
5107 /*
5108 * Locklessly grab a valid page. If the page is not valid or not yet
5109 * allocated this will fall back to the object lock method.
5110 */
5111 int
vm_page_grab_valid_unlocked(vm_page_t * mp,vm_object_t object,vm_pindex_t pindex,int allocflags)5112 vm_page_grab_valid_unlocked(vm_page_t *mp, vm_object_t object,
5113 vm_pindex_t pindex, int allocflags)
5114 {
5115 vm_page_t m;
5116 int flags;
5117 int error;
5118
5119 KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
5120 (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
5121 ("vm_page_grab_valid_unlocked: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY "
5122 "mismatch"));
5123 KASSERT((allocflags &
5124 (VM_ALLOC_NOWAIT | VM_ALLOC_WAITFAIL | VM_ALLOC_ZERO)) == 0,
5125 ("vm_page_grab_valid_unlocked: Invalid flags 0x%X", allocflags));
5126
5127 /*
5128 * Attempt a lockless lookup and busy. We need at least an sbusy
5129 * before we can inspect the valid field and return a wired page.
5130 */
5131 flags = allocflags & ~(VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
5132 vm_page_grab_check(flags);
5133 m = vm_page_acquire_unlocked(object, pindex, NULL, flags);
5134 if (m == PAGE_NOT_ACQUIRED)
5135 return (VM_PAGER_FAIL);
5136 if (m != NULL) {
5137 if (vm_page_all_valid(m)) {
5138 if ((allocflags & VM_ALLOC_WIRED) != 0)
5139 vm_page_wire(m);
5140 vm_page_grab_release(m, allocflags);
5141 *mp = m;
5142 return (VM_PAGER_OK);
5143 }
5144 vm_page_busy_release(m);
5145 }
5146 if ((allocflags & VM_ALLOC_NOCREAT) != 0) {
5147 *mp = NULL;
5148 return (VM_PAGER_FAIL);
5149 }
5150 VM_OBJECT_WLOCK(object);
5151 error = vm_page_grab_valid(mp, object, pindex, allocflags);
5152 VM_OBJECT_WUNLOCK(object);
5153
5154 return (error);
5155 }
5156
5157 /*
5158 * Return the specified range of pages from the given object. For each
5159 * page offset within the range, if a page already exists within the object
5160 * at that offset and it is busy, then wait for it to change state. If,
5161 * instead, the page doesn't exist, then allocate it.
5162 *
5163 * The caller must always specify an allocation class.
5164 *
5165 * allocation classes:
5166 * VM_ALLOC_NORMAL normal process request
5167 * VM_ALLOC_SYSTEM system *really* needs the pages
5168 *
5169 * The caller must always specify that the pages are to be busied and/or
5170 * wired.
5171 *
5172 * optional allocation flags:
5173 * VM_ALLOC_IGN_SBUSY do not sleep on soft busy pages
5174 * VM_ALLOC_NOBUSY do not exclusive busy the page
5175 * VM_ALLOC_NOWAIT do not sleep
5176 * VM_ALLOC_SBUSY set page to sbusy state
5177 * VM_ALLOC_WIRED wire the pages
5178 * VM_ALLOC_ZERO zero and validate any invalid pages
5179 *
5180 * If VM_ALLOC_NOWAIT is not specified, this routine may sleep. Otherwise, it
5181 * may return a partial prefix of the requested range.
5182 */
5183 int
vm_page_grab_pages(vm_object_t object,vm_pindex_t pindex,int allocflags,vm_page_t * ma,int count)5184 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
5185 vm_page_t *ma, int count)
5186 {
5187 vm_page_t m, mpred;
5188 int pflags;
5189 int i;
5190
5191 VM_OBJECT_ASSERT_WLOCKED(object);
5192 KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
5193 ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
5194 KASSERT(count > 0,
5195 ("vm_page_grab_pages: invalid page count %d", count));
5196 vm_page_grab_check(allocflags);
5197
5198 pflags = vm_page_grab_pflags(allocflags);
5199 i = 0;
5200 retrylookup:
5201 m = vm_page_mpred(object, pindex + i);
5202 if (m == NULL || m->pindex != pindex + i) {
5203 mpred = m;
5204 m = NULL;
5205 } else
5206 mpred = TAILQ_PREV(m, pglist, listq);
5207 for (; i < count; i++) {
5208 if (m != NULL) {
5209 if (!vm_page_tryacquire(m, allocflags)) {
5210 if (vm_page_grab_sleep(object, m, pindex + i,
5211 "grbmaw", allocflags, true))
5212 goto retrylookup;
5213 break;
5214 }
5215 } else {
5216 if ((allocflags & VM_ALLOC_NOCREAT) != 0)
5217 break;
5218 m = vm_page_alloc_after(object, pindex + i,
5219 pflags | VM_ALLOC_COUNT(count - i), mpred);
5220 if (m == NULL) {
5221 if ((allocflags & (VM_ALLOC_NOWAIT |
5222 VM_ALLOC_WAITFAIL)) != 0)
5223 break;
5224 goto retrylookup;
5225 }
5226 }
5227 if (vm_page_none_valid(m) &&
5228 (allocflags & VM_ALLOC_ZERO) != 0) {
5229 if ((m->flags & PG_ZERO) == 0)
5230 pmap_zero_page(m);
5231 vm_page_valid(m);
5232 }
5233 vm_page_grab_release(m, allocflags);
5234 ma[i] = mpred = m;
5235 m = vm_page_next(m);
5236 }
5237 return (i);
5238 }
5239
5240 /*
5241 * Unlocked variant of vm_page_grab_pages(). This accepts the same flags
5242 * and will fall back to the locked variant to handle allocation.
5243 */
5244 int
vm_page_grab_pages_unlocked(vm_object_t object,vm_pindex_t pindex,int allocflags,vm_page_t * ma,int count)5245 vm_page_grab_pages_unlocked(vm_object_t object, vm_pindex_t pindex,
5246 int allocflags, vm_page_t *ma, int count)
5247 {
5248 vm_page_t m;
5249 int flags;
5250 int i;
5251
5252 KASSERT(count > 0,
5253 ("vm_page_grab_pages_unlocked: invalid page count %d", count));
5254 vm_page_grab_check(allocflags);
5255
5256 /*
5257 * Modify flags for lockless acquire to hold the page until we
5258 * set it valid if necessary.
5259 */
5260 flags = allocflags & ~VM_ALLOC_NOBUSY;
5261 vm_page_grab_check(flags);
5262 m = NULL;
5263 for (i = 0; i < count; i++, pindex++) {
5264 /*
5265 * We may see a false NULL here because the previous page has
5266 * been removed or just inserted and the list is loaded without
5267 * barriers. Switch to radix to verify.
5268 */
5269 if (m == NULL || QMD_IS_TRASHED(m) || m->pindex != pindex ||
5270 atomic_load_ptr(&m->object) != object) {
5271 /*
5272 * This guarantees the result is instantaneously
5273 * correct.
5274 */
5275 m = NULL;
5276 }
5277 m = vm_page_acquire_unlocked(object, pindex, m, flags);
5278 if (m == PAGE_NOT_ACQUIRED)
5279 return (i);
5280 if (m == NULL)
5281 break;
5282 if ((flags & VM_ALLOC_ZERO) != 0 && vm_page_none_valid(m)) {
5283 if ((m->flags & PG_ZERO) == 0)
5284 pmap_zero_page(m);
5285 vm_page_valid(m);
5286 }
5287 /* m will still be wired or busy according to flags. */
5288 vm_page_grab_release(m, allocflags);
5289 ma[i] = m;
5290 m = TAILQ_NEXT(m, listq);
5291 }
5292 if (i == count || (allocflags & VM_ALLOC_NOCREAT) != 0)
5293 return (i);
5294 count -= i;
5295 VM_OBJECT_WLOCK(object);
5296 i += vm_page_grab_pages(object, pindex, allocflags, &ma[i], count);
5297 VM_OBJECT_WUNLOCK(object);
5298
5299 return (i);
5300 }
5301
5302 /*
5303 * Mapping function for valid or dirty bits in a page.
5304 *
5305 * Inputs are required to range within a page.
5306 */
5307 vm_page_bits_t
vm_page_bits(int base,int size)5308 vm_page_bits(int base, int size)
5309 {
5310 int first_bit;
5311 int last_bit;
5312
5313 KASSERT(
5314 base + size <= PAGE_SIZE,
5315 ("vm_page_bits: illegal base/size %d/%d", base, size)
5316 );
5317
5318 if (size == 0) /* handle degenerate case */
5319 return (0);
5320
5321 first_bit = base >> DEV_BSHIFT;
5322 last_bit = (base + size - 1) >> DEV_BSHIFT;
5323
5324 return (((vm_page_bits_t)2 << last_bit) -
5325 ((vm_page_bits_t)1 << first_bit));
5326 }
5327
5328 void
vm_page_bits_set(vm_page_t m,vm_page_bits_t * bits,vm_page_bits_t set)5329 vm_page_bits_set(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t set)
5330 {
5331
5332 #if PAGE_SIZE == 32768
5333 atomic_set_64((uint64_t *)bits, set);
5334 #elif PAGE_SIZE == 16384
5335 atomic_set_32((uint32_t *)bits, set);
5336 #elif (PAGE_SIZE == 8192) && defined(atomic_set_16)
5337 atomic_set_16((uint16_t *)bits, set);
5338 #elif (PAGE_SIZE == 4096) && defined(atomic_set_8)
5339 atomic_set_8((uint8_t *)bits, set);
5340 #else /* PAGE_SIZE <= 8192 */
5341 uintptr_t addr;
5342 int shift;
5343
5344 addr = (uintptr_t)bits;
5345 /*
5346 * Use a trick to perform a 32-bit atomic on the
5347 * containing aligned word, to not depend on the existence
5348 * of atomic_{set, clear}_{8, 16}.
5349 */
5350 shift = addr & (sizeof(uint32_t) - 1);
5351 #if BYTE_ORDER == BIG_ENDIAN
5352 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5353 #else
5354 shift *= NBBY;
5355 #endif
5356 addr &= ~(sizeof(uint32_t) - 1);
5357 atomic_set_32((uint32_t *)addr, set << shift);
5358 #endif /* PAGE_SIZE */
5359 }
5360
5361 static inline void
vm_page_bits_clear(vm_page_t m,vm_page_bits_t * bits,vm_page_bits_t clear)5362 vm_page_bits_clear(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t clear)
5363 {
5364
5365 #if PAGE_SIZE == 32768
5366 atomic_clear_64((uint64_t *)bits, clear);
5367 #elif PAGE_SIZE == 16384
5368 atomic_clear_32((uint32_t *)bits, clear);
5369 #elif (PAGE_SIZE == 8192) && defined(atomic_clear_16)
5370 atomic_clear_16((uint16_t *)bits, clear);
5371 #elif (PAGE_SIZE == 4096) && defined(atomic_clear_8)
5372 atomic_clear_8((uint8_t *)bits, clear);
5373 #else /* PAGE_SIZE <= 8192 */
5374 uintptr_t addr;
5375 int shift;
5376
5377 addr = (uintptr_t)bits;
5378 /*
5379 * Use a trick to perform a 32-bit atomic on the
5380 * containing aligned word, to not depend on the existence
5381 * of atomic_{set, clear}_{8, 16}.
5382 */
5383 shift = addr & (sizeof(uint32_t) - 1);
5384 #if BYTE_ORDER == BIG_ENDIAN
5385 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5386 #else
5387 shift *= NBBY;
5388 #endif
5389 addr &= ~(sizeof(uint32_t) - 1);
5390 atomic_clear_32((uint32_t *)addr, clear << shift);
5391 #endif /* PAGE_SIZE */
5392 }
5393
5394 static inline vm_page_bits_t
vm_page_bits_swap(vm_page_t m,vm_page_bits_t * bits,vm_page_bits_t newbits)5395 vm_page_bits_swap(vm_page_t m, vm_page_bits_t *bits, vm_page_bits_t newbits)
5396 {
5397 #if PAGE_SIZE == 32768
5398 uint64_t old;
5399
5400 old = *bits;
5401 while (atomic_fcmpset_64(bits, &old, newbits) == 0);
5402 return (old);
5403 #elif PAGE_SIZE == 16384
5404 uint32_t old;
5405
5406 old = *bits;
5407 while (atomic_fcmpset_32(bits, &old, newbits) == 0);
5408 return (old);
5409 #elif (PAGE_SIZE == 8192) && defined(atomic_fcmpset_16)
5410 uint16_t old;
5411
5412 old = *bits;
5413 while (atomic_fcmpset_16(bits, &old, newbits) == 0);
5414 return (old);
5415 #elif (PAGE_SIZE == 4096) && defined(atomic_fcmpset_8)
5416 uint8_t old;
5417
5418 old = *bits;
5419 while (atomic_fcmpset_8(bits, &old, newbits) == 0);
5420 return (old);
5421 #else /* PAGE_SIZE <= 4096*/
5422 uintptr_t addr;
5423 uint32_t old, new, mask;
5424 int shift;
5425
5426 addr = (uintptr_t)bits;
5427 /*
5428 * Use a trick to perform a 32-bit atomic on the
5429 * containing aligned word, to not depend on the existence
5430 * of atomic_{set, swap, clear}_{8, 16}.
5431 */
5432 shift = addr & (sizeof(uint32_t) - 1);
5433 #if BYTE_ORDER == BIG_ENDIAN
5434 shift = (sizeof(uint32_t) - sizeof(vm_page_bits_t) - shift) * NBBY;
5435 #else
5436 shift *= NBBY;
5437 #endif
5438 addr &= ~(sizeof(uint32_t) - 1);
5439 mask = VM_PAGE_BITS_ALL << shift;
5440
5441 old = *bits;
5442 do {
5443 new = old & ~mask;
5444 new |= newbits << shift;
5445 } while (atomic_fcmpset_32((uint32_t *)addr, &old, new) == 0);
5446 return (old >> shift);
5447 #endif /* PAGE_SIZE */
5448 }
5449
5450 /*
5451 * vm_page_set_valid_range:
5452 *
5453 * Sets portions of a page valid. The arguments are expected
5454 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5455 * of any partial chunks touched by the range. The invalid portion of
5456 * such chunks will be zeroed.
5457 *
5458 * (base + size) must be less then or equal to PAGE_SIZE.
5459 */
5460 void
vm_page_set_valid_range(vm_page_t m,int base,int size)5461 vm_page_set_valid_range(vm_page_t m, int base, int size)
5462 {
5463 int endoff, frag;
5464 vm_page_bits_t pagebits;
5465
5466 vm_page_assert_busied(m);
5467 if (size == 0) /* handle degenerate case */
5468 return;
5469
5470 /*
5471 * If the base is not DEV_BSIZE aligned and the valid
5472 * bit is clear, we have to zero out a portion of the
5473 * first block.
5474 */
5475 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5476 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
5477 pmap_zero_page_area(m, frag, base - frag);
5478
5479 /*
5480 * If the ending offset is not DEV_BSIZE aligned and the
5481 * valid bit is clear, we have to zero out a portion of
5482 * the last block.
5483 */
5484 endoff = base + size;
5485 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5486 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
5487 pmap_zero_page_area(m, endoff,
5488 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5489
5490 /*
5491 * Assert that no previously invalid block that is now being validated
5492 * is already dirty.
5493 */
5494 KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
5495 ("vm_page_set_valid_range: page %p is dirty", m));
5496
5497 /*
5498 * Set valid bits inclusive of any overlap.
5499 */
5500 pagebits = vm_page_bits(base, size);
5501 if (vm_page_xbusied(m))
5502 m->valid |= pagebits;
5503 else
5504 vm_page_bits_set(m, &m->valid, pagebits);
5505 }
5506
5507 /*
5508 * Set the page dirty bits and free the invalid swap space if
5509 * present. Returns the previous dirty bits.
5510 */
5511 vm_page_bits_t
vm_page_set_dirty(vm_page_t m)5512 vm_page_set_dirty(vm_page_t m)
5513 {
5514 vm_page_bits_t old;
5515
5516 VM_PAGE_OBJECT_BUSY_ASSERT(m);
5517
5518 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m)) {
5519 old = m->dirty;
5520 m->dirty = VM_PAGE_BITS_ALL;
5521 } else
5522 old = vm_page_bits_swap(m, &m->dirty, VM_PAGE_BITS_ALL);
5523 if (old == 0 && (m->a.flags & PGA_SWAP_SPACE) != 0)
5524 vm_pager_page_unswapped(m);
5525
5526 return (old);
5527 }
5528
5529 /*
5530 * Clear the given bits from the specified page's dirty field.
5531 */
5532 static __inline void
vm_page_clear_dirty_mask(vm_page_t m,vm_page_bits_t pagebits)5533 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
5534 {
5535
5536 vm_page_assert_busied(m);
5537
5538 /*
5539 * If the page is xbusied and not write mapped we are the
5540 * only thread that can modify dirty bits. Otherwise, The pmap
5541 * layer can call vm_page_dirty() without holding a distinguished
5542 * lock. The combination of page busy and atomic operations
5543 * suffice to guarantee consistency of the page dirty field.
5544 */
5545 if (vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
5546 m->dirty &= ~pagebits;
5547 else
5548 vm_page_bits_clear(m, &m->dirty, pagebits);
5549 }
5550
5551 /*
5552 * vm_page_set_validclean:
5553 *
5554 * Sets portions of a page valid and clean. The arguments are expected
5555 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
5556 * of any partial chunks touched by the range. The invalid portion of
5557 * such chunks will be zero'd.
5558 *
5559 * (base + size) must be less then or equal to PAGE_SIZE.
5560 */
5561 void
vm_page_set_validclean(vm_page_t m,int base,int size)5562 vm_page_set_validclean(vm_page_t m, int base, int size)
5563 {
5564 vm_page_bits_t oldvalid, pagebits;
5565 int endoff, frag;
5566
5567 vm_page_assert_busied(m);
5568 if (size == 0) /* handle degenerate case */
5569 return;
5570
5571 /*
5572 * If the base is not DEV_BSIZE aligned and the valid
5573 * bit is clear, we have to zero out a portion of the
5574 * first block.
5575 */
5576 if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
5577 (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
5578 pmap_zero_page_area(m, frag, base - frag);
5579
5580 /*
5581 * If the ending offset is not DEV_BSIZE aligned and the
5582 * valid bit is clear, we have to zero out a portion of
5583 * the last block.
5584 */
5585 endoff = base + size;
5586 if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
5587 (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
5588 pmap_zero_page_area(m, endoff,
5589 DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
5590
5591 /*
5592 * Set valid, clear dirty bits. If validating the entire
5593 * page we can safely clear the pmap modify bit. We also
5594 * use this opportunity to clear the PGA_NOSYNC flag. If a process
5595 * takes a write fault on a MAP_NOSYNC memory area the flag will
5596 * be set again.
5597 *
5598 * We set valid bits inclusive of any overlap, but we can only
5599 * clear dirty bits for DEV_BSIZE chunks that are fully within
5600 * the range.
5601 */
5602 oldvalid = m->valid;
5603 pagebits = vm_page_bits(base, size);
5604 if (vm_page_xbusied(m))
5605 m->valid |= pagebits;
5606 else
5607 vm_page_bits_set(m, &m->valid, pagebits);
5608 #if 0 /* NOT YET */
5609 if ((frag = base & (DEV_BSIZE - 1)) != 0) {
5610 frag = DEV_BSIZE - frag;
5611 base += frag;
5612 size -= frag;
5613 if (size < 0)
5614 size = 0;
5615 }
5616 pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
5617 #endif
5618 if (base == 0 && size == PAGE_SIZE) {
5619 /*
5620 * The page can only be modified within the pmap if it is
5621 * mapped, and it can only be mapped if it was previously
5622 * fully valid.
5623 */
5624 if (oldvalid == VM_PAGE_BITS_ALL)
5625 /*
5626 * Perform the pmap_clear_modify() first. Otherwise,
5627 * a concurrent pmap operation, such as
5628 * pmap_protect(), could clear a modification in the
5629 * pmap and set the dirty field on the page before
5630 * pmap_clear_modify() had begun and after the dirty
5631 * field was cleared here.
5632 */
5633 pmap_clear_modify(m);
5634 m->dirty = 0;
5635 vm_page_aflag_clear(m, PGA_NOSYNC);
5636 } else if (oldvalid != VM_PAGE_BITS_ALL && vm_page_xbusied(m))
5637 m->dirty &= ~pagebits;
5638 else
5639 vm_page_clear_dirty_mask(m, pagebits);
5640 }
5641
5642 void
vm_page_clear_dirty(vm_page_t m,int base,int size)5643 vm_page_clear_dirty(vm_page_t m, int base, int size)
5644 {
5645
5646 vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
5647 }
5648
5649 /*
5650 * vm_page_set_invalid:
5651 *
5652 * Invalidates DEV_BSIZE'd chunks within a page. Both the
5653 * valid and dirty bits for the effected areas are cleared.
5654 */
5655 void
vm_page_set_invalid(vm_page_t m,int base,int size)5656 vm_page_set_invalid(vm_page_t m, int base, int size)
5657 {
5658 vm_page_bits_t bits;
5659 vm_object_t object;
5660
5661 /*
5662 * The object lock is required so that pages can't be mapped
5663 * read-only while we're in the process of invalidating them.
5664 */
5665 object = m->object;
5666 VM_OBJECT_ASSERT_WLOCKED(object);
5667 vm_page_assert_busied(m);
5668
5669 if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
5670 size >= object->un_pager.vnp.vnp_size)
5671 bits = VM_PAGE_BITS_ALL;
5672 else
5673 bits = vm_page_bits(base, size);
5674 if (object->ref_count != 0 && vm_page_all_valid(m) && bits != 0)
5675 pmap_remove_all(m);
5676 KASSERT((bits == 0 && vm_page_all_valid(m)) ||
5677 !pmap_page_is_mapped(m),
5678 ("vm_page_set_invalid: page %p is mapped", m));
5679 if (vm_page_xbusied(m)) {
5680 m->valid &= ~bits;
5681 m->dirty &= ~bits;
5682 } else {
5683 vm_page_bits_clear(m, &m->valid, bits);
5684 vm_page_bits_clear(m, &m->dirty, bits);
5685 }
5686 }
5687
5688 /*
5689 * vm_page_invalid:
5690 *
5691 * Invalidates the entire page. The page must be busy, unmapped, and
5692 * the enclosing object must be locked. The object locks protects
5693 * against concurrent read-only pmap enter which is done without
5694 * busy.
5695 */
5696 void
vm_page_invalid(vm_page_t m)5697 vm_page_invalid(vm_page_t m)
5698 {
5699
5700 vm_page_assert_busied(m);
5701 VM_OBJECT_ASSERT_WLOCKED(m->object);
5702 MPASS(!pmap_page_is_mapped(m));
5703
5704 if (vm_page_xbusied(m))
5705 m->valid = 0;
5706 else
5707 vm_page_bits_clear(m, &m->valid, VM_PAGE_BITS_ALL);
5708 }
5709
5710 /*
5711 * vm_page_zero_invalid()
5712 *
5713 * The kernel assumes that the invalid portions of a page contain
5714 * garbage, but such pages can be mapped into memory by user code.
5715 * When this occurs, we must zero out the non-valid portions of the
5716 * page so user code sees what it expects.
5717 *
5718 * Pages are most often semi-valid when the end of a file is mapped
5719 * into memory and the file's size is not page aligned.
5720 */
5721 void
vm_page_zero_invalid(vm_page_t m,boolean_t setvalid)5722 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
5723 {
5724 int b;
5725 int i;
5726
5727 /*
5728 * Scan the valid bits looking for invalid sections that
5729 * must be zeroed. Invalid sub-DEV_BSIZE'd areas ( where the
5730 * valid bit may be set ) have already been zeroed by
5731 * vm_page_set_validclean().
5732 */
5733 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
5734 if (i == (PAGE_SIZE / DEV_BSIZE) ||
5735 (m->valid & ((vm_page_bits_t)1 << i))) {
5736 if (i > b) {
5737 pmap_zero_page_area(m,
5738 b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
5739 }
5740 b = i + 1;
5741 }
5742 }
5743
5744 /*
5745 * setvalid is TRUE when we can safely set the zero'd areas
5746 * as being valid. We can do this if there are no cache consistency
5747 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
5748 */
5749 if (setvalid)
5750 vm_page_valid(m);
5751 }
5752
5753 /*
5754 * vm_page_is_valid:
5755 *
5756 * Is (partial) page valid? Note that the case where size == 0
5757 * will return FALSE in the degenerate case where the page is
5758 * entirely invalid, and TRUE otherwise.
5759 *
5760 * Some callers envoke this routine without the busy lock held and
5761 * handle races via higher level locks. Typical callers should
5762 * hold a busy lock to prevent invalidation.
5763 */
5764 int
vm_page_is_valid(vm_page_t m,int base,int size)5765 vm_page_is_valid(vm_page_t m, int base, int size)
5766 {
5767 vm_page_bits_t bits;
5768
5769 bits = vm_page_bits(base, size);
5770 return (vm_page_any_valid(m) && (m->valid & bits) == bits);
5771 }
5772
5773 /*
5774 * Returns true if all of the specified predicates are true for the entire
5775 * (super)page and false otherwise.
5776 */
5777 bool
vm_page_ps_test(vm_page_t m,int psind,int flags,vm_page_t skip_m)5778 vm_page_ps_test(vm_page_t m, int psind, int flags, vm_page_t skip_m)
5779 {
5780 vm_object_t object;
5781 int i, npages;
5782
5783 object = m->object;
5784 if (skip_m != NULL && skip_m->object != object)
5785 return (false);
5786 VM_OBJECT_ASSERT_LOCKED(object);
5787 KASSERT(psind <= m->psind,
5788 ("psind %d > psind %d of m %p", psind, m->psind, m));
5789 npages = atop(pagesizes[psind]);
5790
5791 /*
5792 * The physically contiguous pages that make up a superpage, i.e., a
5793 * page with a page size index ("psind") greater than zero, will
5794 * occupy adjacent entries in vm_page_array[].
5795 */
5796 for (i = 0; i < npages; i++) {
5797 /* Always test object consistency, including "skip_m". */
5798 if (m[i].object != object)
5799 return (false);
5800 if (&m[i] == skip_m)
5801 continue;
5802 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
5803 return (false);
5804 if ((flags & PS_ALL_DIRTY) != 0) {
5805 /*
5806 * Calling vm_page_test_dirty() or pmap_is_modified()
5807 * might stop this case from spuriously returning
5808 * "false". However, that would require a write lock
5809 * on the object containing "m[i]".
5810 */
5811 if (m[i].dirty != VM_PAGE_BITS_ALL)
5812 return (false);
5813 }
5814 if ((flags & PS_ALL_VALID) != 0 &&
5815 m[i].valid != VM_PAGE_BITS_ALL)
5816 return (false);
5817 }
5818 return (true);
5819 }
5820
5821 /*
5822 * Set the page's dirty bits if the page is modified.
5823 */
5824 void
vm_page_test_dirty(vm_page_t m)5825 vm_page_test_dirty(vm_page_t m)
5826 {
5827
5828 vm_page_assert_busied(m);
5829 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
5830 vm_page_dirty(m);
5831 }
5832
5833 void
vm_page_valid(vm_page_t m)5834 vm_page_valid(vm_page_t m)
5835 {
5836
5837 vm_page_assert_busied(m);
5838 if (vm_page_xbusied(m))
5839 m->valid = VM_PAGE_BITS_ALL;
5840 else
5841 vm_page_bits_set(m, &m->valid, VM_PAGE_BITS_ALL);
5842 }
5843
5844 void
vm_page_lock_KBI(vm_page_t m,const char * file,int line)5845 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
5846 {
5847
5848 mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
5849 }
5850
5851 void
vm_page_unlock_KBI(vm_page_t m,const char * file,int line)5852 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
5853 {
5854
5855 mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
5856 }
5857
5858 int
vm_page_trylock_KBI(vm_page_t m,const char * file,int line)5859 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
5860 {
5861
5862 return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
5863 }
5864
5865 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
5866 void
vm_page_assert_locked_KBI(vm_page_t m,const char * file,int line)5867 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
5868 {
5869
5870 vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
5871 }
5872
5873 void
vm_page_lock_assert_KBI(vm_page_t m,int a,const char * file,int line)5874 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
5875 {
5876
5877 mtx_assert_(vm_page_lockptr(m), a, file, line);
5878 }
5879 #endif
5880
5881 #ifdef INVARIANTS
5882 void
vm_page_object_busy_assert(vm_page_t m)5883 vm_page_object_busy_assert(vm_page_t m)
5884 {
5885
5886 /*
5887 * Certain of the page's fields may only be modified by the
5888 * holder of a page or object busy.
5889 */
5890 if (m->object != NULL && !vm_page_busied(m))
5891 VM_OBJECT_ASSERT_BUSY(m->object);
5892 }
5893
5894 void
vm_page_assert_pga_writeable(vm_page_t m,uint16_t bits)5895 vm_page_assert_pga_writeable(vm_page_t m, uint16_t bits)
5896 {
5897
5898 if ((bits & PGA_WRITEABLE) == 0)
5899 return;
5900
5901 /*
5902 * The PGA_WRITEABLE flag can only be set if the page is
5903 * managed, is exclusively busied or the object is locked.
5904 * Currently, this flag is only set by pmap_enter().
5905 */
5906 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5907 ("PGA_WRITEABLE on unmanaged page"));
5908 if (!vm_page_xbusied(m))
5909 VM_OBJECT_ASSERT_BUSY(m->object);
5910 }
5911 #endif
5912
5913 #include "opt_ddb.h"
5914 #ifdef DDB
5915 #include <sys/kernel.h>
5916
5917 #include <ddb/ddb.h>
5918
DB_SHOW_COMMAND_FLAGS(page,vm_page_print_page_info,DB_CMD_MEMSAFE)5919 DB_SHOW_COMMAND_FLAGS(page, vm_page_print_page_info, DB_CMD_MEMSAFE)
5920 {
5921
5922 db_printf("vm_cnt.v_free_count: %d\n", vm_free_count());
5923 db_printf("vm_cnt.v_inactive_count: %d\n", vm_inactive_count());
5924 db_printf("vm_cnt.v_active_count: %d\n", vm_active_count());
5925 db_printf("vm_cnt.v_laundry_count: %d\n", vm_laundry_count());
5926 db_printf("vm_cnt.v_wire_count: %d\n", vm_wire_count());
5927 db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
5928 db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
5929 db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
5930 db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
5931 }
5932
DB_SHOW_COMMAND_FLAGS(pageq,vm_page_print_pageq_info,DB_CMD_MEMSAFE)5933 DB_SHOW_COMMAND_FLAGS(pageq, vm_page_print_pageq_info, DB_CMD_MEMSAFE)
5934 {
5935 int dom;
5936
5937 db_printf("pq_free %d\n", vm_free_count());
5938 for (dom = 0; dom < vm_ndomains; dom++) {
5939 db_printf(
5940 "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d pq_unsw %d\n",
5941 dom,
5942 vm_dom[dom].vmd_page_count,
5943 vm_dom[dom].vmd_free_count,
5944 vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
5945 vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
5946 vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt,
5947 vm_dom[dom].vmd_pagequeues[PQ_UNSWAPPABLE].pq_cnt);
5948 }
5949 }
5950
DB_SHOW_COMMAND(pginfo,vm_page_print_pginfo)5951 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
5952 {
5953 vm_page_t m;
5954 boolean_t phys, virt;
5955
5956 if (!have_addr) {
5957 db_printf("show pginfo addr\n");
5958 return;
5959 }
5960
5961 phys = strchr(modif, 'p') != NULL;
5962 virt = strchr(modif, 'v') != NULL;
5963 if (virt)
5964 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
5965 else if (phys)
5966 m = PHYS_TO_VM_PAGE(addr);
5967 else
5968 m = (vm_page_t)addr;
5969 db_printf(
5970 "page %p obj %p pidx 0x%jx phys 0x%jx q %d ref 0x%x\n"
5971 " af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
5972 m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
5973 m->a.queue, m->ref_count, m->a.flags, m->oflags,
5974 m->flags, m->a.act_count, m->busy_lock, m->valid, m->dirty);
5975 }
5976 #endif /* DDB */
5977