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